PageSourceSearch

https://www.imperial.space/_next/static/immutable/chunks/2-g78g00keafd.js

js imperial.space collected 2026-10-07 21:59:04 UTC 2,029,938 bytes, 2 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,750815,e=>{"use strict";e.s(["clamp",0,function(e,[t,r]){return Math.min(r,Math.max(t,e))}])},750045,e=>{"use strict";var t=e.i(183023),r=e.i(541078),i=e.i(375039),s=e.i(394390);function n(e){var r;let n,a=(r=e,(n=t.forwardRef((e,r)=>{let{children:s,...n}=e;if(t.isValidElement(s)){var a;let e,l,o=(a=s,(l=(e=Object.getOwnPropertyDescriptor(a.props,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?a.ref:(l=(e=Object.getOwnPropertyDescriptor(a,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?a.props.ref:a.props.ref||a.ref),d=function(e,t){let r={...t};for(let i in t){let s=e[i],n=t[i];/^on[A-Z]/.test(i)?s&&n?r[i]=(...e)=>{let t=n(...e);return s(...e),t}:s&&(r[i]=s):"style"===i?r[i]={...s,...n}:"className"===i&&(r[i]=[s,n].filter(Boolean).join(" "))}return{...e,...r}}(n,s.props);return s.type!==t.Fragment&&(d.ref=r?(0,i.composeRefs)(r,o):o),t.cloneElement(s,d)}return t.Children.count(s)>1?t.Children.only(null):null})).displayName=`${r}.SlotClone`,n),o=t.forwardRef((e,r)=>{let{children:i,...n}=e,o=t.Children.toArray(i),d=o.find(l);if(d){let e=d.props.children,i=o.map(r=>r!==d?r:t.Children.count(e)>1?t.Children.only(null):t.isValidElement(e)?e.props.children:null);return(0,s.jsx)(a,{...n,ref:r,children:t.isValidElement(e)?t.cloneElement(e,void 0,i):null})}return(0,s.jsx)(a,{...n,ref:r,children:i})});return o.displayName=`${e}.Slot`,o}var a=Symbol("radix.slottable");function l(e){return t.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===a}e.s(["createCollection",0,function(e){let a=e+"CollectionProvider",[l,o]=(0,r.createContextScope)(a),[d,c]=l(a,{collectionRef:{current:null},itemMap:new Map}),u=e=>{let{scope:r,children:i}=e,n=t.default.useRef(null),a=t.default.useRef(new Map).current;return(0,s.jsx)(d,{scope:r,itemMap:a,collectionRef:n,children:i})};u.displayName=a;let h=e+"CollectionSlot",p=n(h),m=t.default.forwardRef((e,t)=>{let{scope:r,children:n}=e,a=c(h,r),l=(0,i.useComposedRefs)(t,a.collectionRef);return(0,s.jsx)(p,{ref:l,children:n})});m.displayName=h;let f=e+"CollectionItemSlot",x="data-radix-collection-item",g=n(f),b=t.default.forwardRef((e,r)=>{let{scope:n,children:a,...l}=e,o=t.default.useRef(null),d=(0,i.useComposedRefs)(r,o),u=c(f,n);return t.default.useEffect(()=>(u.itemMap.set(o,{ref:o,...l}),()=>void u.itemMap.delete(o))),(0,s.jsx)(g,{...{[x]:""},ref:d,children:a})});return b.displayName=f,[{Provider:u,Slot:m,ItemSlot:b},function(r){let i=c(e+"CollectionConsumer",r);return t.default.useCallback(()=>{let e=i.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${x}]`));return Array.from(i.itemMap.values()).sort((e,r)=>t.indexOf(e.ref.current)-t.indexOf(r.ref.current))},[i.collectionRef,i.itemMap])},o]}],750045)},936456,e=>{"use strict";var t=e.i(183023);e.i(394390);var r=t.createContext(void 0);e.s(["useDirection",0,function(e){let i=t.useContext(r);return e||i||"ltr"}])},234792,181276,e=>{"use strict";let t,r,i;var s=e.i(183023),n=e.i(489980),a=e.i(375039),l=e.i(541078),o=e.i(204095),d=e.i(671454),c=e.i(750045),u=e.i(936456),h=e.i(310526),p=e.i(507767),m=e.i(151067),f=e.i(729418),x=e.i(839209),g=e.i(406277),b=e.i(837299),v=e.i(506768),y=e.i(394390),w="rovingFocusGroup.onEntryFocus",j={bubbles:!1,cancelable:!0},S="RovingFocusGroup",[k,N,P]=(0,c.createCollection)(S),[T,C]=(0,l.createContextScope)(S,[P]),[M,_]=T(S),A=s.forwardRef((e,t)=>(0,y.jsx)(k.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,y.jsx)(k.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,y.jsx)(E,{...e,ref:t})})}));A.displayName=S;var E=s.forwardRef((e,t)=>{let{__scopeRovingFocusGroup:r,orientation:i,loop:l=!1,dir:c,currentTabStopId:h,defaultCurrentTabStopId:p,onCurrentTabStopIdChange:m,onEntryFocus:f,preventScrollOnEntryFocus:x=!1,...g}=e,b=s.useRef(null),k=(0,a.useComposedRefs)(t,b),P=(0,u.useDirection)(c),[T,C]=(0,o.useControllableState)({prop:h,defaultProp:p??null,onChange:m,caller:S}),[_,A]=s.useState(!1),E=(0,v.useCallbackRef)(f),L=N(r),F=s.useRef(!1),[R,I]=s.useState(0);return s.useEffect(()=>{let e=b.current;if(e)return e.addEventListener(w,E),()=>e.removeEventListener(w,E)},[E]),(0,y.jsx)(M,{scope:r,orientation:i,dir:P,loop:l,currentTabStopId:T,onItemFocus:s.useCallback(e=>C(e),[C]),onItemShiftTab:s.useCallback(()=>A(!0),[]),onFocusableItemAdd:s.useCallback(()=>I(e=>e+1),[]),onFocusableItemRemove:s.useCallback(()=>I(e=>e-1),[]),children:(0,y.jsx)(d.Primitive.div,{tabIndex:_||0===R?-1:0,"data-orientation":i,...g,ref:k,style:{outline:"none",...e.style},onMouseDown:(0,n.composeEventHandlers)(e.onMouseDown,()=>{F.current=!0}),onFocus:(0,n.composeEventHandlers)(e.onFocus,e=>{let t=!F.current;if(e.target===e.currentTarget&&t&&!_){let t=new CustomEvent(w,j);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){let e=L().filter(e=>
1e.focusable);D([e.find(e=>e.active),e.find(e=>e.id===T),...e].filter(Boolean).map(e=>e.ref.current),x)}}F.current=!1}),onBlur:(0,n.composeEventHandlers)(e.onBlur,()=>A(!1))})})}),L="RovingFocusGroupItem",F=s.forwardRef((e,t)=>{let{__scopeRovingFocusGroup:r,focusable:i=!0,active:a=!1,tabStopId:l,children:o,...c}=e,u=(0,f.useId)(),h=l||u,p=_(L,r),m=p.currentTabStopId===h,x=N(r),{onFocusableItemAdd:g,onFocusableItemRemove:b,currentTabStopId:v}=p;return s.useEffect(()=>{if(i)return g(),()=>b()},[i,g,b]),(0,y.jsx)(k.ItemSlot,{scope:r,id:h,focusable:i,active:a,children:(0,y.jsx)(d.Primitive.span,{tabIndex:m?0:-1,"data-orientation":p.orientation,...c,ref:t,onMouseDown:(0,n.composeEventHandlers)(e.onMouseDown,e=>{i?p.onItemFocus(h):e.preventDefault()}),onFocus:(0,n.composeEventHandlers)(e.onFocus,()=>p.onItemFocus(h)),onKeyDown:(0,n.composeEventHandlers)(e.onKeyDown,e=>{if("Tab"===e.key&&e.shiftKey)return void p.onItemShiftTab();if(e.target!==e.currentTarget)return;let t=function(e,t,r){var i;let s=(i=e.key,"rtl"!==r?i:"ArrowLeft"===i?"ArrowRight":"ArrowRight"===i?"ArrowLeft":i);if(!("vertical"===t&&["ArrowLeft","ArrowRight"].includes(s))&&!("horizontal"===t&&["ArrowUp","ArrowDown"].includes(s)))return R[s]}(e,p.orientation,p.dir);if(void 0!==t){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let s=x().filter(e=>e.focusable).map(e=>e.ref.current);if("last"===t)s.reverse();else if("prev"===t||"next"===t){var r,i;"prev"===t&&s.reverse();let n=s.indexOf(e.currentTarget);s=p.loop?(r=s,i=n+1,r.map((e,t)=>r[(i+t)%r.length])):s.slice(n+1)}setTimeout(()=>D(s))}}),children:"function"==typeof o?o({isCurrentTabStop:m,hasTabStop:null!=v}):o})})});F.displayName=L;var R={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function D(e,t=!1){let r=document.activeElement;for(let i of e)if(i===r||(i.focus({preventScroll:t}),document.activeElement!==r))return}e.s(["Item",0,F,"Root",0,A,"createRovingFocusGroupScope",0,C],181276);var I=Symbol("radix.slottable");function U(e){return s.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===I}var O=e.i(370030),B=e.i(710460),z=["Enter"," "],$=["ArrowUp","PageDown","End"],V=["ArrowDown","PageUp","Home",...$],H={ltr:[...z,"ArrowRight"],rtl:[...z,"ArrowLeft"]},W={ltr:["ArrowLeft"],rtl:["ArrowRight"]},q="Menu",[K,G,Y]=(0,c.createCollection)(q),[X,Q]=(0,l.createContextScope)(q,[Y,x.createPopperScope,C]),J=(0,x.createPopperScope)(),Z=C(),[ee,et]=X(q),[er,ei]=X(q),es=e=>{let{__scopeMenu:t,open:r=!1,children:i,dir:n,onOpenChange:a,modal:l=!0}=e,o=J(t),[d,c]=s.useState(null),h=s.useRef(!1),p=(0,v.useCallbackRef)(a),m=(0,u.useDirection)(n);return s.useEffect(()=>{let e=()=>{h.current=!0,document.addEventListener("pointerdown",t,{capture:!0,once:!0}),document.addEventListener("pointermove",t,{capture:!0,once:!0})},t=()=>h.current=!1;return document.addEventListener("keydown",e,{capture:!0}),()=>{document.removeEventListener("keydown",e,{capture:!0}),document.removeEventListener("pointerdown",t,{capture:!0}),document.removeEventListener("pointermove",t,{capture:!0})}},[]),(0,y.jsx)(x.Root,{...o,children:(0,y.jsx)(ee,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:c,children:(0,y.jsx)(er,{scope:t,onClose:s.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:h,dir:m,modal:l,children:i})})})};es.displayName=q;var en=s.forwardRef((e,t)=>{let{__scopeMenu:r,...i}=e,s=J(r);return(0,y.jsx)(x.Anchor,{...s,...i,ref:t})});en.displayName="MenuAnchor";var ea="MenuPortal",[el,eo]=X(ea,{forceMount:void 0}),ed=e=>{let{__scopeMenu:t,forceMount:r,children:i,container:s}=e,n=et(ea,t);return(0,y.jsx)(el,{scope:t,forceMount:r,children:(0,y.jsx)(b.Presence,{present:r||n.open,children:(0,y.jsx)(g.Portal,{asChild:!0,container:s,children:i})})})};ed.displayName=ea;var ec="MenuContent",[eu,eh]=X(ec),ep=s.forwardRef((e,t)=>{let r=eo(ec,e.__scopeMenu),{forceMount:i=r.forceMount,...s}=e,n=et(ec,e.__scopeMenu),a=ei(ec,e.__scopeMenu);return(0,y.jsx)(K.Provider,{scope:e.__scopeMenu,children:(0,y.jsx)(b.Presence,{present:i||n.open,children:(0,y.jsx)(K.Slot,{scope:e.__scopeMenu,children:a.modal?(0,y.jsx)(em,{...s,ref:t}):(0,y.jsx)(ef,{...s,ref:t})})})})}),em=s.forwardRef((e,t)=>
1{let r=et(ec,e.__scopeMenu),i=s.useRef(null),l=(0,a.useComposedRefs)(t,i);return s.useEffect(()=>{let e=i.current;if(e)return(0,O.hideOthers)(e)},[]),(0,y.jsx)(eg,{...e,ref:l,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:(0,n.composeEventHandlers)(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),ef=s.forwardRef((e,t)=>{let r=et(ec,e.__scopeMenu);return(0,y.jsx)(eg,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),ex=((i=s.forwardRef((e,t)=>{let{children:r,...i}=e;if(s.isValidElement(r)){var n;let e,l,o=(n=r,(l=(e=Object.getOwnPropertyDescriptor(n.props,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?n.ref:(l=(e=Object.getOwnPropertyDescriptor(n,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?n.props.ref:n.props.ref||n.ref),d=function(e,t){let r={...t};for(let i in t){let s=e[i],n=t[i];/^on[A-Z]/.test(i)?s&&n?r[i]=(...e)=>{let t=n(...e);return s(...e),t}:s&&(r[i]=s):"style"===i?r[i]={...s,...n}:"className"===i&&(r[i]=[s,n].filter(Boolean).join(" "))}return{...e,...r}}(i,r.props);return r.type!==s.Fragment&&(d.ref=t?(0,a.composeRefs)(t,o):o),s.cloneElement(r,d)}return s.Children.count(r)>1?s.Children.only(null):null})).displayName="MenuContent.ScrollLock.SlotClone",t=i,(r=s.forwardRef((e,r)=>{let{children:i,...n}=e,a=s.Children.toArray(i),l=a.find(U);if(l){let e=l.props.children,i=a.map(t=>t!==l?t:s.Children.count(e)>1?s.Children.only(null):s.isValidElement(e)?e.props.children:null);return(0,y.jsx)(t,{...n,ref:r,children:s.isValidElement(e)?s.cloneElement(e,void 0,i):null})}return(0,y.jsx)(t,{...n,ref:r,children:i})})).displayName="MenuContent.ScrollLock.Slot",r),eg=s.forwardRef((e,t)=>{let{__scopeMenu:r,loop:i=!1,trapFocus:l,onOpenAutoFocus:o,onCloseAutoFocus:d,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:b,onInteractOutside:v,onDismiss:w,disableOutsideScroll:j,...S}=e,k=et(ec,r),N=ei(ec,r),P=J(r),T=Z(r),C=G(r),[M,_]=s.useState(null),E=s.useRef(null),L=(0,a.useComposedRefs)(t,E,k.onContentChange),F=s.useRef(0),R=s.useRef(""),D=s.useRef(0),I=s.useRef(null),U=s.useRef("right"),O=s.useRef(0),z=j?B.RemoveScroll:s.Fragment;s.useEffect(()=>()=>window.clearTimeout(F.current),[]),(0,p.useFocusGuards)();let H=s.useCallback(e=>{var t,r;return U.current===I.current?.side&&(t=e,!!(r=I.current?.area)&&function(e,t){let{x:r,y:i}=e,s=!1;for(let e=0,n=t.length-1;e<t.length;n=e++){let a=t[e],l=t[n],o=a.x,d=a.y,c=l.x,u=l.y;d>i!=u>i&&r<(c-o)*(i-d)/(u-d)+o&&(s=!s)}return s}({x:t.clientX,y:t.clientY},r))},[]);return(0,y.jsx)(eu,{scope:r,searchRef:R,onItemEnter:s.useCallback(e=>{H(e)&&e.preventDefault()},[H]),onItemLeave:s.useCallback(e=>{H(e)||(E.current?.focus(),_(null))},[H]),onTriggerLeave:s.useCallback(e=>{H(e)&&e.preventDefault()},[H]),pointerGraceTimerRef:D,onPointerGraceIntentChange:s.useCallback(e=>{I.current=e},[]),children:(0,y.jsx)(z,{...j?{as:ex,allowPinchZoom:!0}:void 0,children:(0,y.jsx)(m.FocusScope,{asChild:!0,trapped:l,onMountAutoFocus:(0,n.composeEventHandlers)(o,e=>{e.preventDefault(),E.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:d,children:(0,y.jsx)(h.DismissableLayer,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:b,onInteractOutside:v,onDismiss:w,children:(0,y.jsx)(A,{asChild:!0,...T,dir:N.dir,orientation:"vertical",loop:i,currentTabStopId:M,onCurrentTabStopIdChange:_,onEntryFocus:(0,n.composeEventHandlers)(u,e=>{N.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,y.jsx)(x.Content,{role:"menu","aria-orientation":"vertical","data-state":eW(k.open),"data-radix-menu-content":"",dir:N.dir,...P,...S,ref:L,style:{outline:"none",...S.style},onKeyDown:(0,n.composeEventHandlers)(S.onKeyDown,e=>{let t=e.target.closest("[data-radix-menu-content]")===e.currentTarget,r=e.ctrlKey||e.altKey||e.metaKey,i=1===e.key.length;if(t){var s;let t,n,a,l,o,d;"Tab"===e.key&&e.preventDefault(),!r&&i&&(s=e.key,t=R.current+s,n=C().filter(e=>!e.disabled),a=document.activeElement,l=n.find(e=>e.ref.current===a)?.textValue,o=function(e,t,r){var i;let s=t.length>1&&Array.from(t).every(e=>e===t[0])?t[0]:t,n=r?e.indexOf(r):-1,a=(i=Math.max(n,0),e.map((t,r)=>e[(i+r)%e.length]));1===s.length&&(a=a.filter(e=>e!==r));let l=a.find(e=>e.toLowerCase().startsWith(s.toLowerCase()));return l!==r?l:void 0}(n.map(e=>e.textValue),t,l),d=n.find(e=>e.textValue===o)?.ref.current,function e(t){R.current=t,window.clearTimeout(F.current),""!==t&&(F.current=window.setTimeout(()=>e(""),1e3))}(t),d&&setTimeout(()=>d.focus()))}let n=E.current;
1if(e.target!==n||!V.includes(e.key))return;e.preventDefault();let a=C().filter(e=>!e.disabled).map(e=>e.ref.current);$.includes(e.key)&&a.reverse(),function(e){let t=document.activeElement;for(let r of e)if(r===t||(r.focus(),document.activeElement!==t))return}(a)}),onBlur:(0,n.composeEventHandlers)(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(F.current),R.current="")}),onPointerMove:(0,n.composeEventHandlers)(e.onPointerMove,eG(e=>{let t=e.target,r=O.current!==e.clientX;e.currentTarget.contains(t)&&r&&(U.current=e.clientX>O.current?"right":"left",O.current=e.clientX)}))})})})})})})});ep.displayName=ec;var eb=s.forwardRef((e,t)=>{let{__scopeMenu:r,...i}=e;return(0,y.jsx)(d.Primitive.div,{role:"group",...i,ref:t})});eb.displayName="MenuGroup";var ev=s.forwardRef((e,t)=>{let{__scopeMenu:r,...i}=e;return(0,y.jsx)(d.Primitive.div,{...i,ref:t})});ev.displayName="MenuLabel";var ey="MenuItem",ew="menu.itemSelect",ej=s.forwardRef((e,t)=>{let{disabled:r=!1,onSelect:i,...l}=e,o=s.useRef(null),c=ei(ey,e.__scopeMenu),u=eh(ey,e.__scopeMenu),h=(0,a.useComposedRefs)(t,o),p=s.useRef(!1);return(0,y.jsx)(eS,{...l,ref:h,disabled:r,onClick:(0,n.composeEventHandlers)(e.onClick,()=>{let e=o.current;if(!r&&e){let t=new CustomEvent(ew,{bubbles:!0,cancelable:!0});e.addEventListener(ew,e=>i?.(e),{once:!0}),(0,d.dispatchDiscreteCustomEvent)(e,t),t.defaultPrevented?p.current=!1:c.onClose()}}),onPointerDown:t=>{e.onPointerDown?.(t),p.current=!0},onPointerUp:(0,n.composeEventHandlers)(e.onPointerUp,e=>{p.current||e.currentTarget?.click()}),onKeyDown:(0,n.composeEventHandlers)(e.onKeyDown,e=>{let t=""!==u.searchRef.current;r||t&&" "===e.key||z.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})});ej.displayName=ey;var eS=s.forwardRef((e,t)=>{let{__scopeMenu:r,disabled:i=!1,textValue:l,...o}=e,c=eh(ey,r),u=Z(r),h=s.useRef(null),p=(0,a.useComposedRefs)(t,h),[m,f]=s.useState(!1),[x,g]=s.useState("");return s.useEffect(()=>{let e=h.current;e&&g((e.textContent??"").trim())},[o.children]),(0,y.jsx)(K.ItemSlot,{scope:r,disabled:i,textValue:l??x,children:(0,y.jsx)(F,{asChild:!0,...u,focusable:!i,children:(0,y.jsx)(d.Primitive.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...o,ref:p,onPointerMove:(0,n.composeEventHandlers)(e.onPointerMove,eG(e=>{i?c.onItemLeave(e):(c.onItemEnter(e),e.defaultPrevented||e.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:(0,n.composeEventHandlers)(e.onPointerLeave,eG(e=>c.onItemLeave(e))),onFocus:(0,n.composeEventHandlers)(e.onFocus,()=>f(!0)),onBlur:(0,n.composeEventHandlers)(e.onBlur,()=>f(!1))})})})}),ek=s.forwardRef((e,t)=>{let{checked:r=!1,onCheckedChange:i,...s}=e;return(0,y.jsx)(eE,{scope:e.__scopeMenu,checked:r,children:(0,y.jsx)(ej,{role:"menuitemcheckbox","aria-checked":eq(r)?"mixed":r,...s,ref:t,"data-state":eK(r),onSelect:(0,n.composeEventHandlers)(s.onSelect,()=>i?.(!!eq(r)||!r),{checkForDefaultPrevented:!1})})})});ek.displayName="MenuCheckboxItem";var eN="MenuRadioGroup",[eP,eT]=X(eN,{value:void 0,onValueChange:()=>{}}),eC=s.forwardRef((e,t)=>{let{value:r,onValueChange:i,...s}=e,n=(0,v.useCallbackRef)(i);return(0,y.jsx)(eP,{scope:e.__scopeMenu,value:r,onValueChange:n,children:(0,y.jsx)(eb,{...s,ref:t})})});eC.displayName=eN;var eM="MenuRadioItem",e_=s.forwardRef((e,t)=>{let{value:r,...i}=e,s=eT(eM,e.__scopeMenu),a=r===s.value;return(0,y.jsx)(eE,{scope:e.__scopeMenu,checked:a,children:(0,y.jsx)(ej,{role:"menuitemradio","aria-checked":a,...i,ref:t,"data-state":eK(a),onSelect:(0,n.composeEventHandlers)(i.onSelect,()=>s.onValueChange?.(r),{checkForDefaultPrevented:!1})})})});e_.displayName=eM;var eA="MenuItemIndicator",[eE,eL]=X(eA,{checked:!1}),eF=s.forwardRef((e,t)=>{let{__scopeMenu:r,forceMount:i,...s}=e,n=eL(eA,r);return(0,y.jsx)(b.Presence,{present:i||eq(n.checked)||!0===n.checked,children:(0,y.jsx)(d.Primitive.span,{...s,ref:t,"data-state":eK(n.checked)})})});eF.displayName=eA;var eR=s.forwardRef((e,t)=>{let{__scopeMenu:r,...i}=e;return(0,y.jsx)(d.Primitive.div,{role:"separator","aria-orientation":"horizontal",...i,ref:t})});eR.displayName="MenuSeparator";var eD=s.forwardRef((e,t)=>
1{let{__scopeMenu:r,...i}=e,s=J(r);return(0,y.jsx)(x.Arrow,{...s,...i,ref:t})});eD.displayName="MenuArrow";var eI="MenuSub",[eU,eO]=X(eI),eB=e=>{let{__scopeMenu:t,children:r,open:i=!1,onOpenChange:n}=e,a=et(eI,t),l=J(t),[o,d]=s.useState(null),[c,u]=s.useState(null),h=(0,v.useCallbackRef)(n);return s.useEffect(()=>(!1===a.open&&h(!1),()=>h(!1)),[a.open,h]),(0,y.jsx)(x.Root,{...l,children:(0,y.jsx)(ee,{scope:t,open:i,onOpenChange:h,content:c,onContentChange:u,children:(0,y.jsx)(eU,{scope:t,contentId:(0,f.useId)(),triggerId:(0,f.useId)(),trigger:o,onTriggerChange:d,children:r})})})};eB.displayName=eI;var ez="MenuSubTrigger",e$=s.forwardRef((e,t)=>{let r=et(ez,e.__scopeMenu),i=ei(ez,e.__scopeMenu),l=eO(ez,e.__scopeMenu),o=eh(ez,e.__scopeMenu),d=s.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=o,h={__scopeMenu:e.__scopeMenu},p=s.useCallback(()=>{d.current&&window.clearTimeout(d.current),d.current=null},[]);return s.useEffect(()=>p,[p]),s.useEffect(()=>{let e=c.current;return()=>{window.clearTimeout(e),u(null)}},[c,u]),(0,y.jsx)(en,{asChild:!0,...h,children:(0,y.jsx)(eS,{id:l.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":l.contentId,"data-state":eW(r.open),...e,ref:(0,a.composeRefs)(t,l.onTriggerChange),onClick:t=>{e.onClick?.(t),e.disabled||t.defaultPrevented||(t.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:(0,n.composeEventHandlers)(e.onPointerMove,eG(t=>{o.onItemEnter(t),!t.defaultPrevented&&(e.disabled||r.open||d.current||(o.onPointerGraceIntentChange(null),d.current=window.setTimeout(()=>{r.onOpenChange(!0),p()},100)))})),onPointerLeave:(0,n.composeEventHandlers)(e.onPointerLeave,eG(e=>{p();let t=r.content?.getBoundingClientRect();if(t){let i=r.content?.dataset.side,s="right"===i,n=t[s?"left":"right"],a=t[s?"right":"left"];o.onPointerGraceIntentChange({area:[{x:e.clientX+(s?-5:5),y:e.clientY},{x:n,y:t.top},{x:a,y:t.top},{x:a,y:t.bottom},{x:n,y:t.bottom}],side:i}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(e),e.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:(0,n.composeEventHandlers)(e.onKeyDown,t=>{let s=""!==o.searchRef.current;e.disabled||s&&" "===t.key||H[i.dir].includes(t.key)&&(r.onOpenChange(!0),r.content?.focus(),t.preventDefault())})})})});e$.displayName=ez;var eV="MenuSubContent",eH=s.forwardRef((e,t)=>{let r=eo(ec,e.__scopeMenu),{forceMount:i=r.forceMount,...l}=e,o=et(ec,e.__scopeMenu),d=ei(ec,e.__scopeMenu),c=eO(eV,e.__scopeMenu),u=s.useRef(null),h=(0,a.useComposedRefs)(t,u);return(0,y.jsx)(K.Provider,{scope:e.__scopeMenu,children:(0,y.jsx)(b.Presence,{present:i||o.open,children:(0,y.jsx)(K.Slot,{scope:e.__scopeMenu,children:(0,y.jsx)(eg,{id:c.contentId,"aria-labelledby":c.triggerId,...l,ref:h,align:"start",side:"rtl"===d.dir?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{d.isUsingKeyboardRef.current&&u.current?.focus(),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:(0,n.composeEventHandlers)(e.onFocusOutside,e=>{e.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:(0,n.composeEventHandlers)(e.onEscapeKeyDown,e=>{d.onClose(),e.preventDefault()}),onKeyDown:(0,n.composeEventHandlers)(e.onKeyDown,e=>{let t=e.currentTarget.contains(e.target),r=W[d.dir].includes(e.key);t&&r&&(o.onOpenChange(!1),c.trigger?.focus(),e.preventDefault())})})})})})});function eW(e){return e?"open":"closed"}function eq(e){return"indeterminate"===e}function eK(e){return eq(e)?"indeterminate":e?"checked":"unchecked"}function eG(e){return t=>"mouse"===t.pointerType?e(t):void 0}eH.displayName=eV;var eY="DropdownMenu",[eX,eQ]=(0,l.createContextScope)(eY,[Q]),eJ=Q(),[eZ,e0]=eX(eY),e1=e=>{let{__scopeDropdownMenu:t,children:r,dir:i,open:n,defaultOpen:a,onOpenChange:l,modal:d=!0}=e,c=eJ(t),u=s.useRef(null),[h,p]=(0,o.useControllableState)({prop:n,defaultProp:a??!1,onChange:l,caller:eY});return(0,y.jsx)(eZ,{scope:t,triggerId:(0,f.useId)(),triggerRef:u,contentId:(0,f.useId)(),open:h,onOpenChange:p,onOpenToggle:s.useCallback(()=>p(e=>!e),[p]),modal:d,children:(0,y.jsx)(es,{...c,open:h,onOpenChange:p,dir:i,modal:d,children:r})})};e1.displayName=eY;var e2="DropdownMenuTrigger",e5=s.forwardRef((e,t)=>
1{let{__scopeDropdownMenu:r,disabled:i=!1,...s}=e,l=e0(e2,r),o=eJ(r);return(0,y.jsx)(en,{asChild:!0,...o,children:(0,y.jsx)(d.Primitive.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":i?"":void 0,disabled:i,...s,ref:(0,a.composeRefs)(t,l.triggerRef),onPointerDown:(0,n.composeEventHandlers)(e.onPointerDown,e=>{!i&&0===e.button&&!1===e.ctrlKey&&(l.onOpenToggle(),l.open||e.preventDefault())}),onKeyDown:(0,n.composeEventHandlers)(e.onKeyDown,e=>{!i&&(["Enter"," "].includes(e.key)&&l.onOpenToggle(),"ArrowDown"===e.key&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(e.key)&&e.preventDefault())})})})});e5.displayName=e2;var e3=e=>{let{__scopeDropdownMenu:t,...r}=e,i=eJ(t);return(0,y.jsx)(ed,{...i,...r})};e3.displayName="DropdownMenuPortal";var e4="DropdownMenuContent",e6=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,a=e0(e4,r),l=eJ(r),o=s.useRef(!1);return(0,y.jsx)(ep,{id:a.contentId,"aria-labelledby":a.triggerId,...l,...i,ref:t,onCloseAutoFocus:(0,n.composeEventHandlers)(e.onCloseAutoFocus,e=>{o.current||a.triggerRef.current?.focus(),o.current=!1,e.preventDefault()}),onInteractOutside:(0,n.composeEventHandlers)(e.onInteractOutside,e=>{let t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,i=2===t.button||r;(!a.modal||i)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});e6.displayName=e4;var e8=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eb,{...s,...i,ref:t})});e8.displayName="DropdownMenuGroup";var e9=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(ev,{...s,...i,ref:t})});e9.displayName="DropdownMenuLabel";var e7=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(ej,{...s,...i,ref:t})});e7.displayName="DropdownMenuItem";var te=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(ek,{...s,...i,ref:t})});te.displayName="DropdownMenuCheckboxItem";var tt=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eC,{...s,...i,ref:t})});tt.displayName="DropdownMenuRadioGroup";var tr=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(e_,{...s,...i,ref:t})});tr.displayName="DropdownMenuRadioItem";var ti=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eF,{...s,...i,ref:t})});ti.displayName="DropdownMenuItemIndicator";var ts=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eR,{...s,...i,ref:t})});ts.displayName="DropdownMenuSeparator",s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eD,{...s,...i,ref:t})}).displayName="DropdownMenuArrow";var tn=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(e$,{...s,...i,ref:t})});tn.displayName="DropdownMenuSubTrigger";var ta=s.forwardRef((e,t)=>{let{__scopeDropdownMenu:r,...i}=e,s=eJ(r);return(0,y.jsx)(eH,{...s,...i,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ta.displayName="DropdownMenuSubContent",e.s(["CheckboxItem",0,te,"Content",0,e6,"Group",0,e8,"Item",0,e7,"ItemIndicator",0,ti,"Label",0,e9,"Portal",0,e3,"RadioGroup",0,tt,"RadioItem",0,tr,"Root",0,e1,"Separator",0,ts,"Sub",0,e=>{let{__scopeDropdownMenu:t,children:r,open:i,onOpenChange:s,defaultOpen:n}=e,a=eJ(t),[l,d]=(0,o.useControllableState)({prop:i,defaultProp:n??!1,onChange:s,caller:"DropdownMenuSub"});return(0,y.jsx)(eB,{...a,open:l,onOpenChange:d,children:r})},"SubContent",0,ta,"SubTrigger",0,tn,"Trigger",0,e5],234792)},327494,e=>{"use strict";var t=e.i(183023);
1e.s(["usePrevious",0,function(e){let r=t.useRef({value:e,previous:e});return t.useMemo(()=>(r.current.value!==e&&(r.current.previous=r.current.value,r.current.value=e),r.current.previous),[e])}])},175701,758169,e=>{"use strict";var t=e.i(313828),r=e.i(242132);function i(e){return{onFetch:(t,i)=>{let a=t.options,l=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],d=t.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=async()=>{let i=!1,h=(0,r.ensureQueryFn)(t.options,t.fetchOptions),p=async(e,s,n)=>{let a;if(i)return Promise.reject();if(null==s&&e.pages.length)return Promise.resolve(e);let l=(a={client:t.client,queryKey:t.queryKey,pageParam:s,direction:n?"backward":"forward",meta:t.options.meta},(0,r.addConsumeAwareSignal)(a,()=>t.signal,()=>i=!0),a),o=await h(l),{maxPages:d}=t.options,c=n?r.addToStart:r.addToEnd;return{pages:c(e.pages,o,d),pageParams:c(e.pageParams,s,d)}};if(l&&o.length){let e="backward"===l,t={pages:o,pageParams:d},r=(e?n:s)(a,t);c=await p(t,r,e)}else{let t=e??o.length;do{let e=0===u?d[0]??a.initialPageParam:s(a,c);if(u>0&&null==e)break;c=await p(c,e),u++}while(u<t)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(h,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},i):t.fetchFn=h}}}function s(e,{pages:t,pageParams:r}){let i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,r[i],r):void 0}function n(e,{pages:t,pageParams:r}){return t.length>0?e.getPreviousPageParam?.(t[0],t,r[0],r):void 0}function a(e,t){return!!t&&null!=s(e,t)}function l(e,t){return!!t&&!!e.getPreviousPageParam&&null!=n(e,t)}e.s(["hasNextPage",0,a,"hasPreviousPage",0,l,"infiniteQueryBehavior",0,i],758169);var o=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:i()})}getOptimisticResult(e){return e.behavior=i(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:r}=e,i=super.createResult(e,t),{isFetching:s,isRefetching:n,isError:o,isRefetchError:d}=i,c=r.fetchMeta?.fetchMore?.direction,u=o&&"forward"===c,h=s&&"forward"===c,p=o&&"backward"===c,m=s&&"backward"===c;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:a(t,r.data),hasPreviousPage:l(t,r.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:d&&!u&&!p,isRefetching:n&&!h&&!m}}},d=e.i(326704);e.s(["useInfiniteQuery",0,function(e,t){return(0,d.useBaseQuery)(e,o,t)}],175701)},435023,e=>{"use strict";var t=e.i(183023),r=e.i(483007),i=e.i(313828),s=e.i(780174),n=e.i(242132);function a(e,t){let r=new Set(t);return e.filter(e=>!r.has(e))}var l=class extends s.Subscribable{#e;#t;#r;#i;#s;#n;#a;#l;#o=[];constructor(e,t,r){super(),this.#e=e,this.#i=r,this.#r=[],this.#s=[],this.#t=[],this.setQueries(t)}onSubscribe(){1===this.listeners.size&&this.#s.forEach(e=>{e.subscribe(t=>{this.#d(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#s.forEach(e=>{e.destroy()})}setQueries(e,t){this.#r=e,this.#i=t,r.notifyManager.batch(()=>{let e=this.#s,t=this.#c(this.#r);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let r=t.map(e=>e.observer),i=r.map(e=>e.getCurrentResult()),s=e.length!==r.length,l=r.some((t,r)=>t!==e[r]),o=s||l,d=!!o||i.some((e,t)=>{let r=this.#t[t];return!r||!(0,n.shallowEqualObjects)(e,r)});(o||d)&&(o&&(this.#o=t,this.#s=r),this.#t=i,this.hasListeners()&&(o&&(a(e,r).forEach(e=>{e.destroy()}),a(r,e).forEach(e=>{e.subscribe(t=>{this.#d(e,t)})})),this.#u()))})}getCurrentResult(){return this.#t}getQueries(){return this.#s.map(e=>e.getCurrentQuery())}getObservers(){return this.#s}getOptimisticResult(e,t){let r=this.#c(e),i=r.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions));return[i,e=>this.#h(e??i,t),()=>this.#p(i,r)]}#p(e,t){return t.map((r,i)=>{let s=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?s:r.observer.trackResult(s,e=>{t.forEach(t=>{t.observer.trackProp(e)})})})}#h(e,t){return t?(this.#n&&this.#t===this.#l&&t===this.#a||(this.#a=t,this.#l=this.#t,this.#n=(0,n.replaceEqualDeep)(this.#n,t(e))),this.#n):e}#c(e){let t=new Map;
1this.#s.forEach(e=>{let r=e.options.queryHash;if(!r)return;let i=t.get(r);i?i.push(e):t.set(r,[e])});let r=[];return e.forEach(e=>{let s=this.#e.defaultQueryOptions(e),n=t.get(s.queryHash)?.shift()??new i.QueryObserver(this.#e,s);r.push({defaultedQueryOptions:s,observer:n})}),r}#d(e,t){let r=this.#s.indexOf(e);if(-1!==r){var i;let e;this.#t=(i=this.#t,(e=i.slice(0))[r]=t,e),this.#u()}}#u(){if(this.hasListeners()){let e=this.#n,t=this.#p(this.#t,this.#o);e!==this.#h(t,this.#i?.combine)&&r.notifyManager.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},o=e.i(514049),d=e.i(90390),c=e.i(468425),u=e.i(853249),h=e.i(40688);e.s(["useQueries",0,function({queries:e,...s},a){let p=(0,o.useQueryClient)(a),m=(0,d.useIsRestoring)(),f=(0,c.useQueryErrorResetBoundary)(),x=t.useMemo(()=>e.map(e=>{let t=p.defaultQueryOptions(e);return t._optimisticResults=m?"isRestoring":"optimistic",t}),[e,p,m]);x.forEach(e=>{(0,h.ensureSuspenseTimers)(e);let t=p.getQueryCache().get(e.queryHash);(0,u.ensurePreventErrorBoundaryRetry)(e,f,t)}),(0,u.useClearResetErrorBoundary)(f);let[g]=t.useState(()=>new l(p,x,s)),[b,v,y]=g.getOptimisticResult(x,s.combine),w=!m&&!1!==s.subscribed;t.useSyncExternalStore(t.useCallback(e=>w?g.subscribe(r.notifyManager.batchCalls(e)):n.noop,[g,w]),()=>g.getCurrentResult(),()=>g.getCurrentResult()),t.useEffect(()=>{g.setQueries(x,s)},[x,s,g]);let j=b.some((e,t)=>(0,h.shouldSuspend)(x[t],e))?b.flatMap((e,t)=>{let r=x[t];if(r){let t=new i.QueryObserver(p,r);if((0,h.shouldSuspend)(r,e))return(0,h.fetchOptimistic)(r,t,f);(0,h.willFetch)(e,m)&&(0,h.fetchOptimistic)(r,t,f)}return[]}):[];if(j.length>0)throw Promise.all(j);let S=b.find((e,t)=>{let r=x[t];return r&&(0,u.getHasError)({result:e,errorResetBoundary:f,throwOnError:r.throwOnError,query:p.getQueryCache().get(r.queryHash),suspense:r.suspense})});if(S?.error)throw S.error;return v(y())}],435023)},875174,(e,t,r)=>{!function(){"use strict";var t=function(){this.init()};t.prototype={init:function(){var e=this||i;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="u">typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||i;if(e=parseFloat(e),t.ctx||u(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,i.ctx.currentTime);for(var r=0;r<t._howls.length;r++)if(!t._howls[r]._webAudio)for(var s=t._howls[r]._getSoundIds(),n=0;n<s.length;n++){var a=t._howls[r]._soundById(s[n]);a&&a._node&&(a._node.volume=a._volume*e)}return t}return t._volume},mute:function(e){var t=this||i;t.ctx||u(),t._muted=e,t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e?0:t._volume,i.ctx.currentTime);for(var r=0;r<t._howls.length;r++)if(!t._howls[r]._webAudio)for(var s=t._howls[r]._getSoundIds(),n=0;n<s.length;n++){var a=t._howls[r]._soundById(s[n]);a&&a._node&&(a._node.muted=!!e||a._muted)}return t},stop:function(){for(var e=this||i,t=0;t<e._howls.length;t++)e._howls[t].stop();return e},unload:function(){for(var e=this||i,t=e._howls.length-1;t>=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,u()),e},codecs:function(e){return(this||i)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||i;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("u">typeof Audio)try{var t=new Audio;void 0===t.oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{var t=new Audio;t.muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||i,t=null;try{t="u">typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var r=t.canPlayType("audio/mpeg;").replace(/^no$/,""),s=e._navigator?e._navigator.userAgent:"",n=s.match(/OPR\/(\d+)/g),a=n&&33>parseInt(n[0].split("/")[1],10),l=-1!==s.indexOf("Safari")&&-1===s.indexOf("Chrome"),o=s.match(/Version\/(.*?) /),d=l&&o&&15>parseInt(o[1],10);return e._codecs={mp3:!!(!a&&(r||t.canPlayType("audio/mp3;").replace(/^no$/,""))),mpeg:!!r,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!(!d&&t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!!(!d&&t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||i;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(r){for(;e._html5AudioPool.length<e.html5PoolSize;)try{var i=new Audio;i._unlocked=!0,e._releaseHtml5Audio(i)}catch(t){e.noAudio=!0;break}for(var s=0;s<e._howls.length;s++)if(!e._howls[s]._webAudio)for(var n=e._howls[s]._getSoundIds(),a=0;a<n.length;a++){var l=e._howls[s]._soundById(n[a]);l&&l._node&&!l._node._unlocked&&(l._node._unlocked=!0,l._node.load())}e._autoResume();var o=e.ctx.createBufferSource();o.buffer=e._scratchBuffer,o.connect(e.ctx.destination),void 0===o.start?o.noteOn(0):o.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),o.onended=function(){o.disconnect(0),e._audioUnlocked=!0,document.removeEventListener("touchstart",t,!0),document.removeEventListener("touchend",t,!0),document.removeEventListener("click",t,!0),document.removeEventListener("keydown",t,!0);for(var r=0;r<e._howls.length;r++)e._howls[r]._emit("unlock")}};return document.addEventListener("touchstart",t,!0),document.addEventListener("touchend",t,!0),document.addEventListener("click",t,!0),document.addEventListener("keydown",t,!0),e}},_obtainHtml5Audio:function(){var e=this||i;if(e._html5AudioPool.length)return e._html5AudioPool.pop();var t=new Audio().play();return t&&"u">typeof Promise&&(t instanceof Promise||"function"==typeof t.then)&&t.catch(function(){console.warn("HTML5 Audio pool exhausted, returning potentially locked audio object.")}),new Audio},_releaseHtml5Audio:function(e){var t=this||i;
1return e._unlocked&&t._html5AudioPool.push(e),t},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&i.usingWebAudio){for(var t=0;t<e._howls.length;t++)if(e._howls[t]._webAudio){for(var r=0;r<e._howls[t]._sounds.length;r++)if(!e._howls[t]._sounds[r]._paused)return e}return e._suspendTimer&&clearTimeout(e._suspendTimer),e._suspendTimer=setTimeout(function(){if(e.autoSuspend){e._suspendTimer=null,e.state="suspending";var t=function(){e.state="suspended",e._resumeAfterSuspend&&(delete e._resumeAfterSuspend,e._autoResume())};e.ctx.suspend().then(t,t)}},3e4),e}},_autoResume:function(){var e=this;if(e.ctx&&void 0!==e.ctx.resume&&i.usingWebAudio)return"running"===e.state&&"interrupted"!==e.ctx.state&&e._suspendTimer?(clearTimeout(e._suspendTimer),e._suspendTimer=null):"suspended"===e.state||"running"===e.state&&"interrupted"===e.ctx.state?(e.ctx.resume().then(function(){e.state="running";for(var t=0;t<e._howls.length;t++)e._howls[t]._emit("resume")}),e._suspendTimer&&(clearTimeout(e._suspendTimer),e._suspendTimer=null)):"suspending"===e.state&&(e._resumeAfterSuspend=!0),e}};var i=new t,s=function(e){e.src&&0!==e.src.length?this.init(e):console.error("An array of source files must be passed with any new Howl.")};s.prototype={init:function(e){var t=this;return i.ctx||u(),t._autoplay=e.autoplay||!1,t._format="string"!=typeof e.format?e.format:[e.format],t._html5=e.html5||!1,t._muted=e.mute||!1,t._loop=e.loop||!1,t._pool=e.pool||5,t._preload="boolean"!=typeof e.preload&&"metadata"!==e.preload||e.preload,t._rate=e.rate||1,t._sprite=e.sprite||{},t._src="string"!=typeof e.src?e.src:[e.src],t._volume=void 0!==e.volume?e.volume:1,t._xhr={method:e.xhr&&e.xhr.method?e.xhr.method:"GET",headers:e.xhr&&e.xhr.headers?e.xhr.headers:null,withCredentials:!!e.xhr&&!!e.xhr.withCredentials&&e.xhr.withCredentials},t._duration=0,t._state="unloaded",t._sounds=[],t._endTimers={},t._queue=[],t._playLock=!1,t._onend=e.onend?[{fn:e.onend}]:[],t._onfade=e.onfade?[{fn:e.onfade}]:[],t._onload=e.onload?[{fn:e.onload}]:[],t._onloaderror=e.onloaderror?[{fn:e.onloaderror}]:[],t._onplayerror=e.onplayerror?[{fn:e.onplayerror}]:[],t._onpause=e.onpause?[{fn:e.onpause}]:[],t._onplay=e.onplay?[{fn:e.onplay}]:[],t._onstop=e.onstop?[{fn:e.onstop}]:[],t._onmute=e.onmute?[{fn:e.onmute}]:[],t._onvolume=e.onvolume?[{fn:e.onvolume}]:[],t._onrate=e.onrate?[{fn:e.onrate}]:[],t._onseek=e.onseek?[{fn:e.onseek}]:[],t._onunlock=e.onunlock?[{fn:e.onunlock}]:[],t._onresume=[],t._webAudio=i.usingWebAudio&&!t._html5,void 0!==i.ctx&&i.ctx&&i.autoUnlock&&i._unlockAudio(),i._howls.push(t),t._autoplay&&t._queue.push({event:"play",action:function(){t.play()}}),t._preload&&"none"!==t._preload&&t.load(),t},load:function(){var e,t,r=null;if(i.noAudio)return void this._emit("loaderror",null,"No audio support.");"string"==typeof this._src&&(this._src=[this._src]);for(var s=0;s<this._src.length;s++){if(this._format&&this._format[s])e=this._format[s];else{if("string"!=typeof(t=this._src[s])){this._emit("loaderror",null,"Non-string found in selected audio sources - ignoring.");continue}(e=/^data:audio\/([^;,]+);/i.exec(t))||(e=/\.([^.]+)$/.exec(t.split("?",1)[0])),e&&(e=e[1].toLowerCase())}if(e||console.warn('No file extension was found. Consider using the "format" property or specify an extension.'),e&&i.codecs(e)){r=this._src[s];break}}return r?(this._src=r,this._state="loading","https:"===window.location.protocol&&"http:"===r.slice(0,5)&&(this._html5=!0,this._webAudio=!1),new n(this),this._webAudio&&l(this),this):void this._emit("loaderror",null,"No codec support for selected audio sources.")},play:function(e,t){var r=this,s=null;if("number"==typeof e)s=e,e=null;else if("string"==typeof e&&"loaded"===r._state&&!r._sprite[e])return null;else if(void 0===e&&(e="__default",!r._playLock)){for(var n=0,a=0;a<r._sounds.length;a++)r._sounds[a]._paused&&!r._sounds[a]._ended&&(n++,s=r._sounds[a]._id);1===n?e=null:s=null}var l=s?r._soundById(s):r._inactiveSound();if(!l)return null;if(s&&!e&&(e=l._sprite||"__default"),"loaded"!==r._state){l._sprite=e,l._ended=!1;var o=l._id;return r._queue.push({event:"play",action:function(){r.play(o)}}),o}if(s&&!l._paused)return t||r._loadQueue("play"),l._id;r._webAudio&&i._autoResume();var d=Math.max(0,l._seek>0?l._seek:r._sprite[e][0]/1e3),c=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),u=1e3*c/Math.abs(l._rate),h=r._sprite[e][0]/1e3,p=(r._sprite[e][0]+r._sprite[e][1])/1e3;l._sprite=e,l._ended=!1;var m=function(){l._paused=!1,l._seek=d,l._start=h,l._stop=p,l._loop=!!(l._loop||r._sprite[e][2])};if(d>=p)return void r._ended(l);var f=l._node;if(r._webAudio){var x=function(){r._playLock=!1,m(),r._refreshBuffer(l);var e=l._muted||r._muted?0:l._volume;f.gain.setValueAtTime(e,i.ctx.currentTime),l._playStart=i.ctx.currentTime,void 0===f.bufferSource.start?l._loop?f.bufferSource.noteGrainOn(0,d,86400):f.bufferSource.noteGrainOn(0,d,c):l._loop?f.bufferSource.start(0,d,86400):f.bufferSource.start(0,d,c),u!==1/0&&(r._endTimers[l._id]=setTimeout(r._ended.bind(r,l),u)),t||setTimeout(function(){r._emit("play",l._id),r._loadQueue()},0)};"running"===i.state&&"interrupted"!==i.ctx.state?x():(r._playLock=!0,r.once("resume",x),r._clearTimer(l._id))}else{var g=function(){f.currentTime=d,f.muted=l._muted||r._muted||i._muted||f.muted,f.volume=l._volume*i.volume(),f.playbackRate=l._rate;try{var s=f.play();if(s&&"u">typeof Promise&&(s instanceof Promise||"function"==typeof s.then)?(r._playLock=!0,m(),s.then(function(){r._playLock=!1,f._unlocked=!0,t?r._loadQueue():r._emit("play",l._id)}
1).catch(function(){r._playLock=!1,r._emit("playerror",l._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),l._ended=!0,l._paused=!0})):t||(r._playLock=!1,m(),r._emit("play",l._id)),f.playbackRate=l._rate,f.paused)return void r._emit("playerror",l._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||l._loop?r._endTimers[l._id]=setTimeout(r._ended.bind(r,l),u):(r._endTimers[l._id]=function(){r._ended(l),f.removeEventListener("ended",r._endTimers[l._id],!1)},f.addEventListener("ended",r._endTimers[l._id],!1))}catch(e){r._emit("playerror",l._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===f.src&&(f.src=r._src,f.load());var b=window&&window.ejecta||!f.readyState&&i._navigator.isCocoonJS;if(f.readyState>=3||b)g();else{r._playLock=!0,r._state="loading";var v=function(){r._state="loaded",g(),f.removeEventListener(i._canPlayEvent,v,!1)};f.addEventListener(i._canPlayEvent,v,!1),r._clearTimer(l._id)}}return l._id},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var r=t._getSoundIds(e),i=0;i<r.length;i++){t._clearTimer(r[i]);var s=t._soundById(r[i]);if(s&&!s._paused&&(s._seek=t.seek(r[i]),s._rateSeek=0,s._paused=!0,t._stopFade(r[i]),s._node))if(t._webAudio){if(!s._node.bufferSource)continue;void 0===s._node.bufferSource.stop?s._node.bufferSource.noteOff(0):s._node.bufferSource.stop(0),t._cleanBuffer(s._node)}else isNaN(s._node.duration)&&s._node.duration!==1/0||s._node.pause();arguments[1]||t._emit("pause",s?s._id:null)}return t},stop:function(e,t){var r=this;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"stop",action:function(){r.stop(e)}}),r;for(var i=r._getSoundIds(e),s=0;s<i.length;s++){r._clearTimer(i[s]);var n=r._soundById(i[s]);n&&(n._seek=n._start||0,n._rateSeek=0,n._paused=!0,n._ended=!0,r._stopFade(i[s]),n._node&&(r._webAudio?n._node.bufferSource&&(void 0===n._node.bufferSource.stop?n._node.bufferSource.noteOff(0):n._node.bufferSource.stop(0),r._cleanBuffer(n._node)):isNaN(n._node.duration)&&n._node.duration!==1/0||(n._node.currentTime=n._start||0,n._node.pause(),n._node.duration===1/0&&r._clearSound(n._node))),t||r._emit("stop",n._id))}return r},mute:function(e,t){var r=this;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"mute",action:function(){r.mute(e,t)}}),r;if(void 0===t)if("boolean"!=typeof e)return r._muted;else r._muted=e;for(var s=r._getSoundIds(t),n=0;n<s.length;n++){var a=r._soundById(s[n]);a&&(a._muted=e,a._interval&&r._stopFade(a._id),r._webAudio&&a._node?a._node.gain.setValueAtTime(e?0:a._volume,i.ctx.currentTime):a._node&&(a._node.muted=!!i._muted||e),r._emit("mute",a._id))}return r},volume:function(){var e,t,r,s=this,n=arguments;if(0===n.length)return s._volume;if(1===n.length||2===n.length&&void 0===n[1]?s._getSoundIds().indexOf(n[0])>=0?t=parseInt(n[0],10):e=parseFloat(n[0]):n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10)),void 0===e||!(e>=0)||!(e<=1))return(r=t?s._soundById(t):s._sounds[0])?r._volume:0;if("loaded"!==s._state||s._playLock)return s._queue.push({event:"volume",action:function(){s.volume.apply(s,n)}}),s;void 0===t&&(s._volume=e),t=s._getSoundIds(t);for(var a=0;a<t.length;a++)(r=s._soundById(t[a]))&&(r._volume=e,n[2]||s._stopFade(t[a]),s._webAudio&&r._node&&!r._muted?r._node.gain.setValueAtTime(e,i.ctx.currentTime):r._node&&!r._muted&&(r._node.volume=e*i.volume()),s._emit("volume",r._id));return s},fade:function(e,t,r,s){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"fade",action:function(){n.fade(e,t,r,s)}}),n;e=Math.min(Math.max(0,parseFloat(e)),1),t=Math.min(Math.max(0,parseFloat(t)),1),r=parseFloat(r),n.volume(e,s);for(var a=n._getSoundIds(s),l=0;l<a.length;l++){var o=n._soundById(a[l]);if(o){if(s||n._stopFade(a[l]),n._webAudio&&!o._muted){var d=i.ctx.currentTime,c=d+r/1e3;o._volume=e,o._node.gain.setValueAtTime(e,d),o._node.gain.linearRampToValueAtTime(t,c)}n._startFadeInterval(o,e,t,r,a[l],void 0===s)}}return n},_startFadeInterval:function(e,t,r,i,s,n){var a=this,l=t,o=r-t,d=Math.abs(o/.01),c=Math.max(4,d>0?i/d:i),u=Date.now();e._fadeTo=r,e._interval=setInterval(function(){var s=(Date.now()-u)/i;u=Date.now(),l+=o*s,l=Math.round(100*l)/100,l=o<0?Math.max(r,l):Math.min(r,l),a._webAudio?e._volume=l:a.volume(l,e._id,!0),n&&(a._volume=l),(r<t&&l<=r||r>t&&l>=r)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(r,e._id),a._emit("fade",e._id))},c)},_stopFade:function(e){var t=this._soundById(e);return t&&t._interval&&(this._webAudio&&t._node.gain.cancelScheduledValues(i.ctx.currentTime),clearInterval(t._interval),t._interval=null,this.volume(t._fadeTo,e),t._fadeTo=null,this._emit("fade",e)),this},loop:function(){var e,t,r,i=arguments;if(0===i.length)return this._loop;if(1===i.length)if("boolean"!=typeof i[0])return!!(r=this._soundById(parseInt(i[0],10)))&&r._loop;else e=i[0],this._loop=e;else 2===i.length&&(e=i[0],t=parseInt(i[1],10));for(var s=this._getSoundIds(t),n=0;n<s.length;n++)(r=this._soundById(s[n]))&&(r._loop=e,this._webAudio&&r._node&&r._node.bufferSource&&(r._node.bufferSource.loop=e,e&&(r._node.bufferSource.loopStart=r._start||0,r._node.bufferSource.loopEnd=r._stop,this.playing(s[n])&&(this.pause(s[n],!0),this.play(s[n],!0)))));return this},rate:function(){var e,t,r,s=this,n=arguments;if(0===n.length?t=s._sounds[0]._id:1===n.length?s._getSoundIds().indexOf(n[0])>=0?t=parseInt(n[0],10):e=parseFloat(n[0]):2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10)),"number"!=typeof e)return(r=s._soundById(t))?r._rate:s._rate;if("loaded"!==s._state||s._playLock)return s._queue.push({event:"rate",action:function(){s.rate.apply(s,n)}}),s;void 0===t&&(s._rate=e),t=s._getSoundIds(t);for(var a=0;a<t.length;a++)if(r=s._soundById(t[a])){s.playing(t[a])&&(r._rateSeek=s.seek(t[a]),r._playStart=s._webAudio?i.ctx.currentTime:r._playStart),r._rate=e,s._webAudio&&r._node&&r._node.bufferSource?r._node.bufferSource.playbackRate.setValueAtTime(e,i.ctx.currentTime):r._node&&(r._node.playbackRate=e);var l=s.seek(t[a]),o=1e3*((s._sprite[r._sprite][0]+s._sprite[r._sprite][1])/1e3-l)/Math.abs(r._rate);(s._endTimers[t[a]]||!r._paused)&&(s._clearTimer(t[a]),s._endTimers[t[a]]=setTimeout(s._ended.bind(s,r),o)),s._emit("rate",r._id)}return s},seek:function(){var e,t,r=this,s=arguments;if(0===s.length?r._sounds.length&&(t=r._sounds[0]._id):1===s.length?r._getSoundIds().indexOf(s[0])>=0?t=parseInt(s[0],10):r._sounds.length&&(t=r._sounds[0]._id,e=parseFloat(s[0])):2===s.length&&(e=parseFloat(s[0]),t=parseInt(s[1],10)),void 0===t)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,s)}}),r;var n=r._soundById(t);if(n)if("number"==typeof e&&e>=0){var a=r.playing(t);a&&r.pause(t,!0),n._seek=e,n._ended=!1,r._clearTimer(t),r._webAudio||!n._node||isNaN(n._node.duration)||(n._node.currentTime=e);
1var l=function(){a&&r.play(t,!0),r._emit("seek",t)};if(a&&!r._webAudio){var o=function(){r._playLock?setTimeout(o,0):l()};setTimeout(o,0)}else l()}else{if(!r._webAudio)return n._node.currentTime;var d=r.playing(t)?i.ctx.currentTime-n._playStart:0,c=n._rateSeek?n._rateSeek-n._seek:0;return n._seek+(c+d*Math.abs(n._rate))}return r},playing:function(e){if("number"==typeof e){var t=this._soundById(e);return!!t&&!t._paused}for(var r=0;r<this._sounds.length;r++)if(!this._sounds[r]._paused)return!0;return!1},duration:function(e){var t=this._duration,r=this._soundById(e);return r&&(t=this._sprite[r._sprite][1]/1e3),t},state:function(){return this._state},unload:function(){for(var e=this,t=e._sounds,r=0;r<t.length;r++)t[r]._paused||e.stop(t[r]._id),e._webAudio||(e._clearSound(t[r]._node),t[r]._node.removeEventListener("error",t[r]._errorFn,!1),t[r]._node.removeEventListener(i._canPlayEvent,t[r]._loadFn,!1),t[r]._node.removeEventListener("ended",t[r]._endFn,!1),i._releaseHtml5Audio(t[r]._node)),delete t[r]._node,e._clearTimer(t[r]._id);var s=i._howls.indexOf(e);s>=0&&i._howls.splice(s,1);var n=!0;for(r=0;r<i._howls.length;r++)if(i._howls[r]._src===e._src||e._src.indexOf(i._howls[r]._src)>=0){n=!1;break}return a&&n&&delete a[e._src],i.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,r,i){var s=this["_on"+e];return"function"==typeof t&&s.push(i?{id:r,fn:t,once:i}:{id:r,fn:t}),this},off:function(e,t,r){var i=this["_on"+e],s=0;if("number"==typeof t&&(r=t,t=null),t||r)for(s=0;s<i.length;s++){var n=r===i[s].id;if(t===i[s].fn&&n||!t&&n){i.splice(s,1);break}}else if(e)this["_on"+e]=[];else{var a=Object.keys(this);for(s=0;s<a.length;s++)0===a[s].indexOf("_on")&&Array.isArray(this[a[s]])&&(this[a[s]]=[])}return this},once:function(e,t,r){return this.on(e,t,r,1),this},_emit:function(e,t,r){for(var i=this["_on"+e],s=i.length-1;s>=0;s--)(!i[s].id||i[s].id===t||"load"===e)&&(setTimeout((function(e){e.call(this,t,r)}).bind(this,i[s].fn),0),i[s].once&&this.off(e,i[s].fn,i[s].id));return this._loadQueue(e),this},_loadQueue:function(e){if(this._queue.length>0){var t=this._queue[0];t.event===e&&(this._queue.shift(),this._loadQueue()),e||t.action()}return this},_ended:function(e){var t=e._sprite;if(!this._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime<e._stop)return setTimeout(this._ended.bind(this,e),100),this;var r=!!(e._loop||this._sprite[t][2]);if(this._emit("end",e._id),!this._webAudio&&r&&this.stop(e._id,!0).play(e._id),this._webAudio&&r){this._emit("play",e._id),e._seek=e._start||0,e._rateSeek=0,e._playStart=i.ctx.currentTime;var s=(e._stop-e._start)*1e3/Math.abs(e._rate);this._endTimers[e._id]=setTimeout(this._ended.bind(this,e),s)}return this._webAudio&&!r&&(e._paused=!0,e._ended=!0,e._seek=e._start||0,e._rateSeek=0,this._clearTimer(e._id),this._cleanBuffer(e._node),i._autoSuspend()),this._webAudio||r||this.stop(e._id,!0),this},_clearTimer:function(e){if(this._endTimers[e]){if("function"!=typeof this._endTimers[e])clearTimeout(this._endTimers[e]);else{var t=this._soundById(e);t&&t._node&&t._node.removeEventListener("ended",this._endTimers[e],!1)}delete this._endTimers[e]}return this},_soundById:function(e){for(var t=0;t<this._sounds.length;t++)if(e===this._sounds[t]._id)return this._sounds[t];return null},_inactiveSound:function(){this._drain();for(var e=0;e<this._sounds.length;e++)if(this._sounds[e]._ended)return this._sounds[e].reset();return new n(this)},_drain:function(){var e=this._pool,t=0,r=0;if(!(this._sounds.length<e)){for(r=0;r<this._sounds.length;r++)this._sounds[r]._ended&&t++;for(r=this._sounds.length-1;r>=0;r--){if(t<=e)return;this._sounds[r]._ended&&(this._webAudio&&this._sounds[r]._node&&this._sounds[r]._node.disconnect(0),this._sounds.splice(r,1),t--)}}},_getSoundIds:function(e){if(void 0!==e)return[e];for(var t=[],r=0;r<this._sounds.length;r++)t.push(this._sounds[r]._id);return t},_refreshBuffer:function(e){return e._node.bufferSource=i.ctx.createBufferSource(),e._node.bufferSource.buffer=a[this._src],e._panner?e._node.bufferSource.connect(e._panner):e._node.bufferSource.connect(e._node),e._node.bufferSource.loop=e._loop,e._loop&&(e._node.bufferSource.loopStart=e._start||0,e._node.bufferSource.loopEnd=e._stop||0),e._node.bufferSource.playbackRate.setValueAtTime(e._rate,i.ctx.currentTime),this},_cleanBuffer:function(e){var t=i._navigator&&i._navigator.vendor.indexOf("Apple")>=0;if(!e.bufferSource)return this;if(i._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=i._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(i._navigator&&i._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var n=function(e){this._parent=e,this.init()};n.prototype={init:function(){var e=this._parent;return this._muted=e._muted,this._loop=e._loop,this._volume=e._volume,this._rate=e._rate,this._seek=0,this._paused=!0,this._ended=!0,this._sprite="__default",this._id=++i._counter,e._sounds.push(this),this.create(),this},create:function(){var e=this._parent,t=i._muted||this._muted||this._parent._muted?0:this._volume;return e._webAudio?(this._node=void 0===i.ctx.createGain?i.ctx.createGainNode():i.ctx.createGain(),this._node.gain.setValueAtTime(t,i.ctx.currentTime),this._node.paused=!0,this._node.connect(i.masterGain)):i.noAudio||(this._node=i._obtainHtml5Audio(),this._errorFn=this._errorListener.bind(this),this._node.addEventListener("error",this._errorFn,!1),this._loadFn=this._loadListener.bind(this),this._node.addEventListener(i._canPlayEvent,this._loadFn,!1),this._endFn=this._endListener.bind(this),this._node.addEventListener("ended",this._endFn,!1),this._node.src=e._src,this._node.preload=!0===e._preload?"auto":e._preload,this._node.volume=t*i.volume(),this._node.load()),this},reset:function(){var e=this._parent;return this._muted=e._muted,this._loop=e._loop,this._volume=e._volume,this._rate=e._rate,this._seek=0,this._rateSeek=0,this._paused=!0,this._ended=!0,this._sprite="__default",this._id=++i._counter,this},_errorListener:function(){this._parent._emit("loaderror",this._id,this._node.error?this._node.error.code:0),this._node.removeEventListener("error",this._errorFn,!1)},_loadListener:function(){var e=this._parent;e._duration=Math.ceil(10*this._node.duration)/10,0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue()),this._node.removeEventListener(i._canPlayEvent,this._loadFn,!1)},_endListener:function(){var e=this._parent;e._duration===1/0&&(e._duration=Math.ceil(10*this._node.duration)/10,e._sprite.__default[1]===1/0&&(e._sprite.__default[1]=1e3*e._duration),e._ended(this)),this._node.removeEventListener("ended",this._endFn,!1)}};var a={},l=function(e){var t=e._src;if(a[t]){e._duration=a[t].duration,c(e);return}if(/^data:[^;]+;base64,/.test(t)){for(var r=atob(t.split(",")[1]),i=new Uint8Array(r.length),s=0;s<r.length;++s)i[s]=r.charCodeAt(s);d(i.buffer,e)}else{var n=new XMLHttpRequest;n.open(e._xhr.method,t,!0),n.withCredentials=e._xhr.withCredentials,n.responseType="arraybuffer",e._xhr.headers&&Object.keys(e._xhr.headers).forEac
1h(function(t){n.setRequestHeader(t,e._xhr.headers[t])}),n.onload=function(){var t=(n.status+"")[0];"0"!==t&&"2"!==t&&"3"!==t?e._emit("loaderror",null,"Failed loading audio file with status: "+n.status+"."):d(n.response,e)},n.onerror=function(){e._webAudio&&(e._html5=!0,e._webAudio=!1,e._sounds=[],delete a[t],e.load())},o(n)}},o=function(e){try{e.send()}catch(t){e.onerror()}},d=function(e,t){var r=function(){t._emit("loaderror",null,"Decoding audio data failed.")},s=function(e){e&&t._sounds.length>0?(a[t._src]=e,c(t,e)):r()};"u">typeof Promise&&1===i.ctx.decodeAudioData.length?i.ctx.decodeAudioData(e).then(s).catch(r):i.ctx.decodeAudioData(e,s,r)},c=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},u=function(){if(i.usingWebAudio){try{"u">typeof AudioContext?i.ctx=new AudioContext:"u">typeof webkitAudioContext?i.ctx=new webkitAudioContext:i.usingWebAudio=!1}catch(e){i.usingWebAudio=!1}i.ctx||(i.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(i._navigator&&i._navigator.platform),t=i._navigator&&i._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=t?parseInt(t[1],10):null;if(e&&r&&r<9){var s=/safari/.test(i._navigator&&i._navigator.userAgent.toLowerCase());i._navigator&&!s&&(i.usingWebAudio=!1)}i.usingWebAudio&&(i.masterGain=void 0===i.ctx.createGain?i.ctx.createGainNode():i.ctx.createGain(),i.masterGain.gain.setValueAtTime(i._muted?0:i._volume,i.ctx.currentTime),i.masterGain.connect(i.ctx.destination)),i._setup()}};"function"==typeof define&&define.amd&&e.v({Howler:i,Howl:s}),r.Howler=i,r.Howl=s,e.g.HowlerGlobal=t,e.g.Howler=i,e.g.Howl=s,e.g.Sound=n}(),function(){"use strict";HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(e){if(!this.ctx||!this.ctx.listener)return this;for(var t=this._howls.length-1;t>=0;t--)this._howls[t].stereo(e);return this},HowlerGlobal.prototype.pos=function(e,t,r){return this.ctx&&this.ctx.listener?(t="number"!=typeof t?this._pos[1]:t,r="number"!=typeof r?this._pos[2]:r,"number"!=typeof e)?this._pos:(this._pos=[e,t,r],void 0!==this.ctx.listener.positionX?(this.ctx.listener.positionX.setTargetAtTime(this._pos[0],Howler.ctx.currentTime,.1),this.ctx.listener.positionY.setTargetAtTime(this._pos[1],Howler.ctx.currentTime,.1),this.ctx.listener.positionZ.setTargetAtTime(this._pos[2],Howler.ctx.currentTime,.1)):this.ctx.listener.setPosition(this._pos[0],this._pos[1],this._pos[2]),this):this},HowlerGlobal.prototype.orientation=function(e,t,r,i,s,n){if(!this.ctx||!this.ctx.listener)return this;var a=this._orientation;return(t="number"!=typeof t?a[1]:t,r="number"!=typeof r?a[2]:r,i="number"!=typeof i?a[3]:i,s="number"!=typeof s?a[4]:s,n="number"!=typeof n?a[5]:n,"number"!=typeof e)?a:(this._orientation=[e,t,r,i,s,n],void 0!==this.ctx.listener.forwardX?(this.ctx.listener.forwardX.setTargetAtTime(e,Howler.ctx.currentTime,.1),this.ctx.listener.forwardY.setTargetAtTime(t,Howler.ctx.currentTime,.1),this.ctx.listener.forwardZ.setTargetAtTime(r,Howler.ctx.currentTime,.1),this.ctx.listener.upX.setTargetAtTime(i,Howler.ctx.currentTime,.1),this.ctx.listener.upY.setTargetAtTime(s,Howler.ctx.currentTime,.1),this.ctx.listener.upZ.setTargetAtTime(n,Howler.ctx.currentTime,.1)):this.ctx.listener.setOrientation(e,t,r,i,s,n),this)},Howl.prototype.init=(e=Howl.prototype.init,function(t){return this._orientation=t.orientation||[1,0,0],this._stereo=t.stereo||null,this._pos=t.pos||null,this._pannerAttr={coneInnerAngle:void 0!==t.coneInnerAngle?t.coneInnerAngle:360,coneOuterAngle:void 0!==t.coneOuterAngle?t.coneOuterAngle:360,coneOuterGain:void 0!==t.coneOuterGain?t.coneOuterGain:0,distanceModel:void 0!==t.distanceModel?t.distanceModel:"inverse",maxDistance:void 0!==t.maxDistance?t.maxDistance:1e4,panningModel:void 0!==t.panningModel?t.panningModel:"HRTF",refDistance:void 0!==t.refDistance?t.refDistance:1,rolloffFactor:void 0!==t.rolloffFactor?t.rolloffFactor:1},this._onstereo=t.onstereo?[{fn:t.onstereo}]:[],this._onpos=t.onpos?[{fn:t.onpos}]:[],this._onorientation=t.onorientation?[{fn:t.onorientation}]:[],e.call(this,t)}),Howl.prototype.stereo=function(e,t){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,t)}}),r;var s=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===t)if("number"!=typeof e)return r._stereo;else r._stereo=e,r._pos=[e,0,0];for(var n=r._getSoundIds(t),a=0;a<n.length;a++){var l=r._soundById(n[a]);if(l)if("number"!=typeof e)return l._stereo;else l._stereo=e,l._pos=[e,0,0],l._node&&(l._pannerAttr.panningModel="equalpower",l._panner&&l._panner.pan||i(l,s),"spatial"===s?void 0!==l._panner.positionX?(l._panner.positionX.setValueAtTime(e,Howler.ctx.currentTime),l._panner.positionY.setValueAtTime(0,Howler.ctx.currentTime),l._panner.positionZ.setValueAtTime(0,Howler.ctx.currentTime)):l._panner.setPosition(e,0,0):l._panner.pan.setValueAtTime(e,Howler.ctx.currentTime)),r._emit
1("stereo",l._id)}return r},Howl.prototype.pos=function(e,t,r,s){var n=this;if(!n._webAudio)return n;if("loaded"!==n._state)return n._queue.push({event:"pos",action:function(){n.pos(e,t,r,s)}}),n;if(t="number"!=typeof t?0:t,r="number"!=typeof r?-.5:r,void 0===s)if("number"!=typeof e)return n._pos;else n._pos=[e,t,r];for(var a=n._getSoundIds(s),l=0;l<a.length;l++){var o=n._soundById(a[l]);if(o)if("number"!=typeof e)return o._pos;else o._pos=[e,t,r],o._node&&((!o._panner||o._panner.pan)&&i(o,"spatial"),void 0!==o._panner.positionX?(o._panner.positionX.setValueAtTime(e,Howler.ctx.currentTime),o._panner.positionY.setValueAtTime(t,Howler.ctx.currentTime),o._panner.positionZ.setValueAtTime(r,Howler.ctx.currentTime)):o._panner.setPosition(e,t,r)),n._emit("pos",o._id)}return n},Howl.prototype.orientation=function(e,t,r,s){var n=this;if(!n._webAudio)return n;if("loaded"!==n._state)return n._queue.push({event:"orientation",action:function(){n.orientation(e,t,r,s)}}),n;if(t="number"!=typeof t?n._orientation[1]:t,r="number"!=typeof r?n._orientation[2]:r,void 0===s)if("number"!=typeof e)return n._orientation;else n._orientation=[e,t,r];for(var a=n._getSoundIds(s),l=0;l<a.length;l++){var o=n._soundById(a[l]);if(o)if("number"!=typeof e)return o._orientation;else o._orientation=[e,t,r],o._node&&(o._panner||(o._pos||(o._pos=n._pos||[0,0,-.5]),i(o,"spatial")),void 0!==o._panner.orientationX?(o._panner.orientationX.setValueAtTime(e,Howler.ctx.currentTime),o._panner.orientationY.setValueAtTime(t,Howler.ctx.currentTime),o._panner.orientationZ.setValueAtTime(r,Howler.ctx.currentTime)):o._panner.setOrientation(e,t,r)),n._emit("orientation",o._id)}return n},Howl.prototype.pannerAttr=function(){var e,t,r,s=arguments;if(!this._webAudio)return this;if(0===s.length)return this._pannerAttr;if(1===s.length)if("object"!=typeof s[0])return(r=this._soundById(parseInt(s[0],10)))?r._pannerAttr:this._pannerAttr;else e=s[0],void 0===t&&(e.pannerAttr||(e.pannerAttr={coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor,panningModel:e.panningModel}),this._pannerAttr={coneInnerAngle:void 0!==e.pannerAttr.coneInnerAngle?e.pannerAttr.coneInnerAngle:this._coneInnerAngle,coneOuterAngle:void 0!==e.pannerAttr.coneOuterAngle?e.pannerAttr.coneOuterAngle:this._coneOuterAngle,coneOuterGain:void 0!==e.pannerAttr.coneOuterGain?e.pannerAttr.coneOuterGain:this._coneOuterGain,distanceModel:void 0!==e.pannerAttr.distanceModel?e.pannerAttr.distanceModel:this._distanceModel,maxDistance:void 0!==e.pannerAttr.maxDistance?e.pannerAttr.maxDistance:this._maxDistance,refDistance:void 0!==e.pannerAttr.refDistance?e.pannerAttr.refDistance:this._refDistance,rolloffFactor:void 0!==e.pannerAttr.rolloffFactor?e.pannerAttr.rolloffFactor:this._rolloffFactor,panningModel:void 0!==e.pannerAttr.panningModel?e.pannerAttr.panningModel:this._panningModel});else 2===s.length&&(e=s[0],t=parseInt(s[1],10));for(var n=this._getSoundIds(t),a=0;a<n.length;a++)if(r=this._soundById(n[a])){var l=r._pannerAttr;l={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:l.coneInnerAngle,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:l.coneOuterAngle,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:l.coneOuterGain,distanceModel:void 0!==e.distanceModel?e.distanceModel:l.distanceModel,maxDistance:void 0!==e.maxDistance?e.maxDistance:l.maxDistance,refDistance:void 0!==e.refDistance?e.refDistance:l.refDistance,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:l.rolloffFactor,panningModel:void 0!==e.panningModel?e.panningModel:l.panningModel};var o=r._panner;o||(r._pos||(r._pos=this._pos||[0,0,-.5]),i(r,"spatial"),o=r._panner),o.coneInnerAngle=l.coneInnerAngle,o.coneOuterAngle=l.coneOuterAngle,o.coneOuterGain=l.coneOuterGain,o.distanceModel=l.distanceModel,o.maxDistance=l.maxDistance,o.refDistance=l.refDistance,o.rolloffFactor=l.rolloffFactor,o.panningModel=l.panningModel}return this},Sound.prototype.init=(t=Sound.prototype.init,function(){var e=this._parent;this._orientation=e._orientation,this._stereo=e._stereo,this._pos=e._pos,this._pannerAttr=e._pannerAttr,t.call(this),this._stereo?e.stereo(this._stereo):this._pos&&e.pos(this._pos[0],this._pos[1],this._pos[2],this._id)}),Sound.prototype.reset=(r=Sound.prototype.reset,function(){var e=this._parent;return this._orientation=e._orientation,this._stereo=e._stereo,this._pos=e._pos,this._pannerAttr=e._pannerAttr,this._stereo?e.stereo(this._stereo):this._pos?e.pos(this._pos[0],this._pos[1],this._pos[2],this._id):this._panner&&(this._panner.disconnect(0),this._panner=void 0,e._refreshBuffer(this)),r.call(this)});var e,t,r,i=function(e,t){"spatial"===(t=t||"spatial")?(e._panner=Howler.ctx.createPanner(),e._panner.coneInnerAngle=e._pannerAttr.coneInnerAngle,e._panner.coneOuterAngle=e._pannerAttr.coneOuterAngle,e._panner.coneOuterGain=e._pannerAttr.coneOuterGain,e._panner.distanceModel=e._pannerAttr.distanceModel,e._panner.maxDistance=e._pannerAttr.maxDistance,e._panner.refDistance=e._pannerAttr.refDistance,e._panner.rolloffFactor=e._pannerAttr.rolloffFactor,e._panner.panningModel=e._pannerAttr.panningModel,void 0!==e._panner.positionX?(e._panner.positionX.setValueAtTime(e._pos[0],Howler.ctx.currentTime),e._panner.positionY.setValueAtTime(e._pos[1],Howler.ctx.currentTime),e._panner.positionZ.setValueAtTime(e._pos[2],Howler.ctx.currentTime)):e._panner.setPosition(e._pos[0],e._pos[1],e._pos[2]),void 0!==e._panner.orientationX?(e._panner.orientationX.setValueAtTime(e._orientation[0],Howler.ctx.currentTime),e._panner.orientationY.setValueAtTime(e._orientation[1],Howler.ctx.currentTime),e._panner.orientationZ.setValueAtTime(e._orientation[2],Howler.ctx.currentTime)):e._panner.setOrientation(e._orientation[0],e._orientation[1],e._orientation[2])):(e._panner=Howler.ctx.createStereoPanner(),e._panner.pan.setValueAtTime(e._stereo,Howler.ctx.currentTime)),e._panner.connect(e._node),e._paused||e._parent.pause(e._id,!0).play(e._id,!0)}}()},762745,e=>{"use strict";var t=e.i(875174);let r="imperial_sound_enabled";function i(){return"false"!==localStorage.getItem(r)}let s="u">typeof navigator&&/iPad|iPhone|iPod/.test(navigator.userAgent);function n(e,r){return new t.Howl({src:[e],volume:r,html5:s,preload:!0})}let a=null;function l(){return a||(a={orderSubmitted:n("/sounds/order-submitted.wav",.5),orderFilled:n("/sounds/order-filled.wav",.5),orderError:n("/sounds/order-error.wav",.4),positionClosed:n("/sounds/position-closed.wav",.5),orderCancelled:n("/sounds/order-cancelled.wav",.4)}),a}l(),e.s(["isSoundEnabled",0,i,"playSound",0,function(e){if(i())try{l()[e].play()}catch{}},"setSoundEnabled",0,function(e){localStorage.setItem(r,String(e))}])},463547,e=>{"use strict";function t(e){var t=e.width,r=e.height;if(t<0)throw Error("Negative width is not allowed for Size");if(r<0)throw Error("Negative height is not allowed for Size");return{width:t,height:r}}function r(e,t){return e.width===t.width&&e.height===t.height}var i,s,n,a,l,o,d,c,u,h,p,m,f,x,g,b,v,y,w,j,S=function(){function e(e){var t=this;this._resolutionListener=function(){return t._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=e,this._installResolutionListener()}return e.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(e.prototype,"value",{get:function(){return this._window.devicePixelRatio}
1,enumerable:!1,configurable:!0}),e.prototype.subscribe=function(e){var t=this,r={next:e};return this._observers.push(r),{unsubscribe:function(){t._observers=t._observers.filter(function(e){return e!==r})}}},e.prototype._installResolutionListener=function(){if(null!==this._resolutionMediaQueryList)throw Error("Resolution listener is already installed");var e=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(e,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},e.prototype._uninstallResolutionListener=function(){null!==this._resolutionMediaQueryList&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},e.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},e.prototype._onResolutionChanged=function(){var e=this;this._observers.forEach(function(t){return t.next(e._window.devicePixelRatio)}),this._reinstallResolutionListener()},e}(),k=function(){function e(e,r,i){var s;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=e,this._canvasElementClientSize=t({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=null!=r?r:function(e){return e},this._allowResizeObserver=null==(s=null==i?void 0:i.allowResizeObserver)||s,this._chooseAndInitObserver()}return e.prototype.dispose=function(){var e,t;if(null===this._canvasElement)throw Error("Object is disposed");null==(e=this._canvasElementResizeObserver)||e.disconnect(),this._canvasElementResizeObserver=null,null==(t=this._devicePixelRatioObservable)||t.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(e.prototype,"canvasElement",{get:function(){if(null===this._canvasElement)throw Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bitmapSize",{get:function(){return t({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),e.prototype.resizeCanvasElement=function(e){this._canvasElementClientSize=t(e),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},e.prototype.subscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners.push(e)},e.prototype.unsubscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter(function(t){return t!==e})},Object.defineProperty(e.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),e.prototype.subscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners.push(e)},e.prototype.unsubscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter(function(t){return t!==e})},e.prototype.applySuggestedBitmapSize=function(){if(null!==this._suggestedBitmapSize){var e=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(e),this._emitSuggestedBitmapSizeChanged(e,this._suggestedBitmapSize)}},e.prototype._resizeBitmap=function(e){var t=this.bitmapSize;r(t,e)||(this.canvasElement.width=e.width,this.canvasElement.height=e.height,this._emitBitmapSizeChanged(t,e))},e.prototype._emitBitmapSizeChanged=function(e,t){var r=this;this._bitmapSizeChangedListeners.forEach(function(i){return i.call(r,e,t)})},e.prototype._suggestNewBitmapSize=function(e){var i=this._suggestedBitmapSize,s=t(this._transformBitmapSize(e,this._canvasElementClientSize)),n=r(this.bitmapSize,s)?null:s;null===i&&null===n||null!==i&&null!==n&&r(i,n)||(this._suggestedBitmapSize=n,this._emitSuggestedBitmapSizeChanged(i,n))},e.prototype._emitSuggestedBitmapSizeChanged=function(e,t){var r=this;
1this._suggestedBitmapSizeChangedListeners.forEach(function(i){return i.call(r,e,t)})},e.prototype._chooseAndInitObserver=function(){var e=this;this._allowResizeObserver?new Promise(function(e){var t=new ResizeObserver(function(r){e(r.every(function(e){return"devicePixelContentBoxSize"in e})),t.disconnect()});t.observe(document.body,{box:"device-pixel-content-box"})}).catch(function(){return!1}).then(function(t){return t?e._initResizeObserver():e._initDevicePixelRatioObservable()}):this._initDevicePixelRatioObservable()},e.prototype._initDevicePixelRatioObservable=function(){var e=this;if(null!==this._canvasElement){var t=N(this._canvasElement);if(null===t)throw Error("No window is associated with the canvas");this._devicePixelRatioObservable=new S(t),this._devicePixelRatioObservable.subscribe(function(){return e._invalidateBitmapSize()}),this._invalidateBitmapSize()}},e.prototype._invalidateBitmapSize=function(){if(null!==this._canvasElement){var e,r,i=N(this._canvasElement);if(null!==i){var s,n,a=null!=(r=null==(e=this._devicePixelRatioObservable)?void 0:e.value)?r:i.devicePixelRatio,l=this._canvasElement.getClientRects(),o=void 0!==l[0]?(s=l[0],n=a,t({width:Math.round(s.left*n+s.width*n)-Math.round(s.left*n),height:Math.round(s.top*n+s.height*n)-Math.round(s.top*n)})):t({width:this._canvasElementClientSize.width*a,height:this._canvasElementClientSize.height*a});this._suggestNewBitmapSize(o)}}},e.prototype._initResizeObserver=function(){var e=this;null!==this._canvasElement&&(this._canvasElementResizeObserver=new ResizeObserver(function(r){var i=r.find(function(t){return t.target===e._canvasElement});if(i&&i.devicePixelContentBoxSize&&i.devicePixelContentBoxSize[0]){var s=i.devicePixelContentBoxSize[0],n=t({width:s.inlineSize,height:s.blockSize});e._suggestNewBitmapSize(n)}}),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},e}();function N(e){return e.ownerDocument.defaultView}var P=function(){function e(e,t,r){if(0===t.width||0===t.height)throw TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=t,0===r.width||0===r.height)throw TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=r,this._context=e}return e.prototype.useMediaCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),e({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},e.prototype.useBitmapCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),e({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(e.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),e}();function T(e,t){var r=e.canvasElementClientSize;if(0===r.width||0===r.height)return null;var i=e.bitmapSize;if(0===i.width||0===i.height)return null;var s=e.canvasElement.getContext("2d",t);return null===s?null:new P(s,r,i)}let C={title:"",visible:!0,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};function M(e,t){let r={0:[],1:[e.lineWidth,e.lineWidth],2:[2*e.lineWidth,2*e.lineWidth],3:[6*e.lineWidth,6*e.lineWidth],4:[e.lineWidth,4*e.lineWidth]}[t];e.setLineDash(r)}function _(e,t,r,i){e.beginPath();let s=e.lineWidth%2?.5:0;e.moveTo(r,t+s),e.lineTo(i,t+s),e.stroke()}function A(e,t){if(!e)throw Error("Assertion failed"+(t?": "+t:""))}function E(e){if(void 0===e)throw Error("Value is undefined");return e}function L(e){if(null===e)throw Error("Value is null");return e}function F(e){return L(E(e))}(i=p||(p={}))[i.Simple=0]="Simple",i[i.WithSteps=1]="WithSteps",i[i.Curved=2]="Curved",(s=m||(m={}))[s.Solid=0]="Solid",s[s.Dotted=1]="Dotted",s[s.Dashed=2]="Dashed",s[s.LargeDashed=3]="LargeDashed",s[s.SparseDotted=4]="SparseDotted";class R{constructor(){this.t=[]}i(e,t,r){this.t.push({h:e,l:t,o:!0===r})}_(e){let t=this.t.findIndex(t=>e===t.h);t>-1&&this.t.splice(t,1)}u(e){this.t=this.t.filter(t=>t.l!==e)}p(e,t,r){let i=[...this.t];this.t=this.t.filter(e=>
1!e.o),i.forEach(i=>i.h(e,t,r))}v(){return this.t.length>0}m(){this.t=[]}}function D(e,...t){for(let r of t)for(let t in r)void 0!==r[t]&&Object.prototype.hasOwnProperty.call(r,t)&&!["__proto__","constructor","prototype"].includes(t)&&("object"!=typeof r[t]||void 0===e[t]||Array.isArray(r[t])?e[t]=r[t]:D(e[t],r[t]));return e}function I(e){return"number"==typeof e&&isFinite(e)}function U(e){return"number"==typeof e&&e%1==0}function O(e){return"string"==typeof e}function B(e){return"boolean"==typeof e}function z(e){let t,r,i;if(!e||"object"!=typeof e)return e;for(r in t=Array.isArray(e)?[]:{},e)e.hasOwnProperty(r)&&(i=e[r],t[r]=i&&"object"==typeof i?z(i):i);return t}function $(e){return null!==e}function V(e){return null===e?void 0:e}let H="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function W(e,t,r){return void 0===t&&(t=H),`${r=void 0!==r?`${r} `:""}${e}px ${t}`}class q{constructor(e){this.M={S:1,C:5,P:NaN,k:"",T:"",R:"",D:"",V:0,B:0,I:0,A:0,L:0},this.O=e}N(){let e=this.M,t=this.F(),r=this.W();return e.P===t&&e.T===r||(e.P=t,e.T=r,e.k=W(t,r),e.A=2.5/12*t,e.V=e.A,e.B=t/12*e.C,e.I=t/12*e.C,e.L=0),e.R=this.H(),e.D=this.U(),this.M}H(){return this.O.N().layout.textColor}U(){return this.O.$()}F(){return this.O.N().layout.fontSize}W(){return this.O.N().layout.fontFamily}}function K(e){return e<0?0:e>255?255:Math.round(e)||0}function G(e){return .199*e[0]+.687*e[1]+.114*e[2]}class Y{constructor(e,t){this.q=new Map,this.Y=e,t&&(this.q=t)}j(e,t){if("transparent"===e)return e;let r=this.K(e),i=r[3];return`rgba(${r[0]}, ${r[1]}, ${r[2]}, ${t*i})`}X(e){let t=this.K(e);return{Z:`rgb(${t[0]}, ${t[1]}, ${t[2]})`,G:G(t)>160?"black":"white"}}J(e){return G(this.K(e))}tt(e,t,r){var i;let[s,n,a,l]=this.K(e),[o,d,c,u]=this.K(t),h=[K(s+r*(o-s)),K(n+r*(d-n)),K(a+r*(c-a)),(i=l+r*(u-l))<=0||i>1?Math.min(Math.max(i,0),1):Math.round(1e4*i)/1e4];return`rgba(${h[0]}, ${h[1]}, ${h[2]}, ${h[3]})`}K(e){let t,r,i=this.q.get(e);if(i)return i;let s=((t=document.createElement("div")).style.display="none",document.body.appendChild(t),t.style.color=e,r=window.getComputedStyle(t).color,document.body.removeChild(t),r).match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)$/);if(!s){if(this.Y.length)for(let t of this.Y){let r=t(e);if(r)return this.q.set(e,r),r}throw Error(`Failed to parse color: ${e}`)}let n=[parseInt(s[1],10),parseInt(s[2],10),parseInt(s[3],10),s[4]?parseFloat(s[4]):1];return this.q.set(e,n),n}}class X{constructor(){this.it=[]}st(e){this.it=e}nt(e,t,r){this.it.forEach(i=>{i.nt(e,t,r)})}}class Q{nt(e,t,r){e.useBitmapCoordinateSpace(e=>this.et(e,t,r))}}class J extends Q{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:r}){if(null===this.rt||null===this.rt.lt)return;let i=this.rt.lt,s=this.rt,n=Math.max(1,Math.floor(t))%2/2,a=a=>{e.beginPath();for(let l=i.to-1;l>=i.from;--l){let i=s.ot[l],o=Math.round(i._t*t)+n,d=i.ut*r,c=a*r+n;e.moveTo(o,d),e.arc(o,d,c,0,2*Math.PI)}e.fill()};s.ct>0&&(e.fillStyle=s.dt,a(s.ft+s.ct)),e.fillStyle=s.vt,a(s.ft)}}function Z(){return{ot:[{_t:0,ut:0,wt:0,gt:0}],vt:"",dt:"",ft:0,ct:0,lt:null}}let ee={from:0,to:1};class et{constructor(e,t,r){this.Mt=new X,this.bt=[],this.St=[],this.xt=!0,this.O=e,this.Ct=t,this.Pt=r,this.Mt.st(this.bt)}yt(e){this.kt(),this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.Mt}kt(){let e=this.Pt.Dt();e.length!==this.bt.length&&(this.St=e.map(Z),this.bt=this.St.map(e=>{let t=new J;return t.ht(e),t}),this.Mt.st(this.bt))}Rt(){let e=2===this.Ct.N().mode||!this.Ct.Vt(),t=this.Pt.Bt(),r=this.Ct.It(),i=this.O.Et();this.kt(),t.forEach((t,s)=>{let n=this.St[s],a=t.At(r),l=t.zt();!e&&null!==a&&t.Vt()&&null!==l?(n.vt=a.Lt,n.ft=a.ft,n.ct=a.Ot,n.ot[0].gt=a.gt,n.ot[0].ut=t.Ft().Nt(a.gt,l.Wt),n.dt=a.Ht??this.O.Ut(n.ot[0].ut/t.Ft().$t()),n.ot[0].wt=r,n.ot[0]._t=i.qt(r),n.lt=ee):n.lt=null})}}class er extends Q{constructor(e){super(),this.Yt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:r,verticalPixelRatio:i}){var s;let n;if(null===this.Yt)return;let a=this.Yt.jt.Vt,l=this.Yt.Kt.Vt;if(!a&&!l)return;let o=Math.round(this.Yt._t*r),d=Math.round(this.Yt.ut*i);e.lineCap="butt",a&&o>=0&&(e.lineWidth=Math.floor(this.Yt.jt.ct*r),e.strokeStyle=this.Yt.jt.R,e.fillStyle=this.Yt.jt.R,M(e,this.Yt.jt.Xt),s=t.height,e.beginPath(),n=e.lineWidth%2?.5:0,e.moveTo(o+n,0),e.lineTo(o+n,s),e.stroke()),l&&d>=0&&(e.lineWidth=Math.floor(this.Yt.Kt.ct*i),e.strokeStyle=this.Yt.Kt.R,e.fillStyle=this.Yt.Kt.R,M(e,this.Yt.Kt.Xt),_(e,d,0,t.width))}}class ei{constructor(e,t){this.xt=!0,this.Zt={jt:{ct:1,Xt:0,R:"",Vt:!1},Kt:{ct:1,Xt:0,R:"",Vt:!1},_t:0,ut:0},this.Gt=new er(this.Zt),this.Jt=e,this.Pt=t}yt(){this.xt=!0}Tt(e){return this.xt&&(this.Rt(),this.xt=!1),this.Gt}Rt(){let e=this.Jt.Vt(),t=this.Pt.Qt().N().crosshair,r=this.Zt;2===t.mode?(r.Kt.Vt=!1,r.jt.Vt=!1):(r.Kt.Vt=e&&this.Jt.ti(this.Pt),r.jt.Vt=e&&this.Jt.ii(),r.Kt.ct=t.horzLine.width,r.Kt.Xt=t.horzLine.style,r.Kt.R=t.horzLine.color,r.jt.ct=t.vertLine.width,r.jt.Xt=t.vertLine.style,r.jt.R=t.vertLine.color,r._t=this.Jt.si(),r.ut=this.Jt.ni())}}function es(e,t,r,i,s,n){e.save(),e.globalCompositeOperation="copy",e.fillStyle=n,e.fillRect(t,r,i,s),e.restore(
1)}function en(e,t,r,i,s,n){e.beginPath(),e.roundRect?e.roundRect(t,r,i,s,n):(e.lineTo(t+i-n[1],r),0!==n[1]&&e.arcTo(t+i,r,t+i,r+n[1],n[1]),e.lineTo(t+i,r+s-n[2]),0!==n[2]&&e.arcTo(t+i,r+s,t+i-n[2],r+s,n[2]),e.lineTo(t+n[3],r+s),0!==n[3]&&e.arcTo(t,r+s,t,r+s-n[3],n[3]),e.lineTo(t,r+n[0]),0!==n[0]&&e.arcTo(t,r,t+n[0],r,n[0]))}function ea(e,t,r,i,s,n,a=0,l=[0,0,0,0],o=""){var d;if(e.save(),!a||!o||o===n)return en(e,t,r,i,s,l),e.fillStyle=n,e.fill(),void e.restore();let c=a/2;en(e,t+c,r+c,i-a,s-a,(d=-c,l.map(e=>0===e?e:e+d))),"transparent"!==n&&(e.fillStyle=n,e.fill()),"transparent"!==o&&(e.lineWidth=a,e.strokeStyle=o,e.closePath(),e.stroke()),e.restore()}function el(e,t,r,i,s,n,a){e.save(),e.globalCompositeOperation="copy";let l=e.createLinearGradient(0,0,0,s);l.addColorStop(0,n),l.addColorStop(1,a),e.fillStyle=l,e.fillRect(t,r,i,s),e.restore()}class eo{constructor(e,t){this.ht(e,t)}ht(e,t){this.Yt=e,this.ei=t}$t(e,t){return this.Yt.Vt?e.P+e.A+e.V:0}nt(e,t,r,i){if(!this.Yt.Vt||0===this.Yt.ri.length)return;let s=this.Yt.R,n=this.ei.Z,a=e.useBitmapCoordinateSpace(e=>{let a=e.context;a.font=t.k;let l=this.hi(e,t,r,i),o=l.ai;return l.li?ea(a,o.oi,o._i,o.ui,o.ci,n,o.di,[o.ft,0,0,o.ft],n):ea(a,o.fi,o._i,o.ui,o.ci,n,o.di,[0,o.ft,o.ft,0],n),this.Yt.pi&&(a.fillStyle=s,a.fillRect(o.fi,o.mi,o.wi-o.fi,o.gi)),this.Yt.Mi&&(a.fillStyle=t.D,a.fillRect(l.li?o.bi-o.di:0,o._i,o.di,o.Si-o._i)),l});e.useMediaCoordinateSpace(({context:e})=>{let r=a.xi;e.font=t.k,e.textAlign=a.li?"right":"left",e.textBaseline="middle",e.fillStyle=s,e.fillText(this.Yt.ri,r.Ci,(r._i+r.Si)/2+r.Pi)})}hi(e,t,r,i){let s,n,a,{context:l,bitmapSize:o,mediaSize:d,horizontalPixelRatio:c,verticalPixelRatio:u}=e,h=this.Yt.pi||!this.Yt.yi?t.C:0,p=this.Yt.ki?t.S:0,m=t.A+this.ei.Ti,f=t.V+this.ei.Ri,x=t.B,g=t.I,b=this.Yt.ri,v=t.P,y=r.Di(l,b),w=Math.ceil(r.Vi(l,b)),j=t.S+x+g+w+h,S=Math.max(1,Math.floor(u)),k=Math.round((v+m+f)*u);k%2!=S%2&&(k+=1);let N=p>0?Math.max(1,Math.floor(p*c)):0,P=Math.round(j*c),T=Math.round(h*c),C=Math.round((this.ei.Bi??this.ei.Ii)*u)-Math.floor(.5*u),M=Math.floor(C+S/2-k/2),_=M+k,A="right"===i,E=A?d.width-p:p,L=A?o.width-N:N;return A?(s=L-P,n=L-T,a=E-h-x-p):(s=L+P,n=L+T,a=E+h+x),{li:A,ai:{_i:M,mi:C,Si:_,ui:P,ci:k,ft:2*c,di:N,oi:s,fi:L,wi:n,gi:S,bi:o.width},xi:{_i:M/u,Si:_/u,Ci:a,Pi:y}}}}class ed{constructor(e){this.Ei={Ii:0,Z:"#000",Ri:0,Ti:0},this.Ai={ri:"",Vt:!1,pi:!0,yi:!1,Ht:"",R:"#FFF",Mi:!1,ki:!1},this.zi={ri:"",Vt:!1,pi:!1,yi:!0,Ht:"",R:"#FFF",Mi:!0,ki:!0},this.xt=!0,this.Li=new(e||eo)(this.Ai,this.Ei),this.Oi=new(e||eo)(this.zi,this.Ei)}ri(){return this.Ni(),this.Ai.ri}Ii(){return this.Ni(),this.Ei.Ii}yt(){this.xt=!0}$t(e,t=!1){return Math.max(this.Li.$t(e,t),this.Oi.$t(e,t))}Fi(){return this.Ei.Bi||0}Wi(e){this.Ei.Bi=e}Hi(){return this.Ni(),this.Ai.Vt||this.zi.Vt}Ui(){return this.Ni(),this.Ai.Vt}Tt(e){return this.Ni(),this.Ai.pi=this.Ai.pi&&e.N().ticksVisible,this.zi.pi=this.zi.pi&&e.N().ticksVisible,this.Li.ht(this.Ai,this.Ei),this.Oi.ht(this.zi,this.Ei),this.Li}$i(){return this.Ni(),this.Li.ht(this.Ai,this.Ei),this.Oi.ht(this.zi,this.Ei),this.Oi}Ni(){this.xt&&(this.Ai.pi=!0,this.zi.pi=!1,this.qi(this.Ai,this.zi,this.Ei))}}class ec extends ed{constructor(e,t,r){super(),this.Jt=e,this.Yi=t,this.ji=r}qi(e,t,r){if(e.Vt=!1,2===this.Jt.N().mode)return;let i=this.Jt.N().horzLine;if(!i.labelVisible)return;let s=this.Yi.zt();if(!this.Jt.Vt()||this.Yi.Ki()||null===s)return;let n=this.Yi.Xi().X(i.labelBackgroundColor);r.Z=n.Z,e.R=n.G;let a=2/12*this.Yi.P();r.Ti=a,r.Ri=a;let l=this.ji(this.Yi);r.Ii=l.Ii,e.ri=this.Yi.Zi(l.gt,s),e.Vt=!0}}let eu=/[1-9]/g;class eh{constructor(){this.Yt=null}ht(e){this.Yt=e}nt(e,t){if(null===this.Yt||!1===this.Yt.Vt||0===this.Yt.ri.length)return;let r=e.useMediaCoordinateSpace(({context:e})=>(e.font=t.k,Math.round(t.Gi.Vi(e,L(this.Yt).ri,eu))));if(r<=0)return;let i=t.Ji,s=r+2*i,n=s/2,a=this.Yt.Qi,l=this.Yt.Ii,o=Math.floor(l-n)+.5;o<0?(l+=Math.abs(0-o),o=Math.floor(l-n)+.5):o+s>a&&(l-=Math.abs(a-(o+s)),o=Math.floor(l-n)+.5);let d=o+s,c=Math.ceil(0+t.S+t.C+t.A+t.P+t.V);e.useBitmapCoordinateSpace(({context:e,horizontalPixelRatio:r,verticalPixelRatio:i})=>{let s=L(this.Yt);e.fillStyle=s.Z;let n=Math.round(o*r),a=Math.round(0*i),l=Math.round(d*r),u=Math.round(c*i),h=Math.round(2*r);if(e.beginPath(),e.moveTo(n,a),e.lineTo(n,u-h),e.arcTo(n,u,n+h,u,h),e.lineTo(l-h,u),e.arcTo(l,u,l,u-h,h),e.lineTo(l,a),e.fill(),s.pi){let n=Math.round(s.Ii*r),l=Math.round((a+t.C)*i);e.fillStyle=s.R;let o=Math.max(1,Math.floor(r)),d=Math.floor(.5*r);e.fillRect(n-d,a,o,l-a)}}),e.useMediaCoordinateSpace(({context:e})=>{let r=L(this.Yt),s=0+t.S+t.C+t.A+t.P/2;e.font=t.k,e.textAlign="left",e.textBaseline="middle",e.fillStyle=r.R;let n=t.Gi.Di(e,"Apr0");e.translate(o+i,s+n),e.fillText(r.ri,0,0)})}}class ep{constructor(e,t,r){this.xt=!0,this.Gt=new eh,this.Zt={Vt:!1,Z:"#4c525e",R:"white",ri:"",Qi:0,Ii:NaN,pi:!0},this.Ct=e,this.ts=t,this.ji=r}yt(){this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.Gt.ht(this.Zt),this.Gt}Rt(){let e=this.Zt;if(e.Vt=!1,2===this.Ct.N().mode)return;let t=this.Ct.N().vertLine;if(!t.labelVisible)return;let r=this.ts.Et();if(r.Ki())return;e.Qi=r.Qi();let i=this.ji();if(null===i)return;e.Ii=i.Ii;let s=r.ss(this.Ct.It());e.ri=r.ns(L(s)),e.Vt=!0;
1let n=this.ts.Xi().X(t.labelBackgroundColor);e.Z=n.Z,e.R=n.G,e.pi=r.N().ticksVisible}}class em{constructor(){this.es=null,this.rs=0}hs(){return this.rs}ls(e){this.rs=e}Ft(){return this.es}_s(e){this.es=e}us(e){return[]}cs(){return[]}Vt(){return!0}}(n=f||(f={}))[n.Normal=0]="Normal",n[n.Magnet=1]="Magnet",n[n.Hidden=2]="Hidden",n[n.MagnetOHLC=3]="MagnetOHLC";class ef extends em{constructor(e,t){let r,i,s,n;super(),this.Pt=null,this.ds=NaN,this.fs=0,this.ps=!1,this.vs=new Map,this.ws=!1,this.gs=new WeakMap,this.Ms=new WeakMap,this.bs=NaN,this.Ss=NaN,this.xs=NaN,this.Cs=NaN,this.ts=e,this.Ps=t,this.ys=(r=()=>this.ds,i=()=>this.Ss,e=>{let t=i(),s=r();if(e===L(this.Pt).ks())return{gt:s,Ii:t};{let r=L(e.zt());return{gt:e.Ts(t,r),Ii:t}}});const a=(s=()=>this.fs,n=()=>this.si(),()=>{let e=this.ts.Et().Rs(s()),t=n();return e&&Number.isFinite(t)?{wt:e,Ii:t}:null});this.Ds=new ep(this,e,a)}N(){return this.Ps}Vs(e,t){this.xs=e,this.Cs=t}Bs(){this.xs=NaN,this.Cs=NaN}Is(){return this.xs}Es(){return this.Cs}As(e,t,r){this.ws||(this.ws=!0),this.ps=!0,this.zs(e,t,r)}It(){return this.fs}si(){return this.bs}ni(){return this.Ss}Vt(){return this.ps}Ls(){this.ps=!1,this.Os(),this.ds=NaN,this.bs=NaN,this.Ss=NaN,this.Pt=null,this.Bs(),this.Ns()}Fs(e){let t=this.gs.get(e);t||(t=new ei(this,e),this.gs.set(e,t));let r=this.Ms.get(e);return r||(r=new et(this.ts,this,e),this.Ms.set(e,r)),[t,r]}ti(e){return e===this.Pt&&this.Ps.horzLine.visible}ii(){return this.Ps.vertLine.visible}Ws(e,t){this.ps&&this.Pt===e||this.vs.clear();let r=[];return this.Pt===e&&r.push(this.Hs(this.vs,t,this.ys)),r}cs(){return this.ps?[this.Ds]:[]}Us(){return this.Pt}Ns(){this.ts.$s().forEach(e=>{this.gs.get(e)?.yt(),this.Ms.get(e)?.yt()}),this.vs.forEach(e=>e.yt()),this.Ds.yt()}qs(e){return e&&!e.ks().Ki()?e.ks():null}zs(e,t,r){this.Ys(e,t,r)&&this.Ns()}Ys(e,t,r){let i=this.bs,s=this.Ss,n=this.ds,a=this.fs,l=this.Pt,o=this.qs(r);this.fs=e,this.bs=isNaN(e)?NaN:this.ts.Et().qt(e),this.Pt=r;let d=null!==o?o.zt():null;return null!==o&&null!==d?(this.ds=t,this.Ss=o.Nt(t,d)):(this.ds=NaN,this.Ss=NaN),i!==this.bs||s!==this.Ss||a!==this.fs||n!==this.ds||l!==this.Pt}Os(){let e=this.ts.js().map(e=>e.Xs().Ks()).filter($),t=0===e.length?null:Math.max(...e);this.fs=null!==t?t:NaN}Hs(e,t,r){let i=e.get(t);return void 0===i&&(i=new ec(this,t,r),e.set(t,i)),i}}function ex(e){return"left"===e||"right"===e}class eg{constructor(e){this.Zs=new Map,this.Gs=[],this.Js=e}Qs(e,t){var r;let i=(r=this.Zs.get(e),void 0===r?t:{tn:Math.max(r.tn,t.tn),sn:r.sn||t.sn});this.Zs.set(e,i)}nn(){return this.Js}en(e){let t=this.Zs.get(e);return void 0===t?{tn:this.Js}:{tn:Math.max(this.Js,t.tn),sn:t.sn}}rn(){this.hn(),this.Gs=[{an:0}]}ln(e){this.hn(),this.Gs=[{an:1,Wt:e}]}_n(e){this.un(),this.Gs.push({an:5,Wt:e})}hn(){this.un(),this.Gs.push({an:6})}cn(){this.hn(),this.Gs=[{an:4}]}dn(e){this.hn(),this.Gs.push({an:2,Wt:e})}fn(e){this.hn(),this.Gs.push({an:3,Wt:e})}pn(){return this.Gs}vn(e){for(let t of e.Gs)this.mn(t);this.Js=Math.max(this.Js,e.Js),e.Zs.forEach((e,t)=>{this.Qs(t,e)})}static wn(){return new eg(2)}static gn(){return new eg(3)}mn(e){switch(e.an){case 0:this.rn();break;case 1:this.ln(e.Wt);break;case 2:this.dn(e.Wt);break;case 3:this.fn(e.Wt);break;case 4:this.cn();break;case 5:this._n(e.Wt);break;case 6:this.un()}}un(){let e=this.Gs.findIndex(e=>5===e.an);-1!==e&&this.Gs.splice(e,1)}}class eb{formatTickmarks(e){return e.map(e=>this.format(e))}}function ev(e,t){if(!I(e))return"n/a";if(!U(t)||t<0||t>16)throw TypeError("invalid length");return 0===t?e.toString():("0000000000000000"+e.toString()).slice(-t)}class ey extends eb{constructor(e,t){if(super(),t||(t=1),I(e)&&U(e)||(e=100),e<0)throw TypeError("invalid base");this.Yi=e,this.Mn=t,this.bn()}format(e){let t=e<0?"−":"";return e=Math.abs(e),t+this.Sn(e)}bn(){if(this.xn=0,this.Yi>0&&this.Mn>0){let e=this.Yi;for(;e>1;)e/=10,this.xn++}}Sn(e){let t=this.Yi/this.Mn,r=Math.floor(e),i="",s=void 0!==this.xn?this.xn:NaN;if(t>1){let n=+(Math.round(e*t)-r*t).toFixed(this.xn);n>=t&&(n-=t,r+=1),i="."+ev(n.toFixed(this.xn)*this.Mn,s)}else r=Math.round(r*t)/t,s>0&&(i="."+ev(0,s));return r.toFixed(0)+i}}class ew extends ey{constructor(e=100){super(e)}format(e){return`${super.format(e)}%`}}class ej extends eb{constructor(e){super(),this.Cn=e}format(e){let t="";return e<0&&(t="-",e=-e),e<995?t+this.Pn(e):e<999995?t+this.Pn(e/1e3)+"K":e<0x3b9ac9fb?(e=1e3*Math.round(e/1e3),t+this.Pn(e/1e6)+"M"):(e=1e6*Math.round(e/1e6),t+this.Pn(e/1e9)+"B")}Pn(e){let t=Math.pow(10,this.Cn);return((e=Math.round(e*t)/t)>=1e-15&&e<1?e.toFixed(this.Cn).replace(/\.?0+$/,""):String(e)).replace(/(\.[1-9]*)0+$/,(e,t)=>t)}}let eS=/[2-9]/g;class ek{constructor(e=50){this.yn=0,this.kn=1,this.Tn=1,this.Rn={},this.Dn=new Map,this.Vn=e}Bn(){this.yn=0,this.Dn.clear(),this.kn=1,this.Tn=1,this.Rn={}}Vi(e,t,r){return this.In(e,t,r).width}Di(e,t,r){let i=this.In(e,t,r);return((i.actualBoundingBoxAscent||0)-(i.actualBoundingBoxDescent||0))/2}In(e,t,r){let i=String(t).replace(r||eS,"0");if(this.Dn.has(i))return E(this.Dn.get(i)).En;if(this.yn===this.Vn){let e=this.Rn[this.Tn];delete this.Rn[this.Tn],this.Dn.delete(e),this.Tn++,this.yn--}e.save(),e.textBaseline="middle";let s=e.measureText(i);
1return e.restore(),0===s.width&&t.length||(this.Dn.set(i,{En:s,An:this.kn}),this.Rn[this.kn]=i,this.yn++,this.kn++),s}}class eN{constructor(e){this.zn=null,this.M=null,this.Ln="right",this.On=e}Nn(e,t,r){this.zn=e,this.M=t,this.Ln=r}nt(e){null!==this.M&&null!==this.zn&&this.zn.nt(e,this.M,this.On,this.Ln)}}class eP{constructor(e,t,r){this.Fn=e,this.On=new ek(50),this.Wn=t,this.O=r,this.F=-1,this.Gt=new eN(this.On)}Tt(){let e=this.O.Hn(this.Wn);if(null===e)return null;let t=e.Un(this.Wn)?e.$n():this.Wn.Ft();if(null===t)return null;let r=e.qn(t);if("overlay"===r)return null;let i=this.O.Yn();return i.P!==this.F&&(this.F=i.P,this.On.Bn()),this.Gt.Nn(this.Fn.$i(),i,r),this.Gt}}class eT extends Q{constructor(){super(...arguments),this.Yt=null}ht(e){this.Yt=e}jn(e,t){if(!this.Yt?.Vt)return null;let{ut:r,ct:i,Kn:s}=this.Yt;return t>=r-i-7&&t<=r+i+7?{Xn:this.Yt,Kn:s}:null}et({context:e,bitmapSize:t,horizontalPixelRatio:r,verticalPixelRatio:i}){if(null===this.Yt||!1===this.Yt.Vt)return;let s=Math.round(this.Yt.ut*i);s<0||s>t.height||(e.lineCap="butt",e.strokeStyle=this.Yt.R,e.lineWidth=Math.floor(this.Yt.ct*r),M(e,this.Yt.Xt),_(e,s,0,t.width))}}class eC{constructor(e){this.Zn={ut:0,R:"rgba(0, 0, 0, 0)",ct:1,Xt:0,Vt:!1},this.Gn=new eT,this.xt=!0,this.Jn=e,this.Qn=e.Qt(),this.Gn.ht(this.Zn)}yt(){this.xt=!0}Tt(){return this.Jn.Vt()?(this.xt&&(this.te(),this.xt=!1),this.Gn):null}}class eM extends eC{constructor(e){super(e)}te(){this.Zn.Vt=!1;let e=this.Jn.Ft(),t=e.ie().ie;if(2!==t&&3!==t)return;let r=this.Jn.N();if(!r.baseLineVisible||!this.Jn.Vt())return;let i=this.Jn.zt();null!==i&&(this.Zn.Vt=!0,this.Zn.ut=e.Nt(i.Wt,i.Wt),this.Zn.R=r.baseLineColor,this.Zn.ct=r.baseLineWidth,this.Zn.Xt=r.baseLineStyle)}}class e_ extends Q{constructor(){super(...arguments),this.Yt=null}ht(e){this.Yt=e}se(){return this.Yt}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:r}){let i=this.Yt;if(null===i)return;let s=Math.max(1,Math.floor(t)),n=s%2/2,a=Math.round(i.ne.x*t)+n,l=i.ne.y*r;e.fillStyle=i.ee,e.beginPath();let o=Math.max(2,1.5*i.re)*t;e.arc(a,l,o,0,2*Math.PI,!1),e.fill(),e.fillStyle=i.he,e.beginPath(),e.arc(a,l,i.ft*t,0,2*Math.PI,!1),e.fill(),e.lineWidth=s,e.strokeStyle=i.ae,e.beginPath(),e.arc(a,l,i.ft*t+s/2,0,2*Math.PI,!1),e.stroke()}}let eA=[{le:0,oe:.25,_e:4,ue:10,ce:.25,de:0,fe:.4,pe:.8},{le:.25,oe:.525,_e:10,ue:14,ce:0,de:0,fe:.8,pe:0},{le:.525,oe:1,_e:14,ue:14,ce:0,de:0,fe:0,pe:0}];class eE{constructor(e){this.Gt=new e_,this.xt=!0,this.ve=!0,this.me=performance.now(),this.we=this.me-1,this.ge=e}Me(){this.we=this.me-1,this.yt()}be(){if(this.yt(),2===this.ge.N().lastPriceAnimation){let e=performance.now(),t=this.we-e;if(t>0)return void(t<650&&(this.we+=2600));this.me=e,this.we=e+2600}}yt(){this.xt=!0}Se(){this.ve=!0}Vt(){return 0!==this.ge.N().lastPriceAnimation}xe(){switch(this.ge.N().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.we}}Tt(){return this.xt?(this.Rt(),this.xt=!1,this.ve=!1):this.ve&&(this.Ce(),this.ve=!1),this.Gt}Rt(){this.Gt.ht(null);let e=this.ge.Qt().Et(),t=e.Pe(),r=this.ge.zt();if(null===t||null===r)return;let i=this.ge.ye(!0);if(i.ke||!t.Te(i.Re))return;let s={x:e.qt(i.Re),y:this.ge.Ft().Nt(i.gt,r.Wt)},n=i.R,a=this.ge.N().lineWidth,l=this.De(this.Ve(),n);this.Gt.ht({ee:n,re:a,he:l.he,ae:l.ae,ft:l.ft,ne:s})}Ce(){let e=this.Gt.se();if(null!==e){let t=this.De(this.Ve(),e.ee);e.he=t.he,e.ae=t.ae,e.ft=t.ft}}Ve(){return this.xe()?performance.now()-this.me:2599}Be(e,t,r,i){return this.ge.Qt().Xi().j(e,r+(i-r)*t)}De(e,t){var r;let i,s=e%2600/2600;for(let e of eA)if(s>=e.le&&s<=e.oe){i=e;break}A(void 0!==i,"Last price animation internal logic error");let n=(s-i.le)/(i.oe-i.le);return{he:this.Be(t,n,i.ce,i.de),ae:this.Be(t,n,i.fe,i.pe),ft:(r=i._e)+(i.ue-r)*n}}}class eL extends eC{constructor(e){super(e)}te(){let e=this.Zn;e.Vt=!1;let t=this.Jn.N();if(!t.priceLineVisible||!this.Jn.Vt())return;let r=this.Jn.ye(0===t.priceLineSource);r.ke||(e.Vt=!0,e.ut=r.Ii,e.R=this.Jn.Ie(r.R),e.ct=t.priceLineWidth,e.Xt=t.priceLineStyle)}}class eF extends ed{constructor(e){super(),this.Jt=e}qi(e,t,r){e.Vt=!1,t.Vt=!1;let i=this.Jt;if(!i.Vt())return;let s=i.N(),n=s.lastValueVisible,a=""!==i.Ee(),l=0===s.seriesLastValueMode,o=i.ye(!1);if(o.ke)return;n&&(e.ri=this.Ae(o,n,l),e.Vt=0!==e.ri.length),(a||l)&&(t.ri=this.ze(o,n,a,l),t.Vt=t.ri.length>0);let d=i.Ie(o.R),c=this.Jt.Qt().Xi().X(d);r.Z=c.Z,r.Ii=o.Ii,t.Ht=i.Qt().Ut(o.Ii/i.Ft().$t()),e.Ht=d,e.R=c.G,t.R=c.G}
1ze(e,t,r,i){let s="",n=this.Jt.Ee();return r&&0!==n.length&&(s+=`${n} `),t&&i&&(s+=this.Jt.Ft().Le()?e.Oe:e.Ne),s.trim()}Ae(e,t,r){return t?r?this.Jt.Ft().Le()?e.Ne:e.Oe:e.ri:""}}function eR(e,t,r,i){let s=Number.isFinite(t),n=Number.isFinite(r);return s&&n?e(t,r):s||n?s?t:r:i}class eD{constructor(e,t){this.Fe=e,this.We=t}He(e){return null!==e&&this.Fe===e.Fe&&this.We===e.We}Ue(){return new eD(this.Fe,this.We)}$e(){return this.Fe}qe(){return this.We}Ye(){return this.We-this.Fe}Ki(){return this.We===this.Fe||Number.isNaN(this.We)||Number.isNaN(this.Fe)}vn(e){return null===e?this:new eD(eR(Math.min,this.$e(),e.$e(),-1/0),eR(Math.max,this.qe(),e.qe(),1/0))}je(e){if(!I(e)||0==this.We-this.Fe)return;let t=.5*(this.We+this.Fe),r=this.We-t,i=this.Fe-t;r*=e,i*=e,this.We=t+r,this.Fe=t+i}Ke(e){I(e)&&(this.We+=e,this.Fe+=e)}Xe(){return{minValue:this.Fe,maxValue:this.We}}static Ze(e){return null===e?null:new eD(e.minValue,e.maxValue)}}class eI{constructor(e,t){this.Ge=e,this.Je=t||null}Qe(){return this.Ge}tr(){return this.Je}Xe(){return{priceRange:null===this.Ge?null:this.Ge.Xe(),margins:this.Je||void 0}}static Ze(e){return null===e?null:new eI(eD.Ze(e.priceRange),e.margins)}}class eU extends eC{constructor(e,t){super(e),this.ir=t}te(){let e=this.Zn;e.Vt=!1;let t=this.ir.N();if(!this.Jn.Vt()||!t.lineVisible)return;let r=this.ir.sr();null!==r&&(e.Vt=!0,e.ut=r,e.R=t.color,e.ct=t.lineWidth,e.Xt=t.lineStyle,e.Kn=this.ir.N().id)}}class eO extends ed{constructor(e,t){super(),this.ge=e,this.ir=t}qi(e,t,r){e.Vt=!1,t.Vt=!1;let i=this.ir.N(),s=i.axisLabelVisible,n=""!==i.title,a=this.ge;if(!s||!a.Vt())return;let l=this.ir.sr();if(null===l)return;n&&(t.ri=i.title,t.Vt=!0),t.Ht=a.Qt().Ut(l/a.Ft().$t()),e.ri=this.nr(i.price),e.Vt=!0;let o=this.ge.Qt().Xi().X(i.axisLabelColor||i.color);r.Z=o.Z;let d=i.axisLabelTextColor||o.G;e.R=d,t.R=d,r.Ii=l}nr(e){let t=this.ge.zt();return null===t?"":this.ge.Ft().Zi(e,t.Wt)}}class eB{constructor(e,t){this.ge=e,this.Ps=t,this.er=new eU(e,this),this.Fn=new eO(e,this),this.rr=new eP(this.Fn,e,e.Qt())}hr(e){D(this.Ps,e),this.yt(),this.ge.Qt().ar()}N(){return this.Ps}lr(){return this.er}_r(){return this.rr}ur(){return this.Fn}yt(){this.er.yt(),this.Fn.yt()}sr(){let e=this.ge,t=e.Ft();if(e.Qt().Et().Ki()||t.Ki())return null;let r=e.zt();return null===r?null:t.Nt(this.Ps.price,r.Wt)}}class ez extends em{constructor(e){super(),this.ts=e}Qt(){return this.ts}}let e$={Bar:(e,t,r,i)=>{let s=t.upColor,n=t.downColor,a=L(e(r,i)),l=F(a.Wt[0])<=F(a.Wt[3]);return{cr:a.R??(l?s:n)}},Candlestick:(e,t,r,i)=>{let s=t.upColor,n=t.downColor,a=t.borderUpColor,l=t.borderDownColor,o=t.wickUpColor,d=t.wickDownColor,c=L(e(r,i)),u=F(c.Wt[0])<=F(c.Wt[3]);return{cr:c.R??(u?s:n),dr:c.Ht??(u?a:l),pr:c.vr??(u?o:d)}},Custom:(e,t,r,i)=>({cr:L(e(r,i)).R??t.color}),Area:(e,t,r,i)=>{let s=L(e(r,i));return{cr:s.vt??t.lineColor,vt:s.vt??t.lineColor,mr:s.mr??t.topColor,wr:s.wr??t.bottomColor}},Baseline:(e,t,r,i)=>{let s=L(e(r,i));return{cr:s.Wt[3]>=t.baseValue.price?t.topLineColor:t.bottomLineColor,gr:s.gr??t.topLineColor,Mr:s.Mr??t.bottomLineColor,br:s.br??t.topFillColor1,Sr:s.Sr??t.topFillColor2,Cr:s.Cr??t.bottomFillColor1,Pr:s.Pr??t.bottomFillColor2}},Line:(e,t,r,i)=>{let s=L(e(r,i));return{cr:s.R??t.color,vt:s.R??t.color}},Histogram:(e,t,r,i)=>({cr:L(e(r,i)).R??t.color})};class eV{constructor(e){this.yr=(e,t)=>void 0!==t?t.Wt:this.ge.Xs().kr(e),this.ge=e,this.Tr=e$[e.Rr()]}Dr(e,t){return this.Tr(this.yr,this.ge.N(),e,t)}}function eH(e,t,r,i,s=0,n=t.length){let a=n-s;for(;0<a;){let n=a>>1,l=s+n;i(t[l],r)===e?(s=l+1,a-=n+1):a=n}return s}let eW=eH.bind(null,!0),eq=eH.bind(null,!1);(a=x||(x={}))[a.NearestLeft=-1]="NearestLeft",a[a.None=0]="None",a[a.NearestRight=1]="NearestRight";class eK{constructor(){this.Vr=[],this.Br=new Map,this.Ir=new Map,this.Er=[]}Ar(){return this.zr()>0?this.Vr[this.Vr.length-1]:null}Lr(){return this.zr()>0?this.Or(0):null}Ks(){return this.zr()>0?this.Or(this.Vr.length-1):null}zr(){return this.Vr.length}Ki(){return 0===this.zr()}Te(e){return null!==this.Nr(e,0)}kr(e){return this.Fr(e)}Fr(e,t=0){let r=this.Nr(e,t);return null===r?null:{...this.Wr(r),Re:this.Or(r)}}Hr(){return this.Vr}Ur(e,t,r){if(this.Ki())return null;let i=null;for(let s of r)i=eG(i,this.$r(e,t,s));return i}ht(e){this.Ir.clear(),this.Br.clear(),this.Vr=e,this.Er=e.map(e=>e.Re)}qr(){return this.Er}Or(e){return this.Vr[e].Re}Wr(e){return this.Vr[e]}Nr(e,t){let r=this.Yr(e);if(null===r&&0!==t)switch(t){case -1:return this.jr(e);case 1:return this.Kr(e);default:throw TypeError("Unknown search mode")}return r}jr(e){let t=this.Xr(e);return t>0&&(t-=1),t!==this.Vr.length&&this.Or(t)<e?t:null}Kr(e){let t=this.Zr(e);return t!==this.Vr.length&&e<this.Or(t)?t:null}Yr(e){let t=this.Xr(e);return t===this.Vr.length||e<this.Vr[t].Re?null:t}Xr(e){return eW(this.Vr,e,(e,t)=>e.Re<t)}Zr(e){return eq(this.Vr,e,(e,t)=>e.Re>t)}Gr(e,t,r){let i=null;for(let s=e;s<t;s++){let e=this.Vr[s].Wt[r];Number.isNaN(e)||(null===i?i={Jr:e,Qr:e}:(e<i.Jr&&(i.Jr=e),e>i.Qr&&(i.Qr=e)))}return i}$r(e,t,r){if(this.Ki())return null;let i=null,s=L(this.Lr()),n=L(this.Ks()),a=Math.max(e,s),l=Math.min(t,n),o=30*Math.ceil(a/30),d=Math.max(o,30*Math.floor(l/30));{let e=this.Xr(a),s=this.Zr(Math.min(l,o,t));i=eG(i,this.Gr(e,s,r))}let c=this.Br.get(r);void 0===c&&(c=new Map,this.Br.set(r,c));for(let e=Math.max(o+1,a);e<d;e+=30){let t=Math.floor(e/30),s=c.get(t);if(void 0===s){let e=this.Xr(30*t),i=this.Zr((t+1)*30-1);s=this.Gr(e,i,r),c.set(t,s)}i=eG(i,s)}{let e=this.Xr(d),t=this.Zr(l);i=eG(i,this.Gr(e,t,r))}return i}}function eG(e,t){return null===e?t:null===t?e:{Jr:Math.min(e.Jr,t.Jr),Qr:Math.max(e.Qr,t.Qr)}}let eY={setLineStyle:M};class eX{constructor(e){this.th=e}nt(e,t,r){this.th.draw(e,eY)}
1ih(e,t,r){this.th.drawBackground?.(e,eY)}}class eQ{constructor(e){this.Dn=null,this.sh=e}Tt(){let e=this.sh.renderer();if(null===e)return null;if(this.Dn?.nh===e)return this.Dn.eh;let t=new eX(e);return this.Dn={nh:e,eh:t},t}rh(){return this.sh.zOrder?.()??"normal"}}class eJ{constructor(e){this.hh=null,this.ah=e}oh(){return this.ah}Ns(){this.ah.updateAllViews?.()}Fs(){let e=this.ah.paneViews?.()??[];if(this.hh?.nh===e)return this.hh.eh;let t=e.map(e=>new eQ(e));return this.hh={nh:e,eh:t},t}jn(e,t){return this.ah.hitTest?.(e,t)??null}}let eZ=class extends eJ{us(){return[]}};class e0{constructor(e){this.th=e}nt(e,t,r){this.th.draw(e,eY)}ih(e,t,r){this.th.drawBackground?.(e,eY)}}class e1{constructor(e){this.Dn=null,this.sh=e}Tt(){let e=this.sh.renderer();if(null===e)return null;if(this.Dn?.nh===e)return this.Dn.eh;let t=new e0(e);return this.Dn={nh:e,eh:t},t}rh(){return this.sh.zOrder?.()??"normal"}}function e2(e){return{ri:e.text(),Ii:e.coordinate(),Bi:e.fixedCoordinate?.(),R:e.textColor(),Z:e.backColor(),Vt:e.visible?.()??!0,pi:e.tickVisible?.()??!0}}class e5{constructor(e,t){this.Gt=new eh,this._h=e,this.uh=t}Tt(){return this.Gt.ht({Qi:this.uh.Qi(),...e2(this._h)}),this.Gt}}class e3 extends ed{constructor(e,t){super(),this._h=e,this.Yi=t}qi(e,t,r){let i=e2(this._h);r.Z=i.Z,e.R=i.R;let s=2/12*this.Yi.P();r.Ti=s,r.Ri=s,r.Ii=i.Ii,r.Bi=i.Bi,e.ri=i.ri,e.Vt=i.Vt,e.pi=i.pi}}class e4 extends eJ{constructor(e,t){super(e),this.dh=null,this.fh=null,this.ph=null,this.mh=null,this.ge=t}cs(){let e=this.ah.timeAxisViews?.()??[];if(this.dh?.nh===e)return this.dh.eh;let t=this.ge.Qt().Et(),r=e.map(e=>new e5(e,t));return this.dh={nh:e,eh:r},r}Ws(){let e=this.ah.priceAxisViews?.()??[];if(this.fh?.nh===e)return this.fh.eh;let t=this.ge.Ft(),r=e.map(e=>new e3(e,t));return this.fh={nh:e,eh:r},r}wh(){let e=this.ah.priceAxisPaneViews?.()??[];if(this.ph?.nh===e)return this.ph.eh;let t=e.map(e=>new e1(e));return this.ph={nh:e,eh:t},t}gh(){let e=this.ah.timeAxisPaneViews?.()??[];if(this.mh?.nh===e)return this.mh.eh;let t=e.map(e=>new e1(e));return this.mh={nh:e,eh:t},t}Mh(e,t){return this.ah.autoscaleInfo?.(e,t)??null}}function e6(e,t,r,i){e.forEach(e=>{t(e).forEach(e=>{e.rh()===r&&i.push(e)})})}function e8(e){return e.Fs()}function e9(e){return e.wh()}function e7(e){return e.gh()}let te=["Area","Line","Baseline"];class tt extends ez{constructor(e,t,r,i,s){super(e),this.Yt=new eK,this.er=new eL(this),this.bh=[],this.Sh=new eM(this),this.xh=null,this.Ch=null,this.Ph=null,this.yh=[],this.Ps=r,this.kh=t;const n=new eF(this);this.vs=[n],this.rr=new eP(n,this,e),te.includes(this.kh)&&(this.xh=new eE(this)),this.Th(),this.sh=i(this,this.Qt(),s)}m(){null!==this.Ph&&clearTimeout(this.Ph)}Ie(e){return this.Ps.priceLineColor||e}ye(e){let t,r,i={ke:!0},s=this.Ft();if(this.Qt().Et().Ki()||s.Ki()||this.Yt.Ki())return i;let n=this.Qt().Et().Pe(),a=this.zt();if(null===n||null===a)return i;if(e){let e=this.Yt.Ar();if(null===e)return i;t=e,r=e.Re}else{let e=this.Yt.Fr(n.bi(),-1);if(null===e||null===(t=this.Yt.kr(e.Re)))return i;r=e.Re}let l=t.Wt[3],o=this.Rh().Dr(r,{Wt:t}),d=s.Nt(l,a.Wt);return{ke:!1,gt:l,ri:s.Zi(l,a.Wt),Oe:s.Dh(l),Ne:s.Vh(l,a.Wt),R:o.cr,Ii:d,Re:r}}Rh(){return null!==this.Ch||(this.Ch=new eV(this)),this.Ch}N(){return this.Ps}hr(e){let t=e.priceScaleId;void 0!==t&&t!==this.Ps.priceScaleId&&this.Qt().Bh(this,t),D(this.Ps,e),void 0!==e.priceFormat&&(this.Th(),this.Qt().Ih()),this.Qt().Eh(this),this.Qt().Ah(),this.sh.yt("options")}ht(e,t){this.Yt.ht(e),this.sh.yt("data"),null!==this.xh&&(t&&t.zh?this.xh.be():0===e.length&&this.xh.Me());let r=this.Qt().Hn(this);this.Qt().Lh(r),this.Qt().Eh(this),this.Qt().Ah(),this.Qt().ar()}Oh(e){let t=new eB(this,e);return this.bh.push(t),this.Qt().Eh(this),t}Nh(e){let t=this.bh.indexOf(e);-1!==t&&this.bh.splice(t,1),this.Qt().Eh(this)}Fh(){return this.bh}Rr(){return this.kh}zt(){let e=this.Wh();return null===e?null:{Wt:e.Wt[3],Hh:e.wt}}Wh(){let e=this.Qt().Et().Pe();if(null===e)return null;let t=e.Uh();return this.Yt.Fr(t,1)}Xs(){return this.Yt}$h(e){let t=this.Yt.kr(e);return null===t?null:"Bar"===this.kh||"Candlestick"===this.kh||"Custom"===this.kh?{qh:t.Wt[0],Yh:t.Wt[1],jh:t.Wt[2],Kh:t.Wt[3]}:t.Wt[3]}Xh(e){let t=[];e6(this.yh,e8,"top",t);let r=this.xh;return null!==r&&r.Vt()&&(null===this.Ph&&r.xe()&&(this.Ph=setTimeout(()=>{this.Ph=null,this.Qt().Zh()},0)),r.Se(),t.unshift(r)),t}Fs(){let e=[];this.Gh()||e.push(this.Sh),e.push(this.sh,this.er);let t=this.bh.map(e=>e.lr());return e.push(...t),e6(this.yh,e8,"normal",e),e}Jh(){return this.Qh(e8,"bottom")}ta(e){return this.Qh(e9,e)}ia(e){return this.Qh(e7,e)}sa(e,t){return this.yh.map(r=>r.jn(e,t)).filter(e=>null!==e)}us(){return[this.rr,...this.bh.map(e=>e._r())]}Ws(e,t){if(t!==this.es&&!this.Gh())return[];let r=[...this.vs];for(let e of this.bh)r.push(e.ur());
1return this.yh.forEach(e=>{r.push(...e.Ws())}),r}cs(){let e=[];return this.yh.forEach(t=>{e.push(...t.cs())}),e}Mh(e,t){if(void 0!==this.Ps.autoscaleInfoProvider){let r=this.Ps.autoscaleInfoProvider(()=>{let r=this.na(e,t);return null===r?null:r.Xe()});return eI.Ze(r)}return this.na(e,t)}nh(){let e=this.Ps.priceFormat;return e.base??1/e.minMove}ea(){return this.ra}Ns(){for(let e of(this.sh.yt(),this.vs))e.yt();for(let e of this.bh)e.yt();this.er.yt(),this.Sh.yt(),this.xh?.yt(),this.yh.forEach(e=>e.Ns())}Ft(){return L(super.Ft())}At(e){if(!(("Line"===this.kh||"Area"===this.kh||"Baseline"===this.kh)&&this.Ps.crosshairMarkerVisible))return null;let t=this.Yt.kr(e);return null===t?null:{gt:t.Wt[3],ft:this.ha(),Ht:this.aa(),Ot:this.la(),Lt:this.oa(e)}}Ee(){return this.Ps.title}Vt(){return this.Ps.visible}_a(e){this.yh.push(new e4(e,this))}ua(e){this.yh=this.yh.filter(t=>t.oh()!==e)}ca(){if("Custom"===this.kh)return e=>this.sh.da(e)}fa(){if("Custom"===this.kh)return e=>this.sh.pa(e)}va(){return this.Yt.qr()}Gh(){return!ex(this.Ft().ma())}na(e,t){if(!U(e)||!U(t)||this.Yt.Ki())return null;let r="Line"===this.kh||"Area"===this.kh||"Baseline"===this.kh||"Histogram"===this.kh?[3]:[2,1],i=this.Yt.Ur(e,t,r),s=null!==i?new eD(i.Jr,i.Qr):null,n=null;if("Histogram"===this.Rr()){let e=this.Ps.base,t=new eD(e,e);s=null!==s?s.vn(t):t}return this.yh.forEach(r=>{let i=r.Mh(e,t);if(i?.priceRange){let e=new eD(i.priceRange.minValue,i.priceRange.maxValue);s=null!==s?s.vn(e):e}i?.margins&&(n=i.margins)}),new eI(s,n)}ha(){switch(this.kh){case"Line":case"Area":case"Baseline":return this.Ps.crosshairMarkerRadius}return 0}aa(){switch(this.kh){case"Line":case"Area":case"Baseline":{let e=this.Ps.crosshairMarkerBorderColor;if(0!==e.length)return e}}return null}la(){switch(this.kh){case"Line":case"Area":case"Baseline":return this.Ps.crosshairMarkerBorderWidth}return 0}oa(e){switch(this.kh){case"Line":case"Area":case"Baseline":{let e=this.Ps.crosshairMarkerBackgroundColor;if(0!==e.length)return e}}return this.Rh().Dr(e).cr}Th(){switch(this.Ps.priceFormat.type){case"custom":{let e=this.Ps.priceFormat.formatter;this.ra={format:e,formatTickmarks:this.Ps.priceFormat.tickmarksFormatter??(t=>t.map(e))};break}case"volume":this.ra=new ej(this.Ps.priceFormat.precision);break;case"percent":this.ra=new ew(this.Ps.priceFormat.precision);break;default:{let e=Math.pow(10,this.Ps.priceFormat.precision);this.ra=new ey(e,this.Ps.priceFormat.minMove*e)}}null!==this.es&&this.es.wa()}Qh(e,t){let r=[];return e6(this.yh,e,t,r),r}}let tr=[3],ti=[0,1,2,3];class ts{constructor(e){this.Ps=e}ga(e,t,r){if(0===this.Ps.mode)return e;let i=r.ks(),s=i.zt();if(null===s)return e;let n=i.Nt(e,s),a=r.Ma().filter(e=>e instanceof tt).reduce((e,i)=>{if(r.Un(i)||!i.Vt())return e;let s=i.Ft(),n=i.Xs();if(s.Ki()||!n.Te(t))return e;let a=n.kr(t);if(null===a)return e;let l=F(i.zt()),o=3===this.Ps.mode?ti:tr;return e.concat(o.map(e=>s.Nt(a.Wt[e],l.Wt)))},[]);if(0===a.length)return e;a.sort((e,t)=>Math.abs(e-n)-Math.abs(t-n));let l=a[0];return i.Ts(l,s)}}function tn(e,t,r){return Math.min(Math.max(e,t),r)}class ta extends Q{constructor(){super(...arguments),this.Yt=null}ht(e){this.Yt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:r,verticalPixelRatio:i}){var s;if(null===this.Yt)return;let n=Math.max(1,Math.floor(r));e.lineWidth=n,s=()=>{let s=L(this.Yt);if(s.ba){for(let i of(e.strokeStyle=s.Sa,M(e,s.xa),e.beginPath(),s.Ca)){let s=Math.round(i.Pa*r);e.moveTo(s,-n),e.lineTo(s,t.height+n)}e.stroke()}if(s.ya){for(let r of(e.strokeStyle=s.ka,M(e,s.Ta),e.beginPath(),s.Ra)){let s=Math.round(r.Pa*i);e.moveTo(-n,s),e.lineTo(t.width+n,s)}e.stroke()}},e.save(),e.lineWidth%2&&e.translate(.5,.5),s(),e.restore()}}class tl{constructor(e){this.Gt=new ta,this.xt=!0,this.Pt=e}yt(){this.xt=!0}Tt(){if(this.xt){let e=this.Pt.Qt().N().grid,t={ya:e.horzLines.visible,ba:e.vertLines.visible,ka:e.horzLines.color,Sa:e.vertLines.color,Ta:e.horzLines.style,xa:e.vertLines.style,Ra:this.Pt.ks().Da(),Ca:(this.Pt.Qt().Et().Da()||[]).map(e=>({Pa:e.coord}))};this.Gt.ht(t),this.xt=!1}return this.Gt}}class to{constructor(e){this.sh=new tl(e)}lr(){return this.sh}}let td={Va:4,Ba:1e-4};function tc(e,t){let r=100*(e-t)/t;return t<0?-r:r}function tu(e,t){let r=100*(e-t)/t+100;return t<0?-r:r}function th(e,t){let r=Math.abs(e);if(r<1e-15)return 0;let i=Math.log10(r+t.Ba)+t.Va;return e<0?-i:i}function tp(e,t){let r=Math.abs(e);if(r<1e-15)return 0;let i=Math.pow(10,r-t.Va)-t.Ba;return e<0?-i:i}
1function tm(e,t){return null===e?null:new eD(th(e.$e(),t),th(e.qe(),t))}function tf(e,t){return null===e?null:new eD(tp(e.$e(),t),tp(e.qe(),t))}function tx(e){if(null===e)return td;let t=Math.abs(e.qe()-e.$e());if(t>=1||t<1e-15)return td;let r=Math.ceil(Math.abs(Math.log10(t))),i=td.Va+r;return{Va:i,Ba:1/Math.pow(10,i)}}class tg{constructor(e,t){if(this.Ia=e,this.Ea=t,function(e){if(e<0)return!1;if(e>1e18)return!0;for(let t=e;t>1;t/=10)if(t%10!=0)return!1;return!0}(this.Ia))this.Aa=[2,2.5,2];else{this.Aa=[];for(let e=this.Ia;1!==e;){if(e%2==0)this.Aa.push(2),e/=2;else{if(e%5!=0)throw Error("unexpected base");this.Aa.push(2,2.5),e/=5}if(this.Aa.length>100)throw Error("something wrong with base")}}}za(e,t,r){let i=0===this.Ia?0:1/this.Ia,s=Math.pow(10,Math.max(0,Math.ceil(Math.log10(e-t)))),n=0,a=this.Ea[0];for(;;){let e=i-s<=1e-14&&s>i+1e-14,t=r*a-s<=1e-14,l=1-s<=1e-14;if(!(e&&t&&l))break;s/=a,a=this.Ea[++n%this.Ea.length]}if(s<=i+1e-14&&(s=i),s=Math.max(1,s),this.Aa.length>0&&1e-14>Math.abs(s-1))for(n=0,a=this.Aa[0];r*a-s<=1e-14&&s>i+1e-14;)s/=a,a=this.Aa[++n%this.Aa.length];return s}}
1class tb{constructor(e,t,r,i){this.La=[],this.Yi=e,this.Ia=t,this.Oa=r,this.Na=i}za(e,t){if(e<t)throw Error("high < low");let r=this.Yi.$t(),i=(e-t)*this.Fa()/r,s=new tg(this.Ia,[2,2.5,2]),n=new tg(this.Ia,[2,2,2.5]),a=new tg(this.Ia,[2.5,2,2]),l=[];return l.push(s.za(e,t,i),n.za(e,t,i),a.za(e,t,i)),function(e){if(e.length<1)throw Error("array is empty");let t=e[0];for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r]);return t}(l)}Wa(){let e=this.Yi,t=e.zt();if(null===t)return void(this.La=[]);let r=e.$t(),i=this.Oa(r-1,t),s=this.Oa(0,t),n=this.Yi.N().entireTextOnly?this.Ha()/2:0,a=r-1-n,l=Math.max(i,s),o=Math.min(i,s);if(l===o)return void(this.La=[]);let d=this.za(l,o);if(this.Ua(t,d,l,o,n,a),e.$a()&&this.qa(d,o,l)){let e=this.Yi.Ya();this.ja(t,d,n,a,e,2*e)}let c=this.La.map(e=>e.Ka),u=this.Yi.Xa(c);for(let e=0;e<this.La.length;e++)this.La[e].Za=u[e]}Da(){return this.La}Ha(){return this.Yi.P()}Fa(){return Math.ceil(2.5*this.Ha())}Ua(e,t,r,i,s,n){let a=this.La,l=this.Yi,o=r%t;o+=o<0?t:0;let d=r>=i?1:-1,c=null,u=0;for(let h=r-o;h>i;h-=t){let r=this.Na(h,e,!0);null!==c&&Math.abs(r-c)<this.Fa()||r<s||r>n||(u<a.length?(a[u].Pa=r,a[u].Za=l.Ga(h),a[u].Ka=h):a.push({Pa:r,Za:l.Ga(h),Ka:h}),u++,c=r,l.Ja()&&(t=this.za(h*d,i)))}a.length=u}ja(e,t,r,i,s,n){let a=this.La,l=this.Qa(e,r,s,n),o=this.Qa(e,i,-n,-s),d=this.Na(0,e,!0)-this.Na(t,e,!0);a.length>0&&a[0].Pa-l.Pa<d/2&&a.shift(),a.length>0&&o.Pa-a[a.length-1].Pa<d/2&&a.pop(),a.unshift(l),a.push(o)}Qa(e,t,r,i){let s=this.Oa(t+r,e),n=this.Oa(t+i,e),a=Math.min(s,n),l=Math.max(s,n),o=Math.max(.1,this.za(l,a)),d=this.Oa(t+(r+i)/2,e),c=d-d%o,u=this.Na(c,e,!0);return{Za:this.Yi.Ga(c),Pa:u,Ka:c}}qa(e,t,r){let i=F(this.Yi.Qe());return this.Yi.Ja()&&(i=tf(i,this.Yi.tl())),i.$e()-t<e&&r-i.qe()<e}}function tv(e){return e.slice().sort((e,t)=>L(e.hs())-L(t.hs()))}(l=g||(g={}))[l.Normal=0]="Normal",l[l.Logarithmic=1]="Logarithmic",l[l.Percentage=2]="Percentage",l[l.IndexedTo100=3]="IndexedTo100";let ty=new ew,tw=new ey(100,1);class tj{constructor(e,t,r,i,s){this.il=0,this.sl=null,this.Ge=null,this.nl=null,this.el={rl:!1,hl:null},this.al=!1,this.ll=0,this.ol=0,this._l=new R,this.ul=new R,this.cl=[],this.dl=null,this.fl=null,this.pl=null,this.vl=null,this.ml=null,this.ra=tw,this.wl=tx(null),this.gl=e,this.Ps=t,this.Ml=r,this.bl=i,this.Sl=s,this.xl=new tb(this,100,this.Cl.bind(this),this.Pl.bind(this))}ma(){return this.gl}N(){return this.Ps}hr(e){if(D(this.Ps,e),this.wa(),void 0!==e.mode&&this.yl({ie:e.mode}),void 0!==e.scaleMargins){let t=E(e.scaleMargins.top),r=E(e.scaleMargins.bottom);if(t<0||t>1)throw Error(`Invalid top margin - expect value between 0 and 1, given=${t}`);if(r<0||r>1)throw Error(`Invalid bottom margin - expect value between 0 and 1, given=${r}`);if(t+r>1)throw Error(`Invalid margins - sum of margins must be less than 1, given=${t+r}`);this.kl(),this.pl=null}}Tl(){return this.Ps.autoScale}Rl(){return this.al}Ja(){return 1===this.Ps.mode}Le(){return 2===this.Ps.mode}Dl(){return 3===this.Ps.mode}tl(){return this.wl}ie(){return{sn:this.Ps.autoScale,Vl:this.Ps.invertScale,ie:this.Ps.mode}}yl(e){let t=this.ie(),r=null;void 0!==e.sn&&(this.Ps.autoScale=e.sn),void 0!==e.ie&&(this.Ps.mode=e.ie,2!==e.ie&&3!==e.ie||(this.Ps.autoScale=!0),this.el.rl=!1),1===t.ie&&e.ie!==t.ie&&(function(e,t){if(null===e)return!1;let r=tp(e.$e(),t),i=tp(e.qe(),t);return isFinite(r)&&isFinite(i)}(this.Ge,this.wl)?null!==(r=tf(this.Ge,this.wl))&&this.Bl(r):this.Ps.autoScale=!0),1===e.ie&&e.ie!==t.ie&&null!==(r=tm(this.Ge,this.wl))&&this.Bl(r);let i=t.ie!==this.Ps.mode;i&&(2===t.ie||this.Le())&&this.wa(),i&&(3===t.ie||this.Dl())&&this.wa(),void 0!==e.Vl&&t.Vl!==e.Vl&&(this.Ps.invertScale=e.Vl,this.Il()),this.ul.p(t,this.ie())}El(){return this.ul}P(){return this.Ml.fontSize}$t(){return this.il}Al(e){this.il!==e&&(this.il=e,this.kl(),this.pl=null)}zl(){if(this.sl)return this.sl;let e=this.$t()-this.Ll()-this.Ol();return this.sl=e,e}Qe(){return this.Nl(),this.Ge}Bl(e,t){let r=this.Ge;(t||null===r&&null!==e||null!==r&&!r.He(e))&&(this.pl=null,this.Ge=e)}Fl(e){this.Bl(e),this.Wl(null!==e)}Ki(){return this.Nl(),0===this.il||!this.Ge||this.Ge.Ki()}Hl(e){return this.Vl()?e:this.$t()-1-e}Nt(e,t){return this.Le()?e=tc(e,t):this.Dl()&&(e=tu(e,t)),this.Pl(e,t)}Ul(e,t,r){this.Nl();let i=this.Ol(),s=L(this.Qe()),n=s.$e(),a=s.qe(),l=this.zl()-1,o=this.Vl(),d=l/(a-n),c=void 0===r?0:r.from,u=void 0===r?e.length:r.to,h=this.$l();for(let r=c;r<u;r++){let s=e[r],a=s.gt;if(isNaN(a))continue;let l=a;null!==h&&(l=h(s.gt,t));let c=i+d*(l-n);s.ut=o?c:this.il-1-c}}ql(e,t,r){this.Nl();let i=this.Ol(),s=L(this.Qe()),n=s.$e(),a=s.qe(),l=this.zl()-1,o=this.Vl(),d=l/(a-n),c=void 0===r?0:r.from,u=void 0===r?e.length:r.to,h=this.$l();for(let r=c;r<u;r++){let s=e[r],a=s.qh,l=s.Yh,c=s.jh,u=s.Kh;null!==h&&(a=h(s.qh,t),l=h(s.Yh,t),c=h(s.jh,t),u=h(s.Kh,t));let p=i+d*(a-n),m=o?p:this.il-1-p;s.Yl=m,p=i+d*(l-n),s.jl=m=o?p:this.il-1-p,p=i+d*(c-n),s.Kl=m=o?p:this.il-1-p,p=i+d*(u-n),s.Xl=m=o?p:this.il-1-p}}Ts(e,t){let r=this.Cl(e,t);return this.Zl(r,t)}Zl(e,t){var r,i;let s=e;return this.Le()?(r=s,t<0&&(r=-r),s=r/100*t+t):this.Dl()&&(i=s-100,t<0&&(i=-i),s=i/100*t+t),s}Ma(){return this.cl}Dt(){return this.fl||(this.fl=tv(this.cl)),this.fl}Gl(e){-1===this.cl.indexOf(e)&&(this.cl.push(e),this.wa(),this.Jl())}Ql(e){let t=this.cl.indexOf(e);if(-1===t)throw Error("source is not attached to scale");this.cl.splice(t,1),0===this.cl.length&&(this.yl({sn:!0}),this.Bl(null)),this.wa(),this.Jl()}zt(){let e=null;for(let t of this.cl){let r=t.zt();null!==r&&(null===e||r.Hh<e.Hh)&&(e=r)}return null===e?null:e.Wt}Vl(){return this.Ps.invertScale}Da(){let e=null===this.zt();if(null!==this.pl&&(e||this.pl.io===e))return this.pl.Da;this.xl.Wa();let t=this.xl.Da();return this.pl={Da:t,io:e},this._l.p(),t}so(){return this._l}no(e){this.Le()||this.Dl()||null===this.vl&&null===this.nl&&(this.Ki()||(this.vl=this.il-e,this.nl=L(this.Qe()).Ue()))}eo(e){if(this.Le()||this.Dl()||null===this.vl)return;this.yl({sn:!1}),(e=this.il-e)<0&&(e=0);let t=(this.vl+.2*(this.il-1))/(e+.2*(this.il-1)),r=L(this.nl).Ue();
1t=Math.max(t,.1),r.je(t),this.Bl(r)}ro(){this.Le()||this.Dl()||(this.vl=null,this.nl=null)}ho(e){this.Tl()||null===this.ml&&null===this.nl&&(this.Ki()||(this.ml=e,this.nl=L(this.Qe()).Ue()))}ao(e){if(this.Tl()||null===this.ml)return;let t=L(this.Qe()).Ye()/(this.zl()-1),r=e-this.ml;this.Vl()&&(r*=-1);let i=r*t,s=L(this.nl).Ue();s.Ke(i),this.Bl(s,!0),this.pl=null}lo(){this.Tl()||null!==this.ml&&(this.ml=null,this.nl=null)}ea(){return this.ra||this.wa(),this.ra}Zi(e,t){switch(this.Ps.mode){case 2:return this.oo(tc(e,t));case 3:return this.ea().format(tu(e,t));default:return this.nr(e)}}Ga(e){switch(this.Ps.mode){case 2:return this.oo(e);case 3:return this.ea().format(e);default:return this.nr(e)}}Xa(e){switch(this.Ps.mode){case 2:return this._o(e);case 3:return this.ea().formatTickmarks(e);default:return this.uo(e)}}Dh(e){return this.nr(e,L(this.dl).ea())}Vh(e,t){return e=tc(e,t),this.oo(e,ty)}co(){return this.cl}do(e){this.el={hl:e,rl:!1}}Ns(){this.cl.forEach(e=>e.Ns())}$a(){return this.Ps.ensureEdgeTickMarksVisible&&this.Tl()}Ya(){return this.P()/2}wa(){this.pl=null;let e=1/0;for(let t of(this.dl=null,this.cl))t.hs()<e&&(e=t.hs(),this.dl=t);let t=100;null!==this.dl&&(t=Math.round(this.dl.nh())),this.ra=tw,this.Le()?(this.ra=ty,t=100):this.Dl()?(this.ra=new ey(100,1),t=100):null!==this.dl&&(this.ra=this.dl.ea()),this.xl=new tb(this,t,this.Cl.bind(this),this.Pl.bind(this)),this.xl.Wa()}Jl(){this.fl=null}fo(){return null===this.dl||this.Le()||this.Dl()?1:1/this.dl.nh()}Xi(){return this.Sl}Wl(e){this.al=e}Ll(){return this.Vl()?this.Ps.scaleMargins.bottom*this.$t()+this.ol:this.Ps.scaleMargins.top*this.$t()+this.ll}Ol(){return this.Vl()?this.Ps.scaleMargins.top*this.$t()+this.ll:this.Ps.scaleMargins.bottom*this.$t()+this.ol}Nl(){this.el.rl||(this.el.rl=!0,this.po())}kl(){this.sl=null}Pl(e,t){if(this.Nl(),this.Ki())return 0;e=this.Ja()&&e?th(e,this.wl):e;let r=L(this.Qe()),i=this.Ol()+(this.zl()-1)*(e-r.$e())/r.Ye();return this.Hl(i)}Cl(e,t){if(this.Nl(),this.Ki())return 0;let r=this.Hl(e),i=L(this.Qe()),s=i.$e()+i.Ye()*((r-this.Ol())/(this.zl()-1));return this.Ja()?tp(s,this.wl):s}Il(){this.pl=null,this.xl.Wa()}po(){var e,t,r,i,s;if(this.Rl()&&!this.Tl())return;let n=this.el.hl;if(null===n)return;let a=null,l=this.co(),o=0,d=0;for(let e of l){if(!e.Vt())continue;let l=e.zt();if(null===l)continue;let c=e.Mh(n.Uh(),n.bi()),u=c&&c.Qe();if(null!==u){switch(this.Ps.mode){case 1:u=tm(u,this.wl);break;case 2:t=u,r=l.Wt,u=new eD(tc(t.$e(),r),tc(t.qe(),r));break;case 3:i=u,s=l.Wt,u=new eD(tu(i.$e(),s),tu(i.qe(),s))}if(a=null===a?u:a.vn(L(u)),null!==c){let e=c.tr();null!==e&&(o=Math.max(o,e.above),d=Math.max(d,e.below))}}}if(this.$a()&&(o=Math.max(o,this.Ya()),d=Math.max(d,this.Ya())),o===this.ll&&d===this.ol||(this.ll=o,this.ol=d,this.pl=null,this.kl()),null!==a){if(a.$e()===a.qe()){let e=5*this.fo();this.Ja()&&(a=tf(a,this.wl)),a=new eD(a.$e()-e,a.qe()+e),this.Ja()&&(a=tm(a,this.wl))}if(this.Ja()){let t=tf(a,this.wl),r=tx(t);if(e=this.wl,r.Va!==e.Va||r.Ba!==e.Ba){let e=null!==this.nl?tf(this.nl,this.wl):null;this.wl=r,a=tm(t,r),null!==e&&(this.nl=tm(e,r))}}this.Bl(a)}else null===this.Ge&&(this.Bl(new eD(-.5,.5)),this.wl=tx(null))}$l(){return this.Le()?tc:this.Dl()?tu:this.Ja()?e=>th(e,this.wl):null}vo(e,t,r){return void 0===t?(void 0===r&&(r=this.ea()),r.format(e)):t(e)}mo(e,t,r){return void 0===t?(void 0===r&&(r=this.ea()),r.formatTickmarks(e)):t(e)}nr(e,t){return this.vo(e,this.bl.priceFormatter,t)}uo(e,t){let r=this.bl.priceFormatter;return this.mo(e,this.bl.tickmarksPriceFormatter??(r?e=>e.map(r):void 0),t)}oo(e,t){return this.vo(e,this.bl.percentageFormatter,t)}_o(e,t){let r=this.bl.percentageFormatter;return this.mo(e,this.bl.tickmarksPercentageFormatter??(r?e=>e.map(r):void 0),t)}}function tS(e){return e instanceof tt}class tk{constructor(e,t){this.cl=[],this.wo=new Map,this.il=0,this.Mo=0,this.bo=1,this.fl=null,this.So=!1,this.xo=new R,this.yh=[],this.uh=e,this.ts=t,this.Co=new to(this);const r=t.N();this.Po=this.yo("left",r.leftPriceScale),this.ko=this.yo("right",r.rightPriceScale),this.Po.El().i(this.To.bind(this,this.Po),this),this.ko.El().i(this.To.bind(this,this.ko),this),this.Ro(r)}Ro(e){if(e.leftPriceScale&&this.Po.hr(e.leftPriceScale),e.rightPriceScale&&this.ko.hr(e.rightPriceScale),e.localization&&(this.Po.wa(),this.ko.wa()),e.overlayPriceScales)for(let t of Array.from(this.wo.values())
1){let r=L(t[0].Ft());r.hr(e.overlayPriceScales),e.localization&&r.wa()}}Do(e){switch(e){case"left":return this.Po;case"right":return this.ko}return this.wo.has(e)?E(this.wo.get(e))[0].Ft():null}m(){this.Qt().Vo().u(this),this.Po.El().u(this),this.ko.El().u(this),this.cl.forEach(e=>{e.m&&e.m()}),this.yh=this.yh.filter(e=>{let t=e.oh();return t.detached&&t.detached(),!1}),this.xo.p()}Bo(){return this.bo}Io(e){this.bo=e}Qt(){return this.ts}Qi(){return this.Mo}$t(){return this.il}Eo(e){this.Mo=e,this.Ao()}Al(e){this.il=e,this.Po.Al(e),this.ko.Al(e),this.cl.forEach(t=>{if(this.Un(t)){let r=t.Ft();null!==r&&r.Al(e)}}),this.Ao()}zo(e){this.So=e}Lo(){return this.So}Oo(){return this.cl.filter(tS)}Ma(){return this.cl}Un(e){let t=e.Ft();return null===t||this.Po!==t&&this.ko!==t}Gl(e,t,r){this.No(e,t,r?e.hs():this.cl.length)}Ql(e,t){let r=this.cl.indexOf(e);A(-1!==r,"removeDataSource: invalid data source"),this.cl.splice(r,1),t||this.cl.forEach((e,t)=>e.ls(t));let i=L(e.Ft()).ma();if(this.wo.has(i)){let t=E(this.wo.get(i)),r=t.indexOf(e);-1!==r&&(t.splice(r,1),0===t.length&&this.wo.delete(i))}let s=e.Ft();s&&s.Ma().indexOf(e)>=0&&(s.Ql(e),this.Fo(s)),this.fl=null}qn(e){return e===this.Po?"left":e===this.ko?"right":"overlay"}Wo(){return this.Po}Ho(){return this.ko}Uo(e,t){e.no(t)}$o(e,t){e.eo(t),this.Ao()}qo(e){e.ro()}Yo(e,t){e.ho(t)}jo(e,t){e.ao(t),this.Ao()}Ko(e){e.lo()}Ao(){this.cl.forEach(e=>{e.Ns()})}ks(){let e=null;return this.ts.N().rightPriceScale.visible&&0!==this.ko.Ma().length?e=this.ko:this.ts.N().leftPriceScale.visible&&0!==this.Po.Ma().length?e=this.Po:0!==this.cl.length&&(e=this.cl[0].Ft()),null===e&&(e=this.ko),e}$n(){let e=null;return this.ts.N().rightPriceScale.visible?e=this.ko:this.ts.N().leftPriceScale.visible&&(e=this.Po),e}Fo(e){null!==e&&e.Tl()&&this.Xo(e)}Zo(e){let t=this.uh.Pe();e.yl({sn:!0}),null!==t&&e.do(t),this.Ao()}Go(){this.Xo(this.Po),this.Xo(this.ko)}Jo(){this.Fo(this.Po),this.Fo(this.ko),this.cl.forEach(e=>{this.Un(e)&&this.Fo(e.Ft())}),this.Ao(),this.ts.ar()}Dt(){return null===this.fl&&(this.fl=tv(this.cl)),this.fl}Qo(e,t){t=tn(t,0,this.cl.length-1);let r=this.cl.indexOf(e);for(let i of(A(-1!==r,"setSeriesOrder: invalid data source"),this.cl.splice(r,1),this.cl.splice(t,0,e),this.cl.forEach((e,t)=>e.ls(t)),this.fl=null,[this.Po,this.ko]))i.Jl(),i.wa();this.ts.ar()}Bt(){return this.Dt().filter(tS)}t_(){return this.xo}i_(){return this.Co}_a(e){this.yh.push(new eZ(e))}ua(e){this.yh=this.yh.filter(t=>t.oh()!==e),e.detached&&e.detached(),this.ts.ar()}s_(){return this.yh}sa(e,t){return this.yh.map(r=>r.jn(e,t)).filter(e=>null!==e)}Xo(e){let t=e.co();if(t&&t.length>0&&!this.uh.Ki()){let t=this.uh.Pe();null!==t&&e.do(t)}e.Ns()}No(e,t,r){let i=this.Do(t);if(null===i&&(i=this.yo(t,this.ts.N().overlayPriceScales)),this.cl.splice(r,0,e),!ex(t)){let r=this.wo.get(t)||[];r.push(e),this.wo.set(t,r)}e.ls(r),i.Gl(e),e._s(i),this.Fo(i),this.fl=null}To(e,t,r){t.ie!==r.ie&&this.Xo(e)}yo(e,t){let r=new tj(e,{visible:!0,autoScale:!0,...z(t)},this.ts.N().layout,this.ts.N().localization,this.ts.Xi());return r.Al(this.$t()),r}}function tN(e){return{n_:e.n_,e_:{Kn:e.r_.externalId},h_:e.r_.cursorStyle}}function tP(e,t,r){let i=[e,...e.Dt()],s=function(e,t,r){var i,s;let n,a;for(let l of e)for(let e of l.sa?.(t,r)??[])i=e.zOrder,(s=n?.zOrder)&&("top"!==i||"top"===s)&&("normal"!==i||"bottom"!==s)||(n=e,a=l);return n&&a?{r_:n,n_:a}:null}(i,t,r);if("top"===s?.r_.zOrder)return tN(s);for(let n of i){if(s&&s.n_===n&&"bottom"!==s.r_.zOrder&&!s.r_.isBackground)return tN(s);if(void 0!==n.Fs){let i=function(e,t,r,i){for(let s of e){let e=s.Tt(i);if(null!==e&&e.jn){let i=e.jn(t,r);if(null!==i)return{a_:s,e_:i}}}return null}(n.Fs(e),t,r,e);if(null!==i)return{n_:n,a_:i.a_,e_:i.e_}}if(s&&s.n_===n&&"bottom"!==s.r_.zOrder&&s.r_.isBackground)return tN(s)}return s?.r_?tN(s):null}class tT{constructor(e,t,r=50){this.yn=0,this.kn=1,this.Tn=1,this.Dn=new Map,this.Rn=new Map,this.l_=e,this.o_=t,this.Vn=r}__(e){let t=e.time,r=this.o_.cacheKey(t),i=this.Dn.get(r);if(void 0!==i)return i.u_;if(this.yn===this.Vn){let e=this.Rn.get(this.Tn);this.Rn.delete(this.Tn),this.Dn.delete(E(e)),this.Tn++,this.yn--}let s=this.l_(e);return this.Dn.set(r,{u_:s,An:this.kn}),this.Rn.set(this.kn,r),this.yn++,this.kn++,s}}class tC{constructor(e,t){A(e<=t,"right should be >= left"),this.c_=e,this.d_=t}Uh(){return this.c_}bi(){return this.d_}f_(){return this.d_-this.c_+1}Te(e){return this.c_<=e&&e<=this.d_}He(e){return this.c_===e.Uh()&&this.d_===e.bi()}}function tM(e,t){return null===e||null===t?e===t:e.He(t)}class t_{constructor(){this.p_=new Map,this.Dn=null,this.v_=!1}m_(e){this.v_=e,this.Dn=null}w_(e,t){this.g_(t),this.Dn=null;for(let r=t;r<e.length;++r){let t=e[r],i=this.p_.get(t.timeWeight);void 0===i&&(i=[],this.p_.set(t.timeWeight,i)),i.push({index:r,t
1ime:t.time,weight:t.timeWeight,originalTime:t.originalTime})}}M_(e,t,r,i,s){let n=Math.ceil(t/e);return null!==this.Dn&&this.Dn.b_===n&&s===this.Dn.S_&&r===this.Dn.x_||(this.Dn={S_:s,x_:r,Da:this.C_(n,r,i),b_:n}),this.Dn.Da}g_(e){if(0===e)return void this.p_.clear();let t=[];for(let r of(this.p_.forEach((r,i)=>{e<=r[0].index?t.push(i):r.splice(eW(r,e,t=>t.index<e),1/0)}),t))this.p_.delete(r)}C_(e,t,r){let i=[],s=e=>!t||r.has(e.index);for(let t of Array.from(this.p_.keys()).sort((e,t)=>t-e)){if(!this.p_.get(t))continue;let r=i;i=[];let n=r.length,a=0,l=E(this.p_.get(t)),o=l.length,d=1/0,c=-1/0;for(let t=0;t<o;t++){let o=l[t],u=o.index;for(;a<n;){let e=r[a],t=e.index;if(!(t<u&&s(e))){d=t;break}a++,i.push(e),c=t,d=1/0}if(d-u>=e&&u-c>=e&&s(o))i.push(o),c=u;else if(this.v_)return r}for(;a<n;a++)s(r[a])&&i.push(r[a])}return i}}class tA{constructor(e){this.P_=e}y_(){return null===this.P_?null:new tC(Math.floor(this.P_.Uh()),Math.ceil(this.P_.bi()))}k_(){return this.P_}static T_(){return new tA(null)}}function tE(e,t){return e.weight>t.weight?e:t}
1class tL{constructor(e,t,r,i){this.Mo=0,this.R_=null,this.D_=[],this.ml=null,this.vl=null,this.V_=new t_,this.B_=new Map,this.I_=tA.T_(),this.E_=!0,this.A_=new R,this.z_=new R,this.L_=new R,this.O_=null,this.N_=null,this.F_=new Map,this.W_=-1,this.H_=[],this.Ps=t,this.bl=r,this.U_=t.rightOffset,this.q_=t.barSpacing,this.ts=e,this.Y_(t),this.o_=i,this.j_(),this.V_.m_(t.uniformDistribution),this.K_()}N(){return this.Ps}X_(e){D(this.bl,e),this.Z_(),this.j_()}hr(e,t){D(this.Ps,e),this.Ps.fixLeftEdge&&this.G_(),this.Ps.fixRightEdge&&this.J_(),void 0!==e.barSpacing&&this.ts.dn(e.barSpacing),void 0!==e.rightOffset&&this.ts.fn(e.rightOffset),this.Y_(e),void 0===e.minBarSpacing&&void 0===e.maxBarSpacing||this.ts.dn(e.barSpacing??this.q_),void 0!==e.ignoreWhitespaceIndices&&e.ignoreWhitespaceIndices!==this.Ps.ignoreWhitespaceIndices&&this.K_(),this.Z_(),this.j_(),this.L_.p()}Rs(e){return this.D_[e]?.time??null}ss(e){return this.D_[e]??null}Q_(e,t){if(this.D_.length<1)return null;if(this.o_.key(e)>this.o_.key(this.D_[this.D_.length-1].time))return t?this.D_.length-1:null;let r=eW(this.D_,this.o_.key(e),(e,t)=>this.o_.key(e.time)<t);return this.o_.key(e)<this.o_.key(this.D_[r].time)?t?r:null:r}Ki(){return 0===this.Mo||0===this.D_.length||null===this.R_}tu(){return this.D_.length>0}Pe(){return this.iu(),this.I_.y_()}su(){return this.iu(),this.I_.k_()}nu(){let e=this.Pe();if(null===e)return null;let t={from:e.Uh(),to:e.bi()};return this.eu(t)}eu(e){let t=Math.round(e.from),r=Math.round(e.to),i=L(this.ru()),s=L(this.hu());return{from:L(this.ss(Math.max(i,t))),to:L(this.ss(Math.min(s,r)))}}au(e){return{from:L(this.Q_(e.from,!0)),to:L(this.Q_(e.to,!0))}}Qi(){return this.Mo}Eo(e){if(!isFinite(e)||e<=0||this.Mo===e)return;let t=this.su(),r=this.Mo;if(this.Mo=e,this.E_=!0,this.Ps.lockVisibleTimeRangeOnResize&&0!==r){let t=this.q_*e/r;this.q_=t}this.Ps.fixLeftEdge&&null!==t&&0>=t.Uh()&&(this.U_-=Math.round((r-e)/this.q_)+1,this.E_=!0),this.lu(),this.ou()}qt(e){if(this.Ki()||!U(e))return 0;let t=this._u()+this.U_-e;return this.Mo-(t+.5)*this.q_-1}uu(e,t){let r=this._u(),i=void 0===t?0:t.from,s=void 0===t?e.length:t.to;for(let t=i;t<s;t++){let i=e[t].wt,s=r+this.U_-i,n=this.Mo-(s+.5)*this.q_-1;e[t]._t=n}}cu(e,t){let r=Math.ceil(this.du(e));return t&&this.Ps.ignoreWhitespaceIndices&&!this.fu(r)?this.pu(r):r}fn(e){this.E_=!0,this.U_=e,this.ou(),this.ts.vu(),this.ts.ar()}mu(){return this.q_}dn(e){let t=this.q_;if(this.wu(e),void 0!==this.Ps.rightOffsetPixels&&0!==t){let e=this.U_*t/this.q_;this.U_=e}this.ou(),this.ts.vu(),this.ts.ar()}gu(){return this.U_}Da(){if(this.Ki())return null;if(null!==this.N_)return this.N_;let e=this.q_,t=5*(this.ts.N().layout.fontSize+4)/8*(this.Ps.tickMarkMaxCharacterLength||8),r=Math.round(t/e),i=L(this.Pe()),s=Math.max(i.Uh(),i.Uh()-r),n=Math.max(i.bi(),i.bi()-r),a=this.V_.M_(e,t,this.Ps.ignoreWhitespaceIndices,this.F_,this.W_),l=this.ru()+r,o=this.hu()-r,d=this.Mu(),c=this.Ps.fixLeftEdge||d,u=this.Ps.fixRightEdge||d,h=0;for(let e of a){let r;s<=e.index&&e.index<=n&&(h<this.H_.length?((r=this.H_[h]).coord=this.qt(e.index),r.label=this.bu(e),r.weight=e.weight):(r={needAlignCoordinate:!1,coord:this.qt(e.index),label:this.bu(e),weight:e.weight},this.H_.push(r)),this.q_>t/2&&!d?r.needAlignCoordinate=!1:r.needAlignCoordinate=c&&e.index<=l||u&&e.index>=o,h++)}return this.H_.length=h,this.N_=this.H_,this.H_}Su(){let e;this.E_=!0,this.dn(this.Ps.barSpacing),e=void 0!==this.Ps.rightOffsetPixels?this.Ps.rightOffsetPixels/this.mu():this.Ps.rightOffset,this.fn(e)}xu(e){this.E_=!0,this.R_=e,this.ou(),this.G_()}Cu(e,t){let r=this.du(e),i=this.mu();this.dn(i+i/10*t),this.Ps.rightBarStaysOnScroll||this.fn(this.gu()+(r-this.du(e)))}no(e){this.ml&&this.lo(),null===this.vl&&null===this.O_&&(this.Ki()||(this.vl=e,this.Pu()))}eo(e){if(null===this.O_)return;let t=tn(this.Mo-e,0,this.Mo),r=tn(this.Mo-L(this.vl),0,this.Mo);0!==t&&0!==r&&this.dn(this.O_.mu*t/r)}ro(){null!==this.vl&&(this.vl=null,this.yu())}ho(e){null===this.ml&&null===this.O_&&(this.Ki()||(this.ml=e,this.Pu()))}ao(e){if(null===this.ml)return;let t=(this.ml-e)/this.mu();this.U_=L(this.O_).gu+t,this.E_=!0,this.ou()}lo(){null!==this.ml&&(this.ml=null,this.yu())}ku(){this.Tu(this.Ps.rightOffset)}
1Tu(e,t=400){if(!isFinite(e))throw RangeError("offset is required and must be finite number");if(!isFinite(t)||t<=0)throw RangeError("animationDuration (optional) must be finite positive number");let r=this.U_,i=performance.now();this.ts._n({Ru:e=>(e-i)/t>=1,Du:s=>{let n=(s-i)/t;return n>=1?e:r+(e-r)*n}})}yt(e,t){this.E_=!0,this.D_=e,this.V_.w_(e,t),this.ou()}Vu(){return this.A_}Bu(){return this.z_}Iu(){return this.L_}_u(){return this.R_||0}Eu(e,t){let r=e.f_(),i=t&&this.Ps.rightOffsetPixels||0;this.wu((this.Mo-i)/r),this.U_=e.bi()-this._u(),t&&(this.U_=i?i/this.mu():this.Ps.rightOffset),this.ou(),this.E_=!0,this.ts.vu(),this.ts.ar()}Au(){let e=this.ru(),t=this.hu();null!==e&&null!==t&&this.Eu(new tC(e,t),!0)}zu(e){let t=new tC(e.from,e.to);this.Eu(t)}ns(e){return void 0!==this.bl.timeFormatter?this.bl.timeFormatter(e.originalTime):this.o_.formatHorzItem(e.time)}K_(){if(this.Ps.ignoreWhitespaceIndices){for(let e of(this.F_.clear(),this.ts.js()))for(let t of e.va())this.F_.set(t,!0);this.W_++}}Mu(){let e=this.ts.N().handleScroll,t=this.ts.N().handleScale;return!(e.horzTouchDrag||e.mouseWheel||e.pressedMouseMove||e.vertTouchDrag||t.axisDoubleClickReset.time||t.axisPressedMouseMove.time||t.mouseWheel||t.pinch)}ru(){return 0===this.D_.length?null:0}hu(){return 0===this.D_.length?null:this.D_.length-1}Lu(e){return(this.Mo-1-e)/this.q_}du(e){let t=this.Lu(e);return Math.round(1e6*(this._u()+this.U_-t))/1e6}wu(e){let t=this.q_;this.q_=e,this.lu(),t!==this.q_&&(this.E_=!0,this.Ou())}iu(){if(!this.E_)return;if(this.E_=!1,this.Ki())return void this.Nu(tA.T_());let e=this._u(),t=this.Mo/this.q_,r=this.U_+e,i=new tC(r-t+1,r);this.Nu(new tA(i))}lu(){let e=tn(this.q_,this.Fu(),this.Wu());this.q_!==e&&(this.q_=e,this.E_=!0)}Wu(){return this.Ps.maxBarSpacing>0?this.Ps.maxBarSpacing:.5*this.Mo}Fu(){return this.Ps.fixLeftEdge&&this.Ps.fixRightEdge&&0!==this.D_.length?this.Mo/this.D_.length:this.Ps.minBarSpacing}ou(){let e=this.Hu();null!==e&&this.U_<e&&(this.U_=e,this.E_=!0);let t=this.Uu();this.U_>t&&(this.U_=t,this.E_=!0)}Hu(){let e=this.ru(),t=this.R_;return null===e||null===t?null:e-t-1+(this.Ps.fixLeftEdge?this.Mo/this.q_:Math.min(2,this.D_.length))}Uu(){return this.Ps.fixRightEdge?0:this.Mo/this.q_-Math.min(2,this.D_.length)}Pu(){this.O_={mu:this.mu(),gu:this.gu()}}yu(){this.O_=null}bu(e){let t=this.B_.get(e.weight);return void 0===t&&(t=new tT(e=>this.$u(e),this.o_),this.B_.set(e.weight,t)),t.__(e)}$u(e){return this.o_.formatTickmark(e,this.bl)}Nu(e){let t=this.I_;this.I_=e,tM(t.y_(),this.I_.y_())||this.A_.p(),tM(t.k_(),this.I_.k_())||this.z_.p(),this.Ou()}Ou(){this.N_=null}Z_(){this.Ou(),this.B_.clear()}j_(){this.o_.updateFormatter(this.bl)}G_(){if(!this.Ps.fixLeftEdge)return;let e=this.ru();if(null===e)return;let t=this.Pe();if(null===t)return;let r=t.Uh()-e;if(r<0){let e=this.U_-r-1;this.fn(e)}this.lu()}J_(){this.ou(),this.lu()}fu(e){return!this.Ps.ignoreWhitespaceIndices||this.F_.get(e)||!1}pu(e){let t=function*(e){let t=Math.round(e),r=t<e,i=1;for(;;)r?(yield t+i,yield t-i):(yield t-i,yield t+i),i++}(e),r=this.hu();for(;r;){let e=t.next().value;if(this.F_.get(e))return e;if(e<0||e>r)break}return e}Y_(e){if(void 0!==e.rightOffsetPixels){let t=e.rightOffsetPixels/(e.barSpacing||this.q_);this.ts.fn(t)}}}(o=b||(b={}))[o.OnTouchEnd=0]="OnTouchEnd",o[o.OnNextTap=1]="OnNextTap";class tF{constructor(e,t,r){this.qu=[],this.Yu=[],this.Mo=0,this.ju=null,this.Ku=new R,this.Xu=new R,this.Zu=null,this.Gu=e,this.Ps=t,this.o_=r,this.Sl=new Y(this.Ps.layout.colorParsers),this.Ju=new q(this),this.uh=new tL(this,t.timeScale,this.Ps.localization,r),this.Ct=new ef(this,t.crosshair),this.Qu=new ts(t.crosshair),t.addDefaultPane&&(this.tc(0),this.qu[0].Io(2)),this.sc=this.nc(0),this.ec=this.nc(1)}Ih(){this.rc(eg.gn())}ar(){this.rc(eg.wn())}Zh(){this.rc(new eg(1))}Eh(e){let t=this.hc(e);this.rc(t)}ac(){return this.ju}lc(e){if(this.ju?.n_===e?.n_&&this.ju?.e_?.Kn===e?.e_?.Kn)return;let t=this.ju;this.ju=e,null!==t&&this.Eh(t.n_),null!==e&&e.n_!==t?.n_&&this.Eh(e.n_)}N(){return this.Ps}hr(e){D(this.Ps,e),this.qu.forEach(t=>t.Ro(e)),void 0!==e.timeScale&&this.uh.hr(e.timeScale),void 0!==e.localization&&this.uh.X_(e.localization),(e.leftPriceScale||e.rightPriceScale)&&this.Ku.p(),this.sc=this.nc(0),this.ec=this.nc(1),this.Ih()}oc(e,t,r=0){let i=this.qu[r];if(void 0===i)return;if("left"===e)return D(this.Ps,{leftPriceScale:t}),i.Ro({leftPriceScale:t}),this.Ku.p(),void this.Ih();if("right"===e)return D(this.Ps,{rightPriceScale:t}),i.Ro({rightPriceScale:t}),this.Ku.p(),void this.Ih();let s=this._c(e,r);null!==s&&(s.Ft.hr(t),this.Ku.p())}_c(e,t){let r=this.qu[t];if(void 0===r)return null;let i=r.Do(e);return null!==i?{Us:r,Ft:i}:null}Et(){return this.uh}$s(){return this.qu}uc(){return this.Ct}cc(){return this.Xu}dc(e,t){e.Al(t),this.vu()}Eo(e){this.Mo=e,this.uh.Eo(this.Mo),this.qu.forEach(t=>t.Eo(e)),this.vu()}fc(e){1!==this.qu.length&&(A(e>=0&&e<this.qu.length,"Invalid pane index"),this.qu.splice(e,1),this.Ih())}vc(e,t){if(this.qu.length<2)return;A(e>=0&&e<this.qu.length,"Invalid pane index");let r=this.qu[e],i=this.qu.reduce((e,t)=>
1e+t.Bo(),0),s=this.qu.reduce((e,t)=>e+t.$t(),0),n=s-30*(this.qu.length-1);t=Math.min(n,Math.max(30,t));let a=i/s,l=r.$t();r.Io(t*a);let o=t-l,d=this.qu.length-1;for(let e of this.qu)if(e!==r){let t=Math.min(n,Math.max(30,e.$t()-o/d));o-=e.$t()-t,d-=1;let r=t*a;e.Io(r)}this.Ih()}mc(e,t){A(e>=0&&e<this.qu.length&&t>=0&&t<this.qu.length,"Invalid pane index");let r=this.qu[e],i=this.qu[t];this.qu[e]=i,this.qu[t]=r,this.Ih()}wc(e,t){if(A(e>=0&&e<this.qu.length&&t>=0&&t<this.qu.length,"Invalid pane index"),e===t)return;let[r]=this.qu.splice(e,1);this.qu.splice(t,0,r),this.Ih()}Uo(e,t,r){e.Uo(t,r)}$o(e,t,r){e.$o(t,r),this.Ah(),this.rc(this.gc(e,2))}qo(e,t){e.qo(t),this.rc(this.gc(e,2))}Yo(e,t,r){t.Tl()||e.Yo(t,r)}jo(e,t,r){t.Tl()||(e.jo(t,r),this.Ah(),this.rc(this.gc(e,2)))}Ko(e,t){t.Tl()||(e.Ko(t),this.rc(this.gc(e,2)))}Zo(e,t){e.Zo(t),this.rc(this.gc(e,2))}Mc(e){this.uh.no(e)}bc(e,t){let r=this.Et();if(r.Ki()||0===t)return;let i=r.Qi();e=Math.max(1,Math.min(e,i)),r.Cu(e,t),this.vu()}Sc(e){this.xc(0),this.Cc(e),this.Pc()}yc(e){this.uh.eo(e),this.vu()}kc(){this.uh.ro(),this.ar()}xc(e){this.uh.ho(e)}Cc(e){this.uh.ao(e),this.vu()}Pc(){this.uh.lo(),this.ar()}js(){return this.Yu}Tc(e,t,r,i,s){this.Ct.Vs(e,t);let n=NaN,a=this.uh.cu(e,!0),l=this.uh.Pe();null!==l&&(a=Math.min(Math.max(l.Uh(),a),l.bi()));let o=i.ks(),d=o.zt();if(null!==d&&(n=o.Ts(t,d)),n=this.Qu.ga(n,a,i),this.Ct.As(a,n,i),this.Zh(),!s){let s=tP(i,e,t);this.lc(s&&{n_:s.n_,e_:s.e_,h_:s.h_||null}),this.Xu.p(this.Ct.It(),{x:e,y:t},r)}}Rc(e,t,r){let i=r.ks(),s=i.zt(),n=i.Nt(e,L(s)),a=this.uh.Q_(t,!0),l=this.uh.qt(L(a));this.Tc(l,n,null,r,!0)}Dc(e){this.uc().Ls(),this.Zh(),e||this.Xu.p(null,null,null)}Ah(){let e=this.Ct.Us();if(null!==e){let t=this.Ct.Is(),r=this.Ct.Es();this.Tc(t,r,null,e)}this.Ct.Ns()}Vc(e,t,r){let i=this.uh.Rs(0);void 0!==t&&void 0!==r&&this.uh.yt(t,r);let s=this.uh.Rs(0),n=this.uh._u(),a=this.uh.Pe();if(null!==a&&null!==i&&null!==s){let t=a.Te(n),l=this.o_.key(i)>this.o_.key(s),o=null!==e&&e>n&&!l,d=this.uh.N().allowShiftVisibleRangeOnWhitespaceReplacement,c=t&&(void 0!==r||d)&&this.uh.N().shiftVisibleRangeOnNewBar;if(o&&!c){let t=e-n;this.uh.fn(this.uh.gu()-t)}}this.uh.xu(e)}Lh(e){null!==e&&e.Jo()}Hn(e){if(e instanceof tk)return e;let t=this.qu.find(t=>t.Dt().includes(e));return void 0===t?null:t}vu(){this.qu.forEach(e=>e.Jo()),this.Ah()}m(){this.qu.forEach(e=>e.m()),this.qu.length=0,this.Ps.localization.priceFormatter=void 0,this.Ps.localization.percentageFormatter=void 0,this.Ps.localization.timeFormatter=void 0}Bc(){return this.Ju}Yn(){return this.Ju.N()}Vo(){return this.Ku}Ic(e,t){let r=this.tc(t);this.Ec(e,r),this.Yu.push(e),1===this.Yu.length?this.Ih():this.ar()}Ac(e){let t=this.Hn(e),r=this.Yu.indexOf(e);A(-1!==r,"Series not found");let i=L(t);this.Yu.splice(r,1),i.Ql(e),e.m&&e.m(),this.uh.K_(),this.zc(i)}Bh(e,t){let r=L(this.Hn(e));r.Ql(e,!0),r.Gl(e,t,!0)}Au(){let e=eg.wn();e.rn(),this.rc(e)}Lc(e){let t=eg.wn();t.ln(e),this.rc(t)}cn(){let e=eg.wn();e.cn(),this.rc(e)}dn(e){let t=eg.wn();t.dn(e),this.rc(t)}fn(e){let t=eg.wn();t.fn(e),this.rc(t)}_n(e){let t=eg.wn();t._n(e),this.rc(t)}hn(){let e=eg.wn();e.hn(),this.rc(e)}Oc(){return this.Ps.rightPriceScale.visible?"right":"left"}Nc(e,t){if(A(t>=0,"Index should be greater or equal to 0"),t===this.Fc(e))return;let r=L(this.Hn(e));r.Ql(e);let i=this.tc(t);this.Ec(e,i),0===r.Ma().length&&this.zc(r),this.Ih()}Wc(){return this.ec}$(){return this.sc}Ut(e){let t=this.ec,r=this.sc;if(t===r)return t;if(e=Math.max(0,Math.min(100,Math.round(100*e))),null===this.Zu||this.Zu.mr!==r||this.Zu.wr!==t)this.Zu={mr:r,wr:t,Hc:new Map};else{let t=this.Zu.Hc.get(e);if(void 0!==t)return t}let i=this.Sl.tt(r,t,e/100);return this.Zu.Hc.set(e,i),i}Uc(e){return this.qu.indexOf(e)}Xi(){return this.Sl}$c(){return this.qc()}qc(e){let t=new tk(this.uh,this);this.qu.push(t);let r=e??this.qu.length-1,i=eg.gn();return i.Qs(r,{tn:0,sn:!0}),this.rc(i),t}tc(e){return A(e>=0,"Index should be greater or equal to 0"),(e=Math.min(this.qu.length,e))<this.qu.length?this.qu[e]:this.qc(e)}Fc(e){return this.qu.findIndex(t=>t.Oo().includes(e))}gc(e,t){let r=new eg(t);
1if(null!==e){let i=this.qu.indexOf(e);r.Qs(i,{tn:t})}return r}hc(e,t){return void 0===t&&(t=2),this.gc(this.Hn(e),t)}rc(e){this.Gu&&this.Gu(e),this.qu.forEach(e=>e.i_().lr().yt())}Ec(e,t){let r=e.N().priceScaleId,i=void 0!==r?r:this.Oc();t.Gl(e,i),ex(i)||e.hr(e.N())}nc(e){let t=this.Ps.layout;return"gradient"===t.background.type?0===e?t.background.topColor:t.background.bottomColor:t.background.color}zc(e){!e.Lo()&&0===e.Ma().length&&this.qu.length>1&&this.qu.splice(this.Uc(e),1)}}function tR(e){if(e>=1)return 0;let t=0;for(;t<8&&!(1e-8>Math.abs(Math.round(e)-e));t++)e*=10;return t}function tD(e){return!I(e)&&!O(e)}(d=v||(v={}))[d.Disabled=0]="Disabled",d[d.Continuous=1]="Continuous",d[d.OnDataUpdate=2]="OnDataUpdate",(c=y||(y={}))[c.LastBar=0]="LastBar",c[c.LastVisible=1]="LastVisible",(u=w||(w={})).Solid="solid",u.VerticalGradient="gradient",(h=j||(j={}))[h.Year=0]="Year",h[h.Month=1]="Month",h[h.DayOfMonth=2]="DayOfMonth",h[h.Time=3]="Time",h[h.TimeWithSeconds=4]="TimeWithSeconds";class tI{constructor(e="yyyy-MM-dd",t="default"){this.Yc=e,this.jc=t}__(e){return function(e,t,r){return t.replace(/yyyy/g,ev(e.getUTCFullYear(),4)).replace(/yy/g,ev(e.getUTCFullYear()%100,2)).replace(/MMMM/g,new Date(e.getUTCFullYear(),e.getUTCMonth(),1).toLocaleString(r,{month:"long"})).replace(/MMM/g,new Date(e.getUTCFullYear(),e.getUTCMonth(),1).toLocaleString(r,{month:"short"})).replace(/MM/g,ev(e.getUTCMonth()+1,2)).replace(/dd/g,ev(e.getUTCDate(),2))}(e,this.Yc,this.jc)}}class tU{constructor(e){this.Kc=e||"%h:%m:%s"}__(e){return this.Kc.replace("%h",ev(e.getUTCHours(),2)).replace("%m",ev(e.getUTCMinutes(),2)).replace("%s",ev(e.getUTCSeconds(),2))}}let tO={Xc:"yyyy-MM-dd",Zc:"%h:%m:%s",Gc:" ",Jc:"default"};class tB{constructor(e={}){const t={...tO,...e};this.Qc=new tI(t.Xc,t.Jc),this.td=new tU(t.Zc),this.sd=t.Gc}__(e){return`${this.Qc.__(e)}${this.sd}${this.td.__(e)}`}}function tz(e){return 60*e*6e4}function t$(e){return 60*e*1e3}let tV=[{nd:1e3,ed:10},{nd:t$(1),ed:20},{nd:t$(5),ed:21},{nd:t$(30),ed:22},{nd:tz(1),ed:30},{nd:tz(3),ed:31},{nd:tz(6),ed:32},{nd:tz(12),ed:33}];function tH(e,t){if(e.getUTCFullYear()!==t.getUTCFullYear())return 70;if(e.getUTCMonth()!==t.getUTCMonth())return 60;if(e.getUTCDate()!==t.getUTCDate())return 50;for(let r=tV.length-1;r>=0;--r)if(Math.floor(t.getTime()/tV[r].nd)!==Math.floor(e.getTime()/tV[r].nd))return tV[r].ed;return 0}function tW(e){let t=e;if(O(e)&&(t=tK(e)),!tD(t))throw Error("time must be of type BusinessDay");return{rd:Math.round(new Date(Date.UTC(t.year,t.month-1,t.day,0,0,0,0)).getTime()/1e3),hd:t}}function tq(e){if(!I(e))throw Error("time must be of type isUTCTimestamp");return{rd:e}}function tK(e){let t=new Date(e);if(isNaN(t.getTime()))throw Error(`Invalid date string=${e}, expected format=yyyy-mm-dd`);return{day:t.getUTCDate(),month:t.getUTCMonth()+1,year:t.getUTCFullYear()}}function tG(e){O(e.time)&&(e.time=tK(e.time))}class tY{options(){return this.Ps}setOptions(e){this.Ps=e,this.updateFormatter(e.localization)}preprocessData(e){Array.isArray(e)?e.forEach(tG):tG(e)}createConverterToInternalObj(e){return L(0===e.length?null:tD(e[0].time)||O(e[0].time)?tW:tq)}key(e){return"object"==typeof e&&"rd"in e?e.rd:this.key(this.convertHorzItemToInternal(e))}cacheKey(e){return void 0===e.hd?new Date(1e3*e.rd).getTime():new Date(Date.UTC(e.hd.year,e.hd.month-1,e.hd.day)).getTime()}convertHorzItemToInternal(e){return I(e)?tq(e):tD(e)?tW(e):tW(tK(e))}updateFormatter(e){if(!this.Ps)return;let t=e.dateFormat;this.Ps.timeScale.timeVisible?this.ad=new tB({Xc:t,Zc:this.Ps.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",Gc:"   ",Jc:e.locale}):this.ad=new tI(t,e.locale)}formatHorzItem(e){return this.ad.__(new Date(1e3*e.rd))}formatTickmark(e,t){let r=function(e,t,r){switch(e){case 0:case 10:return t?r?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return t?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(e.weight,this.Ps.timeScale.timeVisible,this.Ps.timeScale.secondsVisible),i=this.Ps.timeScale;if(void 0!==i.tickMarkFormatter){let s=i.tickMarkFormatter(e.originalTime,r,t.locale);if(null!==s)return s}return function(e,t,r){let i={};switch(t){case 0:i.year="numeric";break;case 1:i.month="short";break;case 2:i.day="numeric";break;case 3:i.hour12=!1,i.hour="2-digit",i.minute="2-digit";break;case 4:i.hour12=!1,i.hour="2-digit",i.minute="2-digit",i.second="2-digit"}let s=new Date(void 0===e.hd?1e3*e.rd:Date.UTC(e.hd.year,e.hd.month-1,e.hd.day));return new Date(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate(),s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds(),s.getUTCMilliseconds()).toLocaleStr
1ing(r,i)}(e.time,r,t.locale)}maxTickMarkWeight(e){let t=e.reduce(tE,e[0]).weight;return t>30&&t<50&&(t=30),t}fillWeightsForPoints(e,t){!function(e,t=0){if(0===e.length)return;let r=0===t?null:e[t-1].time.rd,i=null!==r?new Date(1e3*r):null,s=0;for(let n=t;n<e.length;++n){let t=e[n],a=new Date(1e3*t.time.rd);null!==i&&(t.timeWeight=tH(a,i)),s+=t.time.rd-(r||t.time.rd),r=t.time.rd,i=a}if(0===t&&e.length>1){let t=Math.ceil(s/(e.length-1)),r=new Date(1e3*(e[0].time.rd-t));e[0].timeWeight=tH(new Date(1e3*e[0].time.rd),r)}}(e,t)}static ld(e){return D({localization:{dateFormat:"dd MMM 'yy"}},e??{})}}let tX="u">typeof window;function tQ(){return!!tX&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function tJ(){return!!tX&&/iPhone|iPad|iPod/.test(window.navigator.platform)}class tZ{constructor(e,t,r){this.od=0,this._d=null,this.ud={_t:-1/0,ut:1/0},this.dd=0,this.fd=null,this.pd={_t:-1/0,ut:1/0},this.vd=null,this.md=!1,this.wd=null,this.gd=null,this.Md=!1,this.bd=!1,this.Sd=!1,this.xd=null,this.Cd=null,this.Pd=null,this.yd=null,this.kd=null,this.Td=null,this.Rd=null,this.Dd=0,this.Vd=!1,this.Bd=!1,this.Id=!1,this.Ed=0,this.Ad=null,this.zd=!tJ(),this.Ld=e=>{this.Od(e)},this.Nd=e=>{if(this.Fd(e)){let t=this.Wd(e);if(++this.dd,this.fd&&this.dd>1){let{Hd:r}=this.Ud(t2(e),this.pd);r<30&&!this.Sd&&this.$d(t,this.Yd.qd),this.jd()}}else{let t=this.Wd(e);if(++this.od,this._d&&this.od>1){let{Hd:r}=this.Ud(t2(e),this.ud);r<5&&!this.bd&&this.Kd(t,this.Yd.Xd),this.Zd()}}},this.Gd=e,this.Yd=t,this.Ps=r,this.Jd()}m(){null!==this.xd&&(this.xd(),this.xd=null),null!==this.Cd&&(this.Cd(),this.Cd=null),null!==this.yd&&(this.yd(),this.yd=null),null!==this.kd&&(this.kd(),this.kd=null),null!==this.Td&&(this.Td(),this.Td=null),null!==this.Pd&&(this.Pd(),this.Pd=null),this.Qd(),this.Zd()}tf(e){this.yd&&this.yd();let t=this.if.bind(this);if(this.yd=()=>{this.Gd.removeEventListener("mousemove",t)},this.Gd.addEventListener("mousemove",t),this.Fd(e))return;let r=this.Wd(e);this.Kd(r,this.Yd.sf),this.zd=!0}Zd(){null!==this._d&&clearTimeout(this._d),this.od=0,this._d=null,this.ud={_t:-1/0,ut:1/0}}jd(){null!==this.fd&&clearTimeout(this.fd),this.dd=0,this.fd=null,this.pd={_t:-1/0,ut:1/0}}if(e){if(this.Id||null!==this.gd||this.Fd(e))return;let t=this.Wd(e);this.Kd(t,this.Yd.nf),this.zd=!0}ef(e){let t=t3(e.changedTouches,L(this.Ad));if(null===t||(this.Ed=t5(e),null!==this.Rd)||this.Bd)return;this.Vd=!0;let{rf:r,hf:i,Hd:s}=this.Ud(t2(t),L(this.gd));if(this.Md||!(s<5)){if(!this.Md){let e=.5*r,t=i>=e&&!this.Ps.af(),s=e>i&&!this.Ps.lf();t||s||(this.Bd=!0),this.Md=!0,this.Sd=!0,this.Qd(),this.jd()}if(!this.Bd){let r=this.Wd(e,t);this.$d(r,this.Yd._f),t1(e)}}}uf(e){if(0!==e.button)return;let{Hd:t}=this.Ud(t2(e),L(this.wd));if(t>=5&&(this.bd=!0,this.Zd()),this.bd){let t=this.Wd(e);this.Kd(t,this.Yd.cf)}}Ud(e,t){let r=Math.abs(t._t-e._t),i=Math.abs(t.ut-e.ut);return{rf:r,hf:i,Hd:r+i}}df(e){let t=t3(e.changedTouches,L(this.Ad));if(null===t&&0===e.touches.length&&(t=e.changedTouches[0]),null===t)return;this.Ad=null,this.Ed=t5(e),this.Qd(),this.gd=null,this.Td&&(this.Td(),this.Td=null);let r=this.Wd(e,t);if(this.$d(r,this.Yd.ff),++this.dd,this.fd&&this.dd>1){let{Hd:e}=this.Ud(t2(t),this.pd);e<30&&!this.Sd&&this.$d(r,this.Yd.qd),this.jd()}else this.Sd||(this.$d(r,this.Yd.pf),this.Yd.pf&&t1(e));0===this.dd&&t1(e),0===e.touches.length&&this.md&&(this.md=!1,t1(e))}Od(e){if(0!==e.button)return;let t=this.Wd(e);if(this.wd=null,this.Id=!1,this.kd&&(this.kd(),this.kd=null),tQ()&&this.Gd.ownerDocument.documentElement.removeEventListener("mouseleave",this.Ld),!this.Fd(e))if(this.Kd(t,this.Yd.vf),++this.od,this._d&&this.od>1){let{Hd:r}=this.Ud(t2(e),this.ud);r<5&&!this.bd&&this.Kd(t,this.Yd.Xd),this.Zd()}else this.bd||this.Kd(t,this.Yd.mf)}Qd(){null!==this.vd&&(clearTimeout(this.vd),this.vd=null)}wf(e){if(null!==this.Ad)return;let t=e.changedTouches[0];this.Ad=t.identifier,this.Ed=t5(e);let r=this.Gd.ownerDocument.documentElement;this.Sd=!1,this.Md=!1,this.Bd=!1,this.gd=t2(t),this.Td&&(this.Td(),this.Td=null);{let t=this.ef.bind(this),i=this.df.bind(this);this.Td=()=>{r.removeEventListener("touchmove",t),r.removeEventListener("touchend",i)},r.addEventListener("touchmove",t,{passive:!1}),r.addEventListener("touchend",i,{passive:!1}),this.Qd(),this.vd=setTimeout(this.gf.bind(this,e),240)}let i=this.Wd(e,t);this.$d(i,this.Yd.Mf),this.fd||(this.dd=0,this.fd=setTimeout(this.jd.bind(this),500),this.pd=t2(t))}bf(e){if(0!==e.button)return;let t=this.Gd.ownerDocument.documentElement;tQ()&&t.addEventListener("mouseleave",this.Ld),this.bd=!1,this.wd=t2(e),this.kd&&(this.kd(),this.kd=null);{let e=this.uf.bind(this),r=this.Od.bind(this);this.kd=()=>{t.removeEventListener("mousemove",e),t.removeEventListener("mouseup",r)},t.addEventListener("mousemove",e),t.addEventListener("mouseup",r)}if(this.Id=!0,this.Fd(e))return;let r=this.Wd(e);this.Kd(r,this.Yd.Sf),this._d||(this.od=0,this._d=setTimeout(this.Zd.bind(this),500),this.ud=t2(e))}Jd(){var e;this.Gd.addEventListener("mouseenter",this.tf.bind(this)),this.Gd.addEventListener("touchcancel",this.Qd.bind(this));{let e=this.Gd.ownerDocument,t=e=>{this.Yd.xf&&(e.composed&&this.Gd.contains(e.composedPath()[0])||e.target&&this.Gd.contains(e.target)||this.Yd.xf())};this.Cd=()=>{e.removeEventListener("touchstart",t)},this.xd=()=>{e.removeEventListener("mousedown",t)},e.addEventListener("mousedown",t),e.addEventListener("touchstart",t,{passive:!0})}tJ()&&(this.Pd=()=>{this.Gd.removeEventListener("dblclick",this.Nd)},this.Gd.addEventListener("dblclick",this.Nd)),this.Gd.addEventListener("mouseleave",this.Cf.bind(this)),this.Gd.addEventListener("touchstart",this.wf.bind(this),{passive:!0}),e=this.Gd,tX&&void 0!==window.chrome&&e.addEventListener("mousedown",e=>{if(1===e.button)return e.preventDefault(),!1}),this.Gd.addEventListener("mousedown",this.bf.bind(this)),this.Pf(),this.Gd.addEventListener("touchmove",()=>{},{passive:!1})}Pf(){void 0===this.Yd.yf&&void 0===this.Yd.kf&&void 0===this.Yd.Tf||(this.Gd.addEventListener("touchstart",e=>this.Rf(e.touches),{passive:!0}),this.Gd.addEventListener("touchmove",e=>{if(2===e.touches.length&&null!==this.Rd&&void 0!==this.Yd.kf){let t=t0(e.touches[0],e.touches[1])/this.Dd;this.Yd.kf(this.Rd,t),t1(e)}},{passive:!1}),this.Gd.addEventListener("touchend",e=>{this.Rf(e.touches)}))}Rf(e){1===e.length&&(this.Vd=!1),2!==e.length||this.Vd||this.md?this.Df():this.Vf(e)}Vf(e){let t=this.Gd.getBoundingClientRect()||{left:0,top:0};this.Rd={_t:(e[0].clientX-t.left+(e[1].clientX-t.left))/2,ut:(e[0].clientY-t.top+(e[1].clientY-t.top))/2},this.Dd=t0(e[0],e[1]),void 0!==this.Yd.yf&&this.Yd.yf(),this.Qd()}Df(){null!==this.Rd&&(this.Rd=null,void 0!==this.Yd.Tf&&this.Yd.Tf())}Cf(e){if(this.yd&&this.yd(),this.Fd(e)||!this.zd)return;let t=this.Wd(e);this.Kd(t,this.Yd.Bf),this.zd=!tJ()}gf(e){let t=t3(e.touches,L(this.Ad));if(null===t)return;let r=this.Wd(e,t);this.$d(r,this.Yd.If),this.Sd=!0,this.md=!0}Fd(e){return e.sourceCapabilities&&void 0!==e.sourceCapabilities.firesTouchEvents?e.sourceCapabilities.firesTouchEvents:t5(e)<this.Ed+500}$d(e,t){t&&t.call(this.Yd,e)}Kd(e,t){t&&t.call(this.Yd,e)}Wd(e,t){let r=t||e,i=this.Gd.getBoundingClientRect()||{left:0,top:0};return{clientX:r.clientX,clientY:r.clientY,pageX:r.pageX,pageY:r.pageY,screenX:r.screenX,screenY:r.screenY,localX:r.clientX-i.left,localY:r.clientY-i.top,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,Ef:!e.type.startsWith("mouse")&&"contextmenu"!==e.type&&"click"!==e.type,Af:e.type,zf:r.target,a_:e.view,Lf:()=>{"touchstart"!==e.type&&t1(e)}}}}function t0(e,t){let r=e.clientX-t.clientX,i=e.clientY-t.clientY;return Math.sqrt(r*r+i*i)}function t1(e){e.cancelable&&e.preventDefault()}function t2(e){return{_t:e.pageX,ut:e.pageY}}function t5(e){return e.timeStamp||performance.now()}function t3(e,t){for(let r=0;r<e.length;++r)if(e[r].identifier===t)return e[r];return null}class t4{constructor(e,t,r){this.Of=null,this.Nf=null,this.Ff=!0,this.Wf=null,this.Hf=e,this.Uf=e.$f()[t],this.qf=e.$f()[r],this.Yf=document.createElement("tr"),this.Yf.style.height="1px",this.jf=document.createElement("td"),this.jf.style.position="relative",this.jf.style.padding="0",this.jf.style.margin="0",this.jf.setAttribute("colspan","3"),this.Kf(),this.Yf.appendChild(this.jf),this.Ff=this.Hf.N().layout.panes.enableResize,this.Ff?this.Xf():(this.Of=null,this.Nf=null)}m(){null!==this.Nf&&this.Nf.m()}Zf(){return this.Yf}Gf(){return t({width:this.Uf.Gf().width,height:1})}Jf(){return t({width:this.Uf.Jf().width,height:+window.devicePixelRatio})}Qf(e,t,r){let i=this.Jf();e.fillStyle=this.Hf.N().layout.panes.separatorColor,e.fillRect(t,r,i.width,i.height)}yt(){this.Kf(),this.Hf.N().layout.panes.enableResize!==this.Ff&&(this.Ff=this.Hf.N().layout.panes.enableResize,this.Ff?this.Xf():(null!==this.Of&&(this.jf.removeChild(this.Of.tp),this.jf.removeChild(this.Of.ip),this.Of=null),null!==this.Nf&&(this.Nf.m(),this.Nf=null)))}Xf(){let e=document.createElement("div"),t=e.style;t.position="fixed",t.display="none",t.zIndex="49",t.top="0",t.left="0",t.width="100%",t.height="100%",t.cursor="row-resize",this.jf.appendChild(e);let r=document.createElement("div"),i=r.style;i.position="absolute",i.zIndex="50",i.top="-4px",i.height="9px",i.width="100%",i.backgroundColor="",i.cursor="row-resize",this.jf.appendChild(r);let s={sf:this.sp.bind(this),Bf:this.np.bind(this),Sf:this.ep.bind(this),Mf:this.ep.bind(this),cf:this.rp.bind(this),_f:this.rp.bind(this),vf:this.hp.bind(this),ff:this.hp.bind(this)};this.Nf=new tZ(r,s,{af:()=>!1,lf:()=>!0}),this.Of={ip:r,tp:e}}Kf(){this.jf.style.background=this.Hf.N().layout.panes.separatorColor}sp(e){null!==this.Of&&(this.Of.ip.style.backgroundColor=this.Hf.N().layout.panes.separatorHoverColor)}np(e){null!==this.Of&&null===this.Wf&&(this.Of.ip.style.backgroundColor="")}ep(e){if(null===this.Of)return;let t=this.Uf.ap().Bo()+this.qf.ap().Bo(),r=t/(this.Uf.Gf().height+this.qf.Gf().height),i=30*r;t<=2*i||(this.Wf={lp:e.pageY,op:this.Uf.ap().Bo(),_p:t-i,up:t,cp:r,dp:i},this.Of.tp.style.display="block")}rp(e){let t=this.Wf;if(null===t)return;let r=(e.pageY-t.lp)*t.cp,i=tn(t.op+r,t.dp,t._p);this.Uf.ap().Io(i),this.qf.ap().Io(t.up-i),this.Hf.Qt().Ih()}hp(e){null!==this.Wf&&null!==this.Of&&(this.Wf=null,this.Of.tp.style.display="none")}}function t6(e,t,r){let i=(e.fp-t.fp)/(e.wt-t.wt);return Math.sign(i)*Math.min(Math.abs(i),r)}
1class t8{constructor(e,t,r,i){this.pp=null,this.vp=null,this.mp=null,this.wp=null,this.gp=null,this.Mp=0,this.bp=0,this.Sp=e,this.xp=t,this.Cp=r,this.Mn=i}Pp(e,t){if(null!==this.pp){if(this.pp.wt===t)return void(this.pp.fp=e);if(Math.abs(this.pp.fp-e)<this.Mn)return}this.wp=this.mp,this.mp=this.vp,this.vp=this.pp,this.pp={wt:t,fp:e}}le(e,t){var r,i,s,n,a,l,o;let d;if(null===this.pp||null===this.vp||t-this.pp.wt>50)return;let c=0,u=t6(this.pp,this.vp,this.xp),h=(r=this.pp,i=this.vp,r.fp-i.fp),p=[u],m=[h];if(c+=h,null!==this.mp){let e=t6(this.vp,this.mp,this.xp);if(Math.sign(e)===Math.sign(u)){let t=(s=this.vp,n=this.mp,s.fp-n.fp);if(p.push(e),m.push(t),c+=t,null!==this.wp){let e=t6(this.mp,this.wp,this.xp);if(Math.sign(e)===Math.sign(u)){let t=(a=this.mp,l=this.wp,a.fp-l.fp);p.push(e),m.push(t),c+=t}}}}let f=0;for(let e=0;e<p.length;++e)f+=m[e]/c*p[e];Math.abs(f)<this.Sp||(this.gp={fp:e,wt:t},this.bp=f,this.Mp=(o=Math.abs(f),Math.log(-((d=Math.log(this.Cp))/o))/d))}Du(e){let t=L(this.gp),r=e-t.wt;return t.fp+this.bp*(Math.pow(this.Cp,r)-1)/Math.log(this.Cp)}Ru(e){return null===this.gp||this.yp(e)===this.Mp}yp(e){return Math.min(e-L(this.gp).wt,this.Mp)}}class t9{constructor(e,t){this.kp=void 0,this.Tp=void 0,this.Rp=void 0,this.ps=!1,this.Dp=e,this.Vp=t,this.Bp()}yt(){this.Bp()}Ip(){this.kp&&this.Dp.removeChild(this.kp),this.Tp&&this.Dp.removeChild(this.Tp),this.kp=void 0,this.Tp=void 0}Ep(){return this.ps!==this.Ap()||this.Rp!==this.zp()}zp(){return this.Vp.Qt().Xi().J(this.Vp.N().layout.textColor)>160?"dark":"light"}Ap(){return this.Vp.N().layout.attributionLogo}Lp(){let e=new URL(location.href);return e.hostname?"&utm_source="+e.hostname+e.pathname:""}Bp(){this.Ep()&&(this.Ip(),this.ps=this.Ap(),this.ps&&(this.Rp=this.zp(),this.Tp=document.createElement("style"),this.Tp.innerText="a#tv-attr-logo{--fill:#131722;--stroke:#fff;position:absolute;left:10px;bottom:10px;height:19px;width:35px;margin:0;padding:0;border:0;z-index:3;}a#tv-attr-logo[data-dark]{--fill:#D1D4DC;--stroke:#131722;}",this.kp=document.createElement("a"),this.kp.href=`https://www.tradingview.com/?utm_medium=lwc-link&utm_campaign=lwc-chart${this.Lp()}`,this.kp.title="Charting by TradingView",this.kp.id="tv-attr-logo",this.kp.target="_blank",this.kp.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="35" height="19" fill="none"><g fill-rule="evenodd" clip-path="url(#a)" clip-rule="evenodd"><path fill="var(--stroke)" d="M2 0H0v10h6v9h21.4l.5-1.3 6-15 1-2.7H23.7l-.5 1.3-.2.6a5 5 0 0 0-7-.9V0H2Zm20 17h4l5.2-13 .8-2h-7l-1 2.5-.2.5-1.5 3.8-.3.7V17Zm-.8-10a3 3 0 0 0 .7-2.7A3 3 0 1 0 16.8 7h4.4ZM14 7V2H2v6h6v9h4V7h2Z"/><path fill="var(--fill)" d="M14 2H2v6h6v9h6V2Zm12 15h-7l6-15h7l-6 15Zm-7-9a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"/></g><defs><clipPath id="a"><path fill="var(--stroke)" d="M0 0h35v19H0z"/></clipPath></defs></svg>',this.kp.toggleAttribute("data-dark","dark"===this.Rp),this.Dp.appendChild(this.Tp),this.Dp.appendChild(this.kp)))}}function t7(e,t){let r=L(e.ownerDocument).createElement("canvas");e.appendChild(r);let i=function(e,t){if("device-pixel-content-box"===t.type)return new k(e,t.transform,t.options);throw Error("Unsupported binding target")}(r,{type:"device-pixel-content-box",options:{allowResizeObserver:!0},transform:(e,t)=>({width:Math.max(e.width,t.width),height:Math.max(e.height,t.height)})});return i.resizeCanvasElement(t),i}function re(e){e.width=1,e.height=1,e.getContext("2d")?.clearRect(0,0,1,1)}function rt(e,t,r,i){e.ih&&e.ih(t,r,i)}function rr(e,t,r,i){e.nt(t,r,i)}function ri(e,t,r,i){for(let s of e(r,i)){let e=s.Tt(i);null!==e&&t(e)}}function rs(e,t){return r=>void 0===r.Ft||(r.Ft()?.ma()??"")!==t?[]:r.ta?.(e)??[]}function rn(e,t,r,i){if(!e.length)return;let s=0,n=e[0].$t(i,!0),a=1===t?r/2-(e[0].Fi()-n/2):e[0].Fi()-n/2-r/2;a=Math.max(0,a);for(let n=1;n<e.length;n++){let l=e[n],o=e[n-1],d=o.$t(i,!1),c=l.Fi(),u=o.Fi();if(1===t?c>u-d:c<u+d){let i=u-d*t;l.Wi(i);let n=i-t*d/2;if((1===t?n<0:n>r)&&a>0){let i=Math.min(1===t?-1-n:n-r,a);for(let r=s;r<e.length;r++)e[r].Wi(e[r].Fi()+t*i);a-=i}}else s=n,a=1===t?u-d-c:c-(u+d)}}class ra{constructor(e,r,i,s){this.Yi=null,this.Op=null,this.Np=!1,this.Fp=new ek(200),this.Wp=null,this.Hp=0,this.Up=!1,this.$p=()=>{this.Up||this.Pt.qp().Qt().ar()},this.Yp=()=>{this.Up||this.Pt.qp().Qt().ar()},this.Pt=e,this.Ps=r,this.Ml=r.layout,this.Ju=i,this.jp="left"===s,this.Kp=rs("normal",s),this.Xp=rs("top",s),this.Zp=rs("bottom",s),this.jf=document.createElement("div"),this.jf.style.height="100%",this.jf.style.overflow="hidden",this.jf.style.width="25px",this.jf.style.left="0",this.jf.style.position="relative",this.Gp=t7(this.jf,t({width:16,height:16})),this.Gp.subscribeSuggestedBitmapSizeChanged(this.$p);const n=this.Gp.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Jp=t7(this.jf,t({width:16,height:16})),this.Jp.subscribeSuggestedBitmapSizeChanged(this.Yp);const a=this.Jp.canvasElement;a.style.position="absolute",a.style.zIndex="2",a.style.left="0",a.style.top="0";const l={Sf:this.ep.bind(this),Mf:this.ep.bind(this),cf:this.rp.bind(this),_f:this.rp.bind(this),xf:this.Qp.bind(this),vf:this.hp.bind(this),ff:this.hp.bind(this),Xd:this.tv.bind(this),qd:this.tv.bind(this),sf:this.iv.bind(this),Bf:this.np.bind(this)};this.Nf=new tZ(this.Jp.canvasElement,l,{af:()=>!this.Ps.handleScroll.vertTouchDrag,lf:()=>!0})}m(){this.Nf.m(),this.Jp.unsubscribeSuggestedBitmapSizeChanged(this.Yp),re(this.Jp.canvasElement),this.Jp.dispose(),this.Gp.unsubscribeSuggestedBitmapSizeChanged(this.$p),re(this.Gp.canvasElement),this.Gp.dispose(),null!==this.Yi&&this.Yi.so().u(this),this.Yi=null}Zf(){return this.jf}P(){return this.Ml.fontSize}sv(){let e=this.Ju.N();return this.Wp!==e.k&&(this.Fp.Bn(),this.Wp=e.k),e}nv(){var e,t;if(null===this.Yi)return 0;let r=0,i=this.sv(),s=L(this.Gp.canvasElement.getContext("2d",{colorSpace:this.Pt.qp().N().layout.colorSpace}));s.save();let n=this.Yi.Da();s.font=this.ev(),n.length>0&&(r=Math.max(this.Fp.Vi(s,n[0].Za),this.Fp.Vi(s,n[n.length-1].Za)));let a=this.rv();for(let e=a.length;e--;){let t=this.Fp.Vi(s,a[e].ri());t>r&&(r=t)}let l=this.Yi.zt();if(null!==l&&null!==this.Op&&2!==(e=this.Ps.crosshair).mode&&e.horzLine.visible&&e.horzLine.labelVisible){let e=this.Yi.Ts(1,l),t=this.Yi.Ts(this.Op.height-2,l);r=Math.max(r,this.Fp.Vi(s,this.Yi.Zi(Math.floor(Math.min(e,t))+.11111111111111,l)),this.Fp.Vi(s,this.Yi.Zi(Math.ceil(Math.max(e,t))-.11111111111111,l)))}
1s.restore();let o=r||34;return(t=Math.ceil(i.S+i.C+i.B+i.I+5+o))+t%2}hv(e){null!==this.Op&&r(this.Op,e)||(this.Op=e,this.Up=!0,this.Gp.resizeCanvasElement(e),this.Jp.resizeCanvasElement(e),this.Up=!1,this.jf.style.width=`${e.width}px`,this.jf.style.height=`${e.height}px`)}av(){return L(this.Op).width}_s(e){this.Yi!==e&&(null!==this.Yi&&this.Yi.so().u(this),this.Yi=e,e.so().i(this._l.bind(this),this))}Ft(){return this.Yi}Bn(){let e=this.Pt.ap();this.Pt.qp().Qt().Zo(e,L(this.Ft()))}lv(e){if(null===this.Op)return;let t={colorSpace:this.Pt.qp().N().layout.colorSpace};if(1!==e){this.ov(),this.Gp.applySuggestedBitmapSize();let e=T(this.Gp,t);null!==e&&(e.useBitmapCoordinateSpace(e=>{this._v(e),this.uv(e)}),this.Pt.cv(e,this.Zp),this.dv(e),this.Pt.cv(e,this.Kp),this.fv(e))}this.Jp.applySuggestedBitmapSize();let r=T(this.Jp,t);null!==r&&(r.useBitmapCoordinateSpace(({context:e,bitmapSize:t})=>{e.clearRect(0,0,t.width,t.height)}),this.pv(r),this.Pt.cv(r,this.Xp))}Jf(){return this.Gp.bitmapSize}Qf(e,t,r,i){let s=this.Jf();if(s.width>0&&s.height>0&&(e.drawImage(this.Gp.canvasElement,t,r),i)){let i=this.Jp.canvasElement;e.drawImage(i,t,r)}}yt(){this.Yi?.Da()}ep(e){if(null===this.Yi||this.Yi.Ki()||!this.Ps.handleScale.axisPressedMouseMove.price)return;let t=this.Pt.qp().Qt(),r=this.Pt.ap();this.Np=!0,t.Uo(r,this.Yi,e.localY)}rp(e){if(null===this.Yi||!this.Ps.handleScale.axisPressedMouseMove.price)return;let t=this.Pt.qp().Qt(),r=this.Pt.ap(),i=this.Yi;t.$o(r,i,e.localY)}Qp(){if(null===this.Yi||!this.Ps.handleScale.axisPressedMouseMove.price)return;let e=this.Pt.qp().Qt(),t=this.Pt.ap(),r=this.Yi;this.Np&&(this.Np=!1,e.qo(t,r))}hp(e){if(null===this.Yi||!this.Ps.handleScale.axisPressedMouseMove.price)return;let t=this.Pt.qp().Qt(),r=this.Pt.ap();this.Np=!1,t.qo(r,this.Yi)}tv(e){this.Ps.handleScale.axisDoubleClickReset.price&&this.Bn()}iv(e){null!==this.Yi&&(!this.Pt.qp().Qt().N().handleScale.axisPressedMouseMove.price||this.Yi.Le()||this.Yi.Dl()||this.vv(1))}np(e){this.vv(0)}rv(){let e=[],t=null===this.Yi?void 0:this.Yi;return(r=>{for(let i=0;i<r.length;++i){let s=r[i].Ws(this.Pt.ap(),t);for(let t=0;t<s.length;t++)e.push(s[t])}})(this.Pt.ap().Dt()),e}_v({context:e,bitmapSize:t}){let{width:r,height:i}=t,s=this.Pt.ap().Qt(),n=s.$(),a=s.Wc();n===a?es(e,0,0,r,i,n):el(e,0,0,r,i,n,a)}uv({context:e,bitmapSize:t,horizontalPixelRatio:r}){let i;if(null===this.Op||null===this.Yi||!this.Yi.N().borderVisible)return;e.fillStyle=this.Yi.N().borderColor;let s=Math.max(1,Math.floor(this.sv().S*r));i=this.jp?t.width-s:0,e.fillRect(i,0,s,t.height)}dv(e){if(null===this.Op||null===this.Yi)return;let t=this.Yi.Da(),r=this.Yi.N(),i=this.sv(),s=this.jp?this.Op.width-i.C:0;r.borderVisible&&r.ticksVisible&&e.useBitmapCoordinateSpace(({context:e,horizontalPixelRatio:n,verticalPixelRatio:a})=>{e.fillStyle=r.borderColor;let l=Math.max(1,Math.floor(a)),o=Math.floor(.5*a),d=Math.round(i.C*n);for(let r of(e.beginPath(),t))e.rect(Math.floor(s*n),Math.round(r.Pa*a)-o,d,l);e.fill()}),e.useMediaCoordinateSpace(({context:e})=>{e.font=this.ev(),e.fillStyle=r.textColor??this.Ml.textColor,e.textAlign=this.jp?"right":"left",e.textBaseline="middle";let n=this.jp?Math.round(s-i.B):Math.round(s+i.C+i.B),a=t.map(t=>this.Fp.Di(e,t.Za));for(let r=t.length;r--;){let i=t[r];e.fillText(i.Za,n,i.Pa+a[r])}})}ov(){if(null===this.Op||null===this.Yi)return;let e=this.Op.height/2,t=[],r=this.Yi.Dt().slice(),i=this.Pt.ap(),s=this.sv();this.Yi===i.$n()&&this.Pt.ap().Dt().forEach(e=>{i.Un(e)&&r.push(e)});let n=this.Yi.Ma()[0],a=this.Yi;r.forEach(r=>{let s=r.Ws(i,a);s.forEach(e=>{e.Wi(null),e.Hi()&&t.push(e)}),n===r&&s.length>0&&(e=s[0].Ii())}),t.forEach(e=>e.Wi(e.Ii())),this.Yi.N().alignLabels&&this.mv(t,s,e)}mv(e,t,r){if(null===this.Op)return;let i=e.filter(e=>e.Ii()<=r),s=e.filter(e=>e.Ii()>r);for(let r of(i.sort((e,t)=>t.Ii()-e.Ii()),i.length&&s.length&&s.push(i[0]),s.sort((e,t)=>e.Ii()-t.Ii()),e)){let e=Math.floor(r.$t(t)/2),i=r.Ii();i>-e&&i<e&&r.Wi(e),i>this.Op.height-e&&i<this.Op.height+e&&r.Wi(this.Op.height-e)}rn(i,1,this.Op.height,t),rn(s,-1,this.Op.height,t)}fv(e){if(null===this.Op)return;let t=this.rv(),r=this.sv(),i=this.jp?"right":"left";t.forEach(t=>{t.Ui()&&t.Tt(L(this.Yi)).nt(e,r,this.Fp,i)})}pv(e){if(null===this.Op||null===this.Yi)return;let t=this.Pt.qp().Qt(),r=[],i=this.Pt.ap(),s=t.uc().Ws(i,this.Yi);s.length&&r.push(s);let n=this.sv(),a=this.jp?"right":"left";r.forEach(t=>{t.forEach(t=>{t.Tt(L(this.Yi)).nt(e,n,this.Fp,a)})})}vv(e){this.jf.style.cursor=1===e?"ns-resize":"default"}_l(){let e=this.nv();this.Hp<e&&this.Pt.qp().Qt().Ih(),this.Hp=e}ev(){return W(this.Ml.fontSize,this.Ml.fontFamily)}}function rl(e,t){return e.Jh?.(t)??[]}function ro(e,t){return e.Fs?.(t)??[]}function rd(e,t){return e.us?.(t)??[]}function rc(e,t){return e.Xh?.(t)??[]}class ru{constructor(e,r){this.Op=t({width:0,height:0}),this.wv=null,this.gv=null,this.Mv=null,this.bv=null,this.Sv=!1,this.xv=new R,this.Cv=new R,this.Pv=0,this.yv=!1,this.kv=null,this.Tv=!1,this.Rv=null,this.Dv=null,this.Up=!1,this.$p=()=>{this.Up||null===this.Vv||this.ts().ar()},this.Yp=()=>{this.Up||null===this.Vv||this.ts().ar()},this.Vp=e,this.Vv=r,this.Vv.t_().i(this.Bv.bind(this),this,!0),this.Iv=document.createElement("td"),this.Iv.style.padding="0",this.Iv.style.position="relative";const i=document.createElement("div");i.style.width="100%",i.style.height="100%",i.style.position="relative",i.style.overflow="hidden",this.Ev=document.createElement("td"),this.Ev.style.padding="0",this.Av=document.createElement("td"),this.Av.style.padding="0",this.Iv.appendChild(i),this.Gp=t7(i,t({width:16,height:16})),this.Gp.subscribeSuggestedBitmapSizeChanged(this.$p);const s=this.Gp.canvasElement;s.style.position="absolute",s.style.zIndex="1",s.style.left="0",s.style.top="0",this.Jp=t7(i,t({width:16,height:16})),this.Jp.subscribeSuggestedBitmapSizeChanged(this.Yp);const n=this.Jp.canvasElement;n.style.position="absolute",n.style.zIndex="2",n.style.left="0",n.style.top="0",this.Yf=document.createElement("tr"),this.Yf.appendChild(this.Ev),this.Yf.appendChild(this.Iv),this.Yf.appendChild(this.Av),this.zv(),this.Nf=new tZ(this.Jp.canvasElement,this,{af:()=>null===this.kv&&!this.Vp.N().handleScroll.vertTouchDrag,lf:()=>null===this.kv&&!this.Vp.N().handleScroll.horzTouchDrag})}m(){null!==this.wv&&this.wv.m(),null!==this.gv&&this.gv.m(),this.Mv=null,this.Jp.unsubscribeSuggestedBitmapSizeChanged(this.Yp),re(this.Jp.canvasElement),this.Jp.dispose(),this.Gp.unsubscribeSuggestedBitmapSizeChanged(this.$p),re(this.Gp.canvasElement),this.Gp.dispose(),null!==this.Vv&&(this.Vv.t_().u(this),this.Vv.m()),this.Nf.m()}ap(){return L(this.Vv)}Lv(e){null!==this.Vv&&this.Vv.t_().u(this),this.Vv=e,null!==this.Vv&&this.Vv.t_().i(ru.prototype.Bv.bind(this),this,!0),this.zv(),this.Vp.$f().indexOf(this)===this.Vp.$f().length-1?(this.Mv=this.Mv??new t9(this.Iv,this.Vp),this.Mv.yt()):(this.Mv?.Ip(),this.Mv=null)}qp(){return this.Vp}Zf(){return this.Yf}zv(){if(null!==this.Vv&&(this.Ov(),0!==this.ts().js().length)){if(null!==this.wv){let e=this.Vv.Wo();this.wv._s(L(e))}if(null!==this.gv){let e=this.Vv.Ho();this.gv._s(L(e))}}}Nv(){null!==this.wv&&this.wv.yt(),null!==this.gv&&this.gv.yt()}Bo(){return null!==this.Vv?this.Vv.Bo():0}Io(e){this.Vv&&this.Vv.Io(e)}sf(e){if(!this.Vv)return;this.Fv();let t=e.localX,r=e.localY;this.Wv(t,r,e)}Sf(e){this.Fv(),this.Hv(),this.Wv(e.localX,e.localY,e)}nf(e){if(!this.Vv)return;this.Fv();let t=e.localX,r=e.localY;this.Wv(t,r,e)}mf(e){null!==this.Vv&&(this.Fv(),this.Uv(e))}Xd(e){null!==this.Vv&&this.$v(this.Cv,e)}qd(e){this.Xd(e)}cf(e){this.Fv(),this.qv(e),this.Wv(e.localX,e.localY,e)}vf(e){null!==this.Vv&&(this.Fv(),this.yv=!1,this.Yv(e))}pf(e){null!==this.Vv&&this.Uv(e)}If(e){if(this.yv=!0,null===this.kv){let t={x:e.localX,y:e.localY};this.jv(t,t,e)}}Bf(e){null!==this.Vv&&(this.Fv(),this.Vv.Qt().lc(null),this.Kv())}Xv(){return this.xv}Zv(){return this.Cv}yf(){this.Pv=1,this.ts().hn()}kf(e,t){if(!this.Vp.N().handleScale.pinch)return;let r=5*(t-this.Pv);this.Pv=t,this.ts().bc(e._t,r)}Mf(e){this.yv=!1,this.Tv=null!==this.kv,this.Hv();let t=this.ts().uc();null!==this.kv&&t.Vt()&&(this.Rv={x:t.si(),y:t.ni()},this.kv={x:e.localX,y:e.localY})}_f(e){if(null===this.Vv)return;let t=e.localX,r=e.localY;if(null===this.kv)this.qv(e);else{this.Tv=!1;let i=L(this.Rv),s=i.x+(t-this.kv.x),n=i.y+(r-this.kv.y);this.Wv(s,n,e)}}ff(e){0===this.qp().N().trackingMode.exitMode&&(this.Tv=!0),this.Gv(),this.Yv(e)}jn(e,t){let r=this.Vv;return null===r?null:tP(r,e,t)}Jv(e,r){L("left"===r?this.wv:this.gv).hv(t({width:e,height:this.Op.height}))}Gf(){return this.Op}hv(e){r(this.Op,e)||(this.Op=e,this.Up=!0,this.Gp.resizeCanvasElement(e),this.Jp.resizeCanvasElement(e),this.Up=!1,this.Iv.style.width=e.width+"px",this.Iv.style.height=e.height+"px")}Qv(){let e=L(this.Vv);for(let t of(e.Fo(e.Wo()),e.Fo(e.Ho()),e.Ma()))if(e.Un(t)){let r=t.Ft();
1null!==r&&e.Fo(r),t.Ns()}for(let t of e.s_())t.Ns()}Jf(){return this.Gp.bitmapSize}Qf(e,t,r,i){let s=this.Jf();if(s.width>0&&s.height>0&&(e.drawImage(this.Gp.canvasElement,t,r),i)){let i=this.Jp.canvasElement;null!==e&&e.drawImage(i,t,r)}}lv(e){if(0===e||null===this.Vv)return;e>1&&this.Qv(),null!==this.wv&&this.wv.lv(e),null!==this.gv&&this.gv.lv(e);let t={colorSpace:this.Vp.N().layout.colorSpace};if(1!==e){this.Gp.applySuggestedBitmapSize();let e=T(this.Gp,t);null!==e&&(e.useBitmapCoordinateSpace(e=>{this._v(e)}),this.Vv&&(this.tm(e,rl),this.im(e),this.tm(e,ro),this.tm(e,rd)))}this.Jp.applySuggestedBitmapSize();let r=T(this.Jp,t);null!==r&&(r.useBitmapCoordinateSpace(({context:e,bitmapSize:t})=>{e.clearRect(0,0,t.width,t.height)}),this.sm(r),this.tm(r,rc),this.tm(r,rd))}nm(){return this.wv}rm(){return this.gv}cv(e,t){this.tm(e,t)}Bv(){null!==this.Vv&&this.Vv.t_().u(this),this.Vv=null}Uv(e){this.$v(this.xv,e)}$v(e,t){let r=t.localX,i=t.localY;e.v()&&e.p(this.ts().Et().cu(r),{x:r,y:i},t)}_v({context:e,bitmapSize:t}){let{width:r,height:i}=t,s=this.ts(),n=s.$(),a=s.Wc();n===a?es(e,0,0,r,i,a):el(e,0,0,r,i,n,a)}im(e){let t=L(this.Vv),r=t.i_().lr().Tt(t);null!==r&&r.nt(e,!1)}sm(e){this.hm(e,ro,rr,this.ts().uc())}tm(e,t){let r=L(this.Vv),i=r.Dt(),s=r.s_();for(let r of s)this.hm(e,t,rt,r);for(let r of i)this.hm(e,t,rt,r);for(let r of s)this.hm(e,t,rr,r);for(let r of i)this.hm(e,t,rr,r)}hm(e,t,r,i){let s=L(this.Vv),n=s.Qt().ac(),a=null!==n&&n.n_===i,l=null!==n&&a&&void 0!==n.e_?n.e_.Xn:void 0;ri(t,t=>r(t,e,a,l),i,s)}Ov(){if(null===this.Vv)return;let e=this.Vp,t=this.Vv.Wo().N().visible,r=this.Vv.Ho().N().visible;t||null===this.wv||(this.Ev.removeChild(this.wv.Zf()),this.wv.m(),this.wv=null),r||null===this.gv||(this.Av.removeChild(this.gv.Zf()),this.gv.m(),this.gv=null);let i=e.Qt().Bc();t&&null===this.wv&&(this.wv=new ra(this,e.N(),i,"left"),this.Ev.appendChild(this.wv.Zf())),r&&null===this.gv&&(this.gv=new ra(this,e.N(),i,"right"),this.Av.appendChild(this.gv.Zf()))}am(e){return e.Ef&&this.yv||null!==this.kv}lm(e){return Math.max(0,Math.min(e,this.Op.width-1))}om(e){return Math.max(0,Math.min(e,this.Op.height-1))}Wv(e,t,r){this.ts().Tc(this.lm(e),this.om(t),r,L(this.Vv))}Kv(){this.ts().Dc()}Gv(){this.Tv&&(this.kv=null,this.Kv())}jv(e,t,r){this.kv=e,this.Tv=!1,this.Wv(t.x,t.y,r);let i=this.ts().uc();this.Rv={x:i.si(),y:i.ni()}}ts(){return this.Vp.Qt()}Yv(e){if(!this.Sv)return;let t=this.ts(),r=this.ap();if(t.Ko(r,r.ks()),this.bv=null,this.Sv=!1,t.Pc(),null!==this.Dv){let e=performance.now(),r=t.Et();this.Dv.le(r.gu(),e),this.Dv.Ru(e)||t._n(this.Dv)}}Fv(){this.kv=null}Hv(){if(this.Vv){if(this.ts().hn(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)L(document.activeElement).blur();else{let e=document.getSelection();null!==e&&e.removeAllRanges()}this.Vv.ks().Ki()||this.ts().Et().Ki()}}qv(e){if(null===this.Vv)return;let t=this.ts(),r=t.Et();if(r.Ki())return;let i=this.Vp.N(),s=i.handleScroll,n=i.kineticScroll;if((!s.pressedMouseMove||e.Ef)&&(!s.horzTouchDrag&&!s.vertTouchDrag||!e.Ef))return;let a=this.Vv.ks(),l=performance.now();if(null!==this.bv||this.am(e)||(this.bv={x:e.clientX,y:e.clientY,rd:l,_m:e.localX,um:e.localY}),null!==this.bv&&!this.Sv&&(this.bv.x!==e.clientX||this.bv.y!==e.clientY)){if(e.Ef&&n.touch||!e.Ef&&n.mouse){let e=r.mu();this.Dv=new t8(.2/e,7/e,.997,15/e),this.Dv.Pp(r.gu(),this.bv.rd)}else this.Dv=null;a.Ki()||t.Yo(this.Vv,a,e.localY),t.xc(e.localX),this.Sv=!0}this.Sv&&(a.Ki()||t.jo(this.Vv,a,e.localY),t.Cc(e.localX),null!==this.Dv&&this.Dv.Pp(r.gu(),l))}}class rh{constructor(e,r,i,s,n){this.xt=!0,this.Op=t({width:0,height:0}),this.$p=()=>this.lv(3),this.jp="left"===e,this.Ju=i.Bc,this.Ps=r,this.dm=s,this.fm=n,this.jf=document.createElement("div"),this.jf.style.width="25px",this.jf.style.height="100%",this.jf.style.overflow="hidden",this.Gp=t7(this.jf,t({width:16,height:16})),this.Gp.subscribeSuggestedBitmapSizeChanged(this.$p)}m(){this.Gp.unsubscribeSuggestedBitmapSizeChanged(this.$p),re(this.Gp.canvasElement),this.Gp.dispose()}Zf(){return this.jf}Gf(){return this.Op}hv(e){r(this.Op,e)||(this.Op=e,this.Gp.resizeCanvasElement(e),this.jf.style.width=`${e.width}px`,this.jf.style.height=`${e.height}px`,this.xt=!0)}lv(e){if(e<3&&!this.xt||0===this.Op.width||0===this.Op.height)return;this.xt=!1,this.Gp.applySuggestedBitmapSize();let t=T(this.Gp,{colorSpace:this.Ps.layout.colorSpace});null!==t&&t.useBitmapCoordinateSpace(e=>{this._v(e),this.uv(e)})}Jf(){return this.Gp.bitmapSize}Qf(e,t,r){let i=this.Jf();i.width>0&&i.height>0&&e.drawImage(this.Gp.canvasElement,t,r)}uv({context:e,bitmapSize:t,horizontalPixelRatio:r,verticalPixelRatio:i}){if(!this.dm())return;e.fillStyle=this.Ps.timeScale.borderColor;let s=Math.floor(this.Ju.N().S*r),n=Math.floor(this.Ju.N().S*i),a=this.jp?t.width-s:0;e.fillRect(a,0,s,n)}_v({context:e,bitmapSize:t}){es(e,0,0,t.width,t.height,this.fm())}}function rp(e){return t=>t.ia?.(e)??[]}let rm=rp("normal"),rf=rp("top"),rx=rp("bottom");class rg{constructor(e,r){this.pm=null,this.vm=null,this.M=null,this.wm=!1,this.Op=t({width:0,height:0}),this.gm=new R,this.Fp=new ek(5),this.Up=!1,this.$p=()=>{this.Up||this.Vp.Qt().ar()},this.Yp=()=>{this.Up||this.Vp.Qt().ar()},this.Vp=e,this.o_=r,this.Ps=e.N().layout,this.kp=document.createElement("tr"),this.Mm=document.createElement("td"),this.Mm.style.padding="0",this.bm=document.createElement("td"),this.bm.style.padding="0",this.jf=document.createElement("td"),this.jf.style.height="25px",this.jf.style.padding="0",this.Sm=document.createElement("div"),this.Sm.style.width="100%",this.Sm.style.height="100%",this.Sm.style.position="relative",this.Sm.style.overflow="hidden",this.jf.appendChild(this.Sm),this.Gp=t7(this.Sm,t({width:16,height:16})),this.Gp.subscribeSuggestedBitmapSizeChanged(this.$p);const i=this.Gp.canvasElement;i.style.position="absolute",i.style.zIndex="1",i.style.left="0",i.style.top="0",this.Jp=t7(this.Sm,t({width:16,height:16})),this.Jp.subscribeSuggestedBitmapSizeChanged(this.Yp);const s=this.Jp.canvasElement;s.style.position="absolute",s.style.zIndex="2",s.style.left="0",s.style.top="0",this.kp.appendChild(this.Mm),this.kp.appendChild(this.jf),this.kp.appendChild(this.bm),this.xm(),this.Vp.Qt().Vo().i(this.xm.bind(this),this),this.Nf=new tZ(this.Jp.canvasElement,this,{af:()=>!0,lf:()=>!this.Vp.N().handleScroll.horzTouchDrag})}m(){this.Nf.m(),null!==this.pm&&this.pm.m(),null!==this.vm&&this.vm.m(),this.Jp.unsubscribeSuggestedBitmapSizeChanged(this.Yp),re(this.Jp.canvasElement),this.Jp.dispose(),this.Gp.unsubscribeSuggestedBitmapSizeChanged(this.$p),re(this.Gp.canvasElement),this.Gp.dispose()}Zf(){return this.kp}Cm(){return this.pm}Pm(){return this.vm}Sf(e){if(this.wm)return;this.wm=!0;let t=this.Vp.Qt();!t.Et().Ki()&&this.Vp.N().handleScale.axisPressedMouseMove.time&&t.Mc(e.localX)}Mf(e){this.Sf(e)}xf(){let e=this.Vp.Qt();!e.Et().Ki()&&this.wm&&(this.wm=!1,this.Vp.N().handleScale.axisPressedMouseMove.time&&e.kc())}cf(e){let t=this.Vp.Qt();!t.Et().Ki()&&this.Vp.N().handleScale.axisPressedMouseMove.time&&t.yc(e.localX)}_f(e){this.cf(e)}vf(){this.wm=!1;let e=this.Vp.Qt();e.Et().Ki()&&!this.Vp.N().handleScale.axisPressedMouseMove.time||e.kc()}ff(){this.vf()}Xd(){this.Vp.N().handleScale.axisDoubleClickReset.time&&this.Vp.Qt().cn()}qd(){this.Xd()}
1sf(){this.Vp.Qt().N().handleScale.axisPressedMouseMove.time&&this.vv(1)}Bf(){this.vv(0)}Gf(){return this.Op}ym(){return this.gm}km(e,i,s){r(this.Op,e)||(this.Op=e,this.Up=!0,this.Gp.resizeCanvasElement(e),this.Jp.resizeCanvasElement(e),this.Up=!1,this.jf.style.width=`${e.width}px`,this.jf.style.height=`${e.height}px`,this.gm.p(e)),null!==this.pm&&this.pm.hv(t({width:i,height:e.height})),null!==this.vm&&this.vm.hv(t({width:s,height:e.height}))}Tm(){let e=this.Rm();return Math.ceil(e.S+e.C+e.P+e.A+e.V+e.Dm)}yt(){this.Vp.Qt().Et().Da()}Jf(){return this.Gp.bitmapSize}Qf(e,t,r,i){let s=this.Jf();if(s.width>0&&s.height>0&&(e.drawImage(this.Gp.canvasElement,t,r),i)){let i=this.Jp.canvasElement;e.drawImage(i,t,r)}}lv(e){if(0===e)return;let t={colorSpace:this.Ps.colorSpace};if(1!==e){this.Gp.applySuggestedBitmapSize();let r=T(this.Gp,t);null!==r&&(r.useBitmapCoordinateSpace(e=>{this._v(e),this.uv(e),this.Vm(r,rx)}),this.dv(r),this.Vm(r,rm)),null!==this.pm&&this.pm.lv(e),null!==this.vm&&this.vm.lv(e)}this.Jp.applySuggestedBitmapSize();let r=T(this.Jp,t);null!==r&&(r.useBitmapCoordinateSpace(({context:e,bitmapSize:t})=>{e.clearRect(0,0,t.width,t.height)}),this.Bm([...this.Vp.Qt().js(),this.Vp.Qt().uc()],r),this.Vm(r,rf))}Vm(e,t){let r=this.Vp.Qt().js();for(let i of r)ri(t,t=>rt(t,e,!1,void 0),i,void 0);for(let i of r)ri(t,t=>rr(t,e,!1,void 0),i,void 0)}_v({context:e,bitmapSize:t}){es(e,0,0,t.width,t.height,this.Vp.Qt().Wc())}uv({context:e,bitmapSize:t,verticalPixelRatio:r}){if(this.Vp.N().timeScale.borderVisible){e.fillStyle=this.Im();let i=Math.max(1,Math.floor(this.Rm().S*r));e.fillRect(0,0,t.width,i)}}dv(e){let t=this.Vp.Qt().Et(),r=t.Da();if(!r||0===r.length)return;let i=this.o_.maxTickMarkWeight(r),s=this.Rm(),n=t.N();n.borderVisible&&n.ticksVisible&&e.useBitmapCoordinateSpace(({context:e,horizontalPixelRatio:t,verticalPixelRatio:i})=>{e.strokeStyle=this.Im(),e.fillStyle=this.Im();let n=Math.max(1,Math.floor(t)),a=Math.floor(.5*t);e.beginPath();let l=Math.round(s.C*i);for(let i=r.length;i--;){let s=Math.round(r[i].coord*t);e.rect(s-a,0,n,l)}e.fill()}),e.useMediaCoordinateSpace(({context:e})=>{let t=s.S+s.C+s.A+s.P/2;for(let s of(e.textAlign="center",e.textBaseline="middle",e.fillStyle=this.H(),e.font=this.ev(),r))if(s.weight<i){let r=s.needAlignCoordinate?this.Em(e,s.coord,s.label):s.coord;e.fillText(s.label,r,t)}for(let s of(this.Vp.N().timeScale.allowBoldLabels&&(e.font=this.Am()),r))if(s.weight>=i){let r=s.needAlignCoordinate?this.Em(e,s.coord,s.label):s.coord;e.fillText(s.label,r,t)}})}Em(e,t,r){let i=this.Fp.Vi(e,r),s=Math.floor(t-i/2)+.5;return s<0?t+=Math.abs(0-s):s+i>this.Op.width&&(t-=Math.abs(this.Op.width-(s+i))),t}Bm(e,t){let r=this.Rm();for(let i of e)for(let e of i.cs())e.Tt().nt(t,r)}Im(){return this.Vp.N().timeScale.borderColor}H(){return this.Ps.textColor}F(){return this.Ps.fontSize}ev(){return W(this.F(),this.Ps.fontFamily)}Am(){return W(this.F(),this.Ps.fontFamily,"bold")}Rm(){null===this.M&&(this.M={S:1,L:NaN,A:NaN,V:NaN,Ji:NaN,C:5,P:NaN,k:"",Gi:new ek,Dm:0});let e=this.M,t=this.ev();if(e.k!==t){let r=this.F();e.P=r,e.k=t,e.A=3*r/12,e.V=3*r/12,e.Ji=9*r/12,e.L=0,e.Dm=4*r/12,e.Gi.Bn()}return this.M}vv(e){this.jf.style.cursor=1===e?"ew-resize":"default"}xm(){let e=this.Vp.Qt(),t=e.N();t.leftPriceScale.visible||null===this.pm||(this.Mm.removeChild(this.pm.Zf()),this.pm.m(),this.pm=null),t.rightPriceScale.visible||null===this.vm||(this.bm.removeChild(this.vm.Zf()),this.vm.m(),this.vm=null);let r={Bc:this.Vp.Qt().Bc()},i=()=>t.leftPriceScale.borderVisible&&e.Et().N().borderVisible,s=()=>e.Wc();t.leftPriceScale.visible&&null===this.pm&&(this.pm=new rh("left",t,r,i,s),this.Mm.appendChild(this.pm.Zf())),t.rightPriceScale.visible&&null===this.vm&&(this.vm=new rh("right",t,r,i,s),this.bm.appendChild(this.vm.Zf()))}}let rb=!!tX&&!!navigator.userAgentData&&navigator.userAgentData.brands.some(e=>e.brand.includes("Chromium"))&&!!tX&&(navigator?.userAgentData?.platform?"Windows"===navigator.userAgentData.platform:navigator.userAgent.toLowerCase().indexOf("win")>=0);class rv{constructor(e,t,r){var i;this.zm=[],this.Lm=[],this.Om=0,this.il=0,this.Mo=0,this.Nm=0,this.Fm=0,this.Wm=null,this.Hm=!1,this.xv=new R,this.Cv=new R,this.Xu=new R,this.Um=null,this.$m=null,this.Dp=e,this.Ps=t,this.o_=r,this.kp=document.createElement("div"),this.kp.classList.add("tv-lightweight-charts"),this.kp.style.overflow="hidden",this.kp.style.direction="ltr",this.kp.style.width="100%",this.kp.style.height="100%",(i=this.kp).style.userSelect="none",i.style.webkitUserSelect="none",i.style.msUserSelect="none",i.style.MozUserSelect="none",i.style.webkitTapHighlightColor="transparent",this.qm=document.createElement("table"),this.qm.setAttribute("cellspacing","0"),this.kp.appendChild(this.qm),this.Ym=this.jm.bind(this),ry(this.Ps)&&this.Km(!0),this.ts=new tF(this.Gu.bind(this),this.Ps,r),this.Qt().cc().i(this.Xm.bind(this),this),this.Zm=new rg(this,this.o_),this.qm.appendChild(this.Zm.Zf());const s=t.autoSize&&this.Gm();let n=this.Ps.width,a=this.Ps.height;if(s||0===n||0===a){const t=e.getBoundingClientRect();n=n||t.width,a=a||t.height}this.Jm(n,a),this.Qm(),e.appendChild(this.kp),this.tw(),this.ts.Et().Iu().i(this.ts.Ih.bind(this.ts),this),this.ts.Vo().i(this.ts.Ih.bind(this.ts),this)}Qt(){return this.ts}N(){return this.Ps}$f(){return this.zm}iw(){return this.Zm}m(){for(let e of(this.Km(!1),0!==this.Om&&window.cancelAnimationFrame(this.Om),this.ts.cc().u(this),this.ts.Et().Iu().u(this),this.ts.Vo().u(this),this.ts.m(),this.zm))this.qm.removeChild(e.Zf()),e.Xv().u(this),e.Zv().u(this),e.m();for(let e of(this.zm=[],this.Lm))this.sw(e);this.Lm=[],L(this.Zm).m(),null!==this.kp.parentElement&&this.kp.parentElement.removeChild(this.kp),this.Xu.m(),this.xv.m(),this.Cv.m(),this.nw()}Jm(e,r,i=!1){var s;let n,a;if(this.il===r&&this.Mo===e)return;let l=(n=Math.floor((s=t({width:e,height:r})).width),t({width:n-n%2,height:(a=Math.floor(s.height))-a%2}));this.il=l.height,this.Mo=l.width;let o=this.il+"px",d=this.Mo+"px";L(this.kp).style.height=o,L(this.kp).style.width=d,this.qm.style.height=o,this.qm.style.width=d,i?this.ew(eg.gn(),performance.now()):this.ts.Ih()}lv(e){void 0===e&&(e=eg.gn());for(let t=0;t<this.zm.length;t++)this.zm[t].lv(e.en(t).tn);this.Ps.timeScale.visible&&this.Zm.lv(e.nn())}hr(e){let t=ry(this.Ps);this.ts.hr(e);let r=ry(this.Ps);r!==t&&this.Km(r),e.layout?.panes&&this.rw(),this.tw(),this.hw(e)}Xv(){return this.xv}Zv(){return this.Cv}cc(){return this.Xu}aw(e=!1){null!==this.Wm&&(this.ew(this.Wm,performance.now()),this.Wm=null);let t=this.lw(null),r=document.createElement("canvas");r.width=t.width,r.height=t.height;let i=L(r.getContext("2d"));return this.lw(i,e),r}
1ow(e){return("left"!==e||this._w())&&("right"!==e||this.uw())&&0!==this.zm.length?L("left"===e?this.zm[0].nm():this.zm[0].rm()).av():0}cw(){return this.Ps.autoSize&&null!==this.Um}ip(){return this.kp}dw(e){this.$m=e,this.$m?this.ip().style.setProperty("cursor",e):this.ip().style.removeProperty("cursor")}fw(){return this.$m}pw(e){return E(this.zm[e]).Gf()}rw(){this.Lm.forEach(e=>{e.yt()})}hw(e){(void 0!==e.autoSize||!this.Um||void 0===e.width&&void 0===e.height)&&(e.autoSize&&!this.Um&&this.Gm(),!1===e.autoSize&&null!==this.Um&&this.nw(),e.autoSize||void 0===e.width&&void 0===e.height||this.Jm(e.width||this.Mo,e.height||this.il))}lw(e,r){let i=0,s=0,n=this.zm[0],a=(t,i)=>{let s=0;for(let n=0;n<this.zm.length;n++){let a=this.zm[n],l=L("left"===t?a.nm():a.rm()),o=l.Jf();if(null!==e&&l.Qf(e,i,s,r),s+=o.height,n<this.zm.length-1){let t=this.Lm[n],r=t.Jf();null!==e&&t.Qf(e,i,s),s+=r.height}}};this._w()&&(a("left",0),i+=L(n.nm()).Jf().width);for(let t=0;t<this.zm.length;t++){let n=this.zm[t],a=n.Jf();if(null!==e&&n.Qf(e,i,s,r),s+=a.height,t<this.zm.length-1){let r=this.Lm[t],n=r.Jf();null!==e&&r.Qf(e,i,s),s+=n.height}}i+=n.Jf().width,this.uw()&&(a("right",i),i+=L(n.rm()).Jf().width);let l=(t,r,i)=>{L("left"===t?this.Zm.Cm():this.Zm.Pm()).Qf(L(e),r,i)};if(this.Ps.timeScale.visible){let t=this.Zm.Jf();if(null!==e){let i=0;this._w()&&(l("left",i,s),i=L(n.nm()).Jf().width),this.Zm.Qf(e,i,s,r),i+=t.width,this.uw()&&l("right",i,s)}s+=t.height}return t({width:i,height:s})}mw(){var e,r,i;let s=0,n=0,a=0;for(let e of this.zm)this._w()&&(n=Math.max(n,L(e.nm()).nv(),this.Ps.leftPriceScale.minimumWidth)),this.uw()&&(a=Math.max(a,L(e.rm()).nv(),this.Ps.rightPriceScale.minimumWidth)),s+=e.Bo();n=(r=n)+r%2,a=(i=a)+i%2;let l=this.Mo,o=this.il,d=Math.max(l-n-a,0),c=+this.Lm.length,u=this.Ps.timeScale.visible,h=u?Math.max(this.Zm.Tm(),this.Ps.timeScale.minimumHeight):0,p=c+(h=(e=h)+e%2),m=o<p?0:o-p,f=m/s,x=0,g=window.devicePixelRatio||1;for(let e=0;e<this.zm.length;++e){let r=this.zm[e];r.Lv(this.ts.$s()[e]);let i=0;i=Math.max(e===this.zm.length-1?Math.ceil((m-x)*g)/g:Math.round(r.Bo()*f*g)/g,2),x+=i,r.hv(t({width:d,height:i})),this._w()&&r.Jv(n,"left"),this.uw()&&r.Jv(a,"right"),r.ap()&&this.ts.dc(r.ap(),i)}this.Zm.km(t({width:u?d:0,height:h}),u?n:0,u?a:0),this.ts.Eo(d),this.Nm!==n&&(this.Nm=n),this.Fm!==a&&(this.Fm=a)}Km(e){e?this.kp.addEventListener("wheel",this.Ym,{passive:!1}):this.kp.removeEventListener("wheel",this.Ym)}ww(e){switch(e.deltaMode){case e.DOM_DELTA_PAGE:return 120;case e.DOM_DELTA_LINE:return 32}return rb?1/window.devicePixelRatio:1}jm(e){if(!(0!==e.deltaX&&this.Ps.handleScroll.mouseWheel||0!==e.deltaY&&this.Ps.handleScale.mouseWheel))return;let t=this.ww(e),r=t*e.deltaX/100,i=-t*e.deltaY/100;if(e.cancelable&&e.preventDefault(),0!==i&&this.Ps.handleScale.mouseWheel){let t=Math.sign(i)*Math.min(1,Math.abs(i)),r=e.clientX-this.kp.getBoundingClientRect().left;this.Qt().bc(r,t)}0!==r&&this.Ps.handleScroll.mouseWheel&&this.Qt().Sc(-80*r)}ew(e,t){let r=e.nn();3===r&&this.gw(),3!==r&&2!==r||(this.Mw(e),this.bw(e,t),this.Zm.yt(),this.zm.forEach(e=>{e.Nv()}),3===this.Wm?.nn()&&(this.Wm.vn(e),this.gw(),this.Mw(this.Wm),this.bw(this.Wm,t),e=this.Wm,this.Wm=null)),this.lv(e)}bw(e,t){for(let r of e.pn())this.mn(r,t)}Mw(e){let t=this.ts.$s();for(let r=0;r<t.length;r++)e.en(r).sn&&t[r].Go()}mn(e,t){let r=this.ts.Et();switch(e.an){case 0:r.Au();break;case 1:r.zu(e.Wt);break;case 2:r.dn(e.Wt);break;case 3:r.fn(e.Wt);break;case 4:r.Su();break;case 5:e.Wt.Ru(t)||r.fn(e.Wt.Du(t))}}Gu(e){null!==this.Wm?this.Wm.vn(e):this.Wm=e,this.Hm||(this.Hm=!0,this.Om=window.requestAnimationFrame(e=>{if(this.Hm=!1,this.Om=0,null!==this.Wm){let t=this.Wm;for(let r of(this.Wm=null,this.ew(t,e),t.pn()))if(5===r.an&&!r.Wt.Ru(e)){this.Qt()._n(r.Wt);break}}}))}gw(){this.Qm()}sw(e){this.qm.removeChild(e.Zf()),e.m()}Qm(){let e=this.ts.$s(),t=e.length,r=this.zm.length;for(let e=t;e<r;e++){let e=E(this.zm.pop());this.qm.removeChild(e.Zf()),e.Xv().u(this),e.Zv().u(this),e.m();let t=this.Lm.pop();void 0!==t&&this.sw(t)}for(let i=r;i<t;i++){let t=new ru(this,e[i]);if(t.Xv().i(this.Sw.bind(this,t),this),t.Zv().i(this.xw.bind(this,t),this),this.zm.push(t),i>0){let e=new t4(this,i-1,i);this.Lm.push(e),this.qm.insertBefore(e.Zf(),this.Zm.Zf())}this.qm.insertBefore(t.Zf(),this.Zm.Zf())}for(let r=0;r<t;r++){let t=e[r],i=this.zm[r];i.ap()!==t?i.Lv(t):i.zv()}this.tw(),this.mw()}Cw(e,t,r,i){let s,n=new Map;
1if(null!==e&&this.ts.js().forEach(t=>{let r=t.Xs().Fr(e);null!==r&&n.set(t,r)}),null!==e){let t=this.ts.Et().ss(e)?.originalTime;void 0!==t&&(s=t)}let a=this.Qt().ac(),l=null!==a&&a.n_ instanceof tt?a.n_:void 0,o=null!==a&&void 0!==a.e_?a.e_.Kn:void 0,d=this.Pw(i);return{yw:s,Re:e??void 0,kw:t??void 0,Tw:-1!==d?d:void 0,Rw:l,Dw:n,Vw:o,Bw:r??void 0}}Pw(e){let t=-1;if(e)t=this.zm.indexOf(e);else{let e=this.Qt().uc().Us();null!==e&&(t=this.Qt().$s().indexOf(e))}return t}Sw(e,t,r,i){this.xv.p(()=>this.Cw(t,r,i,e))}xw(e,t,r,i){this.Cv.p(()=>this.Cw(t,r,i,e))}Xm(e,t,r){this.dw(this.Qt().ac()?.h_??null),this.Xu.p(()=>this.Cw(e,t,r))}tw(){let e=this.Ps.timeScale.visible?"":"none";this.Zm.Zf().style.display=e}_w(){return this.zm[0].ap().Wo().N().visible}uw(){return this.zm[0].ap().Ho().N().visible}Gm(){return"ResizeObserver"in window&&(this.Um=new ResizeObserver(e=>{let t=e[e.length-1];t&&this.Jm(t.contentRect.width,t.contentRect.height)}),this.Um.observe(this.Dp,{box:"border-box"}),!0)}nw(){null!==this.Um&&this.Um.disconnect(),this.Um=null}}function ry(e){return!!(e.handleScroll.mouseWheel||e.handleScale.mouseWheel)}function rw(e,t,r,i){let s=r.value,n={Re:t,wt:e,Wt:[s,s,s,s],yw:i};return void 0!==r.color&&(n.R=r.color),n}function rj(e,t,r,i){let s=r.value,n={Re:t,wt:e,Wt:[s,s,s,s],yw:i};return void 0!==r.lineColor&&(n.vt=r.lineColor),void 0!==r.topColor&&(n.mr=r.topColor),void 0!==r.bottomColor&&(n.wr=r.bottomColor),n}function rS(e,t,r,i){let s=r.value,n={Re:t,wt:e,Wt:[s,s,s,s],yw:i};return void 0!==r.topLineColor&&(n.gr=r.topLineColor),void 0!==r.bottomLineColor&&(n.Mr=r.bottomLineColor),void 0!==r.topFillColor1&&(n.br=r.topFillColor1),void 0!==r.topFillColor2&&(n.Sr=r.topFillColor2),void 0!==r.bottomFillColor1&&(n.Cr=r.bottomFillColor1),void 0!==r.bottomFillColor2&&(n.Pr=r.bottomFillColor2),n}function rk(e,t,r,i){let s={Re:t,wt:e,Wt:[r.open,r.high,r.low,r.close],yw:i};return void 0!==r.color&&(s.R=r.color),s}function rN(e,t,r,i){let s={Re:t,wt:e,Wt:[r.open,r.high,r.low,r.close],yw:i};return void 0!==r.color&&(s.R=r.color),void 0!==r.borderColor&&(s.Ht=r.borderColor),void 0!==r.wickColor&&(s.vr=r.wickColor),s}function rP(e,t,r,i,s){let n=E(s)(r),a=Math.max(...n),l=Math.min(...n),o=n[n.length-1],{time:d,color:c,...u}=r;return{Re:t,wt:e,Wt:[o,a,l,o],yw:i,se:u,R:c}}function rT(e){return void 0!==e.Wt}function rC(e,t){return void 0!==t.customValues&&(e.Iw=t.customValues),e}function rM(e){return(t,r,i,s,n,a)=>(a?a(i):void 0===i.open&&void 0===i.value)?rC({wt:t,Re:r,yw:s},i):rC(e(t,r,i,s,n),i)}function r_(e){return({Candlestick:rM(rN),Bar:rM(rk),Area:rM(rj),Baseline:rM(rS),Histogram:rM(rw),Line:rM(rw),Custom:rM(rP)})[e]}function rA(e){return{Re:0,Ew:new Map,Hh:e}}function rE(e,t){if(void 0!==e&&0!==e.length)return{Aw:t.key(e[0].wt),zw:t.key(e[e.length-1].wt)}}function rL(e){let t;return e.forEach(e=>{void 0===t&&(t=e.yw)}),E(t)}class rF{constructor(e){this.Lw=new Map,this.Ow=new Map,this.Nw=new Map,this.Fw=[],this.o_=e}m(){this.Lw.clear(),this.Ow.clear(),this.Nw.clear(),this.Fw=[]}Ww(e,t){let r=0!==this.Lw.size,i=!1,s=this.Ow.get(e);if(void 0!==s)if(1===this.Ow.size)r=!1,i=!0,this.Lw.clear();else for(let t of this.Fw)t.pointData.Ew.delete(e)&&(i=!0);let n=[];if(0!==t.length){let r=t.map(e=>e.time),s=this.o_.createConverterToInternalObj(t),a=r_(e.Rr()),l=e.ca(),o=e.fa();n=t.map((t,n)=>{let d=s(t.time),c=this.o_.key(d),u=this.Lw.get(c);void 0===u&&(u=rA(d),this.Lw.set(c,u),i=!0);let h=a(d,u.Re,t,r[n],l,o);return u.Ew.set(e,h),h})}r&&this.Hw(),this.Uw(e,n);let a=-1;if(i){let e=[];this.Lw.forEach(t=>{e.push({timeWeight:0,time:t.Hh,pointData:t,originalTime:rL(t.Ew)})}),e.sort((e,t)=>this.o_.key(e.time)-this.o_.key(t.time)),a=this.$w(e)}return this.qw(e,a,function(e,t,r){let i=rE(e,r),s=rE(t,r);if(void 0!==i&&void 0!==s)return{Yw:!1,zh:i.zw>=s.zw&&i.Aw>=s.Aw}}(this.Ow.get(e),s,this.o_))}Ac(e){return this.Ww(e,[])}jw(e,t,r){void 0===t.yw&&(t.yw=t.time),this.o_.preprocessData(t);let i=this.o_.createConverterToInternalObj([t])(t.time),s=this.Nw.get(e);if(!r&&void 0!==s&&this.o_.key(i)<this.o_.key(s))throw Error(`Cannot update oldest data, last time=${s}, new time=${i}`);let n=this.Lw.get(this.o_.key(i));if(r&&void 0===n)throw Error("Cannot update non-existing data point when historicalUpdate is true");let a=void 0===n;void 0===n&&(n=rA(i),this.Lw.set(this.o_.key(i),n));let l=r_(e.Rr()),o=e.ca(),d=e.fa(),c=l(i,n.Re,t,t.yw,o,d);n.Ew.set(e,c),r?this.Kw(e,c,n.Re):this.Xw(e,c);let u={zh:rT(c),Yw:r};if(!a)return this.qw(e,-1,u);let h={timeWeight:0,time:n.Hh,pointData:n,originalTime:rL(n.Ew)},p=eW(this.Fw,this.o_.key(h.time),(e,t)=>this.o_.key(e.time)<t);this.Fw.splice(p,0,h);for(let e=p;e<this.Fw.length;++e)rR(this.Fw[e].pointData,e);return this.o_.fillWeightsForPoints(this.Fw,p),this.qw(e,p,u)}Zw(e,t){let r=this.Ow.get(e);if(void 0===r||t<=0)return[[],this.Gw()];
1t=Math.min(t,r.length);let i=r.splice(-t).reverse();for(let t of(0===r.length?this.Nw.delete(e):this.Nw.set(e,r[r.length-1].wt),i)){let r=this.Lw.get(this.o_.key(t.wt));if(r&&(r.Ew.delete(e),0===r.Ew.size)){this.Lw.delete(this.o_.key(r.Hh)),this.Fw.splice(r.Re,1);for(let e=r.Re;e<this.Fw.length;++e)rR(this.Fw[e].pointData,e)}}return[i,this.qw(e,this.Fw.length-1,{Yw:!1,zh:!1})]}Xw(e,t){let r=this.Ow.get(e);void 0===r&&(r=[],this.Ow.set(e,r));let i=0!==r.length?r[r.length-1]:null;null===i||this.o_.key(t.wt)>this.o_.key(i.wt)?rT(t)&&r.push(t):rT(t)?r[r.length-1]=t:r.splice(-1,1),this.Nw.set(e,t.wt)}Kw(e,t,r){let i=this.Ow.get(e);if(void 0===i)return;let s=eW(i,r,(e,t)=>e.Re<t);rT(t)?i[s]=t:i.splice(s,1)}Uw(e,t){0!==t.length?(this.Ow.set(e,t.filter(rT)),this.Nw.set(e,t[t.length-1].wt)):(this.Ow.delete(e),this.Nw.delete(e))}Hw(){for(let e of this.Fw)0===e.pointData.Ew.size&&this.Lw.delete(this.o_.key(e.time))}$w(e){let t=-1;for(let r=0;r<this.Fw.length&&r<e.length;++r){let i=this.Fw[r],s=e[r];if(this.o_.key(i.time)!==this.o_.key(s.time)){t=r;break}s.timeWeight=i.timeWeight,rR(s.pointData,r)}if(-1===t&&this.Fw.length!==e.length&&(t=Math.min(this.Fw.length,e.length)),-1===t)return -1;for(let r=t;r<e.length;++r)rR(e[r].pointData,r);return this.o_.fillWeightsForPoints(e,t),this.Fw=e,t}Jw(){if(0===this.Ow.size)return null;let e=0;return this.Ow.forEach(t=>{0!==t.length&&(e=Math.max(e,t[t.length-1].Re))}),e}qw(e,t,r){let i=this.Gw();if(-1!==t)this.Ow.forEach((t,s)=>{i.Oo.set(s,{se:t,Qw:s===e?r:void 0})}),this.Ow.has(e)||i.Oo.set(e,{se:[],Qw:r}),i.Et.tg=this.Fw,i.Et.ig=t;else{let t=this.Ow.get(e);i.Oo.set(e,{se:t||[],Qw:r})}return i}Gw(){return{Oo:new Map,Et:{_u:this.Jw()}}}}function rR(e,t){e.Re=t,e.Ew.forEach(e=>{e.Re=t})}function rD(e,t){return e.wt<t}function rI(e,t){return t<e.wt}class rU{constructor(e,t,r){this.sg=!0,this.ng=!0,this.eg=!0,this.rg=[],this.hg=null,this.Jn=e,this.Qn=t,this.ag=r}yt(e){this.sg=!0,"data"===e&&(this.ng=!0),"options"===e&&(this.eg=!0)}Tt(){return this.Jn.Vt()?(this.lg(),null===this.hg?null:this.og):null}_g(){this.rg=this.rg.map(e=>({...e,...this.Jn.Rh().Dr(e.wt)}))}ug(){this.hg=null}lg(){this.ng&&(this.cg(),this.ng=!1),this.eg&&(this._g(),this.eg=!1),this.sg&&(this.dg(),this.sg=!1)}dg(){let e=this.Jn.Ft(),t=this.Qn.Et();if(this.ug(),t.Ki()||e.Ki())return;let r=t.Pe();if(null===r||0===this.Jn.Xs().zr())return;let i=this.Jn.zt();null!==i&&(this.hg=function(e,t,r){let i=t.Uh(),s=t.bi(),n=eW(e,i,rD),a=eq(e,s,rI);if(!r)return{from:n,to:a};let l=n,o=a;return n>0&&n<e.length&&e[n].wt>=i&&(l=n-1),a>0&&a<e.length&&e[a-1].wt<=s&&(o=a+1),{from:l,to:o}}(this.rg,r,this.ag),this.fg(e,t,i.Wt),this.pg())}}class rO{constructor(e,t){this.vg=e,this.Yi=t}nt(e,t,r){this.vg.draw(e,this.Yi,t,r)}}class rB extends rU{constructor(e,t,r){super(e,t,!1),this.sh=r,this.og=new rO(this.sh.renderer(),t=>{let r=e.zt();return null===r?null:e.Ft().Nt(t,r.Wt)})}da(e){return this.sh.priceValueBuilder(e)}pa(e){return this.sh.isWhitespace(e)}cg(){let e=this.Jn.Rh();this.rg=this.Jn.Xs().Hr().map(t=>({wt:t.Re,_t:NaN,...e.Dr(t.Re),mg:t.se}))}fg(e,t){t.uu(this.rg,V(this.hg))}pg(){this.sh.update({bars:this.rg.map(rz),barSpacing:this.Qn.Et().mu(),visibleRange:this.hg},this.Jn.N())}}function rz(e){return{x:e._t,time:e.wt,originalData:e.mg,barColor:e.cr}}let r$={color:"#2196f3"},rV=(e,t,r)=>new rB(e,t,F(r));function rH(e){let t={value:e.Wt[3],time:e.yw};return void 0!==e.Iw&&(t.customValues=e.Iw),t}function rW(e){let t=rH(e);return void 0!==e.R&&(t.color=e.R),t}function rq(e){let t=rH(e);return void 0!==e.vt&&(t.lineColor=e.vt),void 0!==e.mr&&(t.topColor=e.mr),void 0!==e.wr&&(t.bottomColor=e.wr),t}function rK(e){let t=rH(e);return void 0!==e.gr&&(t.topLineColor=e.gr),void 0!==e.Mr&&(t.bottomLineColor=e.Mr),void 0!==e.br&&(t.topFillColor1=e.br),void 0!==e.Sr&&(t.topFillColor2=e.Sr),void 0!==e.Cr&&(t.bottomFillColor1=e.Cr),void 0!==e.Pr&&(t.bottomFillColor2=e.Pr),t}function rG(e){let t={open:e.Wt[0],high:e.Wt[1],low:e.Wt[2],close:e.Wt[3],time:e.yw};return void 0!==e.Iw&&(t.customValues=e.Iw),t}function rY(e){let t=rG(e);return void 0!==e.R&&(t.color=e.R),t}function rX(e){let t=rG(e),{R:r,Ht:i,vr:s}=e;return void 0!==r&&(t.color=r),void 0!==i&&(t.borderColor=i),void 0!==s&&(t.wickColor=s),t}function rQ(e){return({Area:rq,Line:rW,Baseline:rK,Histogram:rW,Bar:rY,Candlestick:rX,Custom:rJ})[e]}function rJ(e){let t=e.yw;return{...e.se,time:t}}let rZ={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroun
1dColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1},r0={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},r1={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:H,panes:{enableResize:!0,separatorColor:"#E0E3EB",separatorHoverColor:"rgba(178, 181, 189, 0.2)"},attributionLogo:!0,colorSpace:"srgb",colorParsers:[]},r2={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0,ensureEdgeTickMarksVisible:!1},r5={rightOffset:0,barSpacing:6,minBarSpacing:.5,maxBarSpacing:0,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0,ignoreWhitespaceIndices:!1};function r3(){return{addDefaultPane:!0,width:0,height:0,autoSize:!1,layout:r1,crosshair:rZ,grid:r0,overlayPriceScales:{...r2},leftPriceScale:{...r2,visible:!1},rightPriceScale:{...r2,visible:!0},timeScale:r5,localization:{locale:tX?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class r4{constructor(e,t,r){this.Hf=e,this.wg=t,this.gg=r??0}applyOptions(e){this.Hf.Qt().oc(this.wg,e,this.gg)}options(){return this.Yi().N()}width(){return ex(this.wg)?this.Hf.ow(this.wg):0}setVisibleRange(e){this.setAutoScale(!1),this.Yi().Fl(new eD(e.from,e.to))}getVisibleRange(){let e,t,r=this.Yi().Qe();if(null===r)return null;if(this.Yi().Ja()){let i=this.Yi().fo(),s=tR(i);e=Number((Math.round((r=tf(r,this.Yi().tl())).$e()/i)*i).toFixed(s)),t=Number((Math.round(r.qe()/i)*i).toFixed(s))}else e=r.$e(),t=r.qe();return{from:e,to:t}}setAutoScale(e){this.applyOptions({autoScale:e})}Yi(){return L(this.Hf.Qt()._c(this.wg,this.gg)).Ft}}
1class r6{constructor(e,t,r,i){this.Hf=e,this.Pt=r,this.Mg=t,this.bg=i}getHeight(){return this.Pt.$t()}setHeight(e){let t=this.Hf.Qt(),r=t.Uc(this.Pt);t.vc(r,e)}getStretchFactor(){return this.Pt.Bo()}setStretchFactor(e){this.Pt.Io(e),this.Hf.Qt().Ih()}paneIndex(){return this.Hf.Qt().Uc(this.Pt)}moveTo(e){let t=this.paneIndex();t!==e&&(A(e>=0&&e<this.Hf.$f().length,"Invalid pane index"),this.Hf.Qt().wc(t,e))}getSeries(){return this.Pt.Oo().map(e=>this.Mg(e))??[]}getHTMLElement(){let e=this.Hf.$f();return e&&0!==e.length&&e[this.paneIndex()]?e[this.paneIndex()].Zf():null}attachPrimitive(e){this.Pt._a(e),e.attached&&e.attached({chart:this.bg,requestUpdate:()=>this.Pt.Qt().Ih()})}detachPrimitive(e){this.Pt.ua(e)}priceScale(e){if(null===this.Pt.Do(e))throw Error(`Cannot find price scale with id: ${e}`);return new r4(this.Hf,e,this.paneIndex())}setPreserveEmptyPane(e){this.Pt.zo(e)}preserveEmptyPane(){return this.Pt.Lo()}addCustomSeries(e,t={},r=0){return this.bg.addCustomSeries(e,t,r)}addSeries(e,t={}){return this.bg.addSeries(e,t,this.paneIndex())}}let r8={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class r9{constructor(e){this.ir=e}applyOptions(e){this.ir.hr(e)}options(){return this.ir.N()}Sg(){return this.ir}}class r7{constructor(e,t,r,i,s,n){this.xg=new R,this.Jn=e,this.Cg=t,this.Pg=r,this.o_=s,this.bg=i,this.yg=n}m(){this.xg.m()}priceFormatter(){return this.Jn.ea()}priceToCoordinate(e){let t=this.Jn.zt();return null===t?null:this.Jn.Ft().Nt(e,t.Wt)}coordinateToPrice(e){let t=this.Jn.zt();return null===t?null:this.Jn.Ft().Ts(e,t.Wt)}barsInLogicalRange(e){if(null===e)return null;let t=new tA(new tC(e.from,e.to)).y_(),r=this.Jn.Xs();if(r.Ki())return null;let i=r.Fr(t.Uh(),1),s=r.Fr(t.bi(),-1),n=L(r.Lr()),a=L(r.Ks());if(null!==i&&null!==s&&i.Re>s.Re)return{barsBefore:e.from-n,barsAfter:a-e.to};let l={barsBefore:null===i||i.Re===n?e.from-n:i.Re-n,barsAfter:null===s||s.Re===a?a-e.to:a-s.Re};return null!==i&&null!==s&&(l.from=i.yw,l.to=s.yw),l}setData(e){this.o_,this.Jn.Rr(),this.Cg.kg(this.Jn,e),this.Tg("full")}update(e,t=!1){this.Jn.Rr(),this.Cg.Rg(this.Jn,e,t),this.Tg("update")}pop(e=1){let t=this.Cg.Dg(this.Jn,e);0!==t.length&&this.Tg("update");let r=rQ(this.seriesType());return t.map(e=>r(e))}dataByIndex(e,t){let r=this.Jn.Xs().Fr(e,t);return null===r?null:rQ(this.seriesType())(r)}data(){let e=rQ(this.seriesType());return this.Jn.Xs().Hr().map(t=>e(t))}subscribeDataChanged(e){this.xg.i(e)}unsubscribeDataChanged(e){this.xg._(e)}applyOptions(e){this.Jn.hr(e)}options(){return z(this.Jn.N())}priceScale(){return this.Pg.priceScale(this.Jn.Ft().ma(),this.getPane().paneIndex())}createPriceLine(e){let t=D(z(r8),e);return new r9(this.Jn.Oh(t))}removePriceLine(e){this.Jn.Nh(e.Sg())}priceLines(){return this.Jn.Fh().map(e=>new r9(e))}seriesType(){return this.Jn.Rr()}lastValueData(e){let t=this.Jn.ye(e);return t.ke?{noData:!0}:{noData:!1,price:t.gt,color:t.R}}attachPrimitive(e){this.Jn._a(e),e.attached&&e.attached({chart:this.bg,series:this,requestUpdate:()=>this.Jn.Qt().Ih(),horzScaleBehavior:this.o_})}detachPrimitive(e){this.Jn.ua(e),e.detached&&e.detached(),this.Jn.Qt().Ih()}getPane(){let e=this.Jn,t=L(this.Jn.Qt().Hn(e));return this.yg(t)}moveToPane(e){this.Jn.Qt().Nc(this.Jn,e)}seriesOrder(){let e=this.Jn.Qt().Hn(this.Jn);return null===e?-1:e.Oo().indexOf(this.Jn)}setSeriesOrder(e){let t=this.Jn.Qt().Hn(this.Jn);null!==t&&t.Qo(this.Jn,e)}Tg(e){this.xg.v()&&this.xg.p(e)}}class ie{constructor(e,t,r){this.Vg=new R,this.z_=new R,this.gm=new R,this.ts=e,this.uh=e.Et(),this.Zm=t,this.uh.Vu().i(this.Bg.bind(this)),this.uh.Bu().i(this.Ig.bind(this)),this.Zm.ym().i(this.Eg.bind(this)),this.o_=r}m(){this.uh.Vu().u(this),this.uh.Bu().u(this),this.Zm.ym().u(this),this.Vg.m(),this.z_.m(),this.gm.m()}scrollPosition(){return this.uh.gu()}scrollToPosition(e,t){t?this.uh.Tu(e,1e3):this.ts.fn(e)}scrollToRealTime(){this.uh.ku()}getVisibleRange(){let e=this.uh.nu();return null===e?null:{from:e.from.originalTime,to:e.to.originalTime}}setVisibleRange(e){let t={from:this.o_.convertHorzItemToInternal(e.from),to:this.o_.convertHorzItemToInternal(e.to)},r=this.uh.au(t);this.ts.Lc(r)}getVisibleLogicalRange(){let e=this.uh.su();return null===e?null:{from:e.Uh(),to:e.bi()}}setVisibleLogicalRange(e){A(e.from<=e.to,"The from index cannot be after the to index."),this.ts.Lc(e)}resetTimeScale(){this.ts.cn()}fitContent(){this.ts.Au()}logicalToCoordinate(e){let t=this.ts.Et();return t.Ki()?null:t.qt(e)}coordinateToLogical(e){return this.uh.Ki()?null:this.uh.cu(e)}timeToIndex(e,t){let r=this.o_.convertHorzItemToInternal(e);return this.uh.Q_(r,t)}timeToCoordinate(e){let t=this.timeToIndex(e,!1);return null===t?null:this.uh.qt(t)}coordinateToTime(e){let t=this.ts.Et(),r=t.cu(e),i=t.ss(r);return null===i?null:i.originalTime}width(){return this.Zm.Gf().width}height(){return this.Zm.Gf().height}subscribeVisibleTimeRangeChange(e){this.Vg.i(e)}unsubscribeVisibleTimeRangeChange(e){this.Vg._(e)}subscribeVisibleLogicalRangeChange(e){this.z_.i(e)}unsubscribeVisibleLogicalRangeChange(e){this.z_._(e)}subscribeSizeChange(e){this.gm.i(e)}unsubscribeSizeChange(e){this.gm._(e)}
1applyOptions(e){this.uh.hr(e)}options(){return{...z(this.uh.N()),barSpacing:this.uh.mu()}}Bg(){this.Vg.v()&&this.Vg.p(this.getVisibleRange())}Ig(){this.z_.v()&&this.z_.p(this.getVisibleLogicalRange())}Eg(e){this.gm.p(e.width,e.height)}}function it(e){return function(e){if(B(e.handleScale)){let t=e.handleScale;e.handleScale={axisDoubleClickReset:{time:t,price:t},axisPressedMouseMove:{time:t,price:t},mouseWheel:t,pinch:t}}else if(void 0!==e.handleScale){let{axisPressedMouseMove:t,axisDoubleClickReset:r}=e.handleScale;B(t)&&(e.handleScale.axisPressedMouseMove={time:t,price:t}),B(r)&&(e.handleScale.axisDoubleClickReset={time:r,price:r})}let t=e.handleScroll;B(t)&&(e.handleScroll={horzTouchDrag:t,vertTouchDrag:t,mouseWheel:t,pressedMouseMove:t})}(e),e}class ir{constructor(e,t,r){this.Ag=new Map,this.zg=new Map,this.Lg=new R,this.Og=new R,this.Ng=new R,this.qu=new WeakMap,this.Fg=new rF(t);const i=void 0===r?z(r3()):D(z(r3()),it(r));this.Wg=t,this.Hf=new rv(e,i,t),this.Hf.Xv().i(e=>{this.Lg.v()&&this.Lg.p(this.Hg(e()))},this),this.Hf.Zv().i(e=>{this.Og.v()&&this.Og.p(this.Hg(e()))},this),this.Hf.cc().i(e=>{this.Ng.v()&&this.Ng.p(this.Hg(e()))},this);const s=this.Hf.Qt();this.Ug=new ie(s,this.Hf.iw(),this.Wg)}remove(){this.Hf.Xv().u(this),this.Hf.Zv().u(this),this.Hf.cc().u(this),this.Ug.m(),this.Hf.m(),this.Ag.clear(),this.zg.clear(),this.Lg.m(),this.Og.m(),this.Ng.m(),this.Fg.m()}resize(e,t,r){this.autoSizeActive()||this.Hf.Jm(e,t,r)}addCustomSeries(e,t={},r=0){let i,s=(i=F(e),{type:"Custom",isBuiltIn:!1,defaultOptions:{...r$,...i.defaultOptions()},$g:rV,qg:i});return this.Yg(s,t,r)}addSeries(e,t={},r=0){return this.Yg(e,t,r)}removeSeries(e){let t=E(this.Ag.get(e)),r=this.Fg.Ac(t);this.Hf.Qt().Ac(t),this.jg(r),this.Ag.delete(e),this.zg.delete(t)}kg(e,t){this.jg(this.Fg.Ww(e,t))}Rg(e,t,r){this.jg(this.Fg.jw(e,t,r))}Dg(e,t){let[r,i]=this.Fg.Zw(e,t);return 0!==r.length&&this.jg(i),r}subscribeClick(e){this.Lg.i(e)}unsubscribeClick(e){this.Lg._(e)}subscribeCrosshairMove(e){this.Ng.i(e)}unsubscribeCrosshairMove(e){this.Ng._(e)}subscribeDblClick(e){this.Og.i(e)}unsubscribeDblClick(e){this.Og._(e)}priceScale(e,t=0){return new r4(this.Hf,e,t)}timeScale(){return this.Ug}applyOptions(e){this.Hf.hr(it(e))}options(){return this.Hf.N()}takeScreenshot(e=!1,t=!1){let r,i;try{t||(r=this.Hf.Qt().N().crosshair.mode,this.Hf.hr({crosshair:{mode:2}})),i=this.Hf.aw(e)}finally{t||void 0===r||this.Hf.Qt().hr({crosshair:{mode:r}})}return i}addPane(e=!1){let t=this.Hf.Qt().$c();return t.zo(e),this.Kg(t)}removePane(e){this.Hf.Qt().fc(e)}swapPanes(e,t){this.Hf.Qt().mc(e,t)}autoSizeActive(){return this.Hf.cw()}chartElement(){return this.Hf.ip()}panes(){return this.Hf.Qt().$s().map(e=>this.Kg(e))}paneSize(e=0){let t=this.Hf.pw(e);return{height:t.height,width:t.width}}setCrosshairPosition(e,t,r){let i=this.Ag.get(r);if(void 0===i)return;let s=this.Hf.Qt().Hn(i);null!==s&&this.Hf.Qt().Rc(e,t,s)}clearCrosshairPosition(){this.Hf.Qt().Dc(!0)}horzBehaviour(){return this.Wg}Yg(e,t={},r=0){var i;A(void 0!==e.$g),void 0===(i=t.priceFormat)||"custom"===i.type||void 0!==i.minMove&&void 0===i.precision&&(i.precision=tR(i.minMove)),"Candlestick"===e.type&&(void 0!==t.borderColor&&(t.borderUpColor=t.borderColor,t.borderDownColor=t.borderColor),void 0!==t.wickColor&&(t.wickUpColor=t.wickColor,t.wickDownColor=t.wickColor));let s=D(z(C),z(e.defaultOptions),t),n=e.$g,a=new tt(this.Hf.Qt(),e.type,s,n,e.qg);this.Hf.Qt().Ic(a,r);let l=new r7(a,this,this,this,this.Wg,e=>this.Kg(e));return this.Ag.set(l,a),this.zg.set(a,l),l}jg(e){let t=this.Hf.Qt();t.Vc(e.Et._u,e.Et.tg,e.Et.ig),e.Oo.forEach((e,t)=>t.ht(e.se,e.Qw)),t.Et().K_(),t.vu()}Xg(e){return E(this.zg.get(e))}Hg(e){let t=new Map;e.Dw.forEach((e,r)=>{let i=r.Rr(),s=rQ(i)(e);if("Custom"!==i){var n;A(void 0!==(n=s).open||void 0!==n.value)}else{let e=r.fa();A(!e||!1===e(s))}t.set(this.Xg(r),s)});let r=void 0!==e.Rw&&this.zg.has(e.Rw)?this.Xg(e.Rw):void 0;return{time:e.yw,logical:e.Re,point:e.kw,paneIndex:e.Tw,hoveredSeries:r,hoveredObjectId:e.Vw,seriesData:t,sourceEvent:e.Bw}}Kg(e){let t=this.qu.get(e);return t||(t=new r6(this.Hf,e=>this.Xg(e),e,this),this.qu.set(e,t)),t}}class ii extends rU{constructor(e,t){super(e,t,!0)}fg(e,t,r){t.uu(this.rg,V(this.hg)),e.Ul(this.rg,r,V(this.hg))}Zg(e,t){return{wt:e,gt:t,_t:NaN,ut:NaN}}cg(){let e=this.Jn.Rh();this.rg=this.Jn.Xs().Hr().map(t=>{let r=t.Wt[3];return this.Gg(t.Re,r,e)})}}function is(e,t,r,i,s,n,a){if(0===t.length||i.from>=t.length||i.to<=0)return;let{context:l,horizontalPixelRatio:o,verticalPixelRatio:d}=e,c=t[i.from],u=n(e,c),h=c;if(i.to-i.from<2){let t=s/2;l.beginPath();let r={_t:c._t-t,ut:c.ut},i={_t:c._t+t,ut:c.ut};l.moveTo(r._t*o,r.ut*d),l.lineTo(i._t*o,i.ut*d),a(e,u,r,i)}else{let s=(t,r)=>{a(e,u,h,r),l.beginPath(),u=t,h=r},p=h;l.beginPath(),l.moveTo(c._t*o,c.ut*d);for(let a=i.from+1;a<i.to;++a){let i=n(e,p=t[a]);switch(r){case 0:l.lineTo(p._t*o,p.ut*d);break;case 1:l.lineTo(p._t*o,t[a-1].ut*d),i!==u&&(s(i,p),l.lineTo(p._t*o,t[a-1].ut*d)
1),l.lineTo(p._t*o,p.ut*d);break;case 2:{let[e,r]=function(e,t,r){var i,s;let n=Math.max(0,t-1),a=Math.min(e.length-1,r+1);return[(i=e[t],s=il(ia(e[r],e[n]),6),{_t:i._t+s._t,ut:i.ut+s.ut}),ia(e[r],il(ia(e[a],e[t]),6))]}(t,a-1,a);l.bezierCurveTo(e._t*o,e.ut*d,r._t*o,r.ut*d,p._t*o,p.ut*d)}}1!==r&&i!==u&&(s(i,p),l.moveTo(p._t*o,p.ut*d))}(h!==p||h===p&&1===r)&&a(e,u,h,p)}}function ia(e,t){return{_t:e._t-t._t,ut:e.ut-t.ut}}function il(e,t){return{_t:e._t/t,ut:e.ut/t}}function io(e,t){let r=e.context;r.strokeStyle=t,r.stroke()}class id extends Q{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et(e){if(null===this.rt)return;let{ot:t,lt:r,Jg:i,Qg:s,ct:n,Xt:a,tM:l}=this.rt;if(null===r)return;let o=e.context;o.lineCap="butt",o.lineWidth=n*e.verticalPixelRatio,M(o,a),o.lineJoin="round";let d=this.iM.bind(this);void 0!==s&&is(e,t,s,r,i,d,io),l&&function(e,t,r,i,s){if(i.to-i.from<=0)return;let{horizontalPixelRatio:n,verticalPixelRatio:a,context:l}=e,o=null,d=Math.max(1,Math.floor(n))%2/2,c=r*a+d;for(let r=i.to-1;r>=i.from;--r){let i=t[r];if(i){let t=s(e,i);t!==o&&(l.beginPath(),null!==o&&l.fill(),l.fillStyle=t,o=t);let r=Math.round(i._t*n)+d,u=i.ut*a;l.moveTo(r,u),l.arc(r,u,c,0,2*Math.PI)}}l.fill()}(e,t,l,r,d)}}class ic extends id{iM(e,t){return t.vt}}class iu extends ii{constructor(){super(...arguments),this.og=new ic}Gg(e,t,r){return{...this.Zg(e,t),...r.Dr(e)}}pg(){let e=this.Jn.N(),t={ot:this.rg,Xt:e.lineStyle,Qg:e.lineVisible?e.lineType:void 0,ct:e.lineWidth,tM:e.pointMarkersVisible?e.pointMarkersRadius||e.lineWidth/2+2:void 0,lt:this.hg,Jg:this.Qn.Et().mu()};this.og.ht(t)}}function ih(e,t,r,i,s){let{context:n,horizontalPixelRatio:a,verticalPixelRatio:l}=t;n.lineTo(s._t*a,e*l),n.lineTo(i._t*a,e*l),n.closePath(),n.fillStyle=r,n.fill()}class ip extends Q{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et(e){if(null===this.rt)return;let{ot:t,lt:r,Jg:i,ct:s,Xt:n,Qg:a}=this.rt,l=this.rt.lM??(this.rt.oM?0:e.mediaSize.height);if(null===r)return;let o=e.context;o.lineCap="butt",o.lineJoin="round",o.lineWidth=s,M(o,n),o.lineWidth=1,is(e,t,a,r,i,this._M.bind(this),ih.bind(null,l))}}class im{uM(e,t){let r=this.cM,{dM:i,fM:s,pM:n,vM:a,lM:l,mM:o,wM:d}=t;if(void 0===this.gM||void 0===r||r.dM!==i||r.fM!==s||r.pM!==n||r.vM!==a||r.lM!==l||r.mM!==o||r.wM!==d){let{verticalPixelRatio:r}=e,c=l||o>0?r:1,u=o*c,h=d===e.bitmapSize.height?d:d*c,p=e.context.createLinearGradient(0,u,0,h);if(p.addColorStop(0,i),null!=l){let e=tn(((l??0)*c-u)/(h-u),0,1);p.addColorStop(e,s),p.addColorStop(e,n)}p.addColorStop(1,a),this.gM=p,this.cM=t}return this.gM}}class ix extends ip{constructor(){super(...arguments),this.MM=new im}_M(e,t){let r=this.rt;return this.MM.uM(e,{dM:t.br,fM:t.Sr,pM:t.Cr,vM:t.Pr,lM:r.lM,mM:r.mM??0,wM:r.wM??e.bitmapSize.height})}}class ig extends id{constructor(){super(...arguments),this.bM=new im}iM(e,t){let r=this.rt;return this.bM.uM(e,{dM:t.gr,fM:t.gr,pM:t.Mr,vM:t.Mr,lM:r.lM,mM:r.mM??0,wM:r.wM??e.bitmapSize.height})}}class ib extends ii{constructor(e,t){super(e,t),this.og=new X,this.SM=new ix,this.xM=new ig,this.og.st([this.SM,this.xM])}Gg(e,t,r){return{...this.Zg(e,t),...r.Dr(e)}}pg(){let e,t,r=this.Jn.zt();if(null===r)return;let i=this.Jn.N(),s=this.Jn.Ft().Nt(i.baseValue.price,r.Wt),n=this.Qn.Et().mu();if(null!==this.hg&&0!==this.rg.length){if(i.relativeGradient){e=this.rg[this.hg.from].ut,t=this.rg[this.hg.from].ut;for(let r=this.hg.from;r<this.hg.to;r++){let i=this.rg[r];i.ut<e&&(e=i.ut),i.ut>t&&(t=i.ut)}}this.SM.ht({ot:this.rg,ct:i.lineWidth,Xt:i.lineStyle,Qg:i.lineType,lM:s,mM:e,wM:t,oM:!1,lt:this.hg,Jg:n}),this.xM.ht({ot:this.rg,ct:i.lineWidth,Xt:i.lineStyle,Qg:i.lineVisible?i.lineType:void 0,tM:i.pointMarkersVisible?i.pointMarkersRadius||i.lineWidth/2+2:void 0,lM:s,mM:e,wM:t,lt:this.hg,Jg:n})}}}class iv extends ip{constructor(){super(...arguments),this.MM=new im}_M(e,t){return this.MM.uM(e,{dM:t.mr,fM:"",pM:"",vM:t.wr,mM:this.rt?.mM??0,wM:e.bitmapSize.height})}}class iy extends ii{constructor(e,t){super(e,t),this.og=new X,this.CM=new iv,this.PM=new ic,this.og.st([this.CM,this.PM])}Gg(e,t,r){return{...this.Zg(e,t),...r.Dr(e)}}pg(){let e,t=this.Jn.N();if(null!==this.hg&&0!==this.rg.length){if(t.relativeGradient){e=this.rg[this.hg.from].ut;for(let t=this.hg.from;t<this.hg.to;t++){let r=this.rg[t];r.ut<e&&(e=r.ut)}}this.CM.ht({Qg:t.lineType,ot:this.rg,Xt:t.lineStyle,ct:t.lineWidth,lM:null,mM:e,oM:t.invertFilledArea,lt:this.hg,Jg:this.Qn.Et().mu()}),this.PM.ht({Qg:t.lineVisible?t.lineType:void 0,ot:this.rg,Xt:t.lineStyle,ct:t.lineWidth,lt:this.hg,Jg:this.Qn.Et().mu(),tM:t.pointMarkersVisible?t.pointMarkersRadius||t.lineWidth/2+2:void 0})}}}class iw extends rU{constructor(e,t){super(e,t,!1)}fg(e,t,r){t.uu(this.rg,V(this.hg)),e.ql(this.rg,r,V(this.hg))}VM(e,t,r){return{wt:e,qh:t.Wt[0],Yh:t.Wt[1],jh:t.Wt[2],Kh:t.Wt[3],_t:NaN,Yl:NaN,jl:NaN,Kl:NaN,Xl:NaN}}cg(){let e=this.Jn.Rh();this.rg=this.Jn.Xs().Hr().map(t=>this.Gg(t.Re,t,e))}}class ij extends Q{constructor(){super(...arguments),this.Yt=null,this.yM=0}ht(e){this.Yt=e}et(e){if(null===this.Yt||0===this.Yt.Xs.length||null===this.Yt.lt)return;let{horizontalPixelRatio:t}=e;this.yM=function(e,t){if(e>=2.5&&e<=4)return Math.floor(3*t);let r=1-.2*Math.atan(Math.max(4,e)-4)/(.5*Math.PI),i=Math.min(Math.floor(e*r*t),Math.floor(e*t));return Math.max(Math.floor(t),i)}(this.Yt.mu,t),this.yM>=2&&Math.floor(t)%2!=this.yM%2&&this.yM--;let r=this.Yt.Xs;this.Yt.BM&&this.IM(e,r,this.Yt.lt),this.Yt.Mi&&this.uv(e,r,this.Yt.lt);let i=this.EM(t);(!this.Yt.Mi||this.yM>2*i)&&this.AM(e,r,this.Yt.lt)}IM(e,t,r){if(null===this.Yt)return;let{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e,a="",l=Math.min(Math.floor(s),Math.floor(this.Yt.mu*s)),o=Math.floor(.5*(l=M
1ath.max(Math.floor(s),Math.min(l,this.yM)))),d=null;for(let e=r.from;e<r.to;e++){let r=t[e];r.pr!==a&&(i.fillStyle=r.pr,a=r.pr);let c=Math.round(Math.min(r.Yl,r.Xl)*n),u=Math.round(Math.max(r.Yl,r.Xl)*n),h=Math.round(r.jl*n),p=Math.round(r.Kl*n),m=Math.round(s*r._t)-o,f=m+l-1;null!==d&&(m=Math.min(m=Math.max(d+1,m),f));let x=f-m+1;i.fillRect(m,h,x,c-h),i.fillRect(m,u+1,x,p-u),d=f}}EM(e){let t=Math.floor(+e);this.yM<=2*t&&(t=Math.floor(.5*(this.yM-1)));let r=Math.max(Math.floor(e),t);return this.yM<=2*r?Math.max(Math.floor(e),Math.floor(+e)):r}uv(e,t,r){if(null===this.Yt)return;let{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e,a="",l=this.EM(s),o=null;for(let e=r.from;e<r.to;e++){let r=t[e];r.dr!==a&&(i.fillStyle=r.dr,a=r.dr);let h=Math.round(r._t*s)-Math.floor(.5*this.yM),p=h+this.yM-1,m=Math.round(Math.min(r.Yl,r.Xl)*n),f=Math.round(Math.max(r.Yl,r.Xl)*n);if(null!==o&&(h=Math.min(h=Math.max(o+1,h),p)),this.Yt.mu*s>2*l){var d,c,u;d=h,c=p-h+1,u=f-m+1,i.fillRect(d+l,m,c-2*l,l),i.fillRect(d+l,m+u-l,c-2*l,l),i.fillRect(d,m,l,u),i.fillRect(d+c-l,m,l,u)}else{let e=p-h+1;i.fillRect(h,m,e,f-m+1)}o=p}}AM(e,t,r){if(null===this.Yt)return;let{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e,a="",l=this.EM(s);for(let e=r.from;e<r.to;e++){let r=t[e],o=Math.round(Math.min(r.Yl,r.Xl)*n),d=Math.round(Math.max(r.Yl,r.Xl)*n),c=Math.round(r._t*s)-Math.floor(.5*this.yM),u=c+this.yM-1;if(r.cr!==a){let e=r.cr;i.fillStyle=e,a=e}this.Yt.Mi&&(c+=l,o+=l,u-=l,d-=l),o>d||i.fillRect(c,o,u-c+1,d-o+1)}}}class iS extends iw{constructor(){super(...arguments),this.og=new ij}Gg(e,t,r){return{...this.VM(e,t,r),...r.Dr(e)}}pg(){let e=this.Jn.N();this.og.ht({Xs:this.rg,mu:this.Qn.Et().mu(),BM:e.wickVisible,Mi:e.borderVisible,lt:this.hg})}}class ik extends Q{constructor(){super(...arguments),this.Yt=null,this.zM=[]}ht(e){this.Yt=e,this.zM=[]}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:r}){if(null===this.Yt||0===this.Yt.ot.length||null===this.Yt.lt)return;this.zM.length||this.LM(t);let i=Math.max(1,Math.floor(r)),s=Math.round(this.Yt.OM*r)-Math.floor(i/2),n=s+i;for(let t=this.Yt.lt.from;t<this.Yt.lt.to;t++){let a,l,o=this.Yt.ot[t],d=this.zM[t-this.Yt.lt.from],c=Math.round(o.ut*r);e.fillStyle=o.cr,c<=s?(a=c,l=n):(a=s,l=c-Math.floor(i/2)+i),e.fillRect(d.Uh,a,d.bi-d.Uh+1,l-a)}}LM(e){if(null===this.Yt||0===this.Yt.ot.length||null===this.Yt.lt)return void(this.zM=[]);let t=1>=Math.ceil(this.Yt.mu*e)?0:Math.max(1,Math.floor(e)),r=Math.round(this.Yt.mu*e)-t;this.zM=Array(this.Yt.lt.to-this.Yt.lt.from);for(let t=this.Yt.lt.from;t<this.Yt.lt.to;t++){let i,s,n=this.Yt.ot[t],a=Math.round(n._t*e);if(r%2){let e=(r-1)/2;i=a-e,s=a+e}else{let e=r/2;i=a-e,s=a+e-1}this.zM[t-this.Yt.lt.from]={Uh:i,bi:s,NM:a,ne:n._t*e,wt:n.wt}}for(let e=this.Yt.lt.from+1;e<this.Yt.lt.to;e++){let r=this.zM[e-this.Yt.lt.from],i=this.zM[e-this.Yt.lt.from-1];r.wt===i.wt+1&&r.Uh-i.bi!==t+1&&(i.NM>i.ne?i.bi=r.Uh-t-1:r.Uh=i.bi+t+1)}let i=Math.ceil(this.Yt.mu*e);for(let e=this.Yt.lt.from;e<this.Yt.lt.to;e++){let t=this.zM[e-this.Yt.lt.from];t.bi<t.Uh&&(t.bi=t.Uh),i=Math.min(t.bi-t.Uh+1,i)}if(t>0&&i<4)for(let e=this.Yt.lt.from;e<this.Yt.lt.to;e++){let t=this.zM[e-this.Yt.lt.from];t.bi-t.Uh+1>i&&(t.NM>t.ne?t.bi-=1:t.Uh+=1)}}}class iN extends ii{constructor(){super(...arguments),this.og=new ik}Gg(e,t,r){return{...this.Zg(e,t),...r.Dr(e)}}pg(){let e={ot:this.rg,mu:this.Qn.Et().mu(),lt:this.hg,OM:this.Jn.Ft().Nt(this.Jn.N().base,L(this.Jn.zt()).Wt)};this.og.ht(e)}}e.s(["AreaSeries",0,{type:"Area",isBuiltIn:!0,defaultOptions:{topColor:"rgba( 46, 220, 135, 0.4)",bottomColor:"rgba( 40, 221, 100, 0)",invertFilledArea:!1,relativeGradient:!1,lineColor:"#33D778",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},$g:(e,t)=>new iy(e,t)},"BaselineSeries",0,{type:"Baseline",isBuiltIn:!0,defaultOptions:{baseValue:{type:"price",price:0},relativeGradient:!1,topFillColor1:"rgba(38, 166, 154, 0.28)",topFillColor2:"rgba(38, 166, 154, 0.05)",topLineColor:"rgba(38, 166, 154, 1)",bottomFillColor1:"rgba(239, 83, 80, 0.05)",bottomFillColor2:"rgba(239, 83, 80, 0.28)",bottomLineColor:"rgba(239, 83, 80, 1)",lineWidth:3,lineStyle:0,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroun
1dColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},$g:(e,t)=>new ib(e,t)},"CandlestickSeries",0,{type:"Candlestick",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},$g:(e,t)=>new iS(e,t)},"HistogramSeries",0,{type:"Histogram",isBuiltIn:!0,defaultOptions:{color:"#26a69a",base:0},$g:(e,t)=>new iN(e,t)},"LineSeries",0,{type:"Line",isBuiltIn:!0,defaultOptions:{color:"#2196f3",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},$g:(e,t)=>new iu(e,t)},"createChart",0,function(e,t){var r,i;let s;return r=new tY,i=tY.ld(t),s=new ir(function(e){if(O(e)){let t=document.getElementById(e);return A(null!==t,`Cannot find element in DOM with id=${e}`),t}return e}(e),r,i),r.setOptions(s.options()),s}],463547)},373641,e=>{"use strict";let t=(0,e.i(504458).default)("arrow-down-up",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);e.s(["ArrowDownUp",0,t],373641)},242150,e=>{"use strict";let t=(0,e.i(504458).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);e.s(["ArrowDown",0,t],242150)},985433,e=>{"use strict";let t=(0,e.i(504458).default)("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);e.s(["ArrowRight",0,t],985433)},522973,e=>{"use strict";let t=(0,e.i(504458).default)("arrow-up-down",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);e.s(["ArrowUpDown",0,t],522973)},440736,e=>{"use strict";let t=(0,e.i(504458).default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);e.s(["ArrowUp",0,t],440736)},682768,e=>{"use strict";let t=(0,e.i(504458).default)("chart-column",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);e.s(["BarChart3",0,t],682768)},402392,e=>{"use strict";var t=e.i(934361);e.s(["CheckIcon",()=>t.default])},1169,996709,e=>{"use strict";let t=(0,e.i(504458).default)("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);e.s(["default",0,t],996709),e.s(["ChevronDown",0,t],1169)},652538,e=>{"use strict";let t=(0,e.i(504458).default)("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);e.s(["ChevronLeft",0,t],652538)},947056,e=>{"use strict";let t=(0,e.i(504458).default)("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);e.s(["default",0,t])},735006,514469,e=>{"use strict";var t=e.i(947056);e.s(["ChevronUp",()=>t.default],735006);let r=(0,e.i(504458).default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);e.s(["User",0,r],514469)},988462,e=>{"use strict";let t=(0,e.i(504458).default)("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]);e.s(["Download",0,t],988462)},199472,312076,25158,e=>{"use strict";let t=(0,e.i(504458).default)("ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);e.s(["default",0,t],312076),e.s(["Ellipsis",0,t],199472);var r=e.i(394390),i=e.i(183023);let s=(0,i.createContext)(null);e.s(["QuickTradeProvider",0,function({openQuickTrade:e,children:t}){let n=(0,i.useMemo)(()=>({openQuickTrade:e}),[e]);return(0,r.jsx)(s.Provider,{value:n,children:t})},"useQuickTrade",0,function(){return(0,i.useContext)(s)}],25158)},845165,e=>{"use strict";let t=(0,e.i(504458).default)("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);e.s(["ExternalLink",0,t],845165)},865076,e=>{"use strict";let t=(0,e.i(504458).default)("gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);e.s(["Gift",0,t],865076)},613897,865071,328259,e=>{"use strict";var t=e.i(504458);let r=(0,t.default)("grip-vertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);e.s(["GripVertical",0,r],613897);
1let i=(0,t.default)("layout-dashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);e.s(["LayoutDashboard",0,i],865071);let s=(0,t.default)("lock-keyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);e.s(["LockKeyhole",0,s],328259)},741436,303745,205702,e=>{"use strict";var t=e.i(504458);let r=(0,t.default)("link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);e.s(["Link",0,r],741436);let i=(0,t.default)("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);e.s(["LogOut",0,i],303745);let s=(0,t.default)("scroll-text",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);e.s(["ScrollText",0,s],205702)},287196,111778,e=>{"use strict";var t=e.i(504458);let r=(0,t.default)("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);e.s(["Maximize2",0,r],287196);let i=(0,t.default)("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]);e.s(["Minimize2",0,i],111778)},285620,e=>{"use strict";let t=(0,e.i(504458).default)("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);e.s(["Minus",0,t],285620)},31418,194578,e=>{"use strict";var t=e.i(504458);let r=(0,t.default)("panels-top-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);e.s(["PanelsTopLeft",0,r],31418);let i=(0,t.default)("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);e.s(["RotateCcw",0,i],194578)},409686,e=>{"use strict";let t=(0,e.i(504458).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["Plus",0,t],409686)},340053,e=>{"use strict";let t=(0,e.i(504458).default)("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",0,t],340053)},401382,e=>{"use strict";let t=(0,e.i(504458).default)("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);e.s(["Save",0,t],401382)},58596,e=>{"use strict";let t=(0,e.i(504458).default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);e.s(["Search",0,t],58596)},467290,e=>{"use strict";let t=(0,e.i(504458).default)("share-2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);e.s(["Share2",0,t],467290)},525107,e=>{"use strict";let t=(0,e.i(504458).default)("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
1y:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);e.s(["ShieldCheck",0,t],525107)},370051,e=>{"use strict";let t=(0,e.i(504458).default)("shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);e.s(["Shield",0,t],370051)},72226,e=>{"use strict";let t=(0,e.i(504458).default)("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]);e.s(["Sparkles",0,t],72226)},599179,109650,828845,596727,907169,e=>{"use strict";var t=e.i(504458);let r=(0,t.default)("star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);e.s(["Star",0,r],599179);let i=(0,t.default)("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);e.s(["LayoutGrid",0,i],109650);let s=[{id:"all",labelKey:"categoryAll",symbols:new Set},{id:"pre-ipo",labelKey:"categoryPreIpo",symbols:new Set(["ANTHROPIC","OPENAI","OURA","SPACEX","SPCX"])},{id:"crypto",labelKey:"categoryCrypto",symbols:new Set(["0G","1000BONK","1000FLOKI","1000NOT","1000PEPE","1000SHIB","1000TOSHI","2Z","AAVE","ADA","ADI","AERO","AI","AI16Z","ANSEM","APE","APEX","APT","ARB","ARC","ASTER","AVAX","AVNT","AXS","AZTEC","BCH","BERA","BIO","BIRB","BNB","BOME","BONK","BTC","CAP","CASHCAT","CATE","CC","CHIP","CRO","CRV","CTR","DASH","DATA","DOGE","DOLO","DOT","DUSK","DYDX","EDEN","EDGE","EIGEN","ENA","ETH","ETHFI","FARTCOIN","FF","FIL","FOGO","FOLKS","GMX","GRAM","GRASS","HBAR","HYPE","ICP","IP","JITOSOL","JTO","JUP","KAITO","KBONK","KFLOKI","KMNO","KNOT","KPEPE","KSHIB","KTOSHI","LAUNCHCOIN","LDO","LINEA","LINK","LIT","LTC","MEGA","MELANIA","MET","MKR","MNT","MON","MORPHO","MYX","NEAR","NMR","ONDO","OP","ORE","PENDLE","PENGU","PEPE","PIPPIN","POL","PONS","POPCAT","PROVE","PUMP","PYTH","QNT","RAIL","RAY","RESOLV","RIVER","ROBO","S","SAMO","SEI","SHIB","SKR","SKY","SOL","SPX","SPX6900","STABLE","STBL","STRK","SUI","SYRUP","TAO","TIA","TON","TRUMP","TRX","UNI","USELESS","VIRTUAL","VVV","WIF","WLD","WLFI","XLM","XMR","XPL","XRP","YZY","ZEC","ZK","ZORA","ZRO"])},{id:"meme",labelKey:"categoryMeme",symbols:new Set(["1000BONK","1000FLOKI","1000NOT","1000PEPE","1000SHIB","1000TOSHI","AI","AI16Z","ANSEM","APE","BIRB","BOME","BONK","CASHCAT","CATE","DOGE","FARTCOIN","KBONK","KFLOKI","KNOT","KPEPE","KSHIB","KTOSHI","LAUNCHCOIN","MELANIA","PENGU","PEPE","PIPPIN","POPCAT","PUMP","SAMO","SHIB","SKR","SPX","SPX6900","TRUMP","USELESS","WIF","WLFI","YZY"])},{id:"l1",label:"L1",symbols:new Set(["0G","ADA","APT","AVAX","BCH","BERA","BNB","BTC","CC","CRO","DASH","DATA","DOGE","DOT","DUSK","ETH","FIL","FOGO","GRAM","HBAR","HYPE","ICP","IP","LTC","MON","NEAR","S","SEI","SOL","STABLE","SUI","TIA","TON","TRX","XLM","XMR","XPL","XRP","ZEC"])},{id:"l2",label:"L2",symbols:new Set(["ADI","ARB","AZTEC","CTR","LINEA","LIT","MEGA","MNT","OP","POL","STRK","ZK"])},{id:"defi",label:"DeFi",symbols:new Set(["AAVE","AERO","APEX","APT","ASTER","AVNT","CAP","CHIP","CRV","DOLO","DYDX","EDEN","EDGE","EIGEN","ENA","ETHFI","FF","FOGO","FOLKS","GMX","HYPE","JITOSOL","JTO","JUP","KAITO","KMNO","LDO","LINK","LIT","MET","MKR","MORPHO","MYX","NMR","ONDO","ORE","PENDLE","PYTH","RAIL","RAY","RESOLV","RIVER","SEI","SKY","STBL","SYRUP","UNI","VIRTUAL","VVV","WLFI"])},{id:"ai",label:"AI",symbols:new Set(["AI16Z","AMD","ANTHROPIC","ARC","BOTZ","CBRS","CHIP","CRWV","FIL","GRASS","ICP","KAITO","MINIMAX","NBIS","NEAR","NMR","NVDA","OPENAI","PIPPIN","PLTR","ROBO","TAO","VIRTUAL","VVV","WLD","ZHIPU"])},{id:"equities",labelKey:"categoryEquities",symbols:new Set(["AAOI","AAPL","ADBE","AMD","AMZN","ANTHROPIC","ARM","ASML","AVGO","AXTI","BABA","BB","BE","BMNR","BOT","BOTZ","BYD","CBRS","COIN","CRCL","CRWD","CRWV","CXMT","DELL","DIA","DRAM","EWY","GEV","GME","GOOGL","HANMI","HOOD","HYUNDAI","HYUNDAIUSD","IBM","INTC","IREN","IWM","KIOXIA","KORU","KRCOMP","LITE","LLY","MAGS","META","MINIMAX","MRNA","MRVL","MSFT","MSTR","MU","NBIS","NET","NFLX","NOK","NOW","NVDA","OPENAI","ORCL","PLTR","POPMART","QCOM","QQQ","RKLB","SAMSUNG","SAMSUNGUSD","SHEIN","SKHY","SKHYNIX","SKHYNIXUSD","SMIC","SNDK","SONY","SOXL","SOXS","SOXX","SPACEX","SPCX","SPY","STABLECOINX","STRC","TENCENT","TSLA","TSM","TTWO","TXN","UNITREE","URA","US100","US500","WDC","WEN","XIAOMI","ZHIPU"])},{id:"commodities",labelKey:"categoryCommodities",symbols:new Set(["BRENTOIL","CRUDEOIL","H100","NATGAS","PA
1XG","WHEAT","WTI","WTIOIL","XAG","XAGT","XAU","XAUT","XCU","XPD","XPT"])},{id:"forex",labelKey:"categoryForex",symbols:new Set(["AUD","AUDUSD","CNH","EUR","EURUSD","GBP","GBPUSD","JPY","NZD","NZDUSD","USDCAD","USDCHF","USDCNH","USDHKD","USDJPY","USDKRW","USDMXN"])},{id:"bonds",labelKey:"categoryBonds",symbols:new Set(["US10Y"])}];e.s(["ALL_CATEGORY_ID",0,"all","MARKET_CATEGORIES",0,s,"matchesCategory",0,function(e,t){if("all"===t)return!0;let r=s.find(e=>e.id===t);return!r||r.symbols.has(e.toUpperCase())}],828845);var n=e.i(394390),a=e.i(183023),l=e.i(972342),o=e.i(42013),d=e.i(942553),c=e.i(931387);let u=(0,t.default)("ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);var h=e.i(985433),p=e.i(803817),m=e.i(875574),f=e.i(894771),x=e.i(616861),g=e.i(999069),b=e.i(987752),v=e.i(430232);function y(e){return/^\/perps(\/|$)/.test(e)}e.s(["isTerminalRoute",0,y],596727);var w=e.i(774249);let j="imperial_armada_invite_v1",S="imperial_armada_invite_seen_v1",k="imperial_armada_known_v1",N={...w.EMPTY_PREFERENCES},P=!1;function T(){try{let e=(0,w.parsePreferences)(localStorage.getItem(j),Date.now());N={knownUntil:Math.max(N.knownUntil,e.knownUntil),dismissedUntil:Math.max(N.dismissedUntil,e.dismissedUntil),never:N.never||e.never}}catch{}try{let e=document.cookie.split("; ").find(e=>e.startsWith(k+"="))?.split("=")[1],t=Number(e);Number.isFinite(t)&&t>Date.now()&&(N.knownUntil=Math.max(N.knownUntil,Math.min(t,Date.now()+w.REMEMBER_DAYS*w.DAY)))}catch{}return{...N}}function C(e){N=e;try{localStorage.setItem(j,JSON.stringify({v:1,...e}))}catch{}return{...e}}function M(){P=!0;try{sessionStorage.setItem(S,"1")}catch{}}var _=e.i(457058),A=e.i(943494),E=e.i(623075);let L="focus-ring flex min-h-12 w-full items-center justify-center gap-2 rounded-[10px] border border-[#f1d394]/50 bg-gradient-to-r from-[#f1d394] to-[#d7aa63] px-4 text-sm font-semibold text-[#20180d] transition-[filter] enabled:hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60";function F({open:e,onDismiss:t,onConnect:r,onRedeem:i,onUnlocked:s,initialCode:l,showConnect:o,returnFocus:c}){let u=(0,d.useTranslations)("armada"),[h,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),f=(0,a.useRef)(!1),[x,g]=(0,a.useState)(l),[b,v]=(0,a.useState)(!1),[y,w]=(0,a.useState)(null),j="granted"===y||"already_admitted"===y,S=j?2:+!o,k=async()=>{if(!b&&x.trim()){v(!0),w(null);try{w(await i(x))}catch{w("failed")}finally{v(!1)}}};return(0,n.jsx)(E.Dialog,{open:e,onOpenChange:e=>{e||t(h)},children:(0,n.jsxs)(E.DialogContent,{className:"gap-0 overflow-x-hidden rounded-2xl border-[#725335] bg-[#181714] text-[#faf4e8] sm:max-w-[468px] [&>[data-slot=dialog-close]]:size-11 [&>[data-slot=dialog-close]]:rounded-full [&>[data-slot=dialog-close]]:bg-black/65 [&>[data-slot=dialog-close]]:text-white",onOpenAutoFocus:e=>{e.preventDefault(),m.current?.focus()},onCloseAutoFocus:e=>{e.preventDefault(),f.current||c()},children:[(0,n.jsxs)("div",{className:"relative h-[130px] overflow-hidden sm:h-[156px] [@media(max-height:800px)]:h-[88px]","aria-hidden":"true",children:[(0,n.jsx)(_.default,{src:"/armada-access-fleet.jpg",alt:"",fill:!0,loading:"eager",sizes:"(max-width: 500px) 100v
1w, 468px",className:"object-cover"}),(0,n.jsx)("div",{className:"absolute inset-0 bg-gradient-to-t from-[#181714] via-transparent to-transparent"})]}),(0,n.jsxs)("div",{className:"relative px-5 pb-5 text-center sm:px-7 sm:pb-6",children:[(0,n.jsxs)("div",{className:"mt-2 mb-4 flex flex-wrap items-center justify-center gap-4 text-[10px] font-semibold uppercase tracking-[0.11em] text-[#e5bb78]",children:[(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"sr-only",children:u("eyebrow")}),(0,n.jsx)("span",{"aria-hidden":"true",className:"block h-[10px] w-[90px] bg-current [mask:url(/armada-wordmark.svg)_center/contain_no-repeat]"})]}),(0,n.jsx)("span",{className:"border-l border-[#725335] pl-4",children:u("badge")})]}),(0,n.jsx)(E.DialogTitle,{ref:m,tabIndex:-1,className:"mx-auto max-w-[370px] text-[30px] leading-[1.08] font-bold tracking-[-0.035em] text-balance outline-none sm:text-[36px]",children:u("title")}),(0,n.jsx)(E.DialogDescription,{className:"mx-auto mt-3 max-w-[340px] text-[14px] leading-[21px] text-pretty text-[#d0c8bb]",children:u("description")}),(0,n.jsx)("ol",{className:"my-4 grid grid-cols-3 gap-2 text-[11px] leading-4",children:["stepOne","stepTwo","stepThree"].map((e,t)=>{let r=j||t<S,i=t===S;return(0,n.jsxs)("li",{"aria-current":i?"step":void 0,className:"relative flex flex-col items-center gap-3",children:[t<2&&(0,n.jsx)("span",{"aria-hidden":"true",className:"absolute top-3 left-[calc(50%+16px)] h-px w-[calc(100%-24px)] bg-[#534534]"}),(0,n.jsx)("span",{"aria-hidden":"true",className:`flex size-6 items-center justify-center rounded-full border text-[10px] ${r?"border-[#e5bb78] bg-[#e5bb78] text-[#20180d]":i?"border-[#d2a762] bg-[#2c251b] font-semibold text-[#f1d394]":"border-[#725335] text-[#b8b0a3]"}`,children:r?(0,n.jsx)("svg",{viewBox:"0 0 16 16",className:"size-4",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"m3.5 8 3 3 6-6"})}):(0,n.jsxs)(n.Fragment,{children:["0",t+1]})}),(0,n.jsx)("span",{className:`max-w-[100px] ${i?"font-semibold text-[#faf4e8]":"text-[#b8b0a3]"}`,children:u(0===t&&r?"walletConnected":e)})]},e)})}),j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"status",className:"mb-3 text-[13px] text-[#edc587]",children:u(`status.${y}`)}),(0,n.jsx)("button",{type:"button",onClick:s,className:L,children:u("startTrading")})]}):o?(0,n.jsx)("button",{type:"button",onClick:()=>{f.current=!0,r(h)},className:L,children:u("connectToRedeem")}):(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault(),k()},className:"flex flex-col gap-2",children:[(0,n.jsx)("label",{htmlFor:"armada-invite-code",className:"text-left text-[11px] font-semibold text-[#d0c8bb]",children:u("codeLabel")}),(0,n.jsx)("input",{id:"armada-invite-code",value:x,onChange:e=>{g(e.target.value),w(null)},placeholder:u("codePlaceholder"),autoComplete:"off",autoCapitalize:"characters",spellCheck:!1,maxLength:64,"aria-invalid":null!==y,"aria-describedby":y?"armada-invite-result":void 0,className:"min-h-12 w-full rounded-[10px] border border-[#967044] bg-[#100f0d] px-4 text-center font-mono text-base tracking-[0.12em] text-[#faf4e8] uppercase placeholder:normal-case placeholder:tracking-normal placeholder:text-[#aea497] focus:border-[#e5bb78] focus:outline-2 focus:outline-offset-2 focus:outline-[#e5bb78]"}),y&&(0,n.jsx)("p",{id:"armada-invite-result",role:"alert",className:"text-[12px] text-[#f0a38a]",children:u(`status.${y}`)}),(0,n.jsxs)("button",{type:"submit",disabled:b||!x.trim(),className:L,children:[b&&(0,n.jsx)(A.Loader2,{"aria-hidden":"true",className:"size-4 animate-spin motion-reduce:animate-none"}),u(b?"redeeming":"redeem")]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>t(h),className:"focus-ring mt-2 min-h-11 w-full rounded-lg text-[13px] text-[#e3dccf] transition-colors hover:bg-white/5",children:u("keepTrading")}),(0,n.jsxs)("label",{className:"mx-auto mt-1 flex min-h-11 w-fit cursor-pointer items-center justify-center gap-2 rounded text-xs text-[#b8b0a3]",children:[(0,n.jsx)("input",{type:"checkbox",checked:h,onChange:e=>p(e.target.checked),className:"size-4 accent-[#e5bb78] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#e5bb78]"}),u("never")]})]})]})})}function R(e){return e.trim().toUpperCase()}async function D(t,r,i,s){let n=R(r),a={"Content-Type":"application/json"};if(s)a.Authorization=`Bearer ${s}`;else if(i){let r=await i(new TextEncoder().encode(`imperial:armada-invite:${t}:${n}`));a["x-pubkey"]=t,a["x-signature"]=(await e.A(730276)).default.encode(r)}let l=await fetch("https://api.imperial.space/api/v1/armada/invite/redeem",{method:"POST",headers:a,body:JSON.stringify({wallet:t,code:n})});if(!l.ok)throw Error(`Invite redemption failed: ${l.status}`);return(await l.json()).status}let I="armada",U="imperial_armada_linked_code_v1";function O(){try{sessionStorage.removeItem(U)}catch{}}let B=(0,a.createContext)({available:!1,open:()=>{}});function z(){return!!document.querySelector('[role="dialog"][data-state="open"], [role="alertdialog"], dialog[open], [data-privy-dialog]')}function $(){return(0,a.useContext)(B)}e.s(["ArmadaAccessEntry",0,function({compactHeader:e=!1,phone:t=!1}){let r=(0,d.useTranslations)("armada"),i=$(),s=(0,a.useId)();return(0,n.jsxs)("button",{"data-armada-entry":!0,type:"button",onClick:i.open,disabled:!i.available,"aria-label":r(t?"entryShort":"entry"),"aria-describedby":t?s:void 0,title:e||t?r("entry"):void 0,"aria-haspopup":"dialog",tabIndex:i.available?0:-1,className:`focus-ring group flex shrink-0 items-center justify-center rounded-control whitespace-nowrap text-primary transition-colors enabled:hover:bg-primary/[0.08] enabled:hover:text-primary disabled:cursor-not-allowed disabled:opacity-50 ${t?"h-11 min-w-11 text-xs":"h-8 gap-1.5 px-2 text-[13px] md:h-9"} ${i.available?"":"invisible"} ${e&&!t?c.default.iconControl:""}`,children:[!t&&(0,n.jsx)(u,{"aria-hidden":"true",className:"size-3.5 shrink-0 opacity-80"}),(0,n.jsx)("span",{className:`underline decoration-primary/35 underline-offset-4 group-hover:decoration-primary/70 ${e&&!t?c.default.fullLabel:""}`,children:r(t?"entryShort":"entry")}),t&&(0,n.jsx)("span",{id:s,className:"sr-only",children:r("entry")}),!t&&(0,n.jsx)(h.ArrowRight,{"aria-hidden":"true",className:`size-3 shrink-0 opacity-60 ${e?c.default.fullIcon:""}`})]})},"ArmadaAccessProvider",0,function({children:e}){let{isOpen:t}=(0,b.useOnboarding)(),{publicKey:r,isLoading:i,signMessage:s}=(0,m.useUnifiedWalletContext)(),{jwt:d}=(0,x.useMobileAuth)(),{jwt:c}
1=(0,g.useSponsorGas)(),u=d??c,{ready:h,authenticated:N}=(0,l.usePrivy)(),{connecting:_,disconnecting:A,publicKey:E}=(0,o.useWallet)(),{armadaParticipant:L,refreshProfiles:$}=(0,f.useProfile)(),V=(0,p.usePathname)(),H=r?.toBase58()??null,[W,q]=(0,a.useState)(null),[K,G]=(0,a.useState)(null),[Y,X]=(0,a.useState)(null),[Q,J]=(0,a.useState)(null),Z=(0,a.useRef)(!1),ee=(0,a.useRef)(void 0),et=(0,a.useRef)(null),er=!H&&N||null!=E&&E.toBase58()!==H,ei=null!==W&&null!==K&&h&&!i&&!_&&!A&&!er,es=(0,w.audienceFor)(ei,H,L,W??w.EMPTY_PREFERENCES,K??0),en="prospect"===es,ea=en&&null!==Y&&Y.wallet===H&&Y.path===V&&Y.dismissedUntil===W?.dismissedUntil&&Y.never===W?.never;null===Y||ea||X(null);let el=ea&&!t;(0,a.useEffect)(()=>{J(function(){let e=null;try{let t=new URL(window.location.href),r=t.searchParams.get(I);if(null===r)return sessionStorage.getItem(U);t.searchParams.delete(I),window.history.replaceState(window.history.state,"",t),(e=R(r)||null)&&sessionStorage.setItem(U,e)}catch{}return e}());let e=()=>{q(T()),G(Date.now())},t=t=>{(t.key===j||null===t.key)&&e()},r=()=>{Z.current=!0};return e(),window.addEventListener("storage",t),window.addEventListener("focus",e),window.addEventListener("pageshow",e),document.addEventListener("pointerdown",r,{capture:!0}),document.addEventListener("keydown",r,{capture:!0}),()=>{window.removeEventListener("storage",t),window.removeEventListener("focus",e),window.removeEventListener("pageshow",e),document.removeEventListener("pointerdown",r,!0),document.removeEventListener("keydown",r,!0)}},[]),(0,a.useEffect)(()=>{H&&L?.wallet===H&&"member"===L.status&&q(function(){let e=T(),t=Date.now()+w.REMEMBER_DAYS*w.DAY;try{let e=window.location.hostname,r="imperial.space"===e||e.endsWith(".imperial.space")?"; Domain=imperial.space":"";document.cookie=k+"="+t+"; Max-Age="+86400*w.REMEMBER_DAYS+"; Path=/; SameSite=Lax"+r+("https:"===location.protocol?"; Secure":"")}catch{}return C({...e,knownUntil:t})}())},[H,L]),(0,a.useEffect)(()=>{if(!H)return;let e=Date.now(),t=()=>{"visible"!==document.visibilityState||Date.now()-e<1e3||(e=Date.now(),$())};return window.addEventListener("focus",t),window.addEventListener("pageshow",t),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("focus",t),window.removeEventListener("pageshow",t),document.removeEventListener("visibilitychange",t)}},[H,$]);let eo=(0,a.useCallback)(()=>{if(t||!en||z())return;et.current=document.activeElement instanceof HTMLElement?document.activeElement:null,M(),Z.current=!0;let e=T();q(e),X({wallet:H,path:V,dismissedUntil:e.dismissedUntil,never:e.never})},[en,H,V,X,q,t]);(0,a.useEffect)(()=>{if(!W||!y(V)||!(0,w.mayAutoInvite)(es,W,Z.current||function(){try{P||="1"===sessionStorage.getItem(S)}catch{}return P}(),Date.now()))return;let e=requestAnimationFrame(()=>{Z.current||z()||"visible"!==document.visibilityState||eo()});return()=>cancelAnimationFrame(e)},[es,W,V,eo]),(0,a.useEffect)(()=>{if(t||!Q||!en||Y||ee.current===H)return;let e=requestAnimationFrame(()=>{z()||(ee.current=H,eo())});return()=>cancelAnimationFrame(e)},[Q,en,Y,H,eo,t]);let ed=(0,a.useCallback)(e=>{let t;X(null),q((M(),C({...t=T(),dismissedUntil:Date.now()+w.DISMISS_DAYS*w.DAY,never:t.never||e})))},[X,q]),ec=(0,a.useCallback)(e=>{ed(e),O(),J(null)},[ed,J]),eu=(0,a.useCallback)(e=>{ed(e),window.setTimeout(v.promptConnectWallet,0)},[ed]),eh=(0,a.useCallback)(async e=>{if(!H)throw Error("wallet not connected");return D(H,e,s,u)},[H,s,u]),ep=(0,a.useCallback)(()=>{X(null),O(),J(null),$()},[$,X,J]),em=(0,a.useCallback)(()=>{t||(et.current?.isConnected&&et.current!==document.body?et.current.focus({preventScroll:!0}):document.querySelector("[data-armada-entry]:not([disabled])")?.focus({preventScroll:!0}))},[t]),ef=(0,a.useMemo)(()=>({available:en,open:eo}),[en,eo]);return(0,n.jsxs)(B.Provider,{value:ef,children:[e,Y&&(0,n.jsx)(F,{open:el,onDismiss:ec,onConnect:eu,onRedeem:eh,onUnlocked:ep,initialCode:Q??"",showConnect:!H,returnFocus:em})]})},"useArmadaAccess",0,$],907169)},145314,e=>{"use strict";let t=(0,e.i(504458).default)("sword",[["path",{d:"m11 19-6-6",key:"s7kpr"}],["path",{d:"m5 21-2-2",key:"1kw20b"}],["path",{d:"m8 16-4 4",key:"1oqv8h"}
1],["path",{d:"M9.5 17.5 21 6V3h-3L6.5 14.5",key:"pkxemp"}]]);e.s(["Sword",0,t],145314)},282027,351747,462430,e=>{"use strict";var t=e.i(556149);e.s(["TriangleAlert",()=>t.default],282027);var r=e.i(504458);let i=(0,r.default)("volume-2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);e.s(["Volume2",0,i],351747);let s=(0,r.default)("volume-x",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);e.s(["VolumeX",0,s],462430)},343877,e=>{"use strict";let t=(0,e.i(504458).default)("trophy",[["path",{d:"M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978",key:"1n3hpd"}],["path",{d:"M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978",key:"rfe1zi"}],["path",{d:"M18 9h1.5a1 1 0 0 0 0-5H18",key:"7xy6bh"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z",key:"1mhfuq"}],["path",{d:"M6 9H4.5a1 1 0 0 1 0-5H6",key:"tex48p"}]]);e.s(["Trophy",0,t],343877)},897406,e=>{"use strict";let t=(0,e.i(504458).default)("users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]]);e.s(["Users",0,t],897406)},183799,e=>{"use strict";let t=(0,e.i(504458).default)("wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);e.s(["Wallet",0,t],183799)},308294,e=>{"use strict";let t=(0,e.i(504458).default)("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);e.s(["Zap",0,t],308294)},223751,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i={bindSnapshot:function(){return d},createAsyncLocalStorage:function(){return o},createSnapshot:function(){return c}};for(var s in i)Object.defineProperty(r,s,{enumerable:!0,get:i[s]});let n=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class a{disable(){throw n}getStore(){}run(){throw n}exit(){throw n}enterWith(){throw n}static bind(e){return e}}let l="u">typeof globalThis&&globalThis.AsyncLocalStorage;function o(){return l?new l:new a}function d(e){return l?l.bind(e):a.bind(e)}function c(){return l?l.snapshot():function(e,...t){return e(...t)}}},328609,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"workAsyncStorageInstance",{enumerable:!0,get:function(){return i}});let i=(0,e.r(223751).createAsyncLocalStorage)()},105045,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"workAsyncStorage",{enumerable:!0,get:function(){return i.workAsyncStorageInstance}});let i=e.r(328609)},914291,(e,t,r)=>{"use strict";function i(e){return e.split("/").map(e=>encodeURIComponent(e)).join("/")}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"encodeURIPath",{enumerable:!0,get:function(){return i}})},493899,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"BailoutToCSR",{enumerable:!0,get:function(){return s}});let i=e.r(727910);function s({reason:e,children:t}){if("u"<typeof window)throw Object.defineProperty(new i.BailoutToCSRError(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return t}},953586,(e,t,r)=>{"use strict";
1Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"PreloadChunks",{enumerable:!0,get:function(){return o}});let i=e.r(394390),s=e.r(679278),n=e.r(105045),a=e.r(914291),l=e.r(633853);function o({moduleIds:e}){if("u">typeof window)return null;let t=n.workAsyncStorage.getStore();if(void 0===t)return null;let r=[];if(t.reactLoadableManifest&&e){let i=t.reactLoadableManifest;for(let t of e){if(!i[t])continue;let e=i[t].files;r.push(...e)}}if(0===r.length)return null;let d=(0,l.getAssetTokenQuery)();return(0,i.jsx)(i.Fragment,{children:r.map(e=>{let r=`${t.assetPrefix}/_next/${(0,a.encodeURIPath)(e)}${d}`;return e.endsWith(".css")?(0,i.jsx)("link",{precedence:"dynamic",href:r,rel:"stylesheet",as:"style",nonce:t.nonce},e):((0,s.preload)(r,{as:"script",fetchPriority:"low",nonce:t.nonce}),null)})})}},162463,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return d}});let i=e.r(394390),s=e.r(183023),n=e.r(493899),a=e.r(953586);function l(e){return{default:e&&"default"in e?e.default:e}}let o={loader:()=>Promise.resolve(l(()=>null)),loading:null,ssr:!0},d=function(e){let t={...o,...e},r=(0,s.lazy)(()=>t.loader().then(l)),d=t.loading;function c(e){let l=d?(0,i.jsx)(d,{isLoading:!0,pastDelay:!0,error:null}):null,o=!t.ssr||!!t.loading,c=o?s.Suspense:s.Fragment,u=t.ssr?(0,i.jsxs)(i.Fragment,{children:["u"<typeof window?(0,i.jsx)(a.PreloadChunks,{moduleIds:t.modules}):null,(0,i.jsx)(r,{...e})]}):(0,i.jsx)(n.BailoutToCSR,{reason:"next/dynamic",children:(0,i.jsx)(r,{...e})});return(0,i.jsx)(c,{...o?{fallback:l}:{},children:u})}return c.displayName="LoadableComponent",c}},807956,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return s}});let i=e.r(605509)._(e.r(162463));function s(e,t){let r={};"function"==typeof e&&(r.loader=e);let s={...r,...t};return(0,i.default)({...s,modules:s.loadableGenerated?.modules})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},319522,993628,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(942553),s=e.i(457395),n=e.i(409686),a=e.i(967090),l=e.i(116082),o=e.i(299959),d=e.i(153517);let c=e=>`imperial_unpinned_profiles_${e}`,u=e=>`imperial_acct_explainer_dismissed_${e}`,h=new Set,p=null,m=null,f=new Set;function x(){for(let e of f)e()}function g(e){try{let t=JSON.parse(localStorage.getItem(c(e))??"[]");return Array.isArray(t)?t.filter(e=>Number.isInteger(e)):[]}catch{return[]}}function b(e){try{return"1"===localStorage.getItem(u(e))}catch{return!0}}function v(e){if(e.key){if(p&&e.key===c(p.pk))p={pk:p.pk,set:new Set(g(p.pk))};else{if(!m||e.key!==u(m.pk))return;m={pk:m.pk,dismissed:b(m.pk)}}x()}}function y(e,t){return 0===f.size&&window.addEventListener("storage",v),f.add(t),!function(e){if(!e)return;let t=!1;p?.pk!==e&&(p={pk:e,set:new Set(g(e))},t=!0),m?.pk!==e&&(m={pk:e,dismissed:b(e)},t=!0),t&&x()}(e),()=>{f.delete(t),0===f.size&&window.removeEventListener("storage",v)}}function w(e){return e&&p?.pk===e?p.set:h}function j(e){return!e||m?.pk!==e||m.dismissed}function S(e,t,r){let i=r?new Set([...t].filter(e=>r.has(e))):t;p={pk:e,set:i};try{localStorage.setItem(c(e),JSON.stringify([...i]))}catch{}x()}e.s(["EMPTY_UNPINNED",0,h,"pinStored",0,function(e,t){let r=new Set(w(e));r.delete(t)&&S(e,r)},"readUnpinnedStored",0,g,"snapshotExplainer",0,j,"snapshotUnpinned",0,w,"subscribeStore",0,y,"writeExplainerDismissed",0,function(e){m={pk:e,dismissed:!0};try{localStorage.setItem(u(e),"1")}catch{}x()},"writeUnpinned",0,S],993628);let k="flex items-center font-mono text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60";function N(e,t){navigator.clipboard.writeText(e).then(()=>l.toast.success(t),()=>{})}let P={desktop:{list:"space-y-1",row:"relative flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left transition-colors",rowActive:"bg-surface-interactive",rowIdle:"hover:bg-surface-interactive/60",pick:"absolute inset-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",avatar:"pointer-events-none flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-sm border border-border bg-surface font-sans text-xs font-semibold text-secondary-foreground",name:"block truncate text-[12.5px] font-semibold text-foreground",address:`pointer-events-auto relative z-10 w-fit gap-1 text-[10.5px] ${k}`,copyGlyph:"h-2.5 w-2.5",value:"pointer-events-none ml-auto font-mono text-xs font-semibold tabular-nums text-foreground",explainer:"relative mx-0.5 mt-2 rounded-md border border-border bg-surface px-3 py-2.5 text-[11.5px] text-secondary-foreground",dismiss:"absolute right-1.5 top-1.5 flex h-4 w-4 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",dismissGlyph:"h-3 w-3",explainerTitle:"mb-0.5 block pr-4 text-xs font-bold text-foreground",note:"text-imperial-gold",add:"mt-2 flex h-[38px] w-full items-center justify-center gap-[7px] rounded-md border border-border bg-surface text-[12.5px] font-semibold text-secondary-foreground transition-colors hover:bg-surface-interactive hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",addGlyph:"h-3.5 w-3.5"},phone:{list:"space-y-1",row:"relative flex h-[56px] w-full items-center gap-[12.4px] rounded-[5px] pl-[13.7px] pr-[14px] text-left transition-colors",rowActive:"bg-[var(--phone-row)]",rowIdle:"hover:bg-[var(--phone-row)]",pick:"absolute inset-0 rounded-[5px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",avatar:"pointer-events-none flex h-[18.65px] w-[18.65px] shrink-0 items-center justify-center rounded-[4.35px] bg-[var(--phone-avatar)] font-sans text-[9.95px] font-semibold text-[var(--phone-avatar-ink)]",name:"block truncate text-[11.19px] font-semibold text-foreground",address:"pointer-events-auto relative z-10 mt-[3px] flex w-fit items-center gap-1 font-sans text-[9.95px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",copyGlyph:"h-2 w-2",value:"pointer-events-none ml-auto font-sans text-[12.43px] font-semibold tabular-nums text-foreground",explainer:"relative mt-[8.7px] rounded-[5px] bg-[var(--phone-chip)] px-[12.4px] pb-[12px] pt-[11.2px] text-[9.95px] leading-[16.16px] text-[var(--phone-explainer-ink)]",dismiss:"absolute right-[10px] top-[9px] flex h-4 w-4 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",dismissGlyph:"h-[7.5px] w-[7.5px]",explainerTitle:"mb-[3.7px] block pr-4 text-[11.19px] font-semibold text-foreground",note:"text-[var(--phone-gold)]",add:"mt-[3.7px] flex h-[34.8px] w-full items-center justify-center gap-[7px] rounded-[5px] border-[0.93px] border-[var(--phone-outline)] text-[11.19px] font-medium text-foreground transition-colors hover:bg-[var(--phone-row)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",addGlyph:"h-[10
1px] w-[10px]"}};e.s(["AccountsPopoverBody",0,function({profiles:e,activeIndex:r,unpinned:l,addr58:c,values:u,valuesStale:h,explainerDismissed:p,canCreate:m,onPick:f,onDismissExplainer:x,onCreate:g,phone:b=!1,extrasClassName:v}){let y=b?P.phone:P.desktop,w=(0,i.useTranslations)("trading"),j=(0,i.useTranslations)("wallet"),S=(0,i.useTranslations)("common"),k=(0,o.useFormatters)();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:y.list,children:e.map(e=>{let i=e.index===r,n=u.get(e.index)?.unrealizedValue,a=l.has(e.index),o=c.get(e.index)??"",p=e.name??j("profileFallback",{index:String(e.index+1)});return(0,t.jsxs)("div",{className:`${y.row} ${i?y.rowActive:y.rowIdle} ${a?"opacity-85":""}`,children:[(0,t.jsx)("button",{type:"button",onClick:()=>f(e.index),"aria-label":p,"aria-current":i?"true":void 0,className:y.pick}),(0,t.jsx)("span",{"aria-hidden":!0,className:y.avatar,children:e.index+1}),(0,t.jsxs)("span",{className:"pointer-events-none min-w-0 flex-1",children:[(0,t.jsx)("span",{className:y.name,children:p}),(0,t.jsxs)("button",{type:"button",onClick:()=>N(o,j("addressCopied")),className:y.address,children:[(0,d.shortAddress)(o),(0,t.jsx)(s.Copy,{className:y.copyGlyph,"aria-hidden":!0})]})]}),(0,t.jsx)("span",{title:h?w("statusBarUnknown"):void 0,className:`${y.value} ${h?"opacity-60":""}`,children:void 0===n?"—":`$${k.numberShort(n)}`}),a&&(0,t.jsx)("span",{className:"pointer-events-none ml-2 shrink-0 rounded-[6px] border border-dashed border-border-strong px-1.5 py-0.5 text-3xs font-medium text-muted-foreground",children:w("pinTab")})]},e.index)})}),!p&&(0,t.jsxs)("div",{className:v?`${y.explainer} ${v}`:y.explainer,children:[(0,t.jsx)("button",{type:"button",onClick:x,"aria-label":S("close"),className:y.dismiss,children:(0,t.jsx)(a.X,{className:y.dismissGlyph})}),(0,t.jsx)("span",{className:y.explainerTitle,children:w("switchAccountsTitle")}),w("switchAccountsBody")," ",(0,t.jsx)("span",{className:y.note,children:w("switchAccountsNote")})]}),m&&(0,t.jsxs)("button",{type:"button",onClick:g,className:v?`${y.add} ${v}`:y.add,children:[(0,t.jsx)(n.Plus,{className:y.addGlyph}),j("addAccount")]})]})},"COPY_ADDRESS_CLASS",0,k,"copyAddress",0,N,"profileLabel",0,function(e,t){return e.name??t("profileFallback",{index:String(e.index+1)})},"unpinStored",0,function(e,t,r,i,s){let n=new Set(w(e));n.add(t),S(e,n,r),(0,l.toast)(i,{action:{label:s,onClick:()=>{let r=new Set(w(e));r.delete(t),S(e,r)}}})},"useAccountPins",0,function(e){let t=(0,r.useCallback)(t=>y(e,t),[e]);return{unpinned:(0,r.useSyncExternalStore)(t,()=>w(e),()=>h),explainerDismissed:(0,r.useSyncExternalStore)(t,()=>j(e),()=>!0)}}],319522)},541983,e=>{"use strict";e.s(["UnifiedWallet",()=>I],541983);var t=e.i(394390),r=e.i(183023),i=e.i(931387),s=e.i(942553),n=e.i(807956),a=e.i(148292),l=e.i(373641),o=e.i(457395),d=e.i(735006),c=e.i(1169),u=e.i(514469),h=e.i(183799),p=e.i(803817),m=e.i(153517),f=e.i(142298),x=e.i(616861),g=e.i(999069),b=e.i(894771),v=e.i(124593),y=e.i(347554),w=e.i(213076),j=e.i(679555),S=e.i(575146),k=e.i(840209),N=e.i(319522),P=e.i(993628),T=e.i(116082);let C=(0,n.default)(()=>e.A(898027).then(e=>({default:e.CreateProfileDialog})),{loadableGenerated:{modules:[649043]},ssr:!1}),M=(0,n.default)(()=>e.A(256705).then(e=>({default:e.DepositWithdrawDialog})),{loadableGenerated:{modules:[172739]},ssr:!1}),_=({address:e,trigger:n,desktopPerps:_=!1,compactHeader:A=!1})=>{let E=(0,s.useTranslations)("wallet"),[L,F]=r.default.useState(!1),[R,D]=r.default.useState(!1),[I,U]=r.default.useState(!1),[O,B]=r.default.useState(!1),[z,$]=r.default.useState("deposit"),[V,H]=r.default.useState(!1),{disconnect:W,isPrivyWallet:q}=(0,f.useUnifiedWallet)(),{isJWTMode:K,logout:G}=(0,x.useMobileAuth)(),{isSponsorMode:Y,logout:X}=(0,g.useSponsorGas)(),{username:Q,createdProfiles:J,activeProfileIndex:Z,setActiveProfileIndex:ee,canCreateMore:et}=(0,b.useProfile)(),{isPro:er}=(0,v.useProWhitelist)(),{profiles:ei,isStale:es}=(0,y.usePortfolioValues)(),en=e?.toBase58()??null,ea=(0,a.usePrimaryDomain)(en),{unpinned:el,explainerDismissed:eo}=(0,N.useAccountPins)(en),ed=r.default.useMemo(()=>new Map(J.map(e=>[e.index,e.pda.toBase58()])),[J]),ec=J.find(e=>e.index===Z)??null,eu=ec?(0,N.profileLabel)(ec,E):null;if(!e)return(0,t.jsx)(j.Skeleton,{className:"h-full w-full rounded-full"});let eh=L?d.ChevronUp:c.ChevronDown;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(S.Popover,{open:L,onOpenChange:F,children:[(0,t.jsx)(S.PopoverTrigger,{asChild:!0,children:n||(_?(0,t.jsxs)(w.Button,{type:"button",variant:"ghost","aria-label":Q||ea||(0,m.shortAddress)(e),title:e.toBase58(),className:`h-[34px] w-[115px] shrink-0 justify-between gap-2 rounded-[5.112px] border border-[#2b2d2f] bg-[#161719] px-[11px] font-[family-name:var
1(--font-inter)] text-[13.29px] font-medium text-foreground hover:bg-surface-interactive ${A?i.default.identityControl:""}`,children:[(0,t.jsx)("span",{className:`min-w-0 truncate ${A?i.default.identityLabel:""}`,children:Q||ea||(0,m.shortAddress)(e)}),A&&(0,t.jsx)(u.User,{"aria-hidden":!0,className:`size-4 ${i.default.compactIcon}`}),(0,t.jsx)("img",{src:"/desktop-dashboard/profile-chevron.svg",alt:"",className:`${L?"shrink-0 rotate-180":"shrink-0"} ${A?i.default.identityLabel:""}`})]}):(0,t.jsx)("div",{className:"flex items-center h-8 rounded-control text-xs md:h-9 md:text-sm border border-[rgba(251,146,60,0.5)]",style:{background:"linear-gradient(90deg, rgba(255, 138, 61, 0.06) 0%, rgba(0, 0, 0, 0) 100%)"},children:(0,t.jsxs)(w.Button,{className:"text-foreground px-3 gap-2 h-full bg-transparent hover:bg-transparent shadow-none border-0",children:[(0,t.jsx)("span",{className:"truncate",title:e.toBase58(),children:Q||ea||(0,m.shortAddress)(e)}),(0,t.jsx)(eh,{className:"size-4 shrink-0 text-muted-foreground"})]})}))}),(0,t.jsxs)(S.PopoverContent,{align:"end",sideOffset:8,className:"w-[280px] p-3 flex flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"min-w-0 truncate text-sm text-foreground font-medium",title:e.toBase58(),children:ea||(0,m.shortAddress)(e)}),(0,t.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(e.toBase58()),T.toast.success(E("addressCopiedToClipboard"))},className:"text-muted-foreground hover:text-foreground transition-colors",title:E("copyAddress"),children:(0,t.jsx)(o.Copy,{size:14})})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)(p.Link,{href:`/profile/${e.toBase58()}`,onClick:()=>F(!1),className:"flex items-center gap-2 text-sm text-secondary-foreground hover:text-foreground transition-colors",children:[(0,t.jsx)(u.User,{size:14}),E("viewPublicProfile")]}),null!==Z&&(0,t.jsxs)("button",{type:"button",onClick:()=>{$("deposit"),B(!0),F(!1)},className:"flex items-center gap-2 text-sm text-secondary-foreground hover:text-foreground transition-colors text-left",children:[(0,t.jsx)(l.ArrowDownUp,{size:14}),E("depositWithdraw")]})]}),J.length>0&&null!==eu&&(0,t.jsxs)("div",{className:"border-t border-border pt-3 flex flex-col gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:()=>H(e=>!e),"aria-expanded":V,className:"flex w-full items-center gap-2 rounded-md border border-border-strong bg-surface-raised px-2.5 py-2 text-left transition-colors hover:bg-surface-interactive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[(0,t.jsx)("span",{className:"flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-[6px] bg-surface-interactive text-2xs font-semibold text-secondary-foreground",children:(Z??0)+1}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground",children:E("activeAccount")}),(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1 text-xs font-semibold text-foreground",children:[eu,V?(0,t.jsx)(d.ChevronUp,{size:12}):(0,t.jsx)(c.ChevronDown,{size:12})]})]}),V&&(0,t.jsx)(N.AccountsPopoverBody,{profiles:J,activeIndex:Z,unpinned:el,addr58:ed,values:ei,valuesStale:es,explainerDismissed:eo,canCreate:et&&er,onPick:e=>{e!==Z&&ee(e),en&&(0,P.pinStored)(en,e),H(!1),F(!1)},onDismissExplainer:()=>en&&(0,P.writeExplainerDismissed)(en),onCreate:()=>{F(!1),U(!0)}})]}),(0,t.jsxs)("div",{className:"border-t border-border pt-3 flex flex-col gap-2",children:[q&&(0,t.jsxs)("button",{onClick:()=>{F(!1),D(!0)},className:"flex items-center gap-2 text-sm text-secondary-foreground hover:text-foreground transition-colors text-left",children:[(0,t.jsx)(h.Wallet,{size:14}),E("manageWallet")]}),(0,t.jsx)("button",{onClick:()=>{F(!1),Y?X():K?G():W?.()},className:"text-sm text-orange-400 hover:text-orange-300 transition-colors text-left",children:Y?E("disableOneClickTrading"):K?E("endMobileSession"):E("disconnect")}),(Y||K)&&(0,t.jsx)("button",{onClick:()=>{F(!1),W?.()},className:"text-sm text-orange-400 hover:text-orange-300 transition-colors text-left",children:E("disconnectWallet")})]})]})]}),q&&(0,t.jsx)(k.ManagePrivyWalletDialog,{open:R,onOpenChange:D}),(0,t.jsx)(M,{open:O,onOpenChange:B,initialMode:z}),(0,t.jsx)(C,{open:I,onOpenChange:U})]})};var A=e.i(893974),E=e.i(875574),L=e.i(987752),F=e.i(797699);let R=()=>()=>{};function D(e){let i=(0,s.useTranslations)("wallet"),n=(0,r.useSyncExternalStore)(R,()=>!0,()=>!1),{publicKey:a,connected:l}=(0,E.useUnifiedWalletContext)(),{open:o,close:d,isOpen:c}=(0,L.useOnboarding)(),u=(0,r.useRef)(!1),h=(0,r.useRef)(c),p=(0,r.useRef)(!1);if((0,r.useEffect)(()=>
1{if(e.promptHost)return;let t=void 0===e.open&&e.defaultOpen&&!p.current;!0===e.open||t?(p.current=!0,u.current=!0,o()):!1===e.open&&u.current&&(u.current=!1,d())},[e.open,e.defaultOpen,e.promptHost,o,d]),(0,r.useEffect)(()=>{h.current&&!c&&u.current&&(u.current=!1,e.onOpenChange?.(!1)),h.current=c},[c,e.onOpenChange]),e.promptHost)return null;if(l&&a)return(0,t.jsx)(_,{address:a,trigger:e.trigger,desktopPerps:e.desktopPerps,compactHeader:e.compactHeader});if(!n)return(0,t.jsx)(j.Skeleton,{className:e.desktopPerps?"h-[34px] w-24 rounded-[5px]":"h-8 w-24 rounded-control"});let m=t=>{t.defaultPrevented||((0,F.gtagEvent)("wallet_connect_click"),e.onOpenChange?.(!0),void 0===e.open&&(u.current=!0,o()))};return e.trigger?(0,t.jsx)(A.Slot,{onClick:m,"aria-haspopup":"dialog","aria-expanded":c,children:e.trigger}):(0,t.jsx)(w.Button,{type:"button",onClick:m,"aria-label":i("connectWallet"),"aria-haspopup":"dialog","aria-expanded":c,title:e.compactHeader?i("connectWallet"):void 0,"data-login-entry":!0,className:`px-4 border-0 bg-[image:var(--gradient-cta-wide)] font-semibold text-[var(--on-cta-wide)] hover:brightness-105 ${e.desktopPerps?"h-[34px] rounded-[5px] text-[13.29px]":"h-8 rounded-control text-xs md:h-9 md:text-sm"}`,children:(0,t.jsx)("span",{className:"whitespace-nowrap",children:i("connectWallet")})})}function I({desktopPerps:e=!1,compactHeader:r=!1}){let{publicKey:i,connected:s}=(0,f.useUnifiedWallet)();return s&&i?(0,t.jsx)(_,{address:i,desktopPerps:e,compactHeader:r}):(0,t.jsx)(D,{desktopPerps:e,compactHeader:r})}},814276,e=>{"use strict";var t=e.i(394390),r=e.i(183023);function i(e){return e.split("").reduce((e,t)=>-((e^t.charCodeAt(0))*5),5)>>>2}function s(e="",t=95,r=45,n=i){let a=n(e);return[...Array(25*!!e)].reduce((e,t,r)=>a&1<<r%15?e+`<rect x="${r>14?7-~~(r/5):~~(r/5)}" y="${r%5}" width="1" height="1"/>`:e,`<svg viewBox="-1.5 -1.5 8 8" xmlns="http://www.w3.org/2000/svg" fill="hsl(${a%9*40} ${t}% ${r}%)">`)+"</svg>"}globalThis.customElements?.get("minidenticon-svg")||globalThis.customElements?.define("minidenticon-svg",class e extends HTMLElement{static observedAttributes=["username","saturation","lightness"];static #m={};#f=!1;connectedCallback(){this.#x(),this.#f=!0}attributeChangedCallback(){this.#f&&this.#x()}#x(){let t=e.observedAttributes.map(e=>this.getAttribute(e)||void 0),r=t.join(",");this.innerHTML=e.#m[r]??=s(...t)}});var n=e.i(153517),a=e.i(457058);e.s(["Avatar",0,({address:e,imageUrl:i,size:l=48,className:o,alt:d})=>{let[c,u]=r.default.useState(!1);r.default.useEffect(()=>{u(!1)},[i]);let h=r.default.useMemo(()=>e?"string"==typeof e?e:e.toBase58():"",[e]),p=r.default.useMemo(()=>h?"data:image/svg+xml;utf8,"+encodeURIComponent(s(h,90,50)):"",[h]),m=i&&!c?i:p;return(0,t.jsx)("div",{className:(0,n.cn)("relative flex items-center justify-center rounded-full bg-muted p-1 text-muted-foreground overflow-hidden",o),style:{width:l,height:l},children:(0,t.jsx)(a.default,{src:m,alt:d||h||"",width:l,height:l,className:i&&!c?"object-cover rounded-full":"",onError:()=>u(!0),unoptimized:!!i&&!c})})}],814276)},931387,e=>{e.v({accountControl:"header-controls-module__4rfbhW__accountControl",accountName:"header-controls-module__4rfbhW__accountName",brandMark:"header-controls-module__4rfbhW__brandMark",brandWordmark:"header-controls-module__4rfbhW__brandWordmark",compactIcon:"header-controls-module__4rfbhW__compactIcon",fullIcon:"header-controls-module__4rfbhW__fullIcon",fullLabel:"header-controls-module__4rfbhW__fullLabel",iconControl:"header-controls-module__4rfbhW__iconControl",identityControl:"header-controls-module__4rfbhW__identityControl",identityLabel:"header-controls-module__4rfbhW__identityLabel",packLabel:"header-controls-module__4rfbhW__packLabel",packPreview:"header-controls-module__4rfbhW__packPreview",pointsTrigger:"header-controls-module__4rfbhW__pointsTrigger",pointsUnit:"header-controls-module__4rfbhW__pointsUnit",pointsValue:"header-controls-module__4rfbhW__pointsValue",streak:"header-controls-module__4rfbhW__streak",streakFlame:"header-controls-module__4rfbhW__streakFlame"})},967678,e=>{"use strict";let t="bottom-0 left-0 right-0 z-50 lg:hidden border-t border-x border-border bg-[image:var(--gradient-phone-nav)] pb-[env(safe-area-inset-bottom)]",r=`fixed ${t}`,i=`absolute ${t}`;e.s(["IDENTITY_ROW_PX",0,44,"NAV_BAR",0,r,"NAV_BAR_IN_SHELL",0,i,"NAV_CELL",0,"relative flex-1 min-w-0 flex items-center justify-center gap-[5px] transition-colors focus-ring-inset","NAV_CELL_ACTIVE",0,"text-primary after:absolute after:bottom-0 after:left-1/2 after:h-[2px] after:w-[53px] after:-translate-x-1/2 after:rounded-[1px] after:bg-primary after:content-['']","NAV_ICON_MORE",0,"h-4 w-4 shrink-0","NAV_ICON_PACKS",0,"h-4 w-4 shrink-0","NAV_ICON_PERPS",0,"h-3 w-3 shrink-0","NAV_ICON_POINTS",0,"h-3.5 w-3.5 shrink-0","NAV_LABEL",0,"text-[12px] font-semibold truncate","NAV_ROW_PX",0,46,"NAV_TONE_DIM",0,"text-white/40 [&_svg]:text-[#757A82]","NAV_TONE_IDLE",0,"text-[#8E8E93] [&_svg]:text-[#999EA6]","PARKED_OFFSCREEN",0,"fixed left-[-99999px] top-0 w-screen pointer-events-none","PHONE_HEADER_PX",0,84,"PHONE_ROW",0,"flex h-11 items-center text-[12.5px] font-semibold text-foreground","TRADE_BAR_PX",0,65])},946422,e=>{e.v({candleHigh:"mobile-nav-icon-module__sAo_oG__candleHigh",candleLow:"mobile-nav-icon-module__sAo_oG__candleLow",dot:"mobile-nav-icon-module__sAo_oG__dot",dotLeft:"mobile-nav-icon-module__sAo_oG__dotLeft",dotMiddle:"mobile-nav-icon-module__sAo_oG__dotMiddle",dotRight:"mobile-nav-icon-module__sAo_oG__dotRight",icon:"mobile-nav-icon-module__sAo_oG__icon",packEmblem:"mobile-nav-icon-module__sAo_oG__packEmblem",packLid:"mobile-nav-icon-module__sAo_oG__packLid",packReveal:"mobile-nav-icon-module__sAo_oG__packReveal",playing:"mobile-nav-icon-module__sAo_oG__playing",reward:"mobile-nav-icon-module__sAo_oG__reward",rewardStar:"mobile-nav-icon-module__sAo_oG__rewardStar"})},763402,460623,548056,e=>{"use strict";e.s(["SetupChecklistCard",()=>k,"SetupChecklistInline",()=>N],763402),e.s(["useOnboardingReadiness",()=>b],548056);var t=e.i(394390),r=e.i(183023),i=e.i(985433),s=e.i(967090),n=e.i(942553),a=e.i(987752),l=e.i(875574),o=e.i(894771),d=e.i(124431),c=e.i(687229),u=e.i(494286),h=e.i(702193),p=e.i(999069),m=e.i(506744),f=e.i(616861);let x=()=>!1;function g(){let e=(0,l.useUnifiedWalletContext)(),t=(0,p.useSponsorGas)(),i=(0,f.useMobileAuth)(),s=e.publicKey?.toBase58()??"",n=i.walletPubkey?.toBase58(),{hasValidJwtFor:a}=t,o=i.isJWTMode?i.expiresAt:t.expiresAt,d=(0,r.useCallback)(()=>i.isJWTMode?n===s&&null!==(0,m.referralSession)(i.jwt,s)&&Number.isFinite(i.expiresAt)&&1e3*i.expiresAt>Date.now():a(s),[i.isJWTMode,n,i.jwt,i.expiresAt,s,a]),c=(0,r.useCallback)(e=>{let t,r=()=>{let i=o?1e3*o-Date.now():0;i>0&&(t=setTimeout(()=>{e(),r()},Math.min(i+1,0x7fffffff)))};return r(),window.addEventListener("focus",e),()=>{clearTimeout(t),window.removeEventListener("focus",e)}},[o]);return{walletKey:s,sessionValid:(0,r.useSyncExternalStore)(c,d,x),sessionLoaded:i.isLoaded&&!e.isLoading&&(i.isJWTMode||t.jwtsLoaded)}}function b({requireSessionReview:e=!1}={}){var t;let r=(0,l.useUnifiedWalletContext)(),i=(0,o.useProfile)(),{balances:s,isLoading:n}=(0,d.useProfileBalance)(),{positions:a,isLoading:p}=(0,c.useUnifiedPositions)(),{walletKey:m,sessionValid:f,sessionLoaded:x}=g(),v=null!==i.activeProfileIndex&&i.createdProfiles.some(e=>e.index===i.activeProfileIndex),y=a.filter(e=>e.wallet===m&&e.profileIndex===i.activeProfileIndex&&("open"===e.status||"closing"===e.status)&&!e.isStale).length,w=(0,u.useSunriseMargin)(m||null,i.activeProfileIndex,null,v),j=(0,u.armadaAccountWithdrawableUsd)(w.data),S=null!==j||w.isError||!m?(0,h.spendableWithArmadaAccount)(s.USDC,j):null;return{phase:(t={connected:r.connected&&!!m,sessionLoaded:x,sessionValid:f&&!e,profilesLoaded:i.hasLoadedProfiles,hasAccount:v,balancesLoading:n,usdc:S,positionsLoading:p,positionCount:y}).connected?t.sessionLoaded?t.sessionValid?t.profilesLoaded?t.hasAccount?t.positionsLoading||t.balancesLoading||null===t.usdc?"checking":t.usdc>0||t.positionCount>0?"ready":"fund":"account":"checking":"session":"checking":"auth",walletKey:m,activeProfileIndex:i.activeProfileIndex,positionCount:y,sessionValid:f,hasAccount:v,spendableUsdc:S}}e.s(["useWalletSessionStatus",0,g],460623);var v=e.i(619966),y=e.i(797699);let w=new Set,j=new Set;function S(e){w.add(e);let t=()=>e();return window.addEventListener("storage",t),()=>{w.delete(e),window.removeEventListener("storage",t)}}function k(){return!0===(0,v.useIsDesktop)()?(0,t.jsx)(P,{surface:"overlay"}):null}function N(){return(0,t.jsx)(P,{surface:"inline"})}function P({surface:e}){let l=(0,n.useTranslations)("onboarding.resume"),o=(0,a.useOnboarding)(),{phase:d,walletKey:c,activeProfileIndex:u}=b(),h=`imperial_setup_resume:${c}:${u??"uncreated"}:${e}`,p=(0,r.useCallback)(()=>(function(e){try{return"true"===localStorage.getItem(e)||j.has(e)}catch{return j.has(e)}})(h),[h]),m=(0,r.useSyncExternalStore)(S,p,()=>!0);if(o.isOpen||m||"auth"===d||"checking"===d||"ready"===d)return null;let f=(0,t.jsxs)("section",{"aria-label":l("title"),className:"rounded-xl border border-border-strong bg-surface-raised p-4 shadow-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsx)("p",{className:"text-[11px] font-medium text-muted-foreground",children:l("progress",{step:"fund"===d?2:1,total:3})}),(0,t.jsx)("h2",{className:"mt-1 text-sm font-semibold text-foreground",children:l("title")})]}),(0,t.jsx)("button",{type:"button",onClick:()=>(function(e){j.add(e);try{localStorage.setItem(e,"true")}catch{}
1w.forEach(e=>e())})(h),"aria-label":l("dismiss"),className:"-m-2 flex size-11 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:text-foreground focus-ring",children:(0,t.jsx)(s.X,{className:"size-4","aria-hidden":"true"})})]}),(0,t.jsx)("p",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:l(`${d}Hint`)}),(0,t.jsxs)("button",{type:"button",onClick:()=>{(0,y.gtagEvent)("setup_checklist_step",{step:d}),o.open({intent:"fund"===d?"funding":"setup",ownerWallet:c})},className:"mt-3 flex min-h-11 w-full items-center justify-center gap-2 rounded-control bg-[image:var(--gradient-cta-wide)] px-3 text-xs font-semibold text-[var(--on-cta-wide)] hover:brightness-105 focus-ring",children:[l("continue"),(0,t.jsx)(i.ArrowRight,{className:"size-4","aria-hidden":"true"})]}),(0,t.jsx)("p",{className:"mt-2 text-[11px] leading-relaxed text-muted-foreground",children:l("optional")})]});return"overlay"===e?(0,t.jsx)("div",{className:"fixed bottom-4 right-4 z-40 w-[300px]",children:f}):f}},566314,101735,e=>{"use strict";var t=e.i(394390),r=e.i(116082),i=e.i(942553),s=e.i(183023),n=e.i(568801),a=e.i(755818),l=e.i(21859),o=e.i(799227),d=e.i(142298),c=e.i(924416),u=e.i(740713),h=e.i(510079);let p="imperial:report-payment:v1:",m=new Map,f=new Set,x="A report payment may still be submitting. Check this wallet's activity before paying again; another transfer will not be sent.",g="Safe payment coordination is unavailable in this browser. No report payment will be sent.",b="The report price could not be verified. Refresh the price before approving a payment.",v="Payment recovery storage is unavailable. No new payment will be sent until this browser can save its recovery state.";function y(e){return!!e&&Number.isSafeInteger(e.amountMicros)&&e.amountMicros>0&&Number.isFinite(e.amountUsd)&&e.amountUsd>0&&e.amountUsd===e.amountMicros/1e6}function w(e){let t,r=m.get(e);try{t=window.localStorage.getItem(p+e)}catch(e){if(r&&"awaiting-wallet"!==r.status)return r;throw e}if(null===t)return r&&"awaiting-wallet"!==r.status?r:(m.delete(e),null);let i=JSON.parse(t);if(!i||"object"!=typeof i||!("version"in i)||1!==i.version||!("status"in i)||"attemptId"in i&&("string"!=typeof i.attemptId||!/^[a-f0-9-]{36}$/i.test(i.attemptId)))throw Error("Unrecognized report payment recovery record. Review the previous payment before paying again.");let s="attemptId"in i?i.attemptId:void 0;if("baselineReportIds"in i&&(!Array.isArray(i.baselineReportIds)||!i.baselineReportIds.every(e=>"string"==typeof e&&e.length>0)))throw Error("Unrecognized report payment recovery record. Review the previous payment before paying again.");let n="baselineReportIds"in i?i.baselineReportIds:void 0;if("delivered"===i.status&&"signature"in i&&"string"==typeof i.signature&&/^[1-9A-HJ-NP-Za-km-z]{64,128}$/.test(i.signature)){if(r&&"awaiting-wallet"!==r.status&&r.signature!==i.signature)throw Error("Conflicting report payment recovery records. Review these payments before paying again.");return m.delete(e),null}if("awaiting-wallet"===i.status){if(r&&"awaiting-wallet"!==r.status){if(s&&r.attemptId===s)return r;throw Error("Conflicting report payment recovery records. Review these payments before paying again.")}let t={version:1,status:"awaiting-wallet",attemptId:s,baselineReportIds:n};return m.set(e,t),t}if(("submitted"===i.status||"credited"===i.status)&&"signature"in i&&"string"==typeof i.signature&&/^[1-9A-HJ-NP-Za-km-z]{64,128}$/.test(i.signature)){if(r&&"awaiting-wallet"!==r.status&&r.signature!==i.signature)throw Error("Conflicting report payment recovery records. Review these payments before paying again.");let t={version:1,status:i.status,signature:i.signature,attemptId:s,baselineReportIds:n};return m.set(e,t),t}throw Error("Unrecognized report payment recovery record. Review the previous payment before paying again.")}function j(e,t){if(m.set(e,t),"awaiting-wallet"!==t.status){let r=window.localStorage.getItem(p+e);if(null!==r){let e=JSON.parse(r);if(!(e&&"object"==typeof e&&"version"in e&&1===e.version&&"status"in e&&("awaiting-wallet"===e.status?!!t.attemptId&&"attemptId"in e&&e.attemptId===t.attemptId:("submitted"===e.status||"credited"===e.status)&&"signature"in e&&e.signature===t.signature)))throw Error("Conflicting report payment recovery records. Review these payments before paying again.")}}let r=JSON.stringify(t);if(window.localStorage.setItem(p+e,r),window.localStorage.getItem(p+e)!==r)throw Error(v)}async function S(e){let t=()=>Error("Keep this tab open and finish checking your report payment before reloading.");if(f.size)throw t();let r=new Map;for(let[e,i]of m){if("awaiting-wallet"===i.status||"u"<typeof navigator||!navigator.locks?.request)throw t();await navigator.locks.request(p+e,{mode:"exclusive",ifAvailable:!0},async s=>{if(!s||f.size||m.get(e)!==i)throw t();try{j(e,i)}catch{throw t()}r.set(e,i)})}
1if(f.size||[...m].some(([e,t])=>r.get(e)!==t))throw t();e()}function k(e){try{if(window.localStorage.removeItem(p+e),null!==window.localStorage.getItem(p+e))return!1;return m.delete(e),!0}catch{return!1}}class N extends Error{constructor(){super("Paying for a report needs a wallet connected in this browser. A mobile session can't sign the transfer yet."),this.name="MobileSessionCannotPayError"}}e.s(["MobileSessionCannotPayError",0,N,"reloadAfterPreservingReportPayments",0,S,"useReportPayment",0,function(){let{publicKey:e,signAndSendTransaction:t,connection:r,isJWTMode:i}=(0,d.useUnifiedWallet)(),{data:S}=(0,c.useReportPaymentQuote)(!0),P=(0,c.useConfirmReportPayment)(),T=(0,u.useReportOwnerSession)(),C=(0,s.useRef)(T);C.current=T;let[M,_]=(0,s.useState)("idle"),A=(0,s.useRef)(!1),E=e?.toBase58()??null,L=(0,s.useRef)(E);L.current=E;let[F,R]=(0,s.useState)({wallet:null,pending:null,blocked:null}),D=(0,s.useCallback)(e=>{if(L.current===e)try{if("u"<typeof navigator||!navigator.locks?.request)return void R({wallet:e,pending:null,blocked:g});let t=w(e);R({wallet:e,pending:t,blocked:t?.status==="awaiting-wallet"?x:null})}catch(t){R({wallet:e,pending:null,blocked:t instanceof Error?t.message:v})}},[]);(0,s.useEffect)(()=>{if(!E)return;D(E);let e=e=>{(null===e.key||e.key===p+E)&&D(E)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[E,D]);let I=F.wallet===E&&!!F.pending&&"awaiting-wallet"!==F.pending.status,U=(F.wallet===E?F.blocked:null)??(I||!S||y(S)?null:b),O=!!e&&!!T&&F.wallet===E&&!U&&(I||!i&&!!t&&y(S));return{pay:(0,s.useCallback)(async s=>{if(!e)throw Error("Connect a wallet to buy a report");let d=e.toBase58(),c=P.mutateAsync;if(!T)throw Error("Sign in again before paying for a report.");if(L.current!==d)throw Error("Wallet changed. Reopen the report payment for the connected wallet.");if(A.current||f.has(d))throw Error("A report payment is already in progress.");A.current=!0,f.add(d),_("preparing");try{if("u"<typeof navigator||!navigator.locks?.request)throw Error(g);return await navigator.locks.request(p+d,{mode:"exclusive",ifAvailable:!0},async u=>{let p,m;if(!u)throw Error("A report payment is already in progress in another tab.");try{p=w(d)}catch{throw Error(v)}if(p?.status==="awaiting-wallet")throw Error(x);let f=async()=>{let e=await (0,h.fetchReportEligibility)(T);if(!e||!Number.isSafeInteger(e.credits)||e.credits<0||"boolean"!=typeof e.freeReportAvailable||"boolean"!=typeof e.eligible||!Array.isArray(e.reports)||!e.reports.every(e=>e&&"string"==typeof e.id&&e.id.length>0))throw Error("Report credit status could not be verified. No payment was sent.");return e},g=async e=>{let t=await f();if(t.credits>0)return{signature:e.signature};let r=e.baselineReportIds?t.reports.find(t=>!e.baselineReportIds.includes(t.id)):void 0;if(r)return{signature:e.signature,existingReportId:r.id};throw Error("This payment was credited, but its report is not confirmed complete. Check your latest reports or contact support; another payment will not be sent.")};if(p?.status==="credited")return g(p);if(p?.status==="submitted"){m=p;try{j(d,p)}catch{}}else{let c;if(i||!t)throw new N;let u=await f();if(u.credits>0||u.freeReportAvailable)return{signature:null};if(!u.eligible)throw Error("This wallet is not eligible to generate a report. No payment was sent.");if(!s||null!==s.expectedLatestReportId&&"string"!=typeof s.expectedLatestReportId||s.expectedLatestReportId!==(u.reports[0]?.id??null))throw Error("Report status changed. Reopen the report action and confirm its current price before paying.");if(!S)throw Error("Connect a wallet to buy a report");if(!y(S)||u.priceUsd!==S.amountUsd)throw Error(b);let p=await (0,h.fetchPaymentQuote)(T);if(!y(p)||p.amountMicros!==S.amountMicros||p.amountUsd!==S.amountUsd||p.mint!==S.mint||p.treasury!==S.treasury)throw Error(b);let g=u.reports.map(e=>e.id),w=new o.PublicKey(S.mint),P=new o.PublicKey(S.treasury),M=(0,l.getAssociatedTokenAddressSync)(w,e),A=(0,l.getAssociatedTokenAddressSync)(w,P),E=new o.Transaction().add((0,n.createAssociatedTokenAccountIdempotentInstruction)(e,A,P,w),(0,a.createTransferCheckedInstruction)(M,w,A,e,BigInt(S.amountMicros),6)),{blockhash:F}=await r.getLatestBlockhash("confirmed");if(E.recentBlockhash=F,E.feePayer=e,L.current!==d||C.current!==T)throw Error("Wallet or session changed before payment. No transfer was requested.");let R=crypto.randomUUID();try{j(d,{version:1,status:"awaiting-wallet",attemptId:R,baselineReportIds:g})}catch{throw k(d),Error(v)}_("awaiting-wallet");try{c=await t(E)}catch(e){throw function(e){if(!e||"object"!=typeof e)return!1;if("code"in e&&4001===e.code)return!0;let t="message"in e?String(e.message).toLowerCase():"";return t.includes("user rejected")||t.includes("user cancelled")}(e)&&k(d),e}if(!/^[1-9A-HJ-NP-Za-km-z]{64,128}$/.test(c))throw Error(x);m={version:1,status:"submitted",signature:c,attemptId:R,baselineReportIds:g};try{j(d,m)}catch{throw Error("Payment submitted, but recovery storage could not be updated. Retry confirmation in this tab; no second transfer will be sent.")}D(d)}if(L.current!==d)throw Error("Reconnect the wallet used for this payment to confirm its credit. No second transfer is needed.");_("confirming");let P=await c(m.signature);if(!P||"boolean"!=typeof P.credited||!Number.isSafeInteger(P.credits)||P.credits<0)throw Error("Payment c
1onfirmation returned an unverified result. Retry confirmation; no second transfer will be sent.");let M={...m,status:"credited"};try{j(d,M)}catch{}return P.credits>0?{signature:m.signature}:g(M)})}finally{f.delete(d),A.current=!1,_("idle"),D(d)}},[e,t,r,S,P,i,T,D]),completePayment:(0,s.useCallback)(async e=>{if(!E||"u"<typeof navigator||!navigator.locks?.request)throw Error(g);await navigator.locks.request(p+E,{mode:"exclusive",ifAvailable:!0},async t=>{if(!t)throw Error("A report payment is already in progress in another tab.");let r=window.localStorage.getItem(p+E),i=null===r?null:JSON.parse(r);if(!i||"object"!=typeof i||!("version"in i)||1!==i.version||!("signature"in i)||i.signature!==e||!("status"in i)||"credited"!==i.status&&"delivered"!==i.status)throw Error("The completed report does not match this payment recovery receipt.");if("delivered"===i.status){let t=m.get(E);t&&"awaiting-wallet"!==t.status&&t.signature===e&&m.delete(E);return}let s=JSON.stringify({version:1,status:"delivered",signature:e});if(window.localStorage.setItem(p+E,s),window.localStorage.getItem(p+E)!==s)throw Error("The report completed, but its payment recovery record could not be updated. No new payment will be sent.");m.delete(E)}),D(E)},[E,D]),quote:S,paying:"idle"!==M||P.isPending,paymentPhase:M,pendingPayment:I,paymentBlockedReason:U,canPay:O,mobileSessionCannotPay:i}}],101735);var P=e.i(884304),T=e.i(37952),C=e.i(875574),M=e.i(213076),_=e.i(268680),A=e.i(430232),E=e.i(153517);e.s(["ReportOwnerVerification",0,function({compact:e=!1,className:n}){let a=(0,i.useTranslations)("positions"),{publicKey:l}=(0,C.useUnifiedWalletContext)(),{enroll:o,loading:d,canEnroll:c}=(0,T.useSponsorGasEnroll)({ownerSession:!0}),u=(0,s.useSyncExternalStore)(P.subscribeReportAuth,P.reportAuthNeedsReload,()=>!1),h=u?a("reportOwnerReloadHint"):l?c?a("reportOwnerVerifyHint"):a("reportOwnerDelegateHint"):a("reportOwnerConnectHint"),p=(0,t.jsx)(M.Button,{type:"button",variant:"outline",disabled:d,"aria-busy":d,className:e?"h-6 min-h-0 rounded-[4px] px-2 py-1 text-xs":void 0,onClick:()=>{u?S(()=>window.location.reload()).catch(()=>r.toast.error(a("reportOwnerReloadBlocked"))):c?o():(0,A.promptConnectWallet)()},children:u?a("reportOwnerReloadAction"):d?a("reportOwnerVerifying"):c?a("reportOwnerVerifyAction"):a("reportOwnerConnectAction")});return e?(0,t.jsx)("div",{className:(0,E.cn)("inline-flex shrink-0 items-center py-1",n),"data-report-control":!0,children:(0,t.jsx)(_.TooltipProvider,{children:(0,t.jsxs)(_.Tooltip,{children:[(0,t.jsx)(_.TooltipTrigger,{asChild:!0,children:p}),(0,t.jsx)(_.TooltipContent,{className:"max-w-72",children:a("reportOwnerCompactHint",{hint:h})})]})})}):(0,t.jsxs)("div",{className:(0,E.cn)("flex flex-col items-start gap-3 rounded-lg border border-border bg-surface p-5",n),children:[(0,t.jsx)("p",{className:"text-sm text-text-secondary",children:h}),(0,t.jsx)("p",{className:"text-xs text-text-muted",children:a("reportOwnerPaymentHint")}),p]})}],566314)},975735,e=>{e.v({canvas:"desktop-workspace-module__m5AAKG__canvas",chartControls:"desktop-workspace-module__m5AAKG__chartControls",dragHandle:"desktop-workspace-module__m5AAKG__dragHandle",draggingPanel:"desktop-workspace-module__m5AAKG__draggingPanel",dropLabel:"desktop-workspace-module__m5AAKG__dropLabel",dropMessage:"desktop-workspace-module__m5AAKG__dropMessage",dropPreview:"desktop-workspace-module__m5AAKG__dropPreview",hiddenPanel:"desktop-workspace-module__m5AAKG__hiddenPanel",horizontal:"desktop-workspace-module__m5AAKG__horizontal",iconButton:"desktop-workspace-module__m5AAKG__iconButton",interactionShield:"desktop-workspace-module__m5AAKG__interactionShield",layoutNotice:"desktop-workspace-module__m5AAKG__layoutNotice",menu:"desktop-workspace-module__m5AAKG__menu",menuCheck:"desktop-workspace-module__m5AAKG__menuCheck",menuItem:"desktop-workspace-module__m5AAKG__menuItem",menuLabel:"desktop-workspace-module__m5AAKG__menuLabel",menuShortcut:"desktop-workspace-module__m5AAKG__menuShortcut",panel:"desktop-workspace-module__m5AAKG__panel",panelBody:"desktop-workspace-module__m5AAKG__panelBody",resizeActions:"desktop-workspace-module__m5AAKG__resizeActions",resizeControls:"desktop-workspace-module__m5AAKG__resizeControls",resizeShield:"desktop-workspace-module__m5AAKG__resizeShield",resizeSides:"desktop-workspace-module__m5AAKG__resizeSides",saveStatus:"desktop-workspace-module__m5AAKG__saveStatus",saveWarning:"desktop-workspace-module__m5AAKG__saveWarning",screenReaderOnly:"desktop-workspace-module__m5AAKG__screenReaderOnly",scrollBody:"desktop-workspace-module__m5AAKG__scrollBody",separator:"desktop-workspace-module__m5AAKG__separator",statusDot:"desktop-workspace-module__m5AAKG__statusDot",vertical:"desktop-workspace-module__m5AAKG__vertical",viewport:"desktop-workspace-module__m5AAKG__viewport",workspace:"desktop-workspace-module__m5AAKG__workspace",workspaceLauncher:"desktop-workspace-module__m5AAKG__workspaceLauncher"})},157285,682134,106476,710729,918401,e=>{"use strict";let t;var r=e.i(394390),i=e.i(183023),s=e.i(242150),n=e.i(309264),a=e.i(985433),l=e.i(440736),o=e.i(202647),d=e.i(613897),c=e.i(865071),u=e.i(328259),h=e.i(287196),p=e.i(111778),m=e.i(31418),f=e.i(194578),x=e.i(967090),g=e.i(626074);let b=["chart","book","ticket","activity"];function v(e,t){return[e.x,e.y,t.x,t.y,t.width,t.height].every(Number.isFinite)&&t.width>0&&t.height>0&&e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}let y={chart:{width:320,height:288},book:{width:220,height:220},ticket:{width:280,height:340},activity:{width:300,height:38}},w={ticket:420,book:360};function j(e){return"chart"===e||"activity"===e}function S(e,t,r){return"left"===r||"right"===r||j(e)&&j(t)}let k=e=>({type:"panel",panel:e});function N(e="trading"){let t={type:"split",id:"activity",axis:"vertical",ratio:.7,first:"focus"===e?k("chart"):{type:"split",id:"market",axis:"horizontal",ratio:1,first:k("chart"),second:k("book")},second:k("activity")};
1return{version:1,preset:e,locked:!1,tree:{type:"split",id:"ticket",axis:"horizontal",ratio:+("mirrored"!==e),first:"mirrored"===e?k("ticket"):t,second:"mirrored"===e?t:k("ticket")}}}function P(e){return"panel"===e.type?[e.panel]:[...P(e.first),...P(e.second)]}function T(e,t){if("panel"===e.type)return e.panel===t?null:e;let r=T(e.first,t),i=T(e.second,t);return r&&i?{...e,first:r,second:i}:r??i}function C(e,t){return t?e:T(e,"book")??k("chart")}function M(e){if("panel"===e.type)return y[e.panel];let t=M(e.first),r=M(e.second);return"horizontal"===e.axis?{width:t.width+r.width+5,height:Math.max(t.height,r.height)}:{width:Math.max(t.width,r.width),height:t.height+r.height+5}}function _(e,t,r){return Math.min(r,Math.max(t,e))}function A(e){if("panel"===e.type)return w[e.panel]??1/0;let t=A(e.first),r=A(e.second);return"horizontal"===e.axis?t+r+5:Number.isFinite(t)&&Number.isFinite(r)?Math.min(t,r):1/0}function E(e,t=1/0){let r="horizontal"===e.axis?"width":"height",i=M(e.first)[r],s=M(e.second)[r],n=Number.isFinite(A(e.first)),a=Number.isFinite(A(e.second));return n&&a?i/(i+s):n?i/t:a?1-s/t:P(e.first).includes("chart")?.7:.3}function L(e,t){let r=M(e),i={width:Math.min(A(e),Math.max(r.width,Number.isFinite(t.width)?t.width:0)),height:Math.max(r.height,Number.isFinite(t.height)?t.height:0)},s={},n=[];return!function e(t,r){let i={...r,width:Math.min(r.width,A(t))};if("panel"===t.type){s[t.panel]=i;return}let a="horizontal"===t.axis,l=a?"width":"height",o=i[l]-5,d=M(t.first)[l],c=M(t.second)[l],u=Math.max(d/o,a?1-A(t.second)/o:0),h=Math.max(u,Math.min(1-c/o,a?A(t.first)/o:1)),p=_(t.ratio,u,h),m=o*p,f={...i,[l]:m},x={...i,[l]:o-m,[a?"x":"y"]:i[a?"x":"y"]+m+5};n.push({...i,[l]:5,[a?"x":"y"]:i[a?"x":"y"]+m,id:t.id,axis:t.axis,ratio:p,min:u,max:h,balance:_(E(t,o),u,h),parent:i,firstPanels:P(t.first),secondPanels:P(t.second)}),e(t.first,f),e(t.second,x)}(e,{x:0,y:0,...i}),{size:i,panels:s,separators:n}}function F(e,t){let r=_(t,e.min,e.max);if("vertical"!==e.axis)return r;let i=e.parent.height-5;return 1===e.firstPanels.length&&"activity"===e.firstPanels[0]&&r*i<=38.5?0:1===e.secondPanels.length&&"activity"===e.secondPanels[0]&&(1-r)*i<=38.5?1:r}function R(e,t,r){return"panel"!==e.type&&Number.isFinite(r)?e.id===t?{...e,ratio:_(r,0,1)}:{...e,first:R(e.first,t,r),second:R(e.second,t,r)}:e}function D(e,t="dock-0"){let r=new Set;!function e(t){"split"===t.type&&(r.add(t.id),e(t.first),e(t.second))}(e);let i=t,s=0;for(;r.has(i);)i=`dock-${s++}`;return i}function I(e,t,r,i,s){if(t===r||!b.includes(t)||!b.includes(r)||!["left","right","top","bottom"].includes(i)||!S(t,r,i)||!P(e).includes(r)||!s&&("book"===t||"book"===r))return null;let n=T(e,t);if(!n)return null;let a=D(n);return function e(s){if("split"===s.type)return{...s,first:e(s.first),second:e(s.second)};if(s.panel!==r)return s;let n="left"===i||"top"===i,l={type:"split",id:a,axis:"left"===i||"right"===i?"horizontal":"vertical",ratio:.5,first:n?k(t):s,second:n?s:k(t)};return{...l,ratio:E(l)}}(n)}function U(e,t,r,i,s,n=!0){if(!Number.isFinite(s.width)||!Number.isFinite(s.height))return null;let a=I(e,t,r,i,n);if(!a||function e(t){return"panel"!==t.type&&("vertical"===t.axis&&Number.isFinite(A(t.first))!==Number.isFinite(A(t.second))||e(t.first)||e(t.second))}(C(a,n)))return null;let l=M(C(a,n));return l.width<=s.width&&l.height<=s.height?a:null}function O(e){if(!e||e.length>4096)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||1!==t.version||"boolean"!=typeof t.locked||!["trading","focus","mirrored","custom"].includes(t.preset))return null;let r=new Set,i=new Set,s=function e(t,s=0){if(!t||"object"!=typeof t||s>3)return null;if("panel"===t.type)return!b.includes(t.panel)||r.has(t.panel)?null:(r.add(t.panel),k(t.panel));if("split"!==t.type||"string"!=typeof t.id||!/^[a-z0-9-]{1,32}$/.test(t.id)||i.has(t.id)||"horizontal"!==t.axis&&"vertical"!==t.axis||"number"!=typeof t.ratio||!Number.isFinite(t.ratio)||t.ratio<0||t.ratio>1)return null;i.add(t.id);let n=e(t.first,s+1),a=e(t.second,s+1);return n&&a?{type:"split",id:t.id,axis:t.axis,ratio:t.ratio,first:n,second:a}:null}(t.tree);if(!s||!P(s).some(e=>"book"!==e))return null;
1let n={version:1,tree:s,locked:t.locked,preset:t.preset},a=t.hiddenPanels;if(a&&"object"==typeof a&&!Array.isArray(a)){let e={};for(let t of b){if(r.has(t))continue;let i=a[t];i&&"object"==typeof i&&!(!Array.isArray(i.siblings)||!i.siblings.length||i.siblings.length>3||i.siblings.some(e=>!b.includes(e)||e===t))&&new Set(i.siblings).size===i.siblings.length&&["left","right","top","bottom"].includes(i.edge)&&"string"==typeof i.splitId&&/^[a-z0-9-]{1,32}$/.test(i.splitId)&&"number"==typeof i.ratio&&Number.isFinite(i.ratio)&&!(i.ratio<0)&&!(i.ratio>1)&&"number"==typeof i.width&&Number.isFinite(i.width)&&!(i.width<=0)&&"number"==typeof i.height&&Number.isFinite(i.height)&&!(i.height<=0)&&(e[t]={siblings:[...i.siblings],edge:i.edge,splitId:i.splitId,ratio:i.ratio,width:_(i.width,y[t].width,w[t]??Number.MAX_SAFE_INTEGER),height:_(i.height,y[t].height,Number.MAX_SAFE_INTEGER)})}Object.keys(e).length&&(n.hiddenPanels=e)}return n}catch{return null}}var B=e.i(679278),z=e.i(807956);let $="desktop-workspace-controls";e.s(["WORKSPACE_CONTROLS_SLOT_ID",0,$],682134);let V="imperial.multichart-enabled.v1",H={multiChartEnabled:!1,preferenceRevision:0},W=!1,q=new Set;function K(){try{let e;return e=localStorage.getItem(V),"true"===e}catch{return}}function G(e){return t?t.multiChartEnabled!==e&&(t={multiChartEnabled:e,preferenceRevision:t.preferenceRevision+1}):t={multiChartEnabled:e,preferenceRevision:Number(e)},t}function Y(){return t??G(K()??!1)}function X(){q.forEach(e=>e())}function Q(e){if(e.key===V||null===e.key){try{if(e.storageArea&&e.storageArea!==localStorage)return}catch{}W=!1,G(null!==e.key&&"true"===e.newValue),X()}}function J(e){return 0===q.size&&(W||G(K()??t?.multiChartEnabled??!1),window.addEventListener("storage",Q)),q.add(e),()=>{q.delete(e),0===q.size&&window.removeEventListener("storage",Q)}}function Z(e){G(e);try{localStorage.setItem(V,String(e)),W=!1}catch{W=!0}X()}function ee(){return{...(0,i.useSyncExternalStore)(J,Y,()=>H),setMultiChartEnabled:Z}}e.s(["getMultiChartPreference",0,function(){return Y().multiChartEnabled},"getMultiChartPreferenceRevision",0,function(){return Y().preferenceRevision},"useMultiChartPreference",0,ee],106476);let et=(0,i.createContext)(!0),er=(0,i.createContext)(!0),ei=(0,i.createContext)(null),es=(0,i.createContext)(null);e.s(["DesktopWorkspaceActivityContext",0,es,"DesktopWorkspacePanelActiveContext",0,et,"DesktopWorkspacePanelTools",0,function(){return(0,i.useContext)(ei)},"DesktopWorkspacePanelToolsContext",0,ei,"DesktopWorkspacePanelVisibleContext",0,er,"useDesktopWorkspaceActivity",0,function(){return(0,i.useContext)(es)},"useDesktopWorkspacePanelActive",0,function(){return(0,i.useContext)(et)},"useDesktopWorkspacePanelVisible",0,function(){return(0,i.useContext)(er)}],710729);var en=e.i(975735);let ea=(0,z.default)(()=>e.A(871829).then(e=>e.DesktopChartLayoutMenu),{loadableGenerated:{modules:[609222]},ssr:!1});function el(e){let t=e.current;t&&(e.current=null,null!==t.frame&&cancelAnimationFrame(t.frame),t.cleanup(),t.element.hasPointerCapture(t.pointerId)&&t.element.releasePointerCapture(t.pointerId))}let eo=["left","top","right","bottom"],ed={left:n.ArrowLeft,right:a.ArrowRight,top:l.ArrowUp,bottom:s.ArrowDown},ec=e=>({left:e.x,top:e.y,width:e.width,height:e.height});e.s(["DesktopWorkspace",0,function({slots:e,labels:t,availableBook:s,className:n,storageKey:a="imperial.desktop-workspace.v1"}){let{multiChartEnabled:l,setMultiChartEnabled:w}=ee(),M=(0,i.useId)(),[_,A]=(0,i.useState)(()=>N()),E=(0,i.useMemo)(()=>"u">typeof navigator&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘ Z":"Ctrl+Z",[]),[z,V]=(0,i.useState)(!1),[H,W]=(0,i.useState)("unsaved"),[q,K]=(0,i.useState)(""),[G,Y]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[J,Z]=(0,i.useState)(null),[eu,eh]=(0,i.useState)(null),[ep,em]=(0,i.useState)(null),ef=(0,i.useRef)(null),ex=(0,i.useRef)(null),[eg,eb]=(0,i.useState)({width:0,height:0}),ev=(0,i.useRef)(null),ey=(0,i.useRef)(null),ew=(0,i.useRef)(null),ej=(0,i.useRef)(null),eS=(0,i.useRef)({}),ek=(0,i.useRef)({}),[eN,eP]=(0,i.useState)(null),[eT,eC]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=requestAnimationFrame(()=>eC(document.getElementById($)));return()=>cancelAnimationFrame(e)},[]);let eM=(0,i.useMemo)(()=>C(eu??_.tree,s),[eu,_.tree,s]),e_=(0,i.useMemo)(()=>L(eM,eg),[eM,eg]),eA=P(eM),eE=G&&j(G)&&eA.includes(G)?G:null,eL=eE?eg:e_.size,eF=eN&&eA.includes(eN)&&!_.locked&&!eE?eN:null;(0,i.useEffect)(()=>
1{if(!eN||eF)return;let e=requestAnimationFrame(()=>eP(null));return()=>cancelAnimationFrame(e)},[eN,eF]),(0,i.useEffect)(()=>{let e=requestAnimationFrame(()=>{try{let e=O(localStorage.getItem(a));e&&A(function(e){if("custom"===e.preset)return e;let t=N(e.preset);return[!1,!0].some(r=>JSON.stringify(e.tree)===JSON.stringify(function t(r,i){if("panel"===r.type)return r;let s=i?.95:.76,n=i?.05:.24;return{...r,ratio:"ticket"===r.id?"mirrored"===e.preset?n:s:"market"===r.id?s:r.ratio,first:t(r.first,i),second:t(r.second,i)}}(t.tree,r)))?{...e,tree:t.tree}:e}(e))}catch{W("saveUnavailable")}V(!0)});return()=>cancelAnimationFrame(e)},[a]),(0,i.useEffect)(()=>{if(!z)return;let e=setTimeout(()=>{try{localStorage.setItem(a,JSON.stringify(O(JSON.stringify(_))??N())),W("saved")}catch{W("saveUnavailable")}},300);return()=>clearTimeout(e)},[_,z,a]),(0,i.useEffect)(()=>{let e=ev.current;if(!e)return;let t=new ResizeObserver(([e])=>{eb({width:e.contentRect.width,height:e.contentRect.height})});return t.observe(e),()=>t.disconnect()},[]);let eR=(0,i.useCallback)(()=>{el(ew),Q(null),Z(null),eh(null)},[]);function eD(e){A(e),W("unsaved"),K("")}function eI(e){eD(N(e)),Y(null)}function eU(e){return eA.length>1&&("book"===e||eA.filter(e=>"book"!==e).length>1)}function eO(e){if(!eU(e))return;let t=function(e,t,r,i=!0){if(e.locked)return null;let s=function e(t,r){return"panel"===t.type?null:"panel"===t.first.type&&t.first.panel===r?{split:t,sibling:t.second,before:!0}:"panel"===t.second.type&&t.second.panel===r?{split:t,sibling:t.first,before:!1}:e(t.first,r)??e(t.second,r)}(e.tree,t),n=L(C(e.tree,i),r).panels[t],a=T(e.tree,t);if(!s||!n||!a||!P(a).some(e=>"book"!==e))return null;let l="horizontal"===s.split.axis?s.before?"left":"right":s.before?"top":"bottom";return{...e,tree:a,preset:"custom",hiddenPanels:{...e.hiddenPanels,[t]:{siblings:P(s.sibling),edge:l,splitId:s.split.id,ratio:s.split.ratio,width:n.width,height:n.height}}}}(_,e,eg,s);if(t){eD(t),Y(null);let r=eA.find(t=>t!==e);r&&requestAnimationFrame(()=>eS.current[r]?.focus())}}function eB(e,r,i){let n=U(_.tree,e,r,i,eg,s);n?(eD({..._,tree:n,preset:"custom"}),Y(null)):K(t.dockUnavailable)}function ez(e){let t=function(e,t,r,i=!0){let s;if(e.locked||!b.includes(t)||!i&&"book"===t)return null;if(P(e.tree).includes(t))return e;let n=e.hiddenPanels?.[t];if(n){let a=P(e.tree),l=n.siblings.filter(e=>a.includes(e));if(!l.length){let t=P(C(e.tree,i));l.push(t.includes("chart")?"chart":t[0])}let o=function e(t){return"panel"===t.type?t:l.every(e=>P(t.first).includes(e))?e(t.first):l.every(e=>P(t.second).includes(e))?e(t.second):t}(e.tree),d=D(e.tree,n.splitId),c="left"===n.edge||"top"===n.edge,u="left"===n.edge||"right"===n.edge,h=n.ratio,p=L(C(s=function e(r){return r===o?{type:"split",id:d,axis:u?"horizontal":"vertical",ratio:h,first:c?k(t):r,second:c?r:k(t)}:"panel"===r.type?r:{...r,first:e(r.first),second:e(r.second)}}(e.tree),i),r).separators.find(e=>e.id===d);if(p){let e=p.parent[u?"width":"height"]-5,t=n[u?"width":"height"]/e;s=R(s,d,F(p,c?t:1-t))}}else s=function(e,t,r=!0){if(!b.includes(t)||!r&&"book"===t)return null;if(P(e).includes(t))return e;let i=P(C(e,r)),s=i.includes("chart")?"chart":i[0],n="activity"===t&&j(s)?"bottom":"right";return I(e,t,s,n,r)}(e.tree,t,i);if(!s)return null;let a={...e.hiddenPanels};delete a[t];let l={...e,tree:s,preset:"custom"};return Object.keys(a).length?l.hiddenPanels=a:delete l.hiddenPanels,l}(_,e,eg,s);t&&(eD(t),Y(null),requestAnimationFrame(()=>eS.current[e]?.focus()))}(0,i.useEffect)(()=>{let e=e=>{if(_.locked||e.defaultPrevented||e.repeat||e.isComposing||e.altKey||e.shiftKey||!(e.metaKey||e.ctrlKey)||"z"!==e.key.toLowerCase())return;let t=e.target,r=document.activeElement,i=e=>e instanceof HTMLElement&&(e.isContentEditable||!!e.closest("input, textarea, select, [contenteditable], iframe"));i(t)||i(r)||document.querySelector('[data-slot="dialog-content"][data-state="open"], [data-slot="sheet-content"][data-state="open"], [data-slot="popover-content"][data-state="open"], [data-slot="dropdown-menu-content"][data-state="open"], [aria-modal="true"]')||(t===document.body||t===document.documentElement||t instanceof HTMLElement&&(t.closest("[data-workspace-layout-control]")||t.closest("[data-desktop-workspace]")&&!t.closest("[data-workspace-panel]")))&&(e.preventDefault(),eR(),em(null),eP(null),Y(null),A(N()),W("unsaved"),K(""),document.getElementById($)?.querySelector("button")?.focus({preventScroll:!0}))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[_.locked,eR]),(0,i.useEffect)(()=>()=>{el(ew),null!==ej.current&&cancelAnimationFrame(ej.current)},[]),(0,i.useEffect)(()=>{let e=ew.current;e&&(e.initial!==_||e.availableBook!==s||e.viewport.width!==eg.width||e.viewport.height!==eg.height||!e.element.isConnected||eE)&&(el(ew),null===ej.current&&(ej.current=requestAnimationFrame(()=>{ej.current=null,Q(null),Z(null),eh(null)})))},[_,s,eE,eg,eR]),(0,i.useEffect)(()=>
1{if(!ep)return;let e=e=>{ef.current?.contains(e.target)||em(null)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),em(null),ey.current?.querySelector(`[data-workspace-separator="${ep.id}"]`)?.focus())};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0),null!==ex.current&&cancelAnimationFrame(ex.current),ex.current=null}},[ep]),(0,i.useEffect)(()=>{if(eE)return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e);function e(e){"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),Y(null),requestAnimationFrame(()=>(ek.current[eE]??eS.current[eE])?.focus()))}},[eE]);let e$=!ep||_.locked||eE?null:e_.separators.find(e=>e.id===ep.id),eV=e$?.firstPanels.map(e=>t.panels[e]).join(", ")??"",eH=e$?.secondPanels.map(e=>t.panels[e]).join(", ")??"",eW=e$?.axis==="horizontal"?"left":"top",eq=e$?.axis==="horizontal"?"right":"bottom",eK=ed[eW],eG=ed[eq],eY=!!e$&&e$.ratio>e$.min+1e-4,eX=!!e$&&e$.ratio<e$.max-1e-4,eQ=e$?.balance??.5,eJ=e$?("horizontal"===e$.axis?e$.parent.width:e$.parent.height)-5:0,eZ=eJ>0?(e$?.axis==="horizontal"?24:32)/eJ:0,e0=!!e$&&Math.abs(e$.ratio-eQ)>1e-4,e1=X?.target??null,e2=X&&e1?U(_.tree,X.panel,e1.panel,e1.edge,eg,s):null,e5=e2?L(C(e2,s),eg):null;function e3(){let e=ev.current;if(!e)return null;let t=e.getBoundingClientRect(),r=Math.max(0,t.left),i=Math.max(0,t.top);return{x:r,y:i,width:Math.min(window.innerWidth,t.left+e.clientWidth)-r,height:Math.min(window.innerHeight,t.top+e.clientHeight)-i}}function e4(e,t,r){let i=ey.current?.getBoundingClientRect(),s=e3();if(!i||!s)return;let n=t??i.left+e.x+e.width/2,a=r??i.top+e.y+e.height/2;em({id:e.id,x:Math.max(s.x+8,Math.min(s.x+s.width-264,n-128))-i.left,y:Math.max(s.y+8,Math.min(s.y+s.height-78,a+10))-i.top}),requestAnimationFrame(()=>{let e=ef.current;(e?.querySelector('button:not([aria-disabled="true"])')??e?.querySelector("button"))?.focus({preventScroll:!0})})}function e6(e){0===e.button&&e.isPrimary&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))}function e8(e,t){if(_.locked||eE||ew.current||0!==e.button||!e.isPrimary)return;let r=e.currentTarget;if(null!==ej.current&&(cancelAnimationFrame(ej.current),ej.current=null,Q(null),Z(null),eh(null)),em(null),eP(null),!ey.current||!ev.current)return;e.preventDefault(),r.setAttribute("data-pointer-focus",""),r.focus({preventScroll:!0});try{r.setPointerCapture(e.pointerId)}catch{return}let i={pointerId:e.pointerId,element:r,initial:_,availableBook:s,viewport:eg,startX:e.clientX,startY:e.clientY,active:!1,frame:null,latest:{clientX:e.clientX,clientY:e.clientY},cleanup:()=>{},operation:t};ew.current=i,"drag"===t.kind?Q({panel:t.panel,active:!1,target:null}):Z(t.separator.id);let n=document.createElement("style"),a="drag"===t.kind?"grabbing":"horizontal"===t.separator.axis?"col-resize":"row-resize";n.textContent=`html, html * { user-select: none !important; -webkit-user-select: none !important; cursor: ${a} !important; }
2      [data-desktop-workspace] iframe { pointer-events: none !important; }`,document.head.appendChild(n);let l=ey.current.querySelectorAll("iframe"),o=()=>{for(let e of(window.getSelection()?.removeAllRanges(),l))try{e.contentWindow?.getSelection()?.removeAllRanges()}catch{}},d=e=>e.preventDefault(),c=()=>eR(),u=e=>{"Escape"===e.key&&(r.removeAttribute("data-pointer-focus"),e.preventDefault(),e.stopPropagation(),c())},h=()=>{document.hidden&&c()},p=e=>{e.pointerId===i.pointerId&&c()};function m(){if(ew.current!==i)return;i.frame=null;let{clientX:e,clientY:t}=i.latest,s=ey.current?.getBoundingClientRect(),n=e3();if(!s||!n||!r.isConnected)return void c();if("drag"===i.operation.kind){let r=Math.hypot(e-i.startX,t-i.startY);if(!i.active&&r>=5&&(i.active=!0,o()),!i.active)return;let a=function(e,t,r,i,s=null){if(!v(r,i))return null;for(let i of b){let n=e[i];if(i===t||!n||!v(r,n))continue;let a=Math.min(96,.2*n.width),l=Math.min(96,.2*n.height),o=[{edge:"left",distance:r.x-n.x,band:a},{edge:"right",distance:n.x+n.width-r.x,band:a},{edge:"top",distance:r.y-n.y,band:l},{edge:"bottom",distance:n.y+n.height-r.y,band:l}].filter(e=>S(t,i,e.edge)),d=s?.panel===i?o.find(e=>e.edge===s.edge):null;if(d&&d.distance<=d.band+12)return s;let c=o.filter(e=>e.distance<=e.band).sort((e,t)=>
2e.distance/e.band-t.distance/t.band)[0];return c?{panel:i,edge:c.edge}:null}return null}(e_.panels,i.operation.panel,{x:e-s.left,y:t-s.top},{...n,x:n.x-s.left,y:n.y-s.top},i.operation.target);i.operation.target=a,Q({panel:i.operation.panel,active:!0,target:a})}else{let r=i.operation.separator,s="horizontal"===r.axis,n=s?e-i.startX:t-i.startY;if(!i.active&&3>Math.abs(n))return;i.active||(i.active=!0,o());let a=s?r.parent.width:r.parent.height,l=Math.max(r.min,Math.min(r.max,r.ratio+n/(a-5)));i.operation.preview=R(i.initial.tree,r.id,F(r,l)),eh(i.operation.preview)}}let f=e=>{if(e.pointerId===i.pointerId){if(!(1&e.buttons))return void c();e.preventDefault(),i.latest={clientX:e.clientX,clientY:e.clientY},null===i.frame&&(i.frame=requestAnimationFrame(m))}},x=e=>{if(e.pointerId!==i.pointerId||(e.preventDefault(),i.latest={clientX:e.clientX,clientY:e.clientY},null!==i.frame&&cancelAnimationFrame(i.frame),m(),ew.current!==i))return;let t=e3(),r=t&&v({x:e.clientX,y:e.clientY},t);if(eR(),"drag"===i.operation.kind&&!i.active)return void eP(i.operation.panel);if("drag"===i.operation.kind){if(!r)return;let e=i.operation.target;i.active&&e&&eB(i.operation.panel,e.panel,e.edge)}else i.active?eD({...i.initial,tree:i.operation.preview,preset:"custom"}):r&&e4(i.operation.separator,e.clientX,e.clientY)};document.addEventListener("selectstart",d,!0),document.addEventListener("dragstart",d,!0),document.addEventListener("keydown",u,!0),document.addEventListener("visibilitychange",h),window.addEventListener("pointermove",f,{capture:!0,passive:!1}),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",p,!0),window.addEventListener("blur",c),window.addEventListener("resize",c),r.addEventListener("lostpointercapture",p),i.cleanup=()=>{i.active&&o(),n.remove(),document.removeEventListener("selectstart",d,!0),document.removeEventListener("dragstart",d,!0),document.removeEventListener("keydown",u,!0),document.removeEventListener("visibilitychange",h),window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",p,!0),window.removeEventListener("blur",c),window.removeEventListener("resize",c),r.removeEventListener("lostpointercapture",p)}}function e9(e,t){let r=Math.max(e.min,Math.min(e.max,t));1e-4>Math.abs(r-e.ratio)||(A(t=>({...t,tree:R(t.tree,e.id,F(e,r)),preset:"custom"})),W("unsaved"))}let e7=!eE&&!!e_.panels.activity&&e_.panels.activity.height<=38.5,te=(0,i.useCallback)(()=>{if(!e7||_.locked)return;let e=e_.separators.find(e=>"vertical"===e.axis&&(1===e.firstPanels.length&&"activity"===e.firstPanels[0]||1===e.secondPanels.length&&"activity"===e.secondPanels[0]));if(!e)return;let t=160/(e.parent.height-5),r=F(e,"activity"===e.firstPanels[0]?t:1-t);A(t=>({...t,tree:R(t.tree,e.id,r),preset:"custom"})),W("unsaved")},[e7,_.locked,e_.separators]),tt=(0,i.useMemo)(()=>({collapsed:e7,reveal:te}),[e7,te]);function tr(e,i=!1){return(0,r.jsxs)(g.DropdownMenu,{open:eF===e,onOpenChange:t=>eP(t?e:null),children:[(0,r.jsx)(g.DropdownMenuTrigger,{asChild:!0,children:(0,r.jsx)("button",{type:"button",ref:t=>{eS.current[e]=t},className:en.default.dragHandle,"data-workspace-layout-control":"",disabled:i||_.locked||!!eE,"aria-label":`${t.drag}: ${t.panels[e]}`,title:`${t.move}: ${t.panels[e]}`,onPointerDown:t=>e8(t,{kind:"drag",panel:e,target:null}),onBlur:e=>e.currentTarget.removeAttribute("data-pointer-focus"),onKeyDown:e=>e.currentTarget.removeAttribute("data-pointer-focus"),children:(0,r.jsx)(d.GripVertical,{size:13,"aria-hidden":!0})})}),(0,r.jsxs)(g.DropdownMenuContent,{className:en.default.menu,align:"start",children:[(0,r.jsx)(g.DropdownMenuLabel,{className:en.default.menuLabel,children:t.panels[e]}),j(e)&&(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,onSelect:()=>Y(e),children:[(0,r.jsx)(h.Maximize2,{size:13}),t.maximize]}),(0,r.jsxs)(g.DropdownMenuSub,{children:[(0,r.jsx)(g.DropdownMenuSubTrigger,{className:en.default.menuItem,children:t.move}),(0,r.jsx)(g.DropdownMenuSubContent,{className:en.default.menu,children:eA.filter(t=>t!==e).map(i=>(0,r.jsxs)(g.DropdownMenuSub,{children:[(0,r.jsx)(g.DropdownMenuSubTrigger,{className:en.default.menuItem,children:t.panels[i]}),(0,r.jsx)(g.DropdownMenuSubContent,{className:en.default.menu,children:eo.map(n=>{let a=ed[n],l=!!U(_.tree,e,i,n,eg,s);return(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,disabled:!l,onSelect:()=>eB(e,i,n),children:[(0,r.jsx)(a,{size:13}),t[n]]},n)})})]},i))})]}),(0,r.jsx)(g.DropdownMenuSeparator,{}),(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,disabled:!eU(e),onSelect:()=>eO(e),children:[(0,r.jsx)(x.X,{size:13}),t.hide]})]})]})}let ti=(0,r.jsxs)(g.DropdownMenu,{children:[(0,r.jsx)(g.DropdownMenuTrigger,{asChild:!0,children:(0,r.jsx)("button",{type:"button",className:en.default.workspaceLauncher,"data-workspace-layout-control":"","aria-label":t.workspace,title:t.workspace,children:(0,r.jsx)(m.PanelsTopLeft,{size:17,"aria-hidden":!0})})}),(0,r.jsxs)(g.DropdownMenuContent,{className:en.default.menu,align:"end",children:[(0,r.jsx)(g.DropdownMenuCheckboxItem,{className:en.default.menuItem,checked:l,"aria-label":t.multiChart,"aria-describedby":M,onSelect:e=>e.preventDefault(),onCheckedChange:w,children:(0,r.jsxs)("span",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,r.jsx)("span",{children:t.multiChart}),(0,r.jsx)("span",{id:M,className:"text-[11px] text-muted-foreground",children:t.multiChartDescription})]})}),(0,r.jsx)(g.DropdownMenuSeparator,{}),l&&(0,r.jsx)(ea,{}),(0,r.jsxs)(g.DropdownMenuSub,{children:[(0,r.jsxs)(g.DropdownMenuSubTrigger,{className:en.default.menuItem,disabled:_.locked,children:[(0,r.jsx)(c.LayoutDashboard,{size:13}),t.layout]}),(0,r.jsx)(g.DropdownMenuSubContent,{className:en.default.menu,children:["trading","focus","mirrored"].map(e=>(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,onSelect:()=>eI(e),children:[t[e],_.preset===e&&(0,r.jsx)(o.Check,{size:13,className:en.default.menuCheck})]},e))})]}),(0,r.jsxs)(g.DropdownMenuSub,{children:[(0,r.jsx)(g.DropdownMenuSubTrigger,{className:en.default.menuItem,disabled:_.locked,children:t.panelsMenu}),(0,r.jsx)(g.DropdownMenuSubContent,{className:en.default.menu,children:b.filter(e=>"book"!==e||s).map(e=>(0,r.jsx)(g.DropdownMenuCheckboxItem,{className:en.default.menuItem,checked:eA.includes(e),"aria-label":`${eA.includes(e)?t.hide:t.restore}: ${t.panels[e]}`,disabled:eA.includes(e)&&!eU(e),onCheckedChange:t=>t?ez(e):eO(e),children:t.panels[e]},e))})]}),"chart"!==eE&&(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,disabled:_.locked&&!eA.includes("chart"),onSelect:()=>{eA.includes("chart")||ez("chart"),Y("chart")},children:[(0,r.jsx)(h.Maximize2,{size:13}),t.maximize,": ",t.panels.chart]}),eE&&(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,onSelect:()=>Y(null),children:[(0,r.jsx)(p.Minimize2,{size:13}),t.restore,": ",t.panels[eE]]}),(0,r.jsx)(g.DropdownMenuSeparator,{}),(0,r.jsxs)(g.DropdownMenuCheckboxItem,{className:en.default.menuItem,checked:_.locked,onCheckedChange:e=>eD({..._,locked:e}),children:[(0,r.jsx)(u.LockKeyhole,{size:13}),t.locked]}),(0,r.jsxs)(g.DropdownMenuItem,{className:en.default.menuItem,disabled:_.locked,onSelect:()=>eI("trading"),"aria-keyshortcuts":"Meta+Z Control+Z",children:[(0,r.jsx)(f.RotateCcw,{size:13}),t.reset,(0,r.jsx)("kbd",{className:en.default.menuShortcut,"aria-hidden":!0,
2children:E})]}),(0,r.jsx)(g.DropdownMenuSeparator,{}),(0,r.jsxs)("div",{className:`${en.default.saveStatus} ${"saveUnavailable"===H?en.default.saveWarning:""}`,role:"status",children:[(0,r.jsx)("span",{className:en.default.statusDot}),t[H]]})]})]}),ts=(0,r.jsxs)("div",{className:en.default.chartControls,children:[tr("chart",!eA.includes("chart")),(0,r.jsx)("button",{type:"button",ref:e=>{ek.current.chart=e},className:en.default.iconButton,"data-workspace-layout-control":"",onClick:()=>{eA.includes("chart")||ez("chart"),Y("chart"===eE?null:"chart")},"aria-label":`${"chart"===eE?t.restore:t.maximize}: ${t.panels.chart}`,title:`${"chart"===eE?t.restore:t.maximize}: ${t.panels.chart}`,children:"chart"===eE?(0,r.jsx)(p.Minimize2,{size:13}):(0,r.jsx)(h.Maximize2,{size:13})})]});return(0,r.jsxs)("section",{className:`${en.default.workspace} ${n??""}`,"aria-label":t.workspace,"data-desktop-workspace":!0,children:[eT&&(0,B.createPortal)(ti,eT),(0,r.jsx)("div",{ref:ev,className:en.default.viewport,children:(0,r.jsxs)("div",{ref:ey,className:en.default.canvas,style:{width:eL.width,height:eL.height},children:[b.filter(e=>"book"!==e||s).map(i=>{let s=eE===i?{x:0,y:0,...eL}:e_.panels[i]??{x:0,y:0,...y[i]},n=!eA.includes(i)||!!(eE&&eE!==i),a="ticket"===i&&!n&&0===s.y&&s.height===e_.size.height&&eg.height>0&&eg.height<s.height?{position:"sticky",top:0,marginLeft:s.x,width:s.width,height:eg.height}:ec(s);return(0,r.jsx)("section",{className:`${en.default.panel} ${n?en.default.hiddenPanel:""} ${X?.active&&X.panel===i?en.default.draggingPanel:""}`,style:a,"aria-label":t.panels[i],"aria-hidden":n||void 0,inert:n||void 0,"data-workspace-panel":i,"data-activity-collapsed":"activity"===i&&e7||void 0,children:(0,r.jsx)("div",{className:`${en.default.panelBody} ${"ticket"===i?en.default.scrollBody:""}`,children:(0,r.jsx)(er.Provider,{value:!n,children:(0,r.jsx)(et.Provider,{value:!n&&!("activity"===i&&e7)&&!X&&!J&&!e$&&!eF,children:(0,r.jsx)(ei.Provider,{value:"chart"===i?ts:tr(i,n),children:(0,r.jsx)(es.Provider,{value:"activity"===i?tt:null,children:e[i]})})})})})},i)}),!eE&&e_.separators.map(e=>(0,r.jsx)("div",{className:`${en.default.separator} ${"horizontal"===e.axis?en.default.horizontal:en.default.vertical}`,style:ec(e),role:"separator",tabIndex:_.locked?-1:0,"aria-label":`${t.resize}: ${e.firstPanels.map(e=>t.panels[e]).join(", ")}`,"aria-orientation":"horizontal"===e.axis?"vertical":"horizontal","aria-disabled":_.locked,"aria-valuenow":Math.round(100*e.ratio),"aria-valuemin":Math.round(100*e.min),"aria-valuemax":Math.round(100*e.max),"data-workspace-separator":e.id,"data-workspace-layout-control":"","data-active":J===e.id||void 0,onPointerDown:t=>e8(t,{kind:"resize",separator:e,preview:_.tree}),onBlur:e=>e.currentTarget.removeAttribute("data-pointer-focus"),onKeyDown:t=>{if(t.currentTarget.removeAttribute("data-pointer-focus"),_.locked)return;if("Enter"===t.key||" "===t.key){t.preventDefault(),e4(e);return}let r="horizontal"===e.axis?"ArrowLeft":"ArrowUp";[r,"horizontal"===e.axis?"ArrowRight":"ArrowDown","Home","End"].includes(t.key)&&(t.preventDefault(),e9(e,"Home"===t.key?e.min:"End"===t.key?e.max:e.ratio+(t.key===r?-1:1)*(t.shiftKey?4:1)*("horizontal"===e.axis?24:32)/(("horizontal"===e.axis?e.parent.width:e.parent.height)-5)))}},e.id)),ep&&e$&&(0,r.jsxs)("div",{ref:ef,className:en.default.resizeControls,style:{left:ep.x,top:ep.y},role:"group","data-workspace-resize-controls":"","data-workspace-layout-control":"",onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(null!==ex.current&&cancelAnimationFrame(ex.current),ex.current=requestAnimationFrame(()=>{ex.current=null,ef.current?.contains(document.activeElement)||em(null)}))},"aria-label":`${t.resize}: ${eV} / ${eH}`,children:[(0,r.jsxs)("div",{className:en.default.resizeSides,"aria-live":"polite",children:[(0,r.jsxs)("span",{title:eV,children:[(0,r.jsx)("span",{children:eV}),(0,r.jsxs)("strong",{children:[Math.round(e$.ratio*eJ),"px"]})]}),(0,r.jsxs)("span",{title:eH,children:[(0,r.jsx)("span",{children:eH}),(0,r.jsxs)("strong",{children:[Math.round((1-e$.ratio)*eJ),"px"]})]})]}),(0,r.jsxs)("div",{className:en.default.resizeActions,children:[(0,r.jsxs)("button",{type:"button",onPointerDown:e6,"aria-label":`${t.move}: ${t[eW]}`,title:`${t.move}: ${t[eW]}`,"aria-disabled":!eY,onClick:()=>{eY&&e9(e$,e$.ratio-eZ)},children:[(0,r.jsx)(eK,{size:12,"aria-hidden":!0}),t[eW]]}),(0,r.jsx)("button",{type:"button",onPointerDown:e6,"aria-label":`${t.balance}: ${eV} / ${eH}`,title:`${t.balance}: ${Math.round(eQ*eJ)}px / ${Math.round((1-eQ)*eJ)}px`,"aria-disabled":!e0,onClick:()=>{e0&&e9(e$,eQ)},children:t.balance}),(0,r.jsxs)("button",{type:"button",onPointerDown:e6,"aria-label":`${t.move}: ${t[eq]}`,title:`${t.move}: ${t[eq]}`,"aria-disabled":!eX,onClick:()=>{eX&&e9(e$,e$.ratio+eZ)},children:[t[eq],(0,r.jsx)(eG,{size:12,"aria-hidden":!0})]})]})]}),(X?.active||J)&&(0,r.jsx)("div",{className:`${en.default.interactionShield} ${J?en.default.resizeShield:""}`}),X?.active&&e5&&(0,r.jsx)("div",{className:en.default.dropPreview,style:ec(e5.panels[X.panel]),"aria-hidden":!0,
2children:(0,r.jsxs)("span",{className:en.default.dropLabel,children:[t.panels[X.panel]," · ",t[e1.edge]]})}),X?.active&&e1&&!e2&&(0,r.jsx)("div",{className:en.default.dropMessage,children:t.dockUnavailable})]})}),(0,r.jsx)("span",{className:q?en.default.layoutNotice:en.default.screenReaderOnly,role:"status","aria-live":"polite",children:q})]})}],157285);var eu=e.i(942553);e.s(["useDesktopWorkspaceLabels",0,function(){let e=(0,eu.useTranslations)("trading"),t=(0,eu.useTranslations)("settings");return{panels:{chart:e("workspaceChart"),book:e("workspaceBook"),ticket:e("workspaceTicket"),activity:e("workspaceActivity")},multiChart:t("multiChart"),multiChartDescription:t("multiChartDescription"),workspace:e("workspaceWorkspace"),layout:e("workspaceLayout"),trading:e("workspaceTrading"),focus:e("workspaceFocus"),mirrored:e("workspaceMirrored"),panelsMenu:e("workspacePanelsMenu"),reset:e("workspaceReset"),saved:e("workspaceSaved"),unsaved:e("workspaceUnsaved"),saveUnavailable:e("workspaceSaveUnavailable"),drag:e("workspaceDrag"),move:e("workspaceMove"),maximize:e("workspaceMaximize"),restore:e("workspaceRestore"),hide:e("workspaceHide"),left:e("workspaceLeft"),right:e("workspaceRight"),top:e("workspaceTop"),bottom:e("workspaceBottom"),shrink:e("workspaceShrink"),expand:e("workspaceExpand"),balance:e("workspaceBalance"),resize:e("workspaceResize"),dockUnavailable:e("workspaceDockUnavailable"),locked:e("workspaceLocked"),unlocked:e("workspaceUnlocked")}}],918401)},565183,332608,403652,555641,260431,111468,495433,744427,727104,227824,47935,e=>{"use strict";var t=e.i(394390),r=e.i(942553),i=e.i(153517),s=e.i(299959),n=e.i(616341),a=e.i(889572);e.s(["AccountHealthRow",0,function({effectiveUsd:e,maintenanceUsd:l,initialUsd:o,legInitialUsd:d,legMaintenanceUsd:c,depositUsd:u,compact:h=!1}){let p=(0,r.useTranslations)("trading"),m=(0,s.useFormatters)();if(null===e||null===l)return null;let f=(0,a.seatHealth)(e,l);if(null===f)return null;let x=(0,a.liquidationBufferUsd)(e,l),g="number"==typeof d&&d>0?{effectiveUsd:e,maintenanceUsd:l,initialUsd:o??0,legInitialUsd:d,legMaintenanceUsd:c,depositUsd:u??0}:null,b=g?(0,a.projectSeatHealth)(g):null,v=(g?(0,a.projectLiquidationBufferUsd)(g):null)??x;return(0,t.jsxs)("div",{className:(0,i.cn)("rounded-[5px]",h?"border-[0.926px] border-[var(--phone-card-border)] bg-[var(--phone-row)] px-3 pb-3 pt-[11px]":"border border-border trading-control-surface px-3 py-2"),children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:(0,i.cn)(h?"text-[10.5px]":"text-3xs","text-label-muted"),children:p("accountHealth")}),(0,t.jsx)(n.HealthMeter,{health:f,projected:b,size:h?"sm":"md"})]}),null!==v&&(0,t.jsx)("div",{className:(0,i.cn)("mt-1.5 font-mono tabular-nums text-label-muted",h?"text-[10px]":"text-3xs"),children:p("healthBeforeLiquidation",{amount:`$${m.number(v)}`})})]})}],565183);var l=e.i(98788);function o(e,t){return!isFinite(t)||t<=0||!isFinite(e.entryPrice)||e.entryPrice<=0||!isFinite(e.sizeUsd)||e.sizeUsd<=0?0:("long"===e.side?1:-1)*e.sizeUsd*(t-e.entryPrice)/e.entryPrice}function d(e,t,r,i){let s=isFinite(r)&&r>0,n=isFinite(e.entryPrice)&&e.entryPrice>0,a=s&&n?e.sizeUsd*r/e.entryPrice:0,l=o(e,r),d=isFinite(i)&&i>0?i:0,c=e.collateralUsd+l+d,u=t.maxLeverage,h=0;if(c>0&&isFinite(u)&&u>0){let e=isFinite(t.takerFeeMicro)&&t.takerFeeMicro>0?t.takerFeeMicro/1e6:0,r=u*c-a-(e>0?1e-6*u:0),i=1+u*e;r>0&&i>0&&(h=r/i)}return{effectiveCollateralUsd:c,unrealizedPnlUsd:l,currentNotionalUsd:a,maxAddSizeUsd:h}}function c(e){return Math.ceil(1e6*e)/1e6}function u(e,t,r){let i=e.filter(([e,t])=>isFinite(e)&&e>0&&isFinite(t)&&t>0).sort(([e],[t])=>"buy"===r?e-t:t-e);if(0===i.length)return null;let s=t,n=0,a=0,l=i[0][0];for(let[e,t]of i){l=e;let r=Math.min(s,e*t);if(n+=r,a+=r/e,(s-=r)<=0)break}return s>0&&(n+=s,a+=s/l),a>0?n/a:null}e.s(["computePhoenixAddHeadroom",0,d,"computePhoenixLiquidationPrice",0,function(e,t,r){let i=t.maxLeverage;if(!isFinite(r)||r<=0||!isFinite(i)||i<=0||!isFinite(e.entryPrice)||e.entryPrice<=0||!isFinite(e.sizeUsd)||e.sizeUsd<=0)return null;let s=("long"===e.side?1:-1)*e.sizeUsd/e.entryPrice,n=e.collateralUsd,a=1/(2*i)*Math.abs(s)-s;if(0===a)return null;let l=(n-s*e.entryPrice)/a;return!isFinite(l)||l<=0||("long"===e.side?l>=r:l<=r)?null:l},"computePhoenixMaxWithdrawUsd",0,function(e,t,r){let i=t.maxLeverage;if(!isFinite(i)||i<=0)return 0;let s=o(e,r);return e.collateralUsd+s-c((!isFinite(r)||r<=0||!isFinite(e.entryPrice)||e.entryPrice<=0||!isFinite(e.sizeUsd)||e.sizeUsd<=0?0:e.sizeUsd*r/e.entryPrice)/i)},"computePhoenixMinLoanForAdd",0,function(e,t,r,i,s){let n=d(e,t,r,i);if(s<=n.maxAddSizeUsd)return 0;let a=t.maxLeverage;if(!isFinite(a)||a<=0)return 0;let l=isFinite(t.takerFeeMicro)&&t.takerFeeMicro>0?t.takerFeeMicro/1e6:0,o=s*(1+a*l)/a+(n.currentNotionalUsd+(l>0?1e-6*a:0))/a-n.effectiveCollateralUsd;return o>0?c(o):0},"computePhoenixUnrealizedPnlUsd",0,o,"estimatePhoenixOpenFillLossFraction",0,function(e,t,r,i){if(!isFinite(r)||r<=0)return 0;if(!isFinite(i)||i<=0)return null;let s=u(e,r,"buy"),n=u(t,r,"sell");return null===s||null===n?null:Math.max(Math.max(0,s/i-1),Math.max(0,1-n/i))},"quotePhoenixMarketOrder",0,function(e,t,r,i,s,n,a,o,d=Date.now()){if
2((0,l.isPhoenixBookRevoked)(o)||!(0,l.isPhoenixBookFresh)(a,d)||!isFinite(r)||r<=0||!isFinite(i)||i<=0)return null;let c=u(s?e:t,r,s?"buy":"sell");if(null===c||!isFinite(c)||c<=0)return null;let h=(c/i-1)*1e4,p=Math.max(1,n),m=c*(s?1+p/1e4:1-p/1e4),f=Math.ceil((s?m/i-1:1-m/i)*1e4),x=p+500;return{fillPrice:c,fillVsIndexBps:h,adverseBps:s?h:-h,slippageBps:Math.min(x,Math.max(p,f)),exceedsAutoWiden:f>x}}],332608);let h=e=>"number"==typeof e?e:parseFloat(e??"");e.s(["blendedEntryPrice",0,function(e,t,r){if(void 0===t||!isFinite(t)||t<=0)return null;if(e?.entryPrice==null||e?.sizeUsd==null)return t;let i=h(e.entryPrice),s=h(e.sizeUsd);return!isFinite(i)||i<=0||!isFinite(s)||s<=0?t:!isFinite(r)||r<=0?i:(i*s+t*r)/(s+r)}],403652);var p=e.i(894771),m=e.i(622463),f=e.i(722732),x=e.i(653982),g=e.i(942289),b=e.i(828047),v=e.i(331613);let y={jupiter:function(e){return null!=x.ASSET_TO_MINT[e.toUpperCase()]||Object.values(x.ASSET_TO_MINT).includes(e)},phoenix:e=>null!=(0,m.resolvePhoenixSymbol)(e),gmtrade:function(e){return(0,f.getGlobalGmTradeRegistry)()?.getMarketBySymbol(e)!=null},armada:function(e){if(!(0,v.sunriseOpensAllowed)())return!1;let t=(0,b.getGlobalSunriseMarkets)();return!!t&&(!!t.has(e.toUpperCase())||[...t].some(t=>x.ASSET_TO_MINT[t]===e))}},w=["phoenix","gmtrade"],j=["jupiter","phoenix"].filter(e=>!g.OPENS_PAUSED_VENUES.has(e)),S=j[0]??"jupiter";function k(e){return Object.keys(y).some(t=>!g.OPENS_PAUSED_VENUES.has(t)&&y[t](e))}function N(e,t){return!!y[t](e)&&(!g.OPENS_PAUSED_VENUES.has(t)||!k(e))}e.s(["pausedVenueForMarket",0,function(e){return k(e)?null:w.find(t=>g.OPENS_PAUSED_VENUES.has(t)&&y[t](e))??null},"resolveConcreteUnderwriter",0,function(e,t,r=[]){let i=new Set(r),s="armada"===e&&!(0,v.sunriseOpensAllowed)();if(!(0,p.isAutoUnderwriter)(e)&&!s&&(!g.OPENS_PAUSED_VENUES.has(e)||N(t,e)))return i.has(e)?j.find(e=>!i.has(e))??e:e;let n=w.filter(e=>N(t,e)),a=n.find(e=>!i.has(e));return a||(n.length>0?n[0]:j.find(e=>!i.has(e))??S)}],555641);var P=e.i(984457);let T="margin-mode-picker-heading";e.s(["MARGIN_PICKER_HEADING_ID",0,T,"MarginModePicker",0,function({current:e,crossUnavailableReason:i,accountName:s,pending:n,onSelect:a}){let l=(0,r.useTranslations)("trading"),o=(0,r.useTranslations)("terms"),d=null!==i&&"unified"!==e,c=[{mode:"isolated",title:o("marginModeIsolated"),disabled:!1,reason:null},{mode:"unified",title:o("marginModeCross"),disabled:d,reason:d?i:null}];return(0,t.jsxs)("div",{className:"grid gap-[10px]",children:[(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,t.jsx)("h6",{id:T,className:"text-3xs font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:l("marginModeHeading")}),s&&(0,t.jsx)("span",{className:"truncate text-3xs font-semibold text-secondary-foreground",children:s})]}),(0,t.jsx)("div",{role:"group","aria-label":l("marginModeHeading"),"aria-busy":n||void 0,className:"grid gap-[8px]",children:c.map(r=>{let i=e===r.mode;return(0,t.jsxs)("button",{type:"button","aria-pressed":i,"aria-disabled":r.disabled||n||void 0,onClick:()=>{r.disabled||n||a(r.mode)},className:`grid grid-cols-[18px_1fr] gap-[10px] rounded-[10px] border px-[12px] py-[10px] text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${r.disabled?"cursor-not-allowed border-border bg-surface opacity-55":i?"border-primary bg-surface shadow-[inset_0_0_0_1px_var(--color-primary)]":"border-border bg-surface hover:border-border-strong"}`,children:[(0,t.jsx)("span",{"aria-hidden":!0,className:`relative mt-[2px] h-[16px] w-[16px] rounded-full border-[1.5px] ${i?"border-primary":"border-border-strong"}`,children:i&&(0,t.jsx)("span",{className:"absolute inset-[3px] rounded-full bg-primary"})}),(0,t.jsxs)("span",{className:"min-w-0",children:[(0,t.jsx)("span",{className:"block text-[13px] font-semibold text-foreground",children:r.title}),r.reason&&(0,t.jsx)("span",{className:"mt-[6px] block text-2xs font-medium leading-[1.45] text-imperial-gold",children:r.reason})]})]},r.mode)})}),n&&(0,t.jsxs)("div",{role:"status",className:"flex items-center justify-center gap-2 text-[13px] text-secondary-foreground",children:[(0,t.jsx)(P.Spinner,{className:"size-3.5"}),l("marginModeConfirmInWallet")]})]})}],260431);var C=e.i(183023),M=e.i(807956),_=e.i(619966),A=e.i(264530);let E=(0,M.default)(()=>e.A(22944).then(e=>({default:e.HotkeyHelpDialog})),{loadableGenerated:{modules:[858912]},ssr:!1}),L="imperial_hotkeys_enabled",F=(0,C.createContext)(null);e.s(["HotkeyProvider",0,function({children:e}){let r=(0,C.useRef)(new Map),[i,s]=(0,C.useState)(!0),[n,a]=(0,C.useState)(!1),[l,o]=(0,C.useState)(!1),d=(0,_.useIsDesktop)();(0,C.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&("false"===localStorage.getItem(L)&&s(!1),a(!0))}),()=>{e=!1}},[]);let c=(0,C.useCallback)(e=>{s(e),localStorage.setItem(L,String(e))},[]),u=(0,C.useRef)({hotkeysEnabled:i,isDesktop:d,helpOpen:l});(0,C.useLayoutEffect)(()=>{u.current={hotkeysEnabled:i,isDesktop:d,helpOpen:l}},[i,d,l]),(0,C.useEffect)(()=>{let e=e=>{var t;let{hotkeysEnabled:i,isDesktop:s,helpOpen:n}=u.current;if(!i||!0!==s)return;let a=A.HOTKEY_BINDINGS.find(t=>t.match(e));if(!a||e.repeat&&!a.allowRepeat||(t=e.target)instanceof HTMLElement&&("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable)&&!a.allowInInput)return;
2let l=!!document.querySelector('[data-workspace-resize-controls], [data-slot="dialog-content"][data-state="open"], [data-slot="sheet-content"][data-state="open"], [data-slot="popover-content"][data-state="open"], [data-slot="dropdown-menu-content"][data-state="open"]');if("toggle-help"===a.id){if(l&&!n)return;e.preventDefault(),o(e=>!e);return}if(l)return;let d=r.current.get(a.id);d&&(e.preventDefault(),d())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]);let h=(0,C.useCallback)((e,t)=>(r.current.set(e,t),()=>{r.current.get(e)===t&&r.current.delete(e)}),[]),p=(0,C.useCallback)(()=>o(!0),[]);return(0,t.jsxs)(F.Provider,{value:{register:h,hotkeysEnabled:i,setHotkeysEnabled:c,isLoaded:n,openHelp:p},children:[e,(0,t.jsx)(E,{open:l,onOpenChange:o})]})},"useHotkey",0,function(e,t,r=!0){let i=(0,C.useContext)(F),s=(0,C.useRef)(t);(0,C.useLayoutEffect)(()=>{s.current=t},[t]);let n=i?.register;(0,C.useEffect)(()=>{if(n&&r)return n(e,()=>s.current())},[n,e,r])},"useHotkeys",0,function(){let e=(0,C.useContext)(F);if(!e)throw Error("useHotkeys must be used within HotkeyProvider");return e}],111468);var R=e.i(43690),D=e.i(514049),I=e.i(190459);async function U(e,t,r,i,s){let n=new URLSearchParams({asset:t.toUpperCase(),requestedHedgeVenue:String((0,I.venueWireBytes)(e).hedgeVenue),depth:String(r)});void 0!==s&&n.set("priceStep",String(s));try{let e=AbortSignal.timeout(1e4),t=["https://api.imperial.space"],[r,s]=await Promise.all(t.map(async t=>{let r=await fetch(`${t}/api/v1/armada/orderbook?${n}`,{signal:i?AbortSignal.any([i,e]):e});if(!r.ok)return null;let s=await r.json();return s.hedgeVenue=(0,I.venueFromWireName)(s.hedgeVenue)??s.hedgeVenue,s}));if(!r||1===t.length)return r;if(!s||s.market!==r.market||s.hedgeVenue!==r.hedgeVenue)return null;return{...s,depthMarkPrice:s.stats.markPrice,stats:r.stats}}catch{return null}}e.s(["fetchSunriseOrderbook",0,U],495433);var O=e.i(710729);function B(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function z(){return"visible"===document.visibilityState}function $(e,t,r,i,s){let n=(0,D.useQueryClient)(),a="armada"===t,l=a&&!!e&&i,{data:o,isPending:d,dataUpdatedAt:c}=(0,R.useQuery)({queryKey:["sunrise-orderbook",e,r??null],queryFn:t=>U("armada",e,30,s?t.signal:void 0,r),enabled:l,staleTime:1e3,refetchInterval:1500,refetchOnWindowFocus:!0});return((0,C.useEffect)(()=>{if(!s)return;let t=n.getQueryCache(),i=["sunrise-orderbook",e,r??null],a=t.find({queryKey:i,exact:!0});if(!a)return;let l=()=>{if("idle"===a.state.fetchStatus||a.isActive())return;let e=a.promise;queueMicrotask(()=>{t.find({queryKey:i,exact:!0})!==a||a.promise!==e||"idle"===a.state.fetchStatus||a.isActive()||a.cancel({revert:!0})})},o=t.subscribe(e=>{e.query===a&&("observerRemoved"===e.type||"observerOptionsUpdated"===e.type)&&l()});return l(),()=>{o(),l()}},[n,l,r,s,e]),a)?{book:o??null,isPending:d,receivedAtMs:c}:{book:null,isPending:!1,receivedAtMs:0}}e.s(["useDisplayedSunriseOrderbook",0,function(e,t,r,i=!0){let s=(0,O.useDesktopWorkspacePanelVisible)(),n=(0,C.useSyncExternalStore)(B,z,()=>!1);return $(e,t,r,i&&s&&n,!0)},"useSunriseOrderbook",0,function(e,t,r){return $(e,t,r,!0,!1)}],744427),e.s(["quoteSunriseMarketOrder",0,function(e,t,r,i,s,n=Date.now()){let a=e?.stats.markPrice;if(!e?.venueReachable||"armada"!==e.hedgeVenue||null!=e.depthMarkPrice||!a||!Number.isFinite(a)||a<=0||!Number.isFinite(t)||t<=0||!Number.isInteger(i)||i<1||i>1e4||!Number.isFinite(s)||s<=0||n<s||n-s>5e3)return null;let l=[...r?e.asks:e.bids];if(l.some(({price:e,size:t})=>!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<0))return null;l.sort((e,t)=>r?e.price-t.price:t.price-e.price);let o=t/a;if(!Number.isFinite(o)||o<=0)return null;let d=o,c=0;for(let e of l){let t=Math.min(d,e.size);if(c+=t*e.price,(d-=t)<=1e-12*o)break}if(d>1e-12*o||!Number.isFinite(c)||c<=0)return null;let u=c/o;return{fillPrice:u,fillVsMarkBps:(u/a-1)*1e4,slippageBps:i}}],727104);let V=(0,e.i(504458).default)("chart-candlestick",[["path",{d:"M9 5v4",key:"14uxtq"}],["rect",{width:"4",height:"6",x:"7",y:"9",rx:"1",key:"f4fvz0"}],["path",{d:"M9 15v2",key:"r5rk32"}],["path",{d:"M17 3v2",key:"1l2re6"}],["rect",{width:"4",height:"8",x:"15",y:"5",rx:"1",key:"z38je5"}],["path",{d:"M17 13v3",key:"5l0wba"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);e.s(["default",0,V],227824),e.s(["CandlestickChart",0,V],47935)},980333,986759,441399,442150,443048,169443,120911,326729,854553,687821,852070,317629,702021,993467,736679,24893,800239,e=>{"use strict";let t;e.s(["PassthroughOrderRow",()=>rO,"SortablePassthroughOrderRow",()=>rB],24893),e.s(["TpSlHoverPopover",()=>ea,"getRatchetDisplayPrice",()=>en],443048),e.s(["ActionRow",()=>U],980333),e.s(["EditOrderDialog",()=>rp],852070),e.s(["OrderDetailSheet",()=>rx],317629);var r,i,s,n,a,l,o,d,c,u,h,p,m,f,x,g,b,v,y,w=e.i(394390),j=e.i(756880),S=e.i(942553),k=e.i(268680),N=e.i(637226),P=e.i(259048),T=e.i(594651),C=e.i(670374),M=e.i(26826),_=e.i(845165);let A="https://orbmarkets.io/tx/",E=[{key:"tx1Signature",labelKey:"txStageRequest",num:1},{key:"tx2Signature",labelKey:"txStageAction",num:2},{key:"tx3Signature",labelKey:"txStageSweep",num:3}];function L({tx1Signature:e,tx2Signature:t,tx3Signature:r}){let i=(0,S.useTranslations)("positions"),s={tx1Signature:e,tx2Signature:t,tx3Signature:r},n=E.filter(({key:e})=>s[e]);return 0===n.length?null:1===n.length?(0,w.jsx)("a",{href:`${A}${t||e}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),children:(0,w.jsx)(_.ExternalLink,{className:"w-3.5 h-3.5"})}):(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("a",{href:`${A}${t||e}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),children:(0,w.jsx)(_.ExternalLink,{className:"w-3.5 h-3.5"})})}),(0,w.jsx)(k.TooltipContent,{side:"top",showArrow:!1,className:"font-mono text-xs",children:(0,w.jsxs)("div",{className:"space-y-1",children:[(0,w.jsx)("div",{className:"font-semibold mb-2",children:i("transactionsLabel")}),n.map(({key:e,labelKey:t,num:r})=>(0,w.jsxs)("a",{href:`${A}${s[e]}`,target:"_blank",rel:"noopener noreferrer",className:"flex justify-between gap-4 text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),children:[(0,w.jsxs)("span",{className:"text-muted-foreground",children:[r,". ",i(t),":"]}),(0,w.jsx)(_.ExternalLink,{className:"w-3 h-3"})]},e))]})})]})})}e.s(["EXPLORER_BASE",0,A,"TxLinks",0,L],986759);var F=e.i(299959);function R(e){if(null==e||""===e.trim())return null;let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function D(e,t){return null===e?"—":new Date(1e3*e).toLocaleStr
2ing(t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function I(e){return null===e?"—":e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}function U({action:e,asset:t,side:r,dcaGroupLabel:i,indented:s,underwriter:n}){var a;let l,o,d,c,u,h,p,m,f=(0,S.useTranslations)("positions"),x=(0,F.useFormatters)(),g="increase"===e.actionType||"add_collateral"===e.actionType||"open"===e.actionType,b=null!=e.sizeDelta&&0===(0,M.parseRawValue)(e.sizeDelta),v=(0,M.depositedCapitalForLeg)(e),y=g?(0,M.parseRawValue)(e.platformFee)-(0,M.parseRawValue)(e.proOrderFee):(0,M.parseRawValue)(e.tx3SwapFee),_=g?0:(0,M.parseRawValue)(e.tx3PlatformFee)-(0,M.parseRawValue)(e.tx3SwapFee)-(0,M.parseRawValue)(e.proOrderFee),A=g?(0,M.parseRawValue)(e.swapSlippage):(0,M.parseRawValue)(e.tx3SweepSlippage),E=(0,M.parseRawValue)(e.jupiterFee),O=(0,M.parseRawValue)(e.interest),B=(0,M.parseRawValue)(e.proOrderFee),z=y+_+A+E+O+B,$=`$${z.toLocaleString(x.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`,V="liquidation"===e.actionType||!!e.forcedCloseReason,H=V&&(null!==e.positionSizeAfter?(0,M.parseRawValue)(e.positionSizeAfter)>0:(0,M.parseRawValue)(e.collateralAfter)>0),W=V?(0,M.legRealizedPnl)(e):null,q=null!==e.orderType&&C.DCA_ORDER_TYPES.has(e.orderType),K=V?f(H?"partialLiquidation":"liquidation"):q&&i?i:f(function(e){switch(e){case"market":default:return"orderTypeMarket";case"limit":return"orderTypeLimit";case"stop_limit":return"orderTypeStop";case"landmine":return"orderTypeLandmine";case"ratchet":return"trailingSl";case"ratchet_entry":return"orderTypeTrailing";case"fib_ratchet":return"orderTypeFibTrailingSl";case"fib_ratchet_entry":return"orderTypeFibTrailing";case"indicator":return"orderTypeRsi";case"indicator_ratchet":return"rsiTrailing";case"dca":return"orderTypeDca";case"dca_close":return"orderTypeDcaClose";case"dca_time_close":return"orderTypeDcaTimeClose";case"dca_ratchet_close":return"orderTypeDcaTrailingClose";case"dca_time":return"orderTypeDcaTime";case"dca_ratchet":return"orderTypeDcaTrailing"}}(e.orderType)),G=("limit"===(a=e.orderType)||"stop_limit"===a||"landmine"===a||"ratchet"===a||"ratchet_entry"===a||"fib_ratchet"===a||"fib_ratchet_entry"===a||"indicator"===a||"indicator_ratchet"===a)&&(e.triggerPrice||e.orderWorstPrice||e.orderThresholdValue),Y=function(e){if("open"===e.actionType)return"receiptOpened";if("add_collateral"===e.actionType)return"receiptCollateralAdded";if("remove_collateral"===e.actionType)return"receiptCollateralRemoved";let t=R(e.sizeDelta),r=R(e.positionSizeAfter);return"increase"===e.actionType?0===t?"receiptCollateralAdded":null!==t&&t>0&&r===t?"receiptOpened":"receiptIncreased":"close"===e.actionType?"receiptClosed":"decrease"===e.actionType?0===t?"receiptCollateralRemoved":0===r?"receiptClosed":"receiptReduced":null}(e),X=g?"+":["decrease","close","liquidation"].includes(e.actionType)?"−":"";return(0,w.jsxs)("tr",{className:`border-b border-border/50${s?" border-l-2 border-l-cyan-500/20 bg-surface/50":""}`,children:[(0,w.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:x.dateTime(e.tx1Timestamp)}),(0,w.jsxs)("td",{className:"px-3 py-2",children:[!V&&(0,w.jsx)("div",{className:"text-xs text-foreground",children:Y?f(Y):"—"}),(0,w.jsx)("div",{className:V?void 0:"[&_span]:text-[10px]",children:G?(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{className:"cursor-help",children:(0,w.jsx)("span",{className:"text-xs text-secondary-foreground underline decoration-dotted underline-offset-2",children:K})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,w.jsxs)("div",{className:"space-y-1",children:[(l="ratchet"===e.orderType||"ratchet_entry"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType?e.entryPrice??e.orderExecutionTriggerPrice??e.triggerPrice:e.orderExecutionTriggerPrice??e.triggerPrice)&&0!==parseFloat(l)?(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("execPriceLabel")}),(0,w.jsx)("span",{children:x.rawPrice(l)})]}):null,"landmine"===e.orderType&&(0,w.jsxs)(w.Fragment,{children:[e.orderWaitPrice&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("waitPrice
2Label")}),(0,w.jsxs)("span",{children:["below"===e.triggerCondition?"≥":"≤"," ",x.rawPrice(e.orderWaitPrice)]})]}),null!==e.orderWaitDurationSecs&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("waitDurationLabel")}),(0,w.jsx)("span",{children:I(e.orderWaitDurationSecs)})]})]}),("ratchet"===e.orderType||"ratchet_entry"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType)&&(0,w.jsxs)(w.Fragment,{children:[e.orderWorstPrice&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("long"===r?"minPriceLabel":"maxPriceLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.orderWorstPrice)})]}),e.orderRatchetSize&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("baseTrailLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.orderRatchetSize)})]})]}),("indicator"===e.orderType||"indicator_ratchet"===e.orderType)&&(0,w.jsxs)(w.Fragment,{children:[e.orderThresholdValue&&(o=e.orderIndicatorConfig?Number(e.orderIndicatorConfig)>>24&255:0,(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("rsiThresholdLabel")}),(0,w.jsxs)("span",{children:[0===o?"< ":"> ",e.orderThresholdValue]})]})),e.orderWorstPrice&&parseFloat(e.orderWorstPrice)>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("long"===r?"minPriceLabel":"maxPriceLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.orderWorstPrice)})]}),e.orderRatchetSize&&parseFloat(e.orderRatchetSize)>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("rsiTrailingLabel")}),(0,w.jsx)("span",{children:e.orderRatchetSize})]})]}),null!==e.orderCreatedAt&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("createdLabel")}),(0,w.jsx)("span",{children:D(e.orderCreatedAt,x.intlTag)})]})]})})]})}):q?(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{className:"cursor-help",children:(0,w.jsx)("span",{className:"text-xs text-secondary-foreground underline decoration-dotted underline-offset-2",children:K})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,w.jsxs)("div",{className:"space-y-1",children:[null!==e.orderDcaLegNumber&&null!==e.orderDcaNumLegs&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("legLabel")}),(0,w.jsxs)("span",{children:[e.orderDcaLegNumber,"/",e.orderDcaNumLegs]})]}),e.orderSizeUsd&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("totalSizeLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.orderSizeUsd)})]}),e.orderDcaStartPrice&&e.orderDcaEndPrice&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("rangeLabel")}),(0,w.jsxs)("span",{children:[x.rawPrice(e.orderDcaStartPrice)," → ",x.rawPrice(e.orderDcaEndPrice)]})]}),("dca_time_close"===e.orderType||"dca_ratchet_close"===e.orderType)&&(e.orderDcaPriceLimit||e.triggerPrice)&&(d=e.orderDcaPriceLimit??e.triggerPrice,c="dca_time_close"===e.orderType&&!(parseFloat(d)>0),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("priceLimitLabel")}),(0,w.jsx)("span",{children:c?"-":`${"below"===e.triggerCondition?"≤":"≥"} ${x.rawPrice(d)}`})]})),"dca_time_close"===e.orderType&&!!e.orderDcaIntervalSeconds&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("intervalLabel")}),(0,w.jsx)("span",{children:I(e.orderDcaIntervalSeconds)})]}),"dca_ratchet_close"===e.orderType&&e.orderRatchetSize&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("trailLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.orderRatchetSize)})]}),(e.orderDcaLegTrigger||e.triggerPrice)&&"dca_time_close"!==e.orderType&&"dca_ratchet_close"!==e.orderType&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("triggerLabel")}),(0,w.jsxs)("span",{children:["below"===e.triggerCondition?"≤":"≥"," ",e.orderDcaLegTrigger?x.rawPrice(e.orderDcaLegTrigger):x.rawPrice(e.triggerPrice)]})]}),null!==e.orderCreatedAt&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("createdLabel")}),(0,w.jsx)("span",{children:D(e.orderCreatedAt,x.intlTag)})]})]})})]})}):V?(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{className:"cursor-help",children:(0,w.jsx)("span",{className:"text-xs text-destructive underline decoration-dotted underline-offset-2",children:K})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,w.jsxs)("div",{className:"space-y-1 max-w-[16rem]",children:[(0,w.jsx)("div",{className:"font-semibold mb-1 text-destructive",children:f(H?"partialLiquidation":"fullLiquidation")}),(0,w.jsx)("div",{className:"text-muted-foreground whitespace-normal mb-1",children:f(H?"partialLiquidationExplainer":"fullLiquidationExplainer")}),(0,M.parseRawValue)(e.entryPrice)>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("execPriceLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.entryPrice)})]}),(0,M.parseRawValue)(e.sizeDelta)>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("sizeCutLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.sizeDelta)})]}),null!==W&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("realizedLossLabel")}),(0,w.jsxs)("span",{className:(0,P.pnlColor)(W),children:[W>
2=0?"+":"-","$",Math.abs(W).toLocaleString(x.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),H&&e.collateralAfter&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border pt-1 mt-1",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("collateralLeftLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.collateralAfter)})]}),H&&e.postLiquidationPriceUsd&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("newLiqPriceLabel")}),(0,w.jsx)("span",{children:x.rawPrice(e.postLiquidationPriceUsd)})]})]})})]})}):(0,w.jsx)("span",{className:"text-xs text-secondary-foreground",children:K})})]}),(0,w.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:(u=e.orderDcaLegTrigger??e.triggerPrice)&&0!==parseFloat(u)?x.rawPrice(u):"—"}),(0,w.jsx)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:b?"-":x.rawPrice(e.entryPrice)}),(0,w.jsx)("td",{className:"px-3 py-2",children:(0,w.jsxs)("div",{className:"flex flex-col",children:[(0,w.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums",children:null==e.sizeDelta?"—":`${(0,M.parseRawValue)(e.sizeDelta)>0?X:""}${x.rawUsd(e.sizeDelta)}`}),e.sizeDeltaTokens&&(0,w.jsxs)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:[e.sizeDeltaTokens," ",t]})]})}),(0,w.jsx)("td",{className:"px-3 py-2",children:(0,w.jsxs)("div",{className:"flex flex-col",children:[g?(0,w.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:v>0?f("receiptCapitalAdded",{amount:`+${x.rawUsd(v.toFixed(6))}`}):"—"}):(0,w.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:null!=e.userReceived?f("receiptCapitalReturned",{amount:x.rawUsd(e.userReceived)}):"—"}),e.collateralAfter&&(0,w.jsx)("span",{className:"text-xs text-label-muted font-mono tabular-nums",children:f("receiptCollateralRemaining",{amount:x.rawUsd(e.collateralAfter)})})]})}),(0,w.jsx)("td",{className:"px-3 py-2",children:(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{className:"cursor-help",children:(0,w.jsx)("span",{className:"text-xs text-amber-400 underline decoration-dotted underline-offset-2",children:$})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,w.jsxs)("div",{className:"space-y-1",children:[(0,w.jsx)("div",{className:"font-semibold mb-2",children:f("feeBreakdownLabel")}),B>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("proOrderFeesLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.proOrderFee)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("platformFeeLabel")}),(0,w.jsxs)("span",{children:["$",y.toLocaleString(x.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("slippageLabel")}),(0,w.jsxs)("span",{className:A<0?"text-green-400":void 0,children:[A<0?"-":"","$",Math.abs(A).toLocaleString(x.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("interestLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.interest)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("openCloseLabel")}),(0,w.jsx)("span",{children:null!=e.pairsImpactFee?x.usdNumber((0,C.openCloseFeeExImpact)(e.jupiterFee,e.pairsImpactFee)):x.rawUsd(e.jupiterFee)})]}),null!=e.pairsImpactFee&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:f("skewImpactLabel")}),(0,w.jsx)("span",{children:x.rawUsd(e.pairsImpactFee)})]})]})})]})})}),(0,w.jsx)("td",{className:"px-3 py-2",children:(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)(L,{tx1Signature:e.tx1Signature,tx2Signature:e.tx2Signature,tx3Signature:e.tx3Signature}),(h=(0,M.parseRawValue)(e.entryPrice),p=e.tx2Timestamp??e.tx1Timestamp,m=(0,T.assetToMint)(t,n),b||h<=0||!p||!m?null:(0,w.jsx)("button",{title:f("showFillOnChart"),className:"text-blue-400 hover:text-blue-300",onClick:e=>
2{e.stopPropagation(),(0,N.showFillOnChart)({marketMint:m,symbol:t,venue:n,timestampSec:p,price:h,locale:x.intlTag})},children:(0,w.jsx)(j.ChartCandlestick,{className:"w-3.5 h-3.5"})}))]})})]})}var O=e.i(183023),B=e.i(116082),z=e.i(409686),$=e.i(943494),V=e.i(888245),H=e.i(153517),W=e.i(626074),q=e.i(1169),K=e.i(328188),G=e.i(323116),Y=e.i(134138);let X=new Set(["phoenix","sunrise"]);function Q(e,t){return`${e}:${t.toLowerCase().replace(/#\d+$/,"")}`}function J(e,t,r,i){if(!t)return i;let s=r?e?.[Q(t,r)]:void 0;return void 0!==s?s:X.has(t)?void 0:i}e.s(["venueLivePrice",0,J,"venueLivePriceKey",0,Q],441399);var Z=e.i(451720);function ee(){let[e,t]=(0,O.useState)(()=>Math.floor(Date.now()/1e3));return(0,O.useEffect)(()=>{let e=setInterval(()=>t(Math.floor(Date.now()/1e3)),1e3);return()=>clearInterval(e)},[]),e}function et({lastLegTimestamp:e,intervalSeconds:t,className:r,now:i}){let s=(0,S.useTranslations)("positions"),n=ee();if(0===e)return(0,w.jsx)("span",{className:(0,H.cn)("text-emerald-400",r),children:s("dcaReady")});let a=e+t-(i??n);if(a<=0)return(0,w.jsx)("span",{className:(0,H.cn)("text-emerald-400",r),children:s("dcaReady")});let l=Math.floor(a/3600),o=Math.floor(a%3600/60),d=a%60,c=l>0?`${l}h ${o.toString().padStart(2,"0")}m`:o>0?`${o}m ${d.toString().padStart(2,"0")}s`:`${d}s`;return(0,w.jsx)("span",{className:(0,H.cn)("text-amber-400 font-mono tabular-nums",r),children:c})}function er({legsExecuted:e,lastLegTimestamp:t,intervalSeconds:r,startAt:i,className:s,stackedLabel:n=!1}){let a=(0,S.useTranslations)("positions"),l=ee(),o=0===e&&i>l,d=(0,Z.dcaCountdownAnchor)(e,t,r,i,l),c=(0,w.jsx)(et,{lastLegTimestamp:d,intervalSeconds:r,className:s,now:l});return n?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)("div",{className:"text-[10px] text-label-muted",children:a(o?"dcaStartsIn":"dcaNextLeg")}),c]}):c}function ei({legsExecuted:e,lastLegTimestamp:t,intervalSeconds:r,startAt:i}){let s=(0,S.useTranslations)("positions"),n=ee(),a=0===e&&i>n,l=(0,Z.dcaCountdownAnchor)(e,t,r,i,n);return(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:s(a?"startsInLabel":"nextLegLabel")}),(0,w.jsx)(et,{lastLegTimestamp:l,intervalSeconds:r,now:n})]})}e.s(["DcaTimeCountdown",0,et,"DcaTimeLegCountdown",0,er,"useDcaNow",0,ee],442150);let es={tpsl:["tp","sl","private_tp","private_sl"],trailing:["ratchet","fib_ratchet","fib_ratchet_entry"],dca:["dca_close","dca_time_close","dca_ratchet_close"],rsi:["indicator","indicator_ratchet"]};function en(e,t,r,i){let s,n,a=parseFloat(e.worstPriceUsd||"0"),l=parseFloat(e.ratchetSizeUsd||"0"),o=parseFloat(e.currentBestPriceUsd||"0"),d=i&&i>0?i:o;d<=0&&void 0!==t&&t>0&&(d=t),void 0!==t&&d>0&&(r&&t>d?d=t:!r&&t<d&&(d=t));let c="fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType;if(c){let t=Math.abs(l-a),r=(l<a?d<=a:d>=a)?Math.abs(d-a):0;s=t>0&&r*G.FIB_RATIO_SCALE/t>=(0,G.fibFirstThreshold)(e.isReverseFib??!1)}else s=r?d>=a+l:d<=a-l;let u="ratchet"===e.orderType?parseFloat(e.stopTriggerPriceUsd||"0"):0,h=(0,Y.isRatchetStopTripped)(u,o,r);if(!s)return{price:a,isLiveUpdating:!1,bestKnown:d,isTracking:s,stopTrigger:u,isStopTripped:h};let p=l;if(c&&l>0){let t=Math.abs(l-a);if(t>0){let r=Math.abs(d-a)*G.FIB_RATIO_SCALE/t;n=(0,G.fibLevel)(r,e.isReverseFib??!1);let i=e.isReverseFib?5-n:n;p=t*G.FIB_RATIOS[i]/G.FIB_RATIO_SCALE}}return{price:r?Math.max(d-p,a):Math.min(d+p,a),isLiveUpdating:void 0!==t&&d===t,bestKnown:d,isTracking:s,stopTrigger:u,isStopTripped:h,fibLevel:n,effectiveSize:void 0!==n?p:void 0}}function ea({readOnly:e=!1,lifecycle:t,onOpenPopover:r,onOpenTpSlTab:i,onCancelPassthroughOrder:s,onCancelJupiterOrder:n,onEditOrder:a,livePrices:l,waitingForOrder:o,filterCategory:d,suppressTooltips:c=!1,desktopLayout:u=!1}){let h=(0,S.useTranslations)("positions"),p=(0,F.useFormatters)(),[m,f]=(0,O.useState)(null),x=(0,O.useRef)(!1),g=(0,O.useRef)(new Map),b=t.tpslOrders||[],v=(0,O.useMemo)(()=>{if(!d)return b;let e=es[d];return b.filter(t=>e.includes(t.orderType))},[b,d]),y=u&&"tpsl"===d,j=y?[v.find(e=>"tp"===e.orderType||"private_tp"===e.orderType),v.find(e=>"sl"===e.orderType||"private_sl"===e.orderType)].filter(e=>!!e):v,N=v.length-j.length,T="long"===t.side,_=(0,C.getMarketMintFromAsset)(t.asset,t.underwriter),A=J(l,t.underwriter,t.asset,_?l?.[_]:void 0);(0,M.parseRawValue)(t.entryPrice);let E=parseFloat(t.sizeUsd||"0"),L=(0,M.feesPaidForRemainingSize)(t),R=async t=>{if(!e&&t.orderPda&&!x.current){x.current=!0,f(t.orderPda);try{"jupiter_native"===t.source?await n(t.orderPda):void 0!==t.profileIndex&&await s(t.orderPda,t.profileIndex)}finally{x.current=!1,f(null)}}},D="tpsl"===d?"TP/SL":"dca"===d?"DCA":"trailing"===d?h("columnTrailing"):"rsi"===d?h("columnIndicator"):null,I=v.length>0||!D?h("manageOrdersAction"):D,U=D?`${h("manageOrdersAction")} ${D}`:h("manageOrdersAction");return(0,w.jsxs)("div",{"data-compact-protection":y||void 0,"data-active-orders":v.length,className:(0,H.cn)("flex flex-col items-center text-xs",u&&V.default.automation),children:[(0,w.jsx)(k.TooltipProvider,{children:j.map((r,i)=>{let s,n,l,o,d,u,f,x,b,v="ratchet"===r.orderType,j="fib_ratchet"===r.orderType||"fib_ratchet_entry"===r.orderType,S=v||j,N="indicator"===r.orderType||"indicator_ratchet"===r.orderType,C="dca_close"===r.orderType||"dca_time_close"===r.orderType||"dca_ratchet_close"===r.orderType,_="tp"===r.orderType||"private_tp"===r.orderType,F="private_tp"===r.orderType||"private_sl"===r.orderType,D=parseFloat(r.sizeUsd||"0"),I="number"==typeof r.closeBps&&r.closeBps>0,U=(0,K.closeFractionOf)(r,E),O=Math.round(100*U),z=I&&E>0?E*U:D,V=!1,W=!1,q=0,Y=0,X=!1;if(S){let e=r.orderPda||`idx-${i}`,t=en(r,A,T,g.current.get(e));g.current.set(e,t.bestKnown),s=t.price,V=t.isLiveUpdating,W=t.isTracking,q=t.bestKnown,Y=t.stopTrigger,X=t.isStopTripped,n=t.fibLevel,l=t.effectiveSize}else s=N?0:parseFloat(r.triggerPriceUsd||"0");let Q="jupiter_native"===r.source,J=N||C?null:(0,M.estimateOrderPnl)(t,{execPrice:s,closeFraction:U,isJupNative:Q});J?.breakdown;let Z=J?.netPnl??null,ee=J?.legPnl??null,et=J?.divergent??!1,er=(0,M.parseRawValue)(t.borrowFeeOwed)*U,es=(0,M.parseRawValue)(t.closeFeeOwed)*U,ea=(0,M.parseRawValue)(t.swapFeeOwed)*U,el=L*U,eo=er+es+ea+el,ed=N?"text-amber-400":j?"text-fuchsia-400":v?"text-blue-400":C?"text-cyan-400":F?"text-purple-400":_?"text-side-long":"text-side-short",ec=N?"indicator_ratchet"===r.orderType?h("rsiTrailing"):"RSI":j?r.isReverseFib?h("orderTypeFibTrailingSlReverse"):h("orderTypeFibTrailingSl"):v?h("trailingSl"):"dca_close"===r.orderType?h("orderTypeDcaClose"):"dca_time_close"===r.orderType?h("orderTypeDcaTimeClose"):"dca_ratchet_close"===r.orderType?h("orderTypeDcaTrailingClose"):F?_?h("orderTypePrivateTp"):h("orderTypePrivateSl"):_?h("takeProfit"):h("stopLoss");r.source;let eu=r.orderPda||`order-${i}`,eh=(0,w.jsx)("button",{onClick:()=>{e||(N||C?B.toast.info(h("orderTypeNotEditable",{type:ec})):a?.(r))},"aria-disabled":e,title:e?h("reviewTradingDisabled"):void 0,className:(0,H.cn)("font-mono tabular-nums cursor-pointer hover:font-bold transition-all",ed,V&&"animate-pulse"),children:m===r.orderPda?(0,w.jsx)($.Loader2,{className:"w-3 h-3 animate-spin"}
2):N||C?ec:(0,w.jsxs)(w.Fragment,{children:[y&&(0,w.jsx)("span",{className:"mr-1 text-[9px]",children:_?"TP":"SL"}),"$",p.number(s)]})},eu);return c?eh:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:eh}),(0,w.jsx)(k.TooltipContent,{side:"left",children:(0,w.jsxs)("div",{className:"space-y-1 text-xs",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("typeLabel")}),(0,w.jsx)("span",{className:ed,children:ec})]}),N&&(0,w.jsxs)(w.Fragment,{children:[r.indicatorThreshold&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("rsiTargetLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["below"===r.indicatorCondition?"< ":"> ",r.indicatorThreshold]})]}),r.indicatorTimeframe&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("timeframeLabel")}),(0,w.jsx)("span",{children:r.indicatorTimeframe})]}),void 0!==r.currentIndicatorValue&&null!==r.currentIndicatorValue&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("currentRsiLabel")}),(0,w.jsx)("span",{className:"text-amber-400 font-mono tabular-nums",children:p.fixed(r.currentIndicatorValue,1)})]}),r.indicatorRatchetSize&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("rsiTrailingLabel")}),(0,w.jsx)("span",{className:"font-mono tabular-nums",children:r.indicatorRatchetSize})]}),r.worstPriceUsd&&parseFloat(r.worstPriceUsd)>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:T?h("minPriceLabel"):h("maxPriceLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(parseFloat(r.worstPriceUsd))]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("sizeColonLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(z)," (",O,"%)"]})]})]}),S&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("statusLabel")}),(0,w.jsx)("span",{className:W?"text-cyan-400":X?"text-emerald-400":"text-amber-400",children:W?h("statusTracking"):X?h("statusStopSet"):h("statusWaiting")})]}),W&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("bestPriceLabel")}),(0,w.jsxs)("span",{className:(0,H.cn)("font-mono tabular-nums",V&&"text-cyan-400"),children:["$",p.number(q)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:W?h("executionPriceLabel"):h("worstPriceLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(s)]})]}),Y>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("stopTriggerLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(Y)," ",(0,w.jsxs)("span",{className:X?"text-emerald-400":"text-amber-400",children:["(",X?h("stopTriggerTripped"):h("stopTriggerNotTripped"),")"]})]})]}),!W&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("dragPriceLabel")}),(0,w.jsxs)("span",{className:"text-blue-400 font-mono tabular-nums",children:["$",p.number((()=>{let e=parseFloat(r.worstPriceUsd||"0"),t=parseFloat(r.ratchetSizeUsd||"0");if(j){let i=Math.abs(t-e),s=(0,G.fibFirstThreshold)(r.isReverseFib??!1)*i/G.FIB_RATIO_SCALE;return T?e+s:e-s}return T?e+t:e-t})())]})]}),r.ratchetSizeUsd&&j&&W&&void 0!==n&&void 0!==l?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("fibLevelLabel")}),(0,w.jsxs)("span",{className:"text-fuchsia-400 font-mono tabular-nums",children:[n," (",p.percent(G.FIB_RATIOS[r.isReverseFib?5-n:n]/G.FIB_RATIO_SCALE*100,1),")"]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("trailingSizeLabel")}),(0,w.jsxs)("span",{className:"text-fuchsia-400 font-mono tabular-nums",children:["$",p.number(l)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("targetPriceLabel")}),(0,w.jsxs)("span",{className:"text-label-muted font-mono tabular-nums",children:["$",p.number(parseFloat(r.ratchetSizeUsd))]})]})]}):r.ratchetSizeUsd?(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("trailSizeLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(parseFloat(r.ratchetSizeUsd))]})]}):null,(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("sizeColonLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(z)," (",O,"%)"]})]})]}),C&&(0,w.jsxs)(w.Fragment,{children:[r.dcaNumLegs&&void 0!==r.dcaLegsExecuted&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("progressLabel")}),(0,w.jsx)("span",{children:h("dcaLegsProgress",{executed:r.dcaLegsExecuted,total:r.dcaNumLegs})})]}),"dca_close"===r.orderType&&r.dcaStartPriceUsd&&r.dcaEndPriceUsd&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("rangeLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(parseFloat(r.dcaStartPriceUsd))," → $",p.number(parseFloat(r.dcaEndPriceUsd))]})]}),("dca_time_close"===r.orderType||"dca_ratchet_close"===r.orderType)&&(o=parseFloat(r.dcaPriceLimitUsd||r.triggerPriceUsd||"0"),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("priceLimitLabel")}),(0,w.jsx)("span",{className:"font-mono tabular-nums",children:"dca_time_close"!==r.orderType||o>0?`$${p.number(o)}`:"-"})]})),"dca_time_close"===r.orderType&&r.dcaIntervalSeconds&&(0,w.jsx)(ei,{legsExecuted:r.dcaLegsExecuted??0,lastLegTimestamp:r.dcaLastLegTimestamp??0,intervalSeconds:r.dcaIntervalSeconds,startAt:r.dcaStartAt??0}),"dca_ratchet_close"===r.orderType&&r.ratchetSizeUsd&&(d=parseFloat(r.ratchetSizeUsd),u=parseFloat(r.dcaPriceLimitUsd||r.triggerPriceUsd||"0"),0===(x=(f=r.currentBestPriceUsd)?parseFloat(f):0)&&A&&(x=A),A&&x>0&&(T&&A>x?x=A:!T&&A<x&&(x=A)),b=x>0&&(T?x>=u+d:x<=u-d),(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("statusLabel")}),(0,w.jsx)("span",{className:b?"text-cyan-400":"text-amber-400",children:b?h("statusTracking"):h("statusWaiting")})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("trailSizeLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(d)]})]}),b&&x>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("bestPriceLabel")}),(0,w.jsxs)("span",{className:"text-cyan-400 font-mono tabular-nums",children:["$",p.number(x)]})]})]})),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("sizeColonLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(z)," (",O,"%)"]})]})]}),!S&&!N&&!C&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("triggerPriceLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(s)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("sizeColonLabel")}),(0,w.jsxs)("span",{className:"font-mono tabular-nums",children:["$",p.number(z)," (",O,"%)"]})]})]}),!N&&!C&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4 pt-1 border-t border-border mt-1",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("netPnlLabel")}),null!==Z?(0,w.jsxs)("span",{className:(0,H.cn)("font-mono tabular-nums",(0,P.pnlColor)(Z)),children:[Z>
2=0?"+":"",p.number(Z)," USD"]}):(0,w.jsx)("span",{className:"text-label-muted",children:"—"})]}),et&&null!==ee&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 ml-1",children:[(0,w.jsx)("span",{className:"text-label-muted",children:h("legPnl")}),(0,w.jsxs)("span",{className:(0,H.cn)("font-mono tabular-nums",(0,P.pnlColorDim)(ee)),children:[ee>=0?"+":"",p.number(ee)," USD"]})]})]}),eo>=.01&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:h("feesLabel")}),(0,w.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",p.number(eo)]})]}),el>=.005&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 ml-1",children:[(0,w.jsx)("span",{className:"text-label-muted",children:h("feeEntry")}),(0,w.jsxs)("span",{className:"text-muted-foreground font-mono tabular-nums",children:["$",p.number(el)]})]}),er>=.005&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 ml-1",children:[(0,w.jsx)("span",{className:"text-label-muted",children:h("feeBorrow")}),(0,w.jsxs)("span",{className:"text-muted-foreground font-mono tabular-nums",children:["$",p.number(er)]})]}),es>=.005&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 ml-1",children:[(0,w.jsx)("span",{className:"text-label-muted",children:h("feeClose")}),(0,w.jsxs)("span",{className:"text-muted-foreground font-mono tabular-nums",children:["$",p.number(es)]})]}),ea>=.005&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 ml-1",children:[(0,w.jsx)("span",{className:"text-label-muted",children:h("feeSwap")}),(0,w.jsxs)("span",{className:"text-muted-foreground font-mono tabular-nums",children:["$",p.number(ea)]})]})]}),(0,w.jsx)("button",{onClick:e=>{e.stopPropagation(),R(r)},disabled:e||m===r.orderPda,title:e?h("reviewTradingDisabled"):void 0,className:"w-full mt-2 px-2 py-1 text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded border border-red-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5",children:m===r.orderPda?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)($.Loader2,{className:"w-3 h-3 animate-spin"}),h("cancelingOrder")]}):h("cancelOrderAction")})]})})]},eu)})}),o?(0,w.jsx)($.Loader2,{className:"w-3 h-3 text-label-muted animate-spin mt-0.5"}):"tpsl"===d&&i?(0,w.jsxs)(W.DropdownMenu,{children:[(0,w.jsx)(W.DropdownMenuTrigger,{asChild:!0,children:(0,w.jsxs)("button",{type:"button",disabled:e,title:e?h("reviewTradingDisabled"):void 0,"aria-label":h("entirePositionTpSl"),className:u?V.default.automationButton:"flex items-center justify-center gap-0.5 h-5 px-1 rounded border border-border-strong text-label-muted hover:text-foreground hover:border-border-strong cursor-pointer transition-colors",children:[(0,w.jsx)(z.Plus,{className:"w-3 h-3"}),u&&(y&&v.length>0?N>0&&(0,w.jsxs)("span",{children:["+",N]}):(0,w.jsx)("span",{children:I})),(0,w.jsx)(q.ChevronDown,{className:"w-2.5 h-2.5"})]})}),(0,w.jsxs)(W.DropdownMenuContent,{align:"start",className:"min-w-[180px]",children:[(0,w.jsx)(W.DropdownMenuItem,{disabled:e,onClick:()=>!e&&i("entire"),className:"text-xs text-foreground hover:bg-surface-interactive",children:h("entirePositionTpSl")}),(0,w.jsx)(W.DropdownMenuItem,{disabled:e,onClick:()=>!e&&i("partial"),className:"text-xs text-foreground hover:bg-surface-interactive",children:h("partialPositionTpSl")})]})]}):(0,w.jsxs)("button",{type:"button","aria-label":U,disabled:e,title:e?h("reviewTradingDisabled"):void 0,onClick:()=>{e||r(d)},className:u?V.default.automationButton:"flex items-center justify-center w-5 h-5 rounded border border-border-strong text-label-muted hover:text-foreground hover:border-border-strong cursor-pointer transition-colors",children:[(0,w.jsx)(z.Plus,{className:"w-3 h-3"}),u&&(0,w.jsx)("span",{children:I})]})]})}var el=e.i(457058),eo=e.i(504458);let ed=(0,eo.default)("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]);e.s(["Play",0,ed],169443);let ec=(0,eo.default)("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]);e.s(["Trash2",0,ec],120911);var eu=e.i(613897),eh=e.i(695109),ep=e.i(984457),em=e.i(679278);let ef="u">typeof window&&void 0!==window.document&&void 0!==window.document.createElement;function ex(e){let t=Object.prototype.toString.call(e);return"[object Window]"===t||"[object global]"===t}function eg(e){return"nodeType"in e}function eb(e){var t,r;return e?ex(e)?e:eg(e)&&null!=(t=null==(r=e.ownerDocument)?void 0:r.defaultView)?t:window:window}function ev(e){let{Document:t}=eb(e);return e instanceof t}function ey(e){return!ex(e)&&e instanceof eb(e).HTMLElement}function ew(e){return e instanceof eb(e).SVGElement}function ej(e){return e?ex(e)?e.document:eg(e)?ev(e)?e:ey(e)||ew(e)?e.ownerDocument:document:document:document}let eS=ef?O.useLayoutEffect:O.useEffect;function ek(e){let t=(0,O.useRef)(e);return eS(()=>{t.current=e}),(0,O.useCallback)(function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];return null==t.current?void 0:t.current(...r)},[])}function eN(e,t){void 0===t&&(t=[e]);let r=(0,O.useRef)(e);return eS(()=>{r.current!==e&&(r.current=e)},t),r}function eP(e,t){let r=(0,O.useRef)();return(0,O.useMemo)(()=>{let t=e(r.current);return r.current=t,t},[...t])}function eT(e){let t=ek(e),r=(0,O.useRef)(null),i=(0,O.useCallback)(e=>{e!==r.current&&(null==t||t(e,r.current)),r.current=e},[]);return[r,i]}function eC(e){let t=(0,O.useRef)();return(0,O.useEffect)(()=>{t.current=e},[e]),t.current}let eM={};function e_(e,t){return(0,O.useMemo)(()=>
2{if(t)return t;let r=null==eM[e]?0:eM[e]+1;return eM[e]=r,e+"-"+r},[e,t])}function eA(e){return function(t){for(var r=arguments.length,i=Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];return i.reduce((t,r)=>{for(let[i,s]of Object.entries(r)){let r=t[i];null!=r&&(t[i]=r+e*s)}return t},{...t})}}let eE=eA(1),eL=eA(-1);function eF(e){if(!e)return!1;let{KeyboardEvent:t}=eb(e.target);return t&&e instanceof t}function eR(e){if(function(e){if(!e)return!1;let{TouchEvent:t}=eb(e.target);return t&&e instanceof t}(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:r}=e.touches[0];return{x:t,y:r}}else if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:r}=e.changedTouches[0];return{x:t,y:r}}}return"clientX"in e&&"clientY"in e?{x:e.clientX,y:e.clientY}:null}let eD=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:r}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:r}=e;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(e){if(e)return[eD.Translate.toString(e),eD.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:i}=e;return t+" "+r+"ms "+i}}}),eI="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]",eU={display:"none"};function eO(e){let{id:t,value:r}=e;return O.default.createElement("div",{id:t,style:eU},r)}function eB(e){let{id:t,announcement:r,ariaLiveType:i="assertive"}=e;return O.default.createElement("div",{id:t,style:{position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"},role:"status","aria-live":i,"aria-atomic":!0},r)}let ez=(0,O.createContext)(null),e$={draggable:"\n    To pick up a draggable item, press the space bar.\n    While dragging, use the arrow keys to move the item.\n    Press space again to drop the item in its new position, or press escape to cancel.\n  "},eV={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function eH(e){var t;let r,{announcements:i=eV,container:s,hiddenTextDescribedById:n,screenReaderInstructions:a=e$}=e,{announce:l,announcement:o}=function(){let[e,t]=(0,O.useState)("");return{announce:(0,O.useCallback)(e=>{null!=e&&t(e)},[]),announcement:e}}(),d=e_("DndLiveRegion"),[c,u]=(0,O.useState)(!1);if((0,O.useEffect)(()=>{u(!0)},[]),t=(0,O.useMemo)(()=>({onDragStart(e){let{active:t}=e;l(i.onDragStart({active:t}))},onDragMove(e){let{active:t,over:r}=e;i.onDragMove&&l(i.onDragMove({active:t,over:r}))},onDragOver(e){let{active:t,over:r}=e;l(i.onDragOver({active:t,over:r}))},onDragEnd(e){let{active:t,over:r}=e;l(i.onDragEnd({active:t,over:r}))},onDragCancel(e){let{active:t,over:r}=e;l(i.onDragCancel({active:t,over:r}))}}),[l,i]),r=(0,O.useContext)(ez),(0,O.useEffect)(()=>{if(!r)throw Error("useDndMonitor must be used within a children of <DndContext>");return r(t)},[t,r]),!c)return null;let h=O.default.createElement(O.default.Fragment,null,O.default.createElement(eO,{id:n,value:a.draggable}),O.default.createElement(eB,{id:d,announcement:o}));return s?(0,em.createPortal)(h,s):h}function eW(){}(r=u||(u={})).DragStart="dragStart",r.DragMove="dragMove",r.DragEnd="dragEnd",r.DragCancel="dragCancel",r.DragOver="dragOver",r.RegisterDroppable="registerDroppable",r.SetDroppableDisabled="setDroppableDisabled",r.UnregisterDroppable="unregisterDroppable";let eq=Object.freeze({x:0,y:0});function eK(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function eG(e,t){let{data:{value:r}}=e,{data:{value:i}}=t;return r-i}function eY(e,t){let{data:{value:r}}=e,{data:{value:i}}=t;return i-r}function eX(e){let{left:t,top:r,height:i,width:s}=e;return[{x:t,y:r},{x:t+s,y:r},{x:t,y:r+i},{x:t+s,y:r+i}]}function eQ(e,t){if(!e||0===e.length)return null;let[r]=e;return t?r[t]:r}function eJ(e,t,r){return void 0===t&&(t=e.left),void 0===r&&(r=e.top),{x:t+.5*e.width,y:r+.5*e.height}}let eZ=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:i}=e,s=[];for(let e of i){let{id:i}=e,n=r.get(i);if(n){let r=function(e,t){let r=Math.max(t.top,e.top),i=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),n=Math.min(t.top+t.height,e.top+e.height);if(i<s&&r<n){let a=t.width*t.height,l=e.width*e.height,o=(s-i)*(n-r);return Number((o/(a+l-o)).toFixed(4))}return 0}(n,t);r>0&&s.push({id:i,data:{droppableContainer:e,value:r}})}}return s.sort(eY)};function e0(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:eq}let e1=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return r.reduce((e,t)=>
2({...e,top:e.top+ +t.y,bottom:e.bottom+ +t.y,left:e.left+ +t.x,right:e.right+ +t.x}),{...e})},e2={ignoreTransform:!1};function e5(e,t){void 0===t&&(t=e2);let r=e.getBoundingClientRect();if(t.ignoreTransform){let{transform:t,transformOrigin:i}=eb(e).getComputedStyle(e);t&&(r=function(e,t,r){let i=function(e){if(e.startsWith("matrix3d(")){let t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}if(e.startsWith("matrix(")){let t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}(t);if(!i)return e;let{scaleX:s,scaleY:n,x:a,y:l}=i,o=e.left-a-(1-s)*parseFloat(r),d=e.top-l-(1-n)*parseFloat(r.slice(r.indexOf(" ")+1)),c=s?e.width/s:e.width,u=n?e.height/n:e.height;return{width:c,height:u,top:d,right:o+c,bottom:d+u,left:o}}(r,t,i))}let{top:i,left:s,width:n,height:a,bottom:l,right:o}=r;return{top:i,left:s,width:n,height:a,bottom:l,right:o}}function e3(e){return e5(e,{ignoreTransform:!0})}function e4(e,t){let r=[];return e?function i(s){var n,a;let l;if(null!=t&&r.length>=t||!s)return r;if(ev(s)&&null!=s.scrollingElement&&!r.includes(s.scrollingElement))return r.push(s.scrollingElement),r;if(!ey(s)||ew(s)||r.includes(s))return r;let o=eb(e).getComputedStyle(s);return(s!==e&&(void 0===(n=o)&&(n=eb(s).getComputedStyle(s)),l=/(auto|scroll|overlay)/,["overflow","overflowX","overflowY"].some(e=>{let t=n[e];return"string"==typeof t&&l.test(t)}))&&r.push(s),void 0===(a=o)&&(a=eb(s).getComputedStyle(s)),"fixed"===a.position)?r:i(s.parentNode)}(e):r}function e6(e){let[t]=e4(e,1);return null!=t?t:null}function e8(e){return ef&&e?ex(e)?e:eg(e)?ev(e)||e===ej(e).scrollingElement?window:ey(e)?e:null:null:null}function e9(e){return ex(e)?e.scrollX:e.scrollLeft}function e7(e){return ex(e)?e.scrollY:e.scrollTop}function te(e){return{x:e9(e),y:e7(e)}}function tt(e){return!!ef&&!!e&&e===document.scrollingElement}function tr(e){let t={x:0,y:0},r=tt(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},i={x:e.scrollWidth-r.width,y:e.scrollHeight-r.height},s=e.scrollTop<=t.y,n=e.scrollLeft<=t.x;return{isTop:s,isLeft:n,isBottom:e.scrollTop>=i.y,isRight:e.scrollLeft>=i.x,maxScroll:i,minScroll:t}}(i=h||(h={}))[i.Forward=1]="Forward",i[i.Backward=-1]="Backward";let ti={x:.2,y:.2};function ts(e){return e.reduce((e,t)=>eE(e,te(t)),eq)}let tn=[["x",["left","right"],function(e){return e.reduce((e,t)=>e+e9(t),0)}],["y",["top","bottom"],function(e){return e.reduce((e,t)=>e+e7(t),0)}]];class ta{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=e4(t),i=ts(r);for(const[t,s,n]of(this.rect={...e},this.width=e.width,this.height=e.height,tn))for(const e of s)Object.defineProperty(this,e,{get:()=>{let s=n(r),a=i[t]-s;return this.rect[e]+a},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class tl{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>{var t;return null==(t=this.target)?void 0:t.removeEventListener(...e)})},this.target=e}add(e,t,r){var i;null==(i=this.target)||i.addEventListener(e,t,r),this.listeners.push([e,t,r])}}function to(e,t){let r=Math.abs(e.x),i=Math.abs(e.y);return"number"==typeof t?Math.sqrt(r**2+i**2)>t:"x"in t&&"y"in t?r>t.x&&i>t.y:"x"in t?r>t.x:"y"in t&&i>t.y}function td(e){e.preventDefault()}function tc(e){e.stopPropagation()}(s=p||(p={})).Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange",(n=m||(m={})).Space="Space",n.Down="ArrowDown",n.Right="ArrowRight",n.Left="ArrowLeft",n.Up="ArrowUp",n.Esc="Escape",n.Enter="Enter",n.Tab="Tab";let tu={start:[m.Space,m.Enter],cancel:[m.Esc],end:[m.Space,m.Enter,m.Tab]},th=(e,t)=>{let{currentCoordinates:r}=t;switch(e.code){case m.Right:return{...r,x:r.x+25};case m.Left:return{...r,x:r.x-25};case m.Down:return{...r,y:r.y+25};case m.Up:return{...r,y:r.y-25}}};class tp{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:t}}=e;this.props=e,this.listeners=new tl(ej(t)),this.windowListeners=new tl(eb(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(p.Resize,this.handleCancel),this.windowListeners.add(p.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(p.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:t}=this.props,r=e.node.current;r&&function(e,t){if(void 0===t&&(t=e5),!e)return;let{top:r,left:i,bottom:s,right:n}=t(e);e6(e)&&(s<=0||n<=0||r>=window.innerHeight||i>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}(r),t(eq)}handleKeyDown(e){if(eF(e)){let{active:t,context:r,options:i}=this.props,{keyboardCodes:s=tu,coordinateGetter:n=th,scrollBehavior:a="smooth"}=i,{code:l}=e;if(s.end.includes(l))return void this.handleEnd(e);if(s.cancel.includes(l))return void this.handleCancel(e);let{collisionRect:o}=r.current,d=o?{x:o.left,y:o.top}:eq;this.referenceCoordinates||(this.referenceCoordinates=d);let c=n(e,{active:t,context:r.current,currentCoordinates:d});if(c){let t=eL(c,d),i={x:0,y:0},{scrollableAncestors:s}=r.current;for(let r of s){let s=e.code,{isTop:n,isRight:l,isLeft:o,isBottom:
2d,maxScroll:u,minScroll:h}=tr(r),p=function(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:t}=window;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}let{top:t,left:r,right:i,bottom:s}=e.getBoundingClientRect();return{top:t,left:r,right:i,bottom:s,width:e.clientWidth,height:e.clientHeight}}(r),f={x:Math.min(s===m.Right?p.right-p.width/2:p.right,Math.max(s===m.Right?p.left:p.left+p.width/2,c.x)),y:Math.min(s===m.Down?p.bottom-p.height/2:p.bottom,Math.max(s===m.Down?p.top:p.top+p.height/2,c.y))},x=s===m.Right&&!l||s===m.Left&&!o,g=s===m.Down&&!d||s===m.Up&&!n;if(x&&f.x!==c.x){let e=r.scrollLeft+t.x,n=s===m.Right&&e<=u.x||s===m.Left&&e>=h.x;if(n&&!t.y)return void r.scrollTo({left:e,behavior:a});n?i.x=r.scrollLeft-e:i.x=s===m.Right?r.scrollLeft-u.x:r.scrollLeft-h.x,i.x&&r.scrollBy({left:-i.x,behavior:a});break}if(g&&f.y!==c.y){let e=r.scrollTop+t.y,n=s===m.Down&&e<=u.y||s===m.Up&&e>=h.y;if(n&&!t.x)return void r.scrollTo({top:e,behavior:a});n?i.y=r.scrollTop-e:i.y=s===m.Down?r.scrollTop-u.y:r.scrollTop-h.y,i.y&&r.scrollBy({top:-i.y,behavior:a});break}}this.handleMove(e,eE(eL(c,this.referenceCoordinates),i))}}}handleMove(e,t){let{onMove:r}=this.props;e.preventDefault(),r(t)}handleEnd(e){let{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){let{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}function tm(e){return!!(e&&"distance"in e)}function tf(e){return!!(e&&"delay"in e)}tp.activators=[{eventName:"onKeyDown",handler:(e,t,r)=>{let{keyboardCodes:i=tu,onActivation:s}=t,{active:n}=r,{code:a}=e.nativeEvent;if(i.start.includes(a)){let t=n.activatorNode.current;return(!t||e.target===t)&&(e.preventDefault(),null==s||s({event:e.nativeEvent}),!0)}return!1}}];class tx{constructor(e,t,r){var i;void 0===r&&(r=function(e){let{EventTarget:t}=eb(e);return e instanceof t?e:ej(e)}(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;const{event:s}=e,{target:n}=s;this.props=e,this.events=t,this.document=ej(n),this.documentListeners=new tl(this.document),this.listeners=new tl(r),this.windowListeners=new tl(eb(n)),this.initialCoordinates=null!=(i=eR(s))?i:eq,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(p.Resize,this.handleCancel),this.windowListeners.add(p.DragStart,td),this.windowListeners.add(p.VisibilityChange,this.handleCancel),this.windowListeners.add(p.ContextMenu,td),this.documentListeners.add(p.Keydown,this.handleKeydown),t){if(null!=r&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(tf(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(tm(t))return void this.handlePending(t)}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){let{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,t)}handleStart(){let{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(p.Click,tc,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(p.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){var t;let{activated:r,initialCoordinates:i,props:s}=this,{onMove:n,options:{activationConstraint:a}}=s;if(!i)return;
2let l=null!=(t=eR(e))?t:eq,o=eL(i,l);if(!r&&a){if(tm(a)){if(null!=a.tolerance&&to(o,a.tolerance))return this.handleCancel();if(to(o,a.distance))return this.handleStart()}return tf(a)&&to(o,a.tolerance)?this.handleCancel():void this.handlePending(a,o)}e.cancelable&&e.preventDefault(),n(l)}handleEnd(){let{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){let{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===m.Esc&&this.handleCancel()}removeTextSelection(){var e;null==(e=this.document.getSelection())||e.removeAllRanges()}}let tg={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class tb extends tx{constructor(e){const{event:t}=e;super(e,tg,ej(t.target))}}tb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:i}=t;return!!r.isPrimary&&0===r.button&&(null==i||i({event:r}),!0)}}];(a=f||(f={}))[a.RightClick=2]="RightClick";(l=x||(x={}))[l.Pointer=0]="Pointer",l[l.DraggableRect=1]="DraggableRect",(o=g||(g={}))[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder";let tv={x:{[h.Backward]:!1,[h.Forward]:!1},y:{[h.Backward]:!1,[h.Forward]:!1}};(d=b||(b={}))[d.Always=0]="Always",d[d.BeforeDragging=1]="BeforeDragging",d[d.WhileDragging=2]="WhileDragging",(v||(v={})).Optimized="optimized";let ty=new Map;function tw(e,t){return eP(r=>e?r||("function"==typeof t?t(e):e):null,[t,e])}function tj(e){let{callback:t,disabled:r}=e,i=ek(t),s=(0,O.useMemo)(()=>{if(r||"u"<typeof window||void 0===window.ResizeObserver)return;let{ResizeObserver:e}=window;return new e(i)},[r]);return(0,O.useEffect)(()=>()=>null==s?void 0:s.disconnect(),[s]),s}function tS(e){return new ta(e5(e),e)}function tk(e,t,r){void 0===t&&(t=tS);let[i,s]=(0,O.useState)(null);function n(){s(i=>{if(!e)return null;if(!1===e.isConnected){var s;return null!=(s=null!=i?i:r)?s:null}let n=t(e);return JSON.stringify(i)===JSON.stringify(n)?i:n})}let a=function(e){let{callback:t,disabled:r}=e,i=ek(t),s=(0,O.useMemo)(()=>{if(r||"u"<typeof window||void 0===window.MutationObserver)return;let{MutationObserver:e}=window;return new e(i)},[i,r]);return(0,O.useEffect)(()=>()=>null==s?void 0:s.disconnect(),[s]),s}({callback(t){if(e)for(let r of t){let{type:t,target:i}=r;if("childList"===t&&i instanceof HTMLElement&&i.contains(e)){n();break}}}}),l=tj({callback:n});return eS(()=>{n(),e?(null==l||l.observe(e),null==a||a.observe(document.body,{childList:!0,subtree:!0})):(null==l||l.disconnect(),null==a||a.disconnect())},[e]),i}let tN=[];function tP(e,t){void 0===t&&(t=[]);let r=(0,O.useRef)(null);return(0,O.useEffect)(()=>{r.current=null},t),(0,O.useEffect)(()=>{let t=e!==eq;t&&!r.current&&(r.current=e),!t&&r.current&&(r.current=null)},[e]),r.current?eL(e,r.current):eq}function tT(e){return(0,O.useMemo)(()=>{let t,r;return e?(t=e.innerWidth,{top:0,left:0,right:t,bottom:r=e.innerHeight,width:t,height:r}):null},[e])}let tC=[],tM=[{sensor:tb,options:{}},{sensor:tp,options:{}}],t_={current:{}},tA={draggable:{measure:e3},droppable:{measure:e3,strategy:b.WhileDragging,frequency:v.Optimized},dragOverlay:{measure:e5}};class tE extends Map{get(e){var t;return null!=e&&null!=(t=super.get(e))?t:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){var t,r;return null!=(t=null==(r=this.get(e))?void 0:r.node.current)?t:void 0}}let tL={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new tE,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:eW},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:tA,measureDroppableContainers:eW,windowRect:null,measuringScheduled:!1},tF={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:eW,draggableNodes:new Map,over:null,measureDroppableContainers:eW},tR=(0,O.createContext)(tF),tD=(0,O.createContext)(tL);function tI(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new tE}}}function tU(e,t){switch(t.type){case u.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case u.DragMove:if(null==e.draggable.active)return e;return{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case u.DragEnd:case u.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case u.RegisterDroppable:{let{element:r}=t,{id:i}
2=r,s=new tE(e.droppable.containers);return s.set(i,r),{...e,droppable:{...e.droppable,containers:s}}}case u.SetDroppableDisabled:{let{id:r,key:i,disabled:s}=t,n=e.droppable.containers.get(r);if(!n||i!==n.key)return e;let a=new tE(e.droppable.containers);return a.set(r,{...n,disabled:s}),{...e,droppable:{...e.droppable,containers:a}}}case u.UnregisterDroppable:{let{id:r,key:i}=t,s=e.droppable.containers.get(r);if(!s||i!==s.key)return e;let n=new tE(e.droppable.containers);return n.delete(r),{...e,droppable:{...e.droppable,containers:n}}}default:return e}}function tO(e){let{disabled:t}=e,{active:r,activatorEvent:i,draggableNodes:s}=(0,O.useContext)(tR),n=eC(i),a=eC(null==r?void 0:r.id);return(0,O.useEffect)(()=>{if(!t&&!i&&n&&null!=a){if(!eF(n)||document.activeElement===n.target)return;let e=s.get(a);if(!e)return;let{activatorNode:t,node:r}=e;(t.current||r.current)&&requestAnimationFrame(()=>{for(let e of[t.current,r.current]){if(!e)continue;let t=e.matches(eI)?e:e.querySelector(eI);if(t){t.focus();break}}})}},[i,t,s,a,n]),null}let tB=(0,O.createContext)({...eq,scaleX:1,scaleY:1});(c=y||(y={}))[c.Uninitialized=0]="Uninitialized",c[c.Initializing=1]="Initializing",c[c.Initialized=2]="Initialized";let tz=(0,O.memo)(function(e){var t,r,i,s,n,a,l,o;let d,c,p,m,f,v,w,j,{id:S,accessibility:k,autoScroll:N=!0,children:P,sensors:T=tM,collisionDetection:C=eZ,measuring:M,modifiers:_,...A}=e,[E,L]=(0,O.useReducer)(tU,void 0,tI),[F,R]=function(){let[e]=(0,O.useState)(()=>new Set),t=(0,O.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,O.useCallback)(t=>{let{type:r,event:i}=t;e.forEach(e=>{var t;return null==(t=e[r])?void 0:t.call(e,i)})},[e]),t]}(),[D,I]=(0,O.useState)(y.Uninitialized),U=D===y.Initialized,{draggable:{active:B,nodes:z,translate:$},droppable:{containers:V}}=E,H=null!=B?z.get(B):null,W=(0,O.useRef)({initial:null,translated:null}),q=(0,O.useMemo)(()=>{var e;return null!=B?{id:B,data:null!=(e=null==H?void 0:H.data)?e:t_,rect:W}:null},[B,H]),K=(0,O.useRef)(null),[G,Y]=(0,O.useState)(null),[X,Q]=(0,O.useState)(null),J=eN(A,Object.values(A)),Z=e_("DndDescribedBy",S),ee=(0,O.useMemo)(()=>V.getEnabled(),[V]),et=(0,O.useMemo)(()=>({draggable:{...tA.draggable,...null==M?void 0:M.draggable},droppable:{...tA.droppable,...null==M?void 0:M.droppable},dragOverlay:{...tA.dragOverlay,...null==M?void 0:M.dragOverlay}}),[null==M?void 0:M.draggable,null==M?void 0:M.droppable,null==M?void 0:M.dragOverlay]),{droppableRects:er,measureDroppableContainers:ei,measuringScheduled:es}=function(e,t){let{dragging:r,dependencies:i,config:s}=t,[n,a]=(0,O.useState)(null),{frequency:l,measure:o,strategy:d}=s,c=(0,O.useRef)(e),u=function(){switch(d){case b.Always:return!1;case b.BeforeDragging:return r;default:return!r}}(),h=eN(u),p=(0,O.useCallback)(function(e){void 0===e&&(e=[]),h.current||a(t=>null===t?e:t.concat(e.filter(e=>!t.includes(e))))},[h]),m=(0,O.useRef)(null),f=eP(t=>{if(u&&!r)return ty;if(!t||t===ty||c.current!==e||null!=n){let t=new Map;for(let r of e){if(!r)continue;if(n&&n.length>0&&!n.includes(r.id)&&r.rect.current){t.set(r.id,r.rect.current);continue}let e=r.node.current,i=e?new ta(o(e),e):null;r.rect.current=i,i&&t.set(r.id,i)}return t}return t},[e,n,r,u,o]);return(0,O.useEffect)(()=>{c.current=e},[e]),(0,O.useEffect)(()=>{u||p()},[r,u]),(0,O.useEffect)(()=>{n&&n.length>0&&a(null)},[JSON.stringify(n)]),(0,O.useEffect)(()=>{u||"number"!=typeof l||null!==m.current||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,u,p,...i]),{droppableRects:f,measureDroppableContainers:p,measuringScheduled:null!=n}}(ee,{dragging:U,dependencies:[$.x,$.y],config:et.droppable}),en=eP(e=>{var t;return null==B?null:null!=(t=null!=f?f:e)?t:null},[f=(m=null!=B?z.get(B):void 0)?m.node.current:null,B]),ea=(0,O.useMemo)(()=>X?eR(X):null,[X]),el=(d=(null==G?void 0:G.autoScrollEnabled)===!1,c="object"==typeof N?!1===N.enabled:!1===N,p=U&&!d&&!c,"object"==typeof N?{...N,enabled:p}:{enabled:p}),eo=tw(en,et.draggable.measure);!function(e){let{activeNode:t,measure:r,initialRect:i,config:s=!0}=e,n=(0,O.useRef)(!1),{x:a,y:l}="boolean"==typeof s?{x:s,y:s}:s;eS(()=>
2{if(!a&&!l||!t){n.current=!1;return}if(n.current||!i)return;let e=null==t?void 0:t.node.current;if(!e||!1===e.isConnected)return;let s=e0(r(e),i);if(a||(s.x=0),l||(s.y=0),n.current=!0,Math.abs(s.x)>0||Math.abs(s.y)>0){let t=e6(e);t&&t.scrollBy({top:s.y,left:s.x})}},[t,a,l,i,r])}({activeNode:null!=B?z.get(B):null,config:el.layoutShiftCompensation,initialRect:eo,measure:et.draggable.measure});let ed=tk(en,et.draggable.measure,eo),ec=tk(en?en.parentElement:null),eu=(0,O.useRef)({activatorEvent:null,active:null,activeNode:en,collisionRect:null,collisions:null,droppableRects:er,draggableNodes:z,draggingNode:null,draggingNodeRect:null,droppableContainers:V,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),eh=V.getNodeFor(null==(t=eu.current.over)?void 0:t.id),ep=function(e){let{measure:t}=e,[r,i]=(0,O.useState)(null),s=tj({callback:(0,O.useCallback)(e=>{for(let{target:r}of e)if(ey(r)){i(e=>{let i=t(r);return e?{...e,width:i.width,height:i.height}:i});break}},[t])}),[n,a]=eT((0,O.useCallback)(e=>{let r=function(e){if(!e)return null;if(e.children.length>1)return e;let t=e.children[0];return ey(t)?t:e}(e);null==s||s.disconnect(),r&&(null==s||s.observe(r)),i(r?t(r):null)},[t,s]));return(0,O.useMemo)(()=>({nodeRef:n,rect:r,setRef:a}),[r,n,a])}({measure:et.dragOverlay.measure}),ex=null!=(r=ep.nodeRef.current)?r:en,eg=U?null!=(i=ep.rect)?i:ed:null,ev=!!(ep.nodeRef.current&&ep.rect),ew=(v=tw(n=ev?null:ed),e0(n,v)),ej=tT(ex?eb(ex):null),ek=(a=U?null!=eh?eh:en:null,w=(0,O.useRef)(a),j=eP(e=>a?e&&e!==tN&&a&&w.current&&a.parentNode===w.current.parentNode?e:e4(a):tN,[a]),(0,O.useEffect)(()=>{w.current=a},[a]),j),eM=function(e,t){void 0===t&&(t=e5);let[r]=e,i=tT(r?eb(r):null),[s,n]=(0,O.useState)(tC);function a(){n(()=>e.length?e.map(e=>tt(e)?i:new ta(t(e),e)):tC)}let l=tj({callback:a});return eS(()=>{null==l||l.disconnect(),a(),e.forEach(e=>null==l?void 0:l.observe(e))},[e]),s}(ek),eA=function(e,t){let{transform:r,...i}=t;return null!=e&&e.length?e.reduce((e,t)=>t({transform:e,...i}),r):r}(_,{transform:{x:$.x-ew.x,y:$.y-ew.y,scaleX:1,scaleY:1},activatorEvent:X,active:q,activeNodeRect:ed,containerNodeRect:ec,draggingNodeRect:eg,over:eu.current.over,overlayNodeRect:ep.rect,scrollableAncestors:ek,scrollableAncestorRects:eM,windowRect:ej}),eL=ea?eE(ea,$):null,eF=function(e){let[t,r]=(0,O.useState)(null),i=(0,O.useRef)(e),s=(0,O.useCallback)(e=>{let t=e8(e.target);t&&r(e=>e?(e.set(t,te(t)),new Map(e)):null)},[]);return(0,O.useEffect)(()=>{let t=i.current;if(e!==t){n(t);let a=e.map(e=>{let t=e8(e);return t?(t.addEventListener("scroll",s,{passive:!0}),[t,te(t)]):null}).filter(e=>null!=e);r(a.length?new Map(a):null),i.current=e}return()=>{n(e),n(t)};function n(e){e.forEach(e=>{let t=e8(e);null==t||t.removeEventListener("scroll",s)})}},[s,e]),(0,O.useMemo)(()=>e.length?t?Array.from(t.values()).reduce((e,t)=>eE(e,t),eq):ts(e):eq,[e,t])}(ek),eD=tP(eF),eI=tP(eF,[ed]),eU=eE(eA,eD),eO=eg?e1(eg,eA):null,eB=q&&eO?C({active:q,collisionRect:eO,droppableRects:er,droppableContainers:ee,pointerCoordinates:eL}):null,e$=eQ(eB,"id"),[eV,eW]=(0,O.useState)(null),eK=(l=ev?eA:eE(eA,eI),o=null!=(s=null==eV?void 0:eV.rect)?s:null,{...l,scaleX:o&&ed?o.width/ed.width:1,scaleY:o&&ed?o.height/ed.height:1}),eG=(0,O.useRef)(null),eY=(0,O.useCallback)((e,t)=>{let{sensor:r,options:i}=t;if(null==K.current)return;let s=z.get(K.current);if(!s)return;let n=e.nativeEvent,a=new r({active:K.current,activeNode:s,event:n,options:i,context:eu,onAbort(e){if(!z.get(e))return;let{onDragAbort:t}=J.current,r={id:e};null==t||t(r),F({type:"onDragAbort",event:r})},onPending(e,t,r,i){if(!z.get(e))return;let{onDragPending:s}=J.current,n={id:e,constraint:t,initialCoordinates:r,offset:i};null==s||s(n),F({type:"onDragPending",event:n})},onStart(e){let t=K.current;if(null==t)return;let r=z.get(t);if(!r)return;let{onDragStart:i}=J.current,s={activatorEvent:n,active:{id:t,data:r.data,rect:W}};(0,em.unstable_batchedUpdates)(()=>{null==i||i(s),I(y.Initializing),L({type:u.DragStart,initialCoordinates:e,active:t}),F({type:"onDragStart",event:s}),Y(eG.current),Q(n)})},onMove(e){L({type:u.DragMove,coordinates:e})},onEnd:l(u.DragEnd),onCancel:l(u.DragCancel)});function l(e){return async function(){let{active:t,collisions:r,over:i,scrollAdjustedTranslate:s}=eu.current,a=null;if(t&&s){let{cancelDrop:l}=J.current;a={activatorEvent:n,active:t,collisions:r,delta:s,over:i},e===u.DragEnd&&"function"==typeof l&&await Promise.resolve(l(a))&&(e=u.DragCancel)}K.current=null,(0,em.unstable_batchedUpdates)(()=>{L({type:e}),I(y.Uninitialized),eW(null),Y(null),Q(null),eG.current=null;let t=e===u.DragEnd?"onDragEnd":"onDragCancel";if(a){let e=J.current[t];null==e||e(a),F({type:t,event:a})}})}}eG.current=a},[z]),eX=(0,O.useCallback)((e,t)=>(r,i)=>{let s=r.nativeEvent,n=z.get(i);null!==K.current||!n||s.dndKit||s.defaultPrevented||!0===e(r,t.options,{active:n})&&(s.dndKit={capturedBy:t.sensor},K.current=i,eY(r,t))},[z,eY]),eJ=(0,O.useMemo)(()=>T.reduce((e,t)=>
2{let{sensor:r}=t;return[...e,...r.activators.map(e=>({eventName:e.eventName,handler:eX(e.handler,t)}))]},[]),[T,eX]);(0,O.useEffect)(()=>{if(!ef)return;let e=T.map(e=>{let{sensor:t}=e;return null==t.setup?void 0:t.setup()});return()=>{for(let t of e)null==t||t()}},T.map(e=>{let{sensor:t}=e;return t})),eS(()=>{ed&&D===y.Initializing&&I(y.Initialized)},[ed,D]),(0,O.useEffect)(()=>{let{onDragMove:e}=J.current,{active:t,activatorEvent:r,collisions:i,over:s}=eu.current;if(!t||!r)return;let n={active:t,activatorEvent:r,collisions:i,delta:{x:eU.x,y:eU.y},over:s};(0,em.unstable_batchedUpdates)(()=>{null==e||e(n),F({type:"onDragMove",event:n})})},[eU.x,eU.y]),(0,O.useEffect)(()=>{let{active:e,activatorEvent:t,collisions:r,droppableContainers:i,scrollAdjustedTranslate:s}=eu.current;if(!e||null==K.current||!t||!s)return;let{onDragOver:n}=J.current,a=i.get(e$),l=a&&a.rect.current?{id:a.id,rect:a.rect.current,data:a.data,disabled:a.disabled}:null,o={active:e,activatorEvent:t,collisions:r,delta:{x:s.x,y:s.y},over:l};(0,em.unstable_batchedUpdates)(()=>{eW(l),null==n||n(o),F({type:"onDragOver",event:o})})},[e$]),eS(()=>{eu.current={activatorEvent:X,active:q,activeNode:en,collisionRect:eO,collisions:eB,droppableRects:er,draggableNodes:z,draggingNode:ex,draggingNodeRect:eg,droppableContainers:V,over:eV,scrollableAncestors:ek,scrollAdjustedTranslate:eU},W.current={initial:eg,translated:eO}},[q,en,eB,eO,z,ex,eg,er,V,eV,ek,eU]),function(e){let t,{acceleration:r,activator:i=x.Pointer,canScroll:s,draggingRect:n,enabled:a,interval:l=5,order:o=g.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:u,delta:p,threshold:m}=e,f=function(e){let{delta:t,disabled:r}=e,i=eC(t);return eP(e=>{if(r||!i||!e)return tv;let s={x:Math.sign(t.x-i.x),y:Math.sign(t.y-i.y)};return{x:{[h.Backward]:e.x[h.Backward]||-1===s.x,[h.Forward]:e.x[h.Forward]||1===s.x},y:{[h.Backward]:e.y[h.Backward]||-1===s.y,[h.Forward]:e.y[h.Forward]||1===s.y}}},[r,t,i])}({delta:p,disabled:!a}),[b,v]=(t=(0,O.useRef)(null),[(0,O.useCallback)((e,r)=>{t.current=setInterval(e,r)},[]),(0,O.useCallback)(()=>{null!==t.current&&(clearInterval(t.current),t.current=null)},[])]),y=(0,O.useRef)({x:0,y:0}),w=(0,O.useRef)({x:0,y:0}),j=(0,O.useMemo)(()=>{switch(i){case x.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case x.DraggableRect:return n}},[i,n,d]),S=(0,O.useRef)(null),k=(0,O.useCallback)(()=>{let e=S.current;if(!e)return;let t=y.current.x*w.current.x,r=y.current.y*w.current.y;e.scrollBy(t,r)},[]),N=(0,O.useMemo)(()=>o===g.TreeOrder?[...c].reverse():c,[o,c]);(0,O.useEffect)(()=>{if(!a||!c.length||!j)return void v();for(let e of N){if((null==s?void 0:s(e))===!1)continue;let t=u[c.indexOf(e)];if(!t)continue;let{direction:i,speed:n}=function(e,t,r,i,s){let{top:n,left:a,right:l,bottom:o}=r;void 0===i&&(i=10),void 0===s&&(s=ti);let{isTop:d,isBottom:c,isLeft:u,isRight:p}=tr(e),m={x:0,y:0},f={x:0,y:0},x={height:t.height*s.y,width:t.width*s.x};return!d&&n<=t.top+x.height?(m.y=h.Backward,f.y=i*Math.abs((t.top+x.height-n)/x.height)):!c&&o>=t.bottom-x.height&&(m.y=h.Forward,f.y=i*Math.abs((t.bottom-x.height-o)/x.height)),!p&&l>=t.right-x.width?(m.x=h.Forward,f.x=i*Math.abs((t.right-x.width-l)/x.width)):!u&&a<=t.left+x.width&&(m.x=h.Backward,f.x=i*Math.abs((t.left+x.width-a)/x.width)),{direction:m,speed:f}}(e,t,j,r,m);for(let e of["x","y"])f[e][i[e]]||(n[e]=0,i[e]=0);if(n.x>0||n.y>0){v(),S.current=e,b(k,l),y.current=n,w.current=i;return}}y.current={x:0,y:0},w.current={x:0,y:0},v()},[r,k,s,v,a,l,JSON.stringify(j),JSON.stringify(f),b,c,N,u,JSON.stringify(m)])}({...el,delta:$,draggingRect:eO,pointerCoordinates:eL,scrollableAncestors:ek,scrollableAncestorRects:eM}
2);let e2=(0,O.useMemo)(()=>({active:q,activeNode:en,activeNodeRect:ed,activatorEvent:X,collisions:eB,containerNodeRect:ec,dragOverlay:ep,draggableNodes:z,droppableContainers:V,droppableRects:er,over:eV,measureDroppableContainers:ei,scrollableAncestors:ek,scrollableAncestorRects:eM,measuringConfiguration:et,measuringScheduled:es,windowRect:ej}),[q,en,ed,X,eB,ec,ep,z,V,er,eV,ei,ek,eM,et,es,ej]),e3=(0,O.useMemo)(()=>({activatorEvent:X,activators:eJ,active:q,activeNodeRect:ed,ariaDescribedById:{draggable:Z},dispatch:L,draggableNodes:z,over:eV,measureDroppableContainers:ei}),[X,eJ,q,ed,L,Z,z,eV,ei]);return O.default.createElement(ez.Provider,{value:R},O.default.createElement(tR.Provider,{value:e3},O.default.createElement(tD.Provider,{value:e2},O.default.createElement(tB.Provider,{value:eK},P)),O.default.createElement(tO,{disabled:(null==k?void 0:k.restoreFocus)===!1})),O.default.createElement(eH,{...k,hiddenTextDescribedById:Z}))}),t$=(0,O.createContext)(null),tV="button";function tH(e){let{id:t,data:r,disabled:i=!1,attributes:s}=e,n=e_("Draggable"),{activators:a,activatorEvent:l,active:o,activeNodeRect:d,ariaDescribedById:c,draggableNodes:u,over:h}=(0,O.useContext)(tR),{role:p=tV,roleDescription:m="draggable",tabIndex:f=0}=null!=s?s:{},x=(null==o?void 0:o.id)===t,g=(0,O.useContext)(x?tB:t$),[b,v]=eT(),[y,w]=eT(),j=(0,O.useMemo)(()=>a.reduce((e,r)=>{let{eventName:i,handler:s}=r;return e[i]=e=>{s(e,t)},e},{}),[a,t]),S=eN(r);return eS(()=>(u.set(t,{id:t,key:n,node:b,activatorNode:y,data:S}),()=>{let e=u.get(t);e&&e.key===n&&u.delete(t)}),[u,t]),{active:o,activatorEvent:l,activeNodeRect:d,attributes:(0,O.useMemo)(()=>({role:p,tabIndex:f,"aria-disabled":i,"aria-pressed":!!x&&p===tV||void 0,"aria-roledescription":m,"aria-describedby":c.draggable}),[i,p,f,x,m,c.draggable]),isDragging:x,listeners:i?void 0:j,node:b,over:h,setNodeRef:v,setActivatorNodeRef:w,transform:g}}function tW(){return(0,O.useContext)(tD)}let tq={timeout:25};function tK(e){let{data:t,disabled:r=!1,id:i,resizeObserverConfig:s}=e,n=e_("Droppable"),{active:a,dispatch:l,over:o,measureDroppableContainers:d}=(0,O.useContext)(tR),c=(0,O.useRef)({disabled:r}),h=(0,O.useRef)(!1),p=(0,O.useRef)(null),m=(0,O.useRef)(null),{disabled:f,updateMeasurementsFor:x,timeout:g}={...tq,...s},b=eN(null!=x?x:i),v=tj({callback:(0,O.useCallback)(()=>{if(!h.current){h.current=!0;return}null!=m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{d(Array.isArray(b.current)?b.current:[b.current]),m.current=null},g)},[g]),disabled:f||!a}),[y,w]=eT((0,O.useCallback)((e,t)=>{v&&(t&&(v.unobserve(t),h.current=!1),e&&v.observe(e))},[v])),j=eN(t);return(0,O.useEffect)(()=>{v&&y.current&&(v.disconnect(),h.current=!1,v.observe(y.current))},[y,v]),(0,O.useEffect)(()=>(l({type:u.RegisterDroppable,element:{id:i,key:n,disabled:r,node:y,rect:p,data:j}}),()=>l({type:u.UnregisterDroppable,key:n,id:i})),[i]),(0,O.useEffect)(()=>{r!==c.current.disabled&&(l({type:u.SetDroppableDisabled,id:i,key:n,disabled:r}),c.current.disabled=r)},[i,n,r,l]),{active:a,rect:p,isOver:(null==o?void 0:o.id)===i,node:y,over:o,setNodeRef:w}}
2let tG={position:"fixed",touchAction:"none"},tY=e=>eF(e)?"transform 250ms ease":void 0;function tX(e,t,r){let i=e.slice();return i.splice(r<0?i.length+r:r,0,i.splice(t,1)[0]),i}function tQ(e){return null!==e&&e>=0}t={styles:{active:{opacity:"0"}}},e.s(["DndContext",0,tz,"KeyboardCode",0,m,"closestCenter",0,e=>{let{collisionRect:t,droppableRects:r,droppableContainers:i}=e,s=eJ(t,t.left,t.top),n=[];for(let e of i){let{id:t}=e,i=r.get(t);if(i){let r=eK(eJ(i),s);n.push({id:t,data:{droppableContainer:e,value:r}})}}return n.sort(eG)},"closestCorners",0,e=>{let{collisionRect:t,droppableRects:r,droppableContainers:i}=e,s=eX(t),n=[];for(let e of i){let{id:t}=e,i=r.get(t);if(i){let r=eX(i),a=Number((s.reduce((e,t,i)=>e+eK(r[i],t),0)/4).toFixed(4));n.push({id:t,data:{droppableContainer:e,value:a}})}}return n.sort(eG)},"getClientRect",0,e5,"getFirstCollision",0,eQ,"getScrollableAncestors",0,e4,"useDndContext",0,tW,"useDraggable",0,tH,"useDroppable",0,tK],326729);let tJ=e=>{let{rects:t,activeIndex:r,overIndex:i,index:s}=e,n=tX(t,i,r),a=t[s],l=n[s];return l&&a?{x:l.left-a.left,y:l.top-a.top,scaleX:l.width/a.width,scaleY:l.height/a.height}:null},tZ={scaleX:1,scaleY:1},t0="Sortable",t1=O.default.createContext({activeIndex:-1,containerId:t0,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:tJ,disabled:{draggable:!1,droppable:!1}}),t2=e=>{let{id:t,items:r,activeIndex:i,overIndex:s}=e;return tX(r,i,s).indexOf(t)},t5=e=>{let{containerId:t,isSorting:r,wasDragging:i,index:s,items:n,newIndex:a,previousItems:l,previousContainerId:o,transition:d}=e;return!!d&&!!i&&(l===n||s!==a)&&(!!r||a!==s&&t===o)},t3={duration:200,easing:"ease"},t4="transform",t6=eD.Transition.toString({property:t4,duration:0,easing:"linear"}),t8={roleDescription:"sortable"};function t9(e){var t,r,i,s;let{animateLayoutChanges:n=t5,attributes:a,disabled:l,data:o,getNewIndex:d=t2,id:c,strategy:u,resizeObserverConfig:h,transition:p=t3}=e,{items:m,containerId:f,activeIndex:x,disabled:g,disableTransforms:b,sortedRects:v,overIndex:y,useDragOverlay:w,strategy:j}=(0,O.useContext)(t1),S=(t=l,r=g,"boolean"==typeof t?{draggable:t,droppable:!1}:{draggable:null!=(i=null==t?void 0:t.draggable)?i:r.draggable,droppable:null!=(s=null==t?void 0:t.droppable)?s:r.droppable}),k=m.indexOf(c),N=(0,O.useMemo)(()=>({sortable:{containerId:f,index:k,items:m},...o}),[f,o,k,m]),P=(0,O.useMemo)(()=>m.slice(m.indexOf(c)),[m,c]),{rect:T,node:C,isOver:M,setNodeRef:_}=tK({id:c,data:N,disabled:S.droppable,resizeObserverConfig:{updateMeasurementsFor:P,...h}}),{active:A,activatorEvent:E,activeNodeRect:L,attributes:F,setNodeRef:R,listeners:D,isDragging:I,over:U,setActivatorNodeRef:B,transform:z}=tH({id:c,data:N,attributes:{...t8,...a},disabled:S.draggable}),$=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return(0,O.useMemo)(()=>e=>{t.forEach(t=>t(e))},t)}(_,R),V=!!A,H=V&&!b&&tQ(x)&&tQ(y),W=!w&&I,q=W&&H?z:null,K=H?null!=q?q:(null!=u?u:j)({rects:v,activeNodeRect:L,activeIndex:x,overIndex:y,index:k}):null,G=tQ(x)&&tQ(y)?d({id:c,items:m,activeIndex:x,overIndex:y}):k,Y=null==A?void 0:A.id,X=(0,O.useRef)({activeId:Y,items:m,newIndex:G,containerId:f}),Q=m!==X.current.items,J=n({active:A,containerId:f,isDragging:I,isSorting:V,id:c,index:k,items:m,newIndex:X.current.newIndex,previousItems:X.current.items,previousContainerId:X.current.containerId,transition:p,wasDragging:null!=X.current.activeId}),Z=function(e){let{disabled:t,index:r,node:i,rect:s}=e,[n,a]=(0,O.useState)(null),l=(0,O.useRef)(r);return eS(()=>{if(!t&&r!==l.current&&i.current){let e=s.current;if(e){let t=e5(i.current,{ignoreTransform:!0}),r={x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height};(r.x||r.y)&&a(r)}}r!==l.current&&(l.current=r)},[t,r,i,s]),(0,O.useEffect)(()=>{n&&a(null)},[n]),n}({disabled:!J,index:k,node:C,rect:T});return(0,O.useEffect)(()=>{V&&X.current.newIndex!==G&&(X.current.newIndex=G),f!==X.current.containerId&&(X.current.containerId=f),m!==X.current.items&&(X.current.items=m)},[V,G,f,m]),(0,O.useEffect)(()=>{if(Y===X.current.activeId)return;if(null!=Y&&null==X.current.activeId){X.current.activeId=Y;return}let e=setTimeout(()=>{X.current.activeId=Y},50);return()=>clearTimeout(e)},[Y]),{active:A,activeIndex:x,attributes:F,data:N,rect:T,index:k,newIndex:G,items:m,isOver:M,isSorting:V,isDragging:I,listeners:D,node:C,overIndex:y,over:U,setNodeRef:$,setActivatorNodeRef:B,setDroppableNodeRef:_,setDraggableNodeRef:R,transform:null!=Z?Z:K,transition:Z||Q&&X.current.newIndex===k?t6:(!W||eF(E))&&p&&(V||J)?eD.Transition.toString({...p,property:t4}):void 0}}m.Down,m.Right,m.Up,m.Left,e.s(["SortableContext",0,function(e){let{children:t,id:r,items:i,strategy:s=tJ,disabled:n=!1}=e,{active:a,dragOverlay:l,droppableRects:o,over:d,measureDroppableContainers:c}=tW(),u=e_(t0,r),h=null!==l.rect,p=(0,O.useMemo)(()=>i.map(e=>"object"==typeof e&&"id"in e?e.id:e),[i]),m=null!=a,f=a?p.indexOf(a.id):-1,x=d?p.indexOf(d.id):-1,g=(0,O.useRef)(p),b=!function(e,t){if(e===t)return!0;
2if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(p,g.current),v=-1!==x&&-1===f||b,y="boolean"==typeof n?{draggable:n,droppable:n}:n;eS(()=>{b&&m&&c(p)},[b,p,m,c]),(0,O.useEffect)(()=>{g.current=p},[p]);let w=(0,O.useMemo)(()=>({activeIndex:f,containerId:u,disabled:y,disableTransforms:v,items:p,overIndex:x,useDragOverlay:h,sortedRects:p.reduce((e,t,r)=>{let i=o.get(t);return i&&(e[r]=i),e},Array(p.length)),strategy:s}),[f,u,y.draggable,y.droppable,v,p,x,o,h,s]);return O.default.createElement(t1.Provider,{value:w},t)},"arrayMove",0,tX,"useSortable",0,t9,"verticalListSortingStrategy",0,e=>{var t,r,i,s;let n,a,l,{activeIndex:o,activeNodeRect:d,index:c,rects:u,overIndex:h}=e,p=null!=(t=u[o])?t:d;if(!p)return null;if(c===o){let e=u[h];return e?{x:0,y:o<h?e.top+e.height-(p.top+p.height):e.top-p.top,...tZ}:null}let m=(r=u,i=c,s=o,n=r[i],a=r[i-1],l=r[i+1],n?s<i?a?n.top-(a.top+a.height):l?l.top-(n.top+n.height):0:l?l.top-(n.top+n.height):a?n.top-(a.top+a.height):0:0);return c>o&&c<=h?{x:0,y:-p.height-m,...tZ}:c<o&&c>=h?{x:0,y:p.height+m,...tZ}:{x:0,y:0,...tZ}}],854553);var t7=e.i(687229),re=e.i(894771),rt=e.i(394802),rr=e.i(727322),ri=e.i(619966),rs=e.i(623075),rn=e.i(685576);let ra="bg-surface-interactive/20 text-muted-foreground",rl=new Set;function ro(e,t){let r=`${e}=${t}`;rl.has(r)||(rl.add(r),console.warn(`[bottom-panel] Unmapped ${e} "${t}" has no localized label; showing the generic Unknown badge`))}e.s(["UNMAPPED_BADGE_CLASS",0,ra,"warnUnmapped",0,ro],687821);var rd=e.i(546642);let rc=new Set(["tp","sl"]),ru={limit:"orderTypeLimit",stop_limit:"orderTypeStop",market:"orderTypeMarket",tp:"takeProfit",sl:"stopLoss",ratchet:"trailingSl",ratchet_entry:"orderTypeTrailingEntry",fib_ratchet:"orderTypeFibTrailingSl",fib_ratchet_entry:"orderTypeFibTrailingEntry",landmine:"orderTypeLandmine",indicator:"orderTypeRsi",indicator_ratchet:"rsiTrailing"};function rh({order:e,onOpenChange:t,livePrice:r,onSuccess:i}){let s=(0,S.useTranslations)("positions"),n=(0,S.useTranslations)("terms"),{updatePassthroughOrder:a}=(0,rr.useTradeActions)(),l=parseFloat(e.triggerPriceUsd||"0"),o=parseFloat(e.sizeUsd||"0"),d=e.collateralAmount??0,c="decrease"===e.action&&"number"==typeof e.closeBps&&e.closeBps>0,u=c?e.closeBps/100:0,[h,p]=(0,O.useState)(l>0?l.toString():""),[m,f]=(0,O.useState)(o>0?o.toString():""),[x,g]=(0,O.useState)(u.toString()),[b,v]=(0,O.useState)(""),[y,j]=(0,O.useState)(!1),k=(0,O.useRef)(!1),[N,P]=(0,O.useState)(e.ratchet?.worstPrice?.toString()??""),[T,M]=(0,O.useState)(e.ratchet?.ratchetSize?.toString()??""),_="ratchet"===e.orderType?e.ratchet?.stopTriggerPrice??0:0,[A,E]=(0,O.useState)(_>0?_.toString():""),[L,R]=(0,O.useState)(e.landMine?.waitPrice?.toString()??""),[D,I]=(0,O.useState)(e.landMine?.waitDurationSeconds?.toString()??""),U="long"===e.side,z=rc.has(e.orderType),$="ratchet"===e.orderType||"ratchet_entry"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType,V="landmine"===e.orderType,W="indicator"===e.orderType||"indicator_ratchet"===e.orderType,q=(0,C.getTokenInfo)(e.marketMint||""),K=ru[e.orderType];K||ro("order type",e.orderType);let G=K?s(K):s("historyUnknownLabel"),X=K?void 0:s("historyUnknownRawTooltip",{value:e.orderType}),Q=parseFloat(h)||0,J=parseFloat(m)||0,Z=Number(x),ee=Math.round(100*Z),et=c&&(!Number.isFinite(Z)||Z<=0||Z>100||ee<1||Math.abs(100*Z-ee)>1e-8),er=""!==b?parseInt(b):void 0,ei=parseFloat(A)||0,es="ratchet"===e.orderType&&ei!==_,en=parseFloat(N)||e.ratchet?.worstPrice||0,ea=parseFloat(T)||e.ratchet?.ratchetSize||0,el="ratchet"===e.orderType&&ei>0&&!(0,Y.isValidRatchetStopTrigger)((0,Y.toOraclePrice)(ei),(0,Y.toOraclePrice)(en),(0,Y.toOraclePrice)(ea),"long"===e.side),eo=!c&&d>0&&o>0?o/d:0,ed=!c&&d>0&&J>0?J/d:0,ec=Math.abs(ed-eo)>.01,eu=(0,F.useFormatters)(),eh=e=>eu.grouped(e,{minimumFractionDigits:2,maximumFractionDigits:2}),ep=(0,O.useMemo)(()=>{let t=[];if(Q>0&&r&&r>0&&(z?"sl"===e.orderType?U&&Q>=r?t.push(s("warnStopLossAboveMark")):!U&&Q<=r&&t.push(s("warnStopLossBelowMark")):"tp"===e.orderType&&(U&&Q<=r?t.push(s("warnTakeProfitBelowMark")):!U&&Q>=r&&t.push(s("warnTakeProfitAboveMark"))):"increase"===e.action&&(U&&Q>=r?t.push(s("warnTriggerAtOrAboveMarket")):!U&&Q<=r&&t.push(s("warnTriggerAtOrBelowMarket")))),ed>50?t.push(s("warnLeverageVeryHigh",{leverage:eu.fixed(ed,1)})):ec&&ed>
220&&t.push(s("warnLeverageChanges",{from:eu.fixed(eo,1),to:eu.fixed(ed,1)})),void 0!==er&&(0===er?t.push(s("warnZeroSlippage")):er>500&&t.push(s("warnSlippageVeryHigh",{bps:er,percent:eu.percent(er/100,1)}))),$&&e.ratchet&&e.ratchet.bestPriceSeen>0){let r=parseFloat(N)||0;r>0&&r!==e.ratchet.worstPrice&&t.push(s("warnOrderActivelyTracking"))}return el&&t.push(s("stopTriggerOutOfRange",{extreme:U?"min":"max"})),t},[Q,r,z,e,U,ed,eo,ec,er,$,N,el]),em=(0,O.useMemo)(()=>{if(Q>0&&Q!==l)return!0;if(c){if(!et&&ee!==e.closeBps)return!0}else if(J>0&&J!==o)return!0;return!!(void 0!==er&&er>0||$&&((parseFloat(N)||0)>0&&(parseFloat(N)||0)!==e.ratchet?.worstPrice||(parseFloat(T)||0)>0&&(parseFloat(T)||0)!==e.ratchet?.ratchetSize||es)||V&&((parseFloat(L)||0)>0&&(parseFloat(L)||0)!==e.landMine?.waitPrice||(parseInt(D)||0)>0&&(parseInt(D)||0)!==e.landMine?.waitDurationSeconds))||!1},[Q,l,J,o,c,et,ee,er,$,N,T,es,e,V,L,D]);async function ef(){if(!k.current&&em&&!y&&!et){if(el)return void B.toast.error(s("stopTriggerOutOfRange",{extreme:U?"min":"max"}));k.current=!0,j(!0);try{let r={orderPda:e.orderPda,profileIndex:e.profileIndex??0,underwriter:e.underwriter};if(Q>0&&Q!==l&&(r.triggerPrice=Q),c?ee!==e.closeBps&&(r.closeBps=ee):J>0&&J!==o&&(r.sizeUsd=J),void 0!==er&&er>0&&er<=1e4&&(r.slippageBps=er),$){let t=parseFloat(N)||void 0,i=parseFloat(T)||void 0;(t!==e.ratchet?.worstPrice||i!==e.ratchet?.ratchetSize||es)&&(r.proOrderUpdate={type:"ratchet",worstPrice:t,ratchetSize:i,stopTriggerPrice:es?ei:void 0})}if(V){let t=parseFloat(L)||void 0,i=parseInt(D)||void 0;(t!==e.landMine?.waitPrice||i!==e.landMine?.waitDurationSeconds)&&(r.proOrderUpdate={type:"landmine",waitPrice:t,waitDurationSeconds:i})}await a(r)?(B.toast.success(s("toastOrderUpdated")),i?.(),t(!1)):B.toast.error(s("toastOrderUpdateStale"))}catch(e){console.error("Failed to update order:",e),B.toast.error(s("toastOrderUpdateFailed"))}finally{k.current=!1,j(!1)}}}return(0,w.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,w.jsx)("span",{className:"text-sm text-foreground font-semibold",children:q.symbol}),(0,w.jsx)("span",{className:(0,H.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded",U?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"),children:U?s("long"):s("short")}),eo>0&&(0,w.jsxs)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-surface-interactive/20 text-secondary-foreground font-mono tabular-nums",children:[eu.fixed(eo,2),"x"]})]}),(0,w.jsxs)("div",{className:"flex gap-4 text-xs",children:[r&&r>0&&(0,w.jsxs)("span",{children:[(0,w.jsxs)("span",{className:"text-label-muted",children:[s("markPrice")," "]}),(0,w.jsxs)("span",{className:"text-foreground font-medium font-mono tabular-nums",children:["$",eh(r)]})]}),d>0&&(0,w.jsxs)("span",{children:[(0,w.jsxs)("span",{className:"text-label-muted",children:[s("collateral")," "]}),(0,w.jsxs)("span",{className:"text-foreground font-medium font-mono tabular-nums",children:["$",eh(d)]})]})]})]}),!W&&(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium",title:X,children:G}),r&&r>0&&(0,w.jsx)("button",{className:"text-xs text-cyan-400",onClick:()=>p(r.toString()),children:s("lastPriceShortcut")})]}),(0,w.jsx)(rd.OrderFormInput,{value:h,onChange:p,placeholder:l>0?eh(l):"0.00"})]}),(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:"flex items-center justify-between mb-1.5",children:(0,w.jsxs)("label",{className:"text-xs text-muted-foreground font-medium",children:[n("size.full"),ec&&J>0&&(0,w.jsxs)("span",{className:(0,H.cn)("ml-1.5 font-mono tabular-nums",ed>30?"text-amber-400":"text-label-muted"),children:[eu.fixed(eo,1),"x → ",eu.fixed(ed,1),"x"]})]})}),c?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(rd.OrderFormInput,{value:x,onChange:g,placeholder:u.toString(),unit:"%"}),(0,w.jsx)("p",{className:"text-[10px] text-label-muted mt-1",children:s("percentOfPosition",{percent:eu.number(et?u:Z)})})]}):(0,w.jsx)(rd.OrderFormInput,{value:m,onChange:f,placeholder:eh(o)})]}),(0,w.jsxs)("div",{children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",children:s("slippage")}),(0,w.jsx)(rd.OrderFormInput,{value:b,onChange:v,placeholder:"100",unit:"bps",inputMode:"numeric",filter:/[^0-9]/g})]}),$&&e.ratchet&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",children:s("worstPrice")}),(0,w.jsx)(rd.OrderFormInput,{value:N,onChange:P,placeholder:eh(e.ratchet.worstPrice)})]}),(0,w.jsxs)("div",{children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",children:"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType?s("targetPrice"):s("trailSize")}),(0,w.jsx)(rd.OrderFormInput,{value:T,onChange:M,placeholder:eh(e.ratchet.ratchetSize)})]}),"ratchet"===e.orderType&&(0,w.jsxs)("div",{children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",title:s("ratchetEarlyStopExplainer",{extreme:U?"min":"max"}),children:s("stopTrigger")}),(0,w.jsx)(rd.OrderFormInput,{value:A,onChange:E,placeholder:s("ratchetEarlyStop")}),(0,w.jsx)("p",{className:"text-3xs text-muted-foreground mt-1",children:s("stopTriggerMarketNote")})]})]}),V&&e.landMine&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{children:[(0,w.jsxs)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",children:[s("proximityPrice"),e.landMine.isArmed&&(0,w.jsx)("span",{className:"text-amber-400 ml-1",children:s("armedSuffix")})]}),(0,w.jsx)(rd.OrderFormInput,{value:L,onChange:R,placeholder:eh(e.landMine.waitPrice)})]}),(0,w.jsxs)("div",{children:[(0,w.jsx)("label",{className:"text-xs text-muted-foreground font-medium mb-1.5 block",children:s("waitDuration")}),(0,w.jsx)(rd.OrderFormInput,{value:D,onChange:I,placeholder:e.landMine.waitDurationSeconds.toString(),unit:s("unitSeconds"),inputMode:"numeric",filter:/[^0-9]/g})]})]}),ep.length>0&&(0,w.jsx)("div",{className:"space-y-1.5",children:ep.map((e,t)=>(0,w.jsxs)("div",{className:"flex items-start gap-2 text-[10px] text-amber-400 bg-amber-500/10 rounded-lg px-3 py-2",children:[(0,w.jsx)(rt.AlertTriangle,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),(0,w.jsx)("span",{children:e})]},t))}),(0,w.jsx)(rd.FormActions,{onCancel:()=>t(!1),onSubmit:ef,submitting:y,disabled:!em||et})]})}function rp(e){let t=(0,S.useTranslations)("positions"),{order:r,open:i,onOpenChange:s}=e,n=(0,ri.useIsMobile)(),a=(0,C.getTokenInfo)(r.marketMint||"");return n?(0,w.jsx)(rn.Sheet,{open:i,onOpenChange:s,children:(0,w.jsxs)(rn.SheetContent,{side:"bottom",className:"bg-canvas border-t border-border rounded-t-xl p-0 max-h-[85dvh] overflow-y-auto",children:[(0,w.jsx)(rn.SheetTitle,{className:"sr-only",children:t("editSymbolOrder",{symbol:a.symbol})}),(0,w.jsx)("div",{className:"p-4 pb-8",children:(0,w.jsx)(rh,{...e})})]})}):(0,w.jsx)(rs.Dialog,{open:i,onOpenChange:s,children:(0,w.jsx)(rs.DialogContent,{className:"sm:max-w-[480px] p-0 gap-0 max-h-[90vh] overflow-hidden",children:(0,w.jsxs)("div",{className:"p-5 overflow-y-auto max-h-[90vh]",children:[(0,w.jsx)(rs.DialogTitle,{className:"text-base font-semibold text-foreground mb-4",children:t("editOrder")}),(0,w.jsx)(rh,{...e})]})})})}let rm={tp:"mobileOrderTypeTakeProfit",sl:"mobileOrderTypeStopLoss",ratchet:"historyOrderTypeTrailingSl",ratchet_entry:"historyOrderTypeTrailing",fib_ratchet:"historyOrderTypeFibTrailingSl",fib_ratchet_entry:"historyOrderTypeFibTrailing",indicator:"historyRsiIndicator",indicator_ratchet:"historyOrderTypeRsiTrailing",dca_close:"historyOrderTypeDcaClose",dca_time_close:"mobileOrderTypeDcaTimeClose",dca_ratchet_close:"mobileOrderTypeDcaTrailingClose"};function rf({label:e,children:t}){return(0,w.jsxs)("div",{className:"flex items-center justify-between py-2",children:[(0,w.jsx)("span",{className:"text-sm text-label-muted",children:e}),(0,w.jsx)("span",{className:"text-sm text-foreground tabular-nums",children:t})]})}function rx({open:e,onOpenChange:t,order:r,asset:i,underwriter:s,side:n,positionSizeUsd:a,livePrice
2s:l,onCancelPassthroughOrder:o,onCancelJupiterOrder:d,onEditOrder:c,lifecycle:u}){let h,p,m,f,x=(0,S.useTranslations)("positions"),g=(0,S.useTranslations)("terms"),b=(0,F.useFormatters)(),[v,y]=(0,O.useState)(!1),j=(0,O.useRef)(!1),k=(0,O.useRef)(0),N="long"===n,T=r.triggerPriceUsd?parseFloat(r.triggerPriceUsd):null,_=r.sizeUsd?parseFloat(r.sizeUsd):null,A=a?parseFloat(a):null,E="number"==typeof r.closeBps&&r.closeBps>0,L=E?r.closeBps/1e4:_&&A&&A>0?_/A:0,R=L>0?Math.round(100*L):null,D=E&&A&&A>0?A*L:_,I=(0,C.getMarketMintFromAsset)(i),U=I?l?.[I]:void 0,B=U??0,z=J(l,s??u?.underwriter,i,U),$=["ratchet","fib_ratchet","fib_ratchet_entry"].includes(r.orderType),V=["indicator","indicator_ratchet"].includes(r.orderType),H=["dca_close","dca_time_close","dca_ratchet_close"].includes(r.orderType),W=r.worstPriceUsd?parseFloat(r.worstPriceUsd):null,q=r.ratchetSizeUsd?parseFloat(r.ratchetSizeUsd):null,K=$?en(r,z,N,k.current||void 0):null;K&&(k.current=K.bestKnown);let G=K?.isTracking??!1,Y=K?.bestKnown??null,X=K?.stopTrigger??0,Q=K?.isStopTripped??!1,Z=K?.price??W,ee=null;W&&q&&!G&&(ee=N?W+q:W-q);let et=u&&D?(0,M.estimateOrderPnl)(u,{execPrice:$?Z??B:T??B,closeFraction:L}):null,er=et?.breakdown??null,ei=et?.netPnl??null,es=et?.legPnl??null,ea=et?.divergent??!1,el=er?er.pricePnl-er.afterFeesPaid:0,eo=u?(0,M.parseRawValue)(u.borrowFeeOwed)*L:0,ed=u?(0,M.parseRawValue)(u.closeFeeOwed)*L:0,ec=u?(0,M.parseRawValue)(u.swapFeeOwed)*L:0,eu=el+eo+ed+ec,eh=async()=>{if(!j.current){j.current=!0,y(!0);try{("imperial_passthrough"===r.source&&r.orderPda&&void 0!==r.profileIndex?await o?.(r.orderPda,r.profileIndex):"jupiter_native"===r.source&&!!r.orderPda&&await d?.(r.orderPda))&&t(!1)}finally{j.current=!1,y(!1)}}},em=!!r.orderPda&&("imperial_passthrough"===r.source?void 0!==r.profileIndex&&!!o:"jupiter_native"===r.source&&!!d),ef=rm[r.orderType];return ef||ro("order type",r.orderType),(0,w.jsx)(rn.Sheet,{open:e,onOpenChange:t,children:(0,w.jsxs)(rn.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4",children:[(0,w.jsx)(rn.SheetTitle,{className:"text-foreground text-lg font-semibold mb-4",children:x("mobileOrderDetails")}),(0,w.jsxs)("div",{className:"mb-6",children:[(0,w.jsx)(rf,{label:x("historySectionType"),children:(0,w.jsx)("span",{className:"font-medium",title:ef?void 0:x("historyUnknownRawTooltip",{value:r.orderType}),children:x(ef?ef:"historyUnknownLabel")})}),$&&(0,w.jsx)(rf,{label:x("historyColStatus"),children:(0,w.jsx)("span",{className:G?"text-cyan-400":Q?"text-emerald-400":"text-amber-400",children:x(G?"mobileRatchetTracking":Q?"statusStopSet":"mobileRatchetWaiting")})}),null!==T&&!$&&(0,w.jsxs)(rf,{label:x("historyRowTriggerPrice"),children:["$",b.number(T)]}),G&&null!==Y&&(0,w.jsx)(rf,{label:x("mobileBestPrice"),children:(0,w.jsxs)("span",{className:"text-cyan-400",children:["$",b.number(Y)]})}),G&&null!==Z?(0,w.jsxs)(rf,{label:x("mobileExecutionPrice"),children:["$",b.number(Z)]}):null!==W&&(0,w.jsxs)(rf,{label:x("mobileWorstPrice"),children:["$",b.number(W)]}),X>0&&(0,w.jsxs)(rf,{label:x("stopTrigger"),children:["$",b.number(X)," ",(0,w.jsxs)("span",{className:Q?"text-emerald-400":"text-amber-400",children:["(",x(Q?"stopTriggerTripped":"stopTriggerNotTripped"),")"]})]}),null!==ee&&(0,w.jsx)(rf,{label:x("mobileDragPrice"),children:(0,w.jsxs)("span",{className:"text-blue-400",children:["$",b.number(ee)]})}),null!==q&&(0,w.jsxs)(rf,{label:x("mobileTrailSize"),children:["$",b.number(q)]}),null!==D&&(0,w.jsxs)(rf,{label:g("size.full"),children:["$",b.number(D),null!==R&&(0,w.jsxs)("span",{className:"text-label-muted ml-1",children:["(",R,"%)"]})]}),null!==ei&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(rf,{label:x("mobileNetPnl"),children:(0,w.jsxs)("span",{className:(0,P.pnlColor)(ei),children:[ei>=0?"+":"",b.number(ei)," USD"]})}),ea&&null!==es&&(0,w.jsxs)("div",{className:"flex items-center justify-between py-1 ml-2",children:[(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:x("mobileLegPnl")}),(0,w.jsxs)("span",{className:`text-xs font-mono tabular-nums ${(0,P.pnlColorDim)(es)}`,children:[es>=0?"+":"",b.number(es)," USD"]})]})]}),eu>=.01&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(rf,{label:x("historyRowFees"),children:(0,w.jsxs)("span",{className:"text-amber-400",children:["$",b.number(eu)]})}),el>=.005&&(0,w.jsxs)("div",{className:"flex items-center justify-between py-1 ml-2",children:[(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:x("mobileEntryFees")}),(0,w.jsxs)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:["$",b.number(el)]})]}),eo>=.005&&(0,w.jsxs)("div",{className:"flex items-center justify-between py-1 ml-2",children:[(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:x("mobileBorrowFee")}),(0,w.jsxs)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:["$",b.number(eo)]})]}),ed>=.005&&(0,w.jsxs)("div",{className:"flex items-center justify-between py-1 ml-2",children:[(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:x("mobileCloseFee")}),(0,w.jsxs)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:["$",b.number(ed)]})]}),ec>=.005&&(0,w.jsxs)("div",{className:"flex items-center justify-between py-1 ml-2",children:[(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:x("mobilePlatformFee")}),(0,w.jsxs)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:["$",b.number(ec)]})]})]}),V&&(0,w.jsxs)(w.Fragment,{children:[r.indicatorThreshold&&(0,w.jsxs)(rf,{label:x("mobileRsiThreshold"),children:[r.indicatorThreshold," (",r.indicatorCondition??"below",")"]}),r.indicatorTimeframe&&(0,w.jsx)(rf,{label:x("mobileTimeframe"),children:r.indicatorTimeframe}),void 0!==r.currentIndicatorValue&&(0,w.jsx)(rf,{label:x("mobileCurrentRsi"),children:(0,w.jsx)("span",{className:"text-cyan-400",children:b.fixed(r.currentIndicatorValue,2)})}),r.indicatorRatchetSize&&(0,w.jsx)(rf,{label:x("mobileRsiTrailSize"),children:r.indicatorRatchetSize})]}
2),H&&(0,w.jsxs)(w.Fragment,{children:[void 0!==r.dcaNumLegs&&(0,w.jsxs)(rf,{label:x("mobileDcaLegs"),children:[r.dcaLegsExecuted??0," / ",r.dcaNumLegs]}),void 0!==r.dcaIntervalSeconds&&(0,w.jsx)(rf,{label:x("historyRowInterval"),children:r.dcaIntervalSeconds>=3600?`${b.fixed(r.dcaIntervalSeconds/3600,1)}h`:`${Math.round(r.dcaIntervalSeconds/60)}m`}),(r.dcaLegsExecuted??0)===0&&(r.dcaStartAt??0)>Math.floor(Date.now()/1e3)&&(p=Math.floor((h=(r.dcaStartAt??0)-Math.floor(Date.now()/1e3))/3600),m=Math.floor(h%3600/60),(0,w.jsx)(rf,{label:x("mobileStartsIn"),children:p>0?`${p}h ${m}m`:`${m}m`})),r.dcaPriceLimitUsd&&(f=parseFloat(r.dcaPriceLimitUsd),(0,w.jsx)(rf,{label:x("mobilePriceLimit"),children:"dca_time_close"!==r.orderType||f>0?`$${b.number(f)}`:"-"}))]})]}),(0,w.jsxs)("div",{className:"flex gap-3",children:[c&&(0,w.jsx)("button",{onClick:()=>{t(!1),c(r)},className:"flex-1 py-3 rounded-lg border border-blue-500/60 text-blue-400 font-semibold text-sm hover:bg-blue-950/50 transition-colors flex items-center justify-center",children:x("mobileEditOrderTitle")}),em&&(0,w.jsx)("button",{onClick:eh,disabled:v,className:"flex-1 py-3 rounded-lg border-0 bg-destructive/10 text-destructive font-semibold text-sm hover:bg-destructive/20 transition-colors disabled:opacity-50 flex items-center justify-center",children:v?(0,w.jsx)(ep.Spinner,{}):x("mobileCancelOrderAction")})]})]})})}e.i(889723);var rg=e.i(465217),rb=e.i(599059),rv=e.i(575146);function ry({open:e,onOpenChange:t,activeCount:r,children:i}){let s=(0,S.useTranslations)("positions");return(0,w.jsxs)(rv.Popover,{open:e,onOpenChange:t,children:[(0,w.jsx)(rv.PopoverTrigger,{asChild:!0,children:(0,w.jsxs)("button",{type:"button",className:V.default.strategyButton,"aria-label":`${s("strategiesLabel")}${r?` \xb7 ${s("strategiesActiveCount",{count:r})}`:""}`,children:[s("strategiesLabel"),r>0&&(0,w.jsx)("span",{className:V.default.strategyCount,children:r}),(0,w.jsx)(q.ChevronDown,{className:"size-3"})]})}),(0,w.jsx)(rv.PopoverContent,{align:"end",sideOffset:6,className:V.default.strategyMenu,onClick:e=>e.stopPropagation(),children:i})]})}e.s(["StrategyDisclosure",0,ry],702021);var rw=e.i(459),rj=e.i(873029),rS=e.i(821043),rk=e.i(665757);e.i(875574);var rN=e.i(142298),rP=e.i(416627);function rT(e,t){let{publicKey:r}=(0,rN.useUnifiedWallet)(),i=r?.toBase58(),s=i&&e.wallet===i&&e.orderPda&&e.marketMint&&e.side&&Number.isInteger(e.profileIndex)?JSON.stringify([i,"pending-entry",e.orderPda,e.marketMint,e.profileIndex,e.underwriter??"jupiter",e.side]):null,[n,a]=(0,O.useReducer)(e=>e+1,0),l=(0,O.useRef)({scope:s,generation:0});l.current.scope!==s&&(l.current={scope:s,generation:l.current.generation+1});let o=l.current,d=(0,O.useRef)(!0);(0,O.useEffect)(()=>(d.current=!0,()=>{d.current=!1}),[]);let c=()=>d.current&&l.current===o;(0,O.useEffect)(()=>(0,rP.subscribeTpSlAttempts)(a),[]),(0,O.useEffect)(()=>{if(!s||!t)return;let e=(0,rP.reconcileTpSlAttempt)(s,"tp",t),r=(0,rP.reconcileTpSlAttempt)(s,"sl",t);(e||r)&&a()},[s,t,n]);let u={tp:s?(0,rP.getTpSlAttempt)(s,"tp"):null,sl:s?(0,rP.getTpSlAttempt)(s,"sl"):null},h=async(r,i,n,l)=>{if(!s||!c())return null;let o=(0,rP.beginTpSlAttempt)(s,r,{...i,parentOrderPda:e.orderPda,baselineOrderPdas:(t??[]).map(e=>e.orderPda)});if(a(),!o)return null;try{let e=await n();return e?(0,rP.settleTpSlAttempt)(s,r,o.attemptId,"submitted",e):!0===l()?(0,rP.rejectTpSlAttempt)(s,r,o.attemptId):(0,rP.settleTpSlAttempt)(s,r,o.attemptId,"uncertain"),c()?e:null}catch(e){if((0,rP.settleTpSlAttempt)(s,r,o.attemptId,"uncertain"),c())throw e;return null}finally{a()}};return{attempts:u,ready:null!==s,scope:s,wallet:i??null,submit:h,refresh:a,isCurrent:c}}e.s(["useOrderTpSlAttempt",0,rT],993467);var rC=e.i(296228),rM=e.i(734195),r_=e.i(936548);function rA({order:e,closeOrders:t,livePrices:r,onClose:i,onPositionChange:s,defaultOrderType:n}){let a,l,o,d=(0,S.useTranslations)("positions"),c=(0,S.useTranslations)("trading"),u=(0,F.useFormatters)(),h=(0,F.useDecimalSeparator)(),[p,m]=(0,O.useState)(n??"tp"),[f,x]=(0,O.useState)(""),[g,b]=(0,O.useState)("price"),[v,y]=(0,O.useState)(100),[j,N]=(0,O.useState)(!1),T=(0,O.useRef)(!1),_=(0,O.useRef)(new Set),[,A]=(0,O.useState)(0),E=rT(e,t),L="tp"===p||"sl"===p?E.attempts[p]:null,R="tp"===p||"sl"===p?null!==L:_.current.has(p),[D,I]=(0,O.useState)(""),[U,z]=(0,O.useState)(""),[$,V]=(0,O.useState)(""),[K,G]=(0,O.useState)(3),[Y,X]=(0,O.useState)(0),[Q,J]=(0,O.useState)("30"),[Z,ee]=(0,O.useState)(!1),[et,er]=(0,O.useState)(""),{createPassthroughOrder:ei,createRatchetOrder:es,createIndicatorCloseOrder:en,wasLastErrorRejection:ea}=(0,rr.useTradeActions)(),eo=()=>{("ratchet"===p||"rsi"===p)&&_.current.add(p),A(e=>e+1),s?.()},ed="long"===e.side,ec=parseFloat(e.sizeUsd||"0"),eu="ratchet_entry"===e.orderType||"fib_ratchet_entry"===e.orderType?e.ratchet?.worstPrice??parseFloat(e.triggerPriceUsd||"0"):parseFloat(e.triggerPriceUsd||"0"),eh=e.marketMint||"",ep=r?.[eh]??eu,em=e.collateralAmount??0,ef=ec*v/100,ex=em*v/100,eg=parseFloat(f)||0,eb=eu>0?eu:ep,ev=(()=>
2{if(eg<=0)return eg;if("pct"===g&&eb>0)return"tp"===p?ed?eb*(1+eg/100):eb*(1-eg/100):ed?eb*(1-eg/100):eb*(1+eg/100);if("pnl"===g&&eu>0&&ec>0){let e="tp"===p?eg:-eg;return(0,M.priceForTargetPnlPct)({sizeUsd:ec,collateralUsd:em,netCapital:null,entryPrice:eu,isLong:ed,targetPnlPct:e})??0}return eg})(),ey=ev>0&&(ed?ev>eb:ev<eb),ew=ev>0&&(ed?ev<eb:ev>eb),ej="rsi"===p||("tp"===p?ey:ew),eS=(0,O.useMemo)(()=>(0,M.calculatePnl)({size:ef,entryPrice:eu,execPrice:ev,isLong:ed})?.total??null,[ev,eu,ef,ed]),ek=(0,O.useMemo)(()=>{let e=parseFloat(D)||0;return(0,M.calculatePnl)({size:ef,entryPrice:eu,execPrice:e,isLong:ed})?.total??null},[D,eu,ef,ed]),eN=async()=>{if(!T.current&&E.ready&&!R){T.current=!0;try{await eP()}finally{T.current=!1}}},eP=async()=>{let t;try{t=(0,C.getCloseOrderTargetFromOrder)(e)}catch(e){B.toast.error((0,r_.displayClientError)(e));return}if("rsi"===p){let e=parseFloat(Q)||0;if(e<=0||e>=100)return void B.toast.error((0,rM.tradingValidationError)("invalidIndicatorThreshold"));if(Z&&0>=(parseFloat(et)||0))return void B.toast.error(d("errorInvalidRsiTrailSize"));try{N(!0);let r=await en({...t,sizeUsd:ef,closeBps:Math.round(100*v),indicatorType:0,timeframeCode:K,period:14,indicatorCondition:Y,thresholdValue:e,ratchetSize:Z?parseFloat(et):void 0});if(!E.isCurrent())return;r?(B.toast.success(d("toastRsiCloseOrderCreated")),i(),s?.()):!0!==ea()&&eo()}catch(e){if(!E.isCurrent())return;eo(),console.error("Error creating RSI close order:",e),B.toast.error(d("toastRsiCloseOrderFailed"))}finally{N(!1)}return}if("ratchet"===p){let e=parseFloat(D)||0,r=parseFloat(U)||0;if(e<=0)return void B.toast.error(d("errorInvalidWorstPrice"));if(r<=0)return void B.toast.error(d("errorInvalidTrailSize"));try{N(!0);let n=await es({...t,sizeUsd:ef,closeBps:Math.round(100*v),currentPrice:ep,worstPrice:e,ratchetSize:r});if(!E.isCurrent())return;n?(B.toast.success(d("toastTrailingSlOrderCreated")),i(),s?.()):!0!==ea()&&eo()}catch(e){if(!E.isCurrent())return;eo(),console.error("Error creating ratchet order:",e),B.toast.error(d("toastTrailingSlOrderFailed"))}finally{N(!1)}return}if(!ev||ev<=0)return void B.toast.error((0,rM.tradingValidationError)("invalidTriggerPrice"));try{N(!0);let e="tp"===p;await E.submit(p,{triggerPrice:ev,closeBps:Math.round(100*v),sizeUsd:ef},()=>ei({...t,sizeUsd:ef,closeBps:Math.round(100*v),triggerPrice:ev,isTakeProfit:e}),ea)?(B.toast.success(d("toastCloseOrderCreated",{type:e?"tp":"sl"})),i(),s?.()):!0!==ea()&&s?.()}catch(e){s?.(),console.error("Error creating order:",e),B.toast.error(d("toastCreateOrderFailed"))}finally{N(!1)}},eT=parseFloat(D)||0,eC=parseFloat(U)||0,eM=eT>0&&eC>0&&v>0,e_=parseFloat(Q)||0,eA=e_>0&&e_<100&&v>0&&(!Z||(parseFloat(et)||0)>0),eE={tp:{label:d("takeProfit"),color:"text-side-long"},sl:{label:d("stopLoss"),color:"text-side-short"},ratchet:{label:d("trailingSl"),color:"text-blue-400"},rsi:{label:"RSI",color:"text-amber-400"}};return(0,w.jsx)("div",{className:"px-4 py-3",children:(0,w.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,w.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:["tp"!==n&&"sl"!==n&&n?"ratchet"===n?(0,w.jsx)(rd.OrderTypeBadge,{label:d("trailingSl"),colorClass:"text-blue-400"}):(0,w.jsx)(rd.OrderTypeBadge,{label:eE[p].label,colorClass:eE[p
2].color}):(0,w.jsx)(rd.TpSlToggle,{value:"sl"===p?"sl":"tp",onChange:e=>{m(e),x("")}}),"ratchet"===p&&(0,w.jsx)(w.Fragment,{children:(0,w.jsx)(k.TooltipProvider,{children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)(rj.Info,{className:"w-3.5 h-3.5 text-muted-foreground cursor-help"})}),(0,w.jsx)(k.TooltipContent,{side:"right",className:"p-1",showArrow:!1,children:(0,w.jsx)(el.default,{src:"/ratchet.png",alt:d("ratchetDiagramAlt"),width:320,height:320,unoptimized:!0})})]})})})]}),(0,w.jsx)(rd.SizeSlider,{value:v,onChange:y}),(0,w.jsxs)("div",{className:"flex flex-col gap-3",children:["rsi"===p?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs text-label-muted w-20",children:"RSI"}),(0,w.jsx)("select",{value:K,onChange:e=>G(Number(e.target.value)),className:"bg-surface-raised border border-border-strong rounded px-2 py-1.5 text-xs text-foreground w-20",children:Object.entries(rw.TIMEFRAME_LABELS).map(([e,t])=>(0,w.jsx)("option",{value:e,children:t},e))})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs text-label-muted w-20",children:d("conditionLabel")}),(0,w.jsx)("select",{value:Y,onChange:e=>X(Number(e.target.value)),className:"bg-surface-raised border border-border-strong rounded px-2 py-1.5 text-xs text-foreground w-28",children:rw.CONDITION_OPTIONS.map(e=>(0,w.jsx)("option",{value:e,children:c(rw.CONDITION_LABEL_KEYS[e])},e))})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs text-label-muted w-20",children:d("thresholdLabel")}),(0,w.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-20",children:(0,w.jsx)(rk.Input,{type:"text",inputMode:"numeric",placeholder:"30",value:Q,onChange:e=>J(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsxs)("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[(0,w.jsx)("input",{type:"checkbox",checked:Z,onChange:e=>ee(e.target.checked),className:"w-3 h-3 rounded border-border-strong bg-surface-raised text-amber-500 focus:ring-0"}),(0,w.jsx)("span",{className:"text-xs text-label-muted",children:d("rsiTrailing")})]}),Z&&(0,w.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-20",children:(0,w.jsx)(rk.Input,{type:"text",inputMode:"decimal",placeholder:"0.5",value:et,onChange:e=>er((0,rS.sanitizeDecimalInput)(e.target.value,h)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]})]}):"ratchet"===p?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)(k.TooltipProvider,{delayDuration:0,children:(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsxs)("span",{className:"text-xs text-label-muted w-20 cursor-help flex items-center gap-1",children:[ed?d("minPrice"):d("maxPrice"),(0,w.jsx)(rj.Info,{className:"w-3 h-3 text-muted-foreground"})]})}),(0,w.jsx)(k.TooltipContent,{side:"left",className:"max-w-[220px]",showArrow:!1,children:(0,w.jsx)("p",{className:"text-xs text-foreground",children:d("ratchetTriggerExplainer",{extreme:ed?"min":"max"})})})]})}),(0,w.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-28",children:(0,w.jsx)(rk.Input,{type:"text",inputMode:"decimal",placeholder:u.number(eu),value:D,onChange:e=>{let t=(0,rS.sanitizeDecimalInput)(e.target.value,h);I(t);let r=parseFloat(t),i=parseFloat($);r>0&&i>0&&z(parseFloat(Math.abs(i-r).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs text-label-muted w-20",children:d("trailSize")}),(0,w.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-28",children:(0,w.jsx)(rk.Input,{type:"text",inputMode:"decimal",placeholder:"0.50",value:U,onChange:e=>{let t=(0,rS.sanitizeDecimalInput)(e.target.value,h);z(t);let r=parseFloat(t),i=parseFloat(D);if(r>0&&i>0){let e=parseFloat((ed?i+r:i-r).toPrecision(12));V(e>0?e.toString():"")}},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs text-label-muted w-20",children:d("dragPrice")}),(0,w.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-28",children:(0,w.jsx)(rk.Input,{type:"text",inputMode:"decimal",placeholder:u.number(ep),value:$,onChange:e=>{let t=(0,rS.sanitizeDecimalInput)(e.target.value,h);V(t);let r=parseFloat(t),i=parseFloat(D);r>0&&i>0&&z(parseFloat(Math.abs(r-i).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]})]}):(0,w.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,w.jsxs)("div",{className:"flex items-center justify-between",children:[(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-xs font-medium text-foreground",children:"tp"===p?d("takeProfit"):d("stopLoss")}),(0,w.jsxs)(W.DropdownMenu,{children:[(0,w.jsx)(W.DropdownMenuTrigger,{asChild:!0,children:(0,w.jsxs)("button",{className:"flex items-center gap-0.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:["price"===g?d("inputModePrice"):"pct"===g?d("inputModePctPrice"):d("inputModePctPnl"),(0,w.jsx)(q.ChevronDown,{className:"w-3 h-3"})]})}),(0,w.jsxs)(W.DropdownMenuContent,{align:"start",className:"min-w-[100px]",children:[(0,w.jsx)(W.DropdownMenuItem,{onClick:()=>{b("price"),x("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:d("inputModePrice")}),(0,w.jsx)(W.DropdownMenuItem,{onClick:()=>{b("pct"),x("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:d("inputModePctPrice")}),(0,w.jsx)(W.DropdownMenuItem,{onClick:()=>{b("pnl"),x("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:d("inputModePctPnl")})]})]})]}),(0,w.jsx)("button",{onClick:()=>{"price"===g&&x((0,rS.toDecimalInputValue)(ep))},className:"text-xs text-label-muted hover:text-foreground transition-colors",children:d("lastPriceShortcut")})]}),(0,w.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5",children:[(0,w.jsx)(rk.Input,{type:"text",inputMode:"decimal",placeholder:"pnl"===g?"tp"===p?d("placeholderPctGain"):d("placeholderPctLoss"):"pct"===g?"tp"===p?d("placeholderIncrease"):d("placeholderDecrease"):"tp"===p?ed?`>${u.number(eb)}`:`<${u.number(eb)}`:ed?`<${u.number(eb)}`:`>${u.number(eb)}`,value:f,onChange:e=>x((0,rS.sanitizeDecimalInput)(e.target.value,h)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,w.jsx)("span",{className:"text-xs text-label-muted ml-2",children:"price"===g?"USD":"%"})]}),"pnl"===g&&(0,w.jsx)(rd.PnlPctPresets,{value:f,onChange:x,orderType:"tp"===p?"tp":"sl"}),("pct"===g||"pnl"===g)&&ev>0&&(0,w.jsxs)("div",{className:"text-[10px] text-label-muted font-mono tabular-nums",children:["≈ $",u.number(ev)]})]}),"rsi"!==p&&(0,w.jsx)(rd.EstimateRow,{label:"ratchet"===p?d("estPnlAtExtreme",{extreme:ed?"min":"max"}):d("estPnl"),value:null!==(a="ratchet"===p?ek:eS)?(0,w.jsxs)("span",{className:(0,H.cn)("font-mono tabular-nums",(0,P.pnlColor)(a)),children:[a>=0?"+":"",u.number(a)," USD"]}):(0,w.jsx)("span",{className:"text-label-muted",children:"—"})}),"rsi"!==p&&(0,w.jsx)(rd.EstimateRow,{label:d("estReturn"),value:null!==(l="ratchet"===p?ek:eS)?(0,w.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[u.number(ex+l)," USD"]}):(0,w.jsx)("span",{className:"text-label-muted",children:"—"})}),!E.ready&&(0,w.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:d("tpslOrderWalletUnavailable")}),R&&(0,w.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:d("tpslSubmissionUncertain")}),L?.persistence==="memory"&&(0,w.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:d("tpslGuardMemoryOnly")}),L&&E.scope&&E.wallet&&("tp"===p||"sl"===p)&&(0,w.jsx)(rC.TpSlAttemptRecovery,{scope:E.scope,leg:p,attempt:L,wallet:E.wallet,market:eh,onRecovered:()=>{x(""),E.refresh(),s?.()}},L.attemptId),(o="rsi"===p?(0,rd.pickMissingLabel)([[v<=0,d("setSize")],[e_<=0||e_>=100,d("setRsiThreshold")],[Z&&0>=(parseFloat(et)||0),d("setTrailSize")]]):"ratchet"===p?(0,rd.pickMissingLabel)([[v<=0,d("setSize")],[eT<=0,ed?d("setMinPrice"):d("setMa
2xPrice")],[eC<=0,d("setTrailSize")]]):(0,rd.pickMissingLabel)([[v<=0,d("setSize")],[!f,d("setTriggerPrice")]]),(0,w.jsx)(rd.FormActions,{onCancel:i,onSubmit:eN,submitLabel:o??d("submit"),submitting:j,disabled:!E.ready||R||null!==o||("rsi"===p?!eA:"ratchet"===p?!eM:!ej)}))]})]})})}var rE=e.i(917898),rL=e.i(392836),rF=e.i(346731);function rR({order:e,shortfallUsd:t,variant:r}){let i=(0,S.useTranslations)("positions"),s=(0,F.useFormatters)();if(1===e.fundingStatus)return null;let n=e.botState===rF.BOT_STATE_INSUFFICIENT_FUNDS;if(!(void 0!==t?t>0:n))return null;let a=void 0===t?i("unfundedTriggeredDetailNoAmount"):i(n?"unfundedTriggeredDetail":"unfundedDetail",{amount:s.usd(t)}),l=(0,w.jsxs)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-destructive/15 text-destructive w-fit inline-flex items-center gap-1",children:[(0,w.jsx)(rt.AlertTriangle,{className:"h-3 w-3 shrink-0"}),i("unfundedBadge")]});return"card"===r?(0,w.jsxs)("div",{className:"flex flex-col gap-1",children:[l,(0,w.jsx)("span",{className:"text-[11px] text-muted-foreground",children:a})]}):(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("span",{tabIndex:0,"aria-label":a,className:"w-fit rounded focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-destructive",children:l})}),(0,w.jsx)(k.TooltipContent,{children:(0,w.jsx)("div",{className:"text-xs max-w-[260px]",children:a})})]})}function rD({order:e,livePrice:t,bestPriceOverride:r}){let i=(0,S.useTranslations)("positions"),s=(0,F.useFormatters)(),{ratchet:n,dragPrice:a,liveTrigger:l,isTracking:o,bestKnown:d,stopTrigger:c,isStopArmed:u}=(0,rE.getRatchetInfo)(e,t,r),h="fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType,p=i(o?"statusTracking":u?"statusStopSet":"statusWaiting"),m=o?"text-cyan-400":u?"text-emerald-400":"text-amber-400";return(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded cursor-help ${o?"bg-cyan-500/20":u?"bg-emerald-500/20":"bg-amber-500/20"} ${m}`,children:p})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"p-3 w-auto",showArrow:!1,children:(0,w.jsxs)("div",{className:"space-y-1 text-xs",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelStatus")}),(0,w.jsx)("span",{className:m,children:p})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelBestPrice")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(d)]})]}),h?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("targetPrice")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(n.ratchetSize)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelRange")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(Math.abs(n.ratchetSize-n.worstPrice))]})]})]}):(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("trailSize")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(n.ratchetSize)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelTrigger")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(o||u?l:a)]})]}),c>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("stopTrigger")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(c)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelLimit")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(n.worstPrice)]})]}),h&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:i("labelMode")}),(0,w.jsx)("span",{className:"text-fuchsia-400",children:i(n.isReverseFib?"fibModeReverse":"fibModeNormal")})]})]})})]})}function rI({order:e,livePrice:t}){let r=(0,S.useTranslations)("positions"),i=(0,S.useTranslations)("trading"),s=(0,F.useFormatters)(),n=e.indicator;if(!n)return(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:"-"});let a=1===n.phase,l=rw.TIMEFRAME_LABELS[n.timeframeCode??0]??"?",o=i(rw.CONDITION_LABEL_KEYS[n.indicatorCondition??0]);if(a&&e.ratchet){let i=(0,rE.getRatchetInfo)(e,t);return(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded cursor-help ${i.isTracking?"bg-cyan-500/20 text-cyan-400":"bg-amber-500/20 text-amber-400"}`,children:r(i.isTracking?"statusTracking":"statusTrailing")})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"p-3 w-auto",showArrow:!1,children:(0,w.jsxs)("div",{className:"space-y-1 text-xs",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelPhase")}),(0,w.jsx)("span",{className:"text-amber-400",children:r("rsiTrailing")})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelBestRsi")}),(0,w.jsx)("span",{className:"text-foreground",children:s.fixed(e.ratchet.bestPriceSeen,1)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelRsiTrailSize")}),(0,w.jsx)("span",{className:"text-foreground",children:s.fixed(e.ratchet.ratchetSize,1)})]}),void 0!==n.currentValue&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelCurrentRsi")}),(0,w.jsx)("span",{className:"text-foreground",children:s.fixed(n.currentValue,1)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("worstPrice")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",s.number(e.ratchet.worstPrice)]})]})]})})]})}return(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded cursor-help bg-amber-500/20 text-amber-400",children:r("statusMonitoring")})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"p-3 w-auto",showArrow:!1,children:(0,w.jsxs)("div",{className:"space-y-1 text-xs",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelIndicator")}
2),(0,w.jsxs)("span",{className:"text-foreground",children:["RSI-",n.period]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelTimeframe")}),(0,w.jsx)("span",{className:"text-foreground",children:l})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("conditionLabel")}),(0,w.jsxs)("span",{className:"text-foreground",children:[o," ",s.fixed(n.thresholdValue,1)]})]}),"indicator_ratchet"===e.orderType&&e.ratchet&&e.ratchet.ratchetSize>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("trailSize")}),(0,w.jsx)("span",{className:"text-foreground",children:s.fixed(e.ratchet.ratchetSize,1)})]}),void 0!==n.currentValue&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelCurrentRsi")}),(0,w.jsx)("span",{className:"text-foreground",children:s.fixed(n.currentValue,1)})]})]})})]})}function rU({order:e,livePrice:t}){let r=(0,S.useTranslations)("positions"),i=(0,F.useFormatters)(),s=e.dcaRatchet??e.dcaRatchetClose;if(!s)return null;let n="long"===e.side,a=e.dcaRatchetClose?n:!n,l=s.bestPriceSeen>0?s.bestPriceSeen:0;void 0!==t&&t>0&&(0===l||a&&t>l?l=t:!a&&t<l&&(l=t));let o=l>0&&(a?l>=s.priceLimit+s.ratchetSize:l<=s.priceLimit-s.ratchetSize);return(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded cursor-help ${o?"bg-cyan-500/20 text-cyan-400":"bg-amber-500/20 text-amber-400"}`,children:r(o?"statusTracking":"statusWaiting")})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"p-3 w-auto",showArrow:!1,children:(0,w.jsxs)("div",{className:"space-y-1 text-xs",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelStatus")}),(0,w.jsx)("span",{className:o?"text-cyan-400":"text-amber-400",children:r(o?"statusTracking":"statusWaiting")})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelPriceLimit")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",i.number(s.priceLimit)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("trailSize")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",i.number(s.ratchetSize)]})]}),l>0&&(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelBestPrice")}),(0,w.jsxs)("span",{className:"text-foreground",children:["$",i.number(l)]})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("span",{className:"text-muted-foreground",children:r("labelLegs")}),(0,w.jsxs)("span",{className:"text-foreground",children:[s.legsExecuted,"/",s.numLegs]})]})]})})]})}function rO({readOnly:e=!1,order:t,onCancel:r,isCanceling:i,livePrice:s,onExecuteNow:n,isExecuting:a,closeOrders:l,livePrices:o,onPositionChange:d,hasActivePosition:c,sortableRef:u,sortableStyle:h,sortableAttributes:p,dragHandleListeners:m,isDragging:f,phoenixFill:x,fundingShortfallUsd:g}){let b,v,y,j=(0,S.useTranslations)("positions"),N=(0,S.useTranslations)("trading"),P=(0,F.useFormatters)(),[T,M]=(0,O.useState)(!1),[_,A]=(0,O.useState)(!1),[E,L]=(0,O.useState)("tp"),[R,D]=(0,O.useState)(!1),[I,U]=(0,O.useState)(null),B=I?(l??[]).find(e=>e.orderPda===I)??null:null,$=!C.DCA_ORDER_TYPES.has(t.orderType)&&"imperial_passthrough"===t.source,{profiles:W}=(0,re.useProfile)(),q=(0,C.getTokenInfo)(t.marketMint||""),K="long"===t.side,G=C.USDC_MINT.toBase58(),Y=async(t,i)=>{if(e)return!1;let s=await r(t,G,i,void 0);return s&&U(null),s},X=parseFloat(t.sizeUsd),Q=t.collateralAmount??0,Z=Q>0?X/Q:0,ee="increase"===t.action,et=!ee&&"number"==typeof t.closeBps&&t.closeBps>0?t.closeBps/100:null,ei=t.profileIndex,es="number"==typeof ei?(W.length>ei?W[ei]?.name:null)??(0===ei?j("mobileAccountMain"):j("profileFallbackName",{index:ei+1})):null,en=parseFloat(t.triggerPriceUsd),ea=("indicator"===t.orderType||"indicator_ratchet"===t.orderType)&&t.indicator,eo=("ratchet"===t.orderType||"ratchet_entry"===t.orderType||"fib_ratchet"===t.orderType||"fib_ratchet_entry"===t.orderType)&&t.ratchet,em=J(o,t.underwriter,t.marketMint?(0,t7.mintToMatchingKey)(t.marketMint):void 0,s),ef=(0,rL.useRatchetPrices)([t],em).get(t.orderPda)?.price,ex=eo?(0,rE.getRatchetInfo)(t,em,ef||void 0):null,eg="dca_ratchet"===t.orderType||"dca_ratchet_close"===t.orderType,eb=t.dcaRatchet??t.dcaRatchetClose;if(ex)b=P.number(ex.isTracking||ex.isStopArmed?ex.liveTrigger:ex.dragPrice);else if(eg&&eb){let e=!!t.dcaRatchetClose,r=e?K:!K,i=eb.bestPriceSeen>0?eb.bestPriceSeen:0;if(void 0!==em&&em>0&&(0===i||r&&em>i?i=em:!r&&em<i&&(i=em)),i>0&&(r?i>=eb.priceLimit+eb.ratchetSize:i<=eb.priceLimit-eb.ratchetSize)){let t=e?K?Math.max(i-eb.ratchetSize,eb.priceLimit):Math.min(i+eb.ratchetSize,eb.priceLimit):K?Math.min(i+eb.ratchetSize,eb.priceLimit):Math.max(i-eb.ratchetSize,eb.priceLimit);b=P.number(t)}else b=P.number(en)}else b=ea&&0===t.indicator.phase?j("triggerRsiCondition",{condition:N(rw.CONDITION_LABEL_KEYS[t.indicator.indicatorCondition??0]),threshold:P.fixed(t.indicator.thresholdValue,0)}):ea&&1===t.indicator.phase&&t.ratchet?t.ratchet.worstPrice>0?P.number(t.ratchet.worstPrice):j("rsiTrailing"):en>0?P.number(en):"-";let ev=(e,t,r)=>{let i=r?{executed:r.legsExecuted,total:r.numLegs}:null;return i?j(e,i):j(t)},ey={landmine:{label:j("orderTypeLandmine"),color:"bg-purple-500/20 text-purple-400"},ratchet:{label:j("trailingSl"),color:"bg-blue-500/20 text-blue-400"},ratchet_entry:{label:j("orderTypeTrailing"),color:"bg-blue-500/20 text-blue-400"},fib_ratchet:{label:j("orderTypeFibTrailingSl"),color:"bg-fuchsia-500/20 text-fuchsia-400"},fib_ratchet_entry:{label:j("orderTypeFibTrailing"),color:"bg-fuchsia-500/20 text-fuchsia-400"}
2,indicator:{label:"RSI",color:"bg-amber-500/20 text-amber-400"},indicator_ratchet:{label:j("rsiTrailing"),color:"bg-amber-500/20 text-amber-400"},dca:{label:ev("orderTypeDcaWithLegs","orderTypeDca",t.dca),color:"bg-cyan-500/20 text-cyan-400"},dca_close:{label:ev("orderTypeDcaCloseWithLegs","orderTypeDcaClose",t.dcaClose),color:"bg-cyan-500/20 text-cyan-400"},dca_time_close:{label:ev("orderTypeDcaTimeWithLegs","orderTypeDcaTime",t.dcaTimeClose),color:"bg-cyan-500/20 text-cyan-400"},dca_ratchet_close:{label:ev("orderTypeDcaTrailingWithLegs","orderTypeDcaTrailing",t.dcaRatchetClose),color:"bg-teal-500/20 text-teal-400"},dca_time:{label:ev("orderTypeDcaTimeWithLegs","orderTypeDcaTime",t.dcaTime),color:"bg-cyan-500/20 text-cyan-400"},dca_ratchet:{label:ev("orderTypeDcaTrailingWithLegs","orderTypeDcaTrailing",t.dcaRatchet),color:"bg-teal-500/20 text-teal-400"},limit:{label:j("orderTypeLimit"),color:"bg-blue-500/20 text-blue-400"},stop_limit:{label:j("orderTypeStop"),color:"bg-side-short/20 text-side-short"},sl:{label:j("orderTypeStop"),color:"bg-side-short/20 text-side-short"},tp:{label:j("takeProfit"),color:"bg-side-long/20 text-side-long"},market:{label:j("orderTypeMarket"),color:"bg-side-long/20 text-side-long"}}[t.orderType];ey||ro("order type",t.orderType);let ew=ey??{label:j("historyUnknownLabel"),color:ra},ej=ey?void 0:j("historyUnknownRawTooltip",{value:t.orderType}),eS=t=>{if(!ee)return(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:"—"});let r={tpsl:["tp","sl"],trailing:["ratchet","fib_ratchet"],dca:["dca_close","dca_time_close","dca_ratchet_close"],rsi:["indicator","indicator_ratchet"]},i=(l??[]).filter(e=>r[t]?.includes(e.orderType)),s={tpsl:"tp",trailing:"ratchet",rsi:"rsi"};return(0,w.jsxs)("div",{className:"flex flex-col items-center text-xs",children:[i.map((e,t)=>{let r="tp"===e.orderType,i="ratchet"===e.orderType||"fib_ratchet"===e.orderType,s="indicator"===e.orderType||"indicator_ratchet"===e.orderType,n=i?e.ratchet?.worstPrice??parseFloat(e.triggerPriceUsd||"0"):parseFloat(e.triggerPriceUsd||"0");return(0,w.jsx)("button",{onClick:()=>{M(!1),e.orderPda&&U(e.orderPda)},className:(0,H.cn)("text-[10px] font-mono tabular-nums font-medium hover:underline",s?"text-amber-400":i?"text-blue-400":r?"text-side-long":"text-side-short"),children:s?"RSI":`$${P.number(n)}`},t)}),"dca"===t||c?(0,w.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded border border-border-strong text-muted-foreground",children:(0,w.jsx)(z.Plus,{className:"w-3 h-3"})}):(0,w.jsx)("button",{disabled:e,title:e?j("reviewTradingDisabled"):void 0,onClick:()=>{e||(M(!1),L(s[t]),A(!0))},"aria-label":"tpsl"===t?"TP/SL":"trailing"===t?j("columnTrailing"):j("columnIndicator"),className:"flex items-center justify-center w-5 h-5 rounded border border-border-strong text-label-muted hover:text-foreground hover:border-border-strong cursor-pointer transition-colors",children:(0,w.jsx)(z.Plus,{className:"w-3 h-3"})})]})},ek=(l??[]).filter(e=>["ratchet","fib_ratchet","dca_close","dca_time_close","dca_ratchet_close","indicator","indicator_ratchet"].includes(e.orderType)).length;return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("tr",{"data-compact-order":!0,ref:u,style:h,...p??{},className:(0,H.cn)("border-b border-border hover:bg-surface-interactive/50",f&&"opacity-50"),children:[(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsxs)("div",{className:"flex items-center gap-1",children:[m&&(0,w.jsx)("button",{...m,className:"p-0.5 text-label-muted hover:text-secondary-foreground cursor-grab active:cursor-grabbing mr-1 flex-shrink-0",title:j("dragToReorderPriority"),children:(0,w.jsx)(eu.GripVertical,{className:"w-3.5 h-3.5"})}),(0,w.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:`text-xs font-medium px-2 py-0.5 rounded ${K?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:K?j("longUpper"):j("shortUpper")}),q.image&&(0,w.jsx)(el.default,{src:q.image,alt:q.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:rg.handleTokenImageError}),(0,w.jsx)("span",{className:"text-xs text-foreground",children:q.symbol})]}),(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[es&&(0,w.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-surface-raised text-secondary-foreground",children:es}),(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:Z>0?`${Math.round(Z)}x`:""}),"jupiter"===t.underwriter&&(0,w.jsx)(el.default,{src:"/jupiter-logo.webp",alt:"Jupiter",width:14,height:14,className:"rounded-full",unoptimized:!0}),(v=t.underwriter?(0,rb.getVenueIcon)(t.underwriter,t.hedgeVenue):null)&&"jupiter"!==t.underwriter?(0,w.jsxs)("span",{className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground",children:[(0,w.jsx)(el.default,{src:v.src,alt:v.alt,width:14,height:14,className:"rounded-full",unoptimized:!0}),(0,w.jsx)("span",{children:v.alt})]}):null]})]})]})}),(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,w.jsx)("span",{title:ej,className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${ew.color} w-fit`,children:ew.label}),1===t.fundingStatus&&(0,w.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-yellow-500/20 text-yellow-400 w-fit inline-flex items-center gap-1",children:j("pendingFundingWithPriority",{priority:t.priority??0})}),(0,w.jsx)(rR,{order:t,shortfallUsd:g,variant:"row"})]})}),(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,w.jsx)("span",{className:"text-xs text-foreground",children:null!=et?j("percentOfPosition",{percent:et.toLocaleStr
2ing(P.intlTag,{maximumFractionDigits:1})}):`$${X.toLocaleString(P.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`}),x&&x.fillFraction>0&&x.fillFraction<1&&(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsxs)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-300 w-fit inline-flex items-center gap-1",children:[j("percentFilled",{percent:Math.floor(100*x.fillFraction)}),!x.isLive&&(0,w.jsx)("span",{className:"opacity-60",children:"·"})]})}),(0,w.jsx)(k.TooltipContent,{children:(0,w.jsxs)("div",{className:"text-xs",children:[x.initialBaseLots>0?j("baseLotsFilled",{filled:x.initialBaseLots-x.remainingBaseLots,total:x.initialBaseLots}):j("partialFillDetected"),!x.isLive&&(0,w.jsx)("div",{className:"text-[10px] text-muted-foreground mt-1",children:j("indexerTrackedFillNote")})]})})]})]})}),(0,w.jsx)("td",{className:"py-3 px-3",children:ee?(0,w.jsxs)("span",{className:"text-xs text-foreground",children:["$",Q.toLocaleString(P.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]}):(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:"-"})}),(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsx)("span",{className:"text-xs text-foreground",children:ea&&0===t.indicator.phase||"-"===b?b:`$${b}`})}),(0,w.jsx)("td",{className:"py-3 px-3",children:1===t.fundingStatus?(0,w.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-yellow-500/20 text-yellow-400 w-fit",children:j("pendingFunding")}):"landmine"===t.orderType&&t.landMine?(0,w.jsx)("span",{className:"text-xs text-foreground",children:j("proximityPriceValue",{price:t.landMine.waitPrice>0?P.number(t.landMine.waitPrice):j("notAvailable")})}):("ratchet"===t.orderType||"ratchet_entry"===t.orderType||"fib_ratchet"===t.orderType||"fib_ratchet_entry"===t.orderType)&&t.ratchet?(0,w.jsx)(rD,{order:t,livePrice:em,bestPriceOverride:ef||void 0}):("indicator"===t.orderType||"indicator_ratchet"===t.orderType)&&t.indicator?(0,w.jsx)(rI,{order:t,livePrice:em}):"dca"===t.orderType&&t.dca?(0,w.jsxs)("span",{className:"text-xs text-foreground",children:["$",P.number(t.dca.startPrice)," → $",P.number(t.dca.endPrice),1===t.dca.leverageWeightingType&&t.dca.startLeverageScaled>0&&(0,w.jsxs)("span",{className:"text-violet-400 ml-1",children:["· ",P.fixed(t.dca.startLeverageScaled/100,1),"x → ",P.fixed(t.dca.endLeverageScaled/100,1),"x"]})]}):"dca_close"===t.orderType&&t.dcaClose?(0,w.jsxs)("span",{className:"text-xs text-foreground",children:["$",P.number(t.dcaClose.startPrice)," → $",P.number(t.dcaClose.endPrice)," (",t.dcaClose.legsExecuted,"/",t.dcaClose.numLegs,")"]}):"dca_time_close"===t.orderType&&t.dcaTimeClose?(0,w.jsxs)("span",{className:"text-xs text-foreground flex items-center gap-1.5",children:[(0,w.jsx)(er,{legsExecuted:t.dcaTimeClose.legsExecuted,lastLegTimestamp:t.dcaTimeClose.lastLegTimestamp,intervalSeconds:t.dcaTimeClose.intervalSeconds,startAt:t.dcaTimeClose.startAt??0,className:"text-[10px]"}),(0,w.jsxs)("span",{children:["(",t.dcaTimeClose.legsExecuted,"/",t.dcaTimeClose.numLegs,")"]})]}):"dca_ratchet_close"===t.orderType&&t.dcaRatchetClose?(0,w.jsxs)("span",{className:"text-xs text-foreground flex items-center gap-1.5",children:[(0,w.jsx)(rU,{order:t,livePrice:em}),(0,w.jsxs)("span",{children:["(",t.dcaRatchetClose.legsExecuted,"/",t.dcaRatchetClose.numLegs,")"]})]}):"dca_time"===t.orderType&&t.dcaTime?(0,w.jsxs)("span",{className:"text-xs text-foreground flex items-center gap-1.5",children:[(0,w.jsx)(er,{legsExecuted:t.dcaTime.legsExecuted,lastLegTimestamp:t.dcaTime.lastLegTimestamp,intervalSeconds:t.dcaTime.intervalSeconds,startAt:t.dcaTime.startAt??0,className:"text-[10px]"}),(0,w.jsxs)("span",{children:["(",t.dcaTime.legsExecuted,"/",t.dcaTime.numLegs,")"]}),1===t.dcaTime.leverageWeightingType&&t.dcaTime.startLeverageScaled>0&&(0,w.jsxs)("span",{className:"text-violet-400",children:["· ",P.fixed(t.dcaTime.startLeverageScaled/100,1),"x → ",P.fixed(t.dcaTime.endLeverageScaled/100,1),"x"]})]}):"dca_ratchet"===t.orderType&&t.dcaRatchet?(0,w.jsxs)("span",{className:"text-xs text-foreground flex items-center gap-1.5",children:[(0,w.jsx)(rU,{order:t,livePrice:em}),(0,w.jsxs)("span",{children:["(",t.dcaRatchet.legsExecuted,"/",t.dcaRatchet.numLegs,")"]}),1===t.dcaRatchet.leverageWeightingType&&t.dcaRatchet.startLeverageScaled>0&&(0,w.jsxs)("span",{className:"text-violet-400",children:["· ",P.fixed(t.dcaRatchet.startLeverageScaled/100,1),"x → ",P.fixed(t.dcaRatchet.endLeverageScaled/100,1),"x"]})]}):(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:"-"})}),(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsx)("span",{className:"text-xs text-muted-foreground",children:t.createdAt?P.dateTime(t.createdAt):j("notAvailable")})}),(0,w.jsx)("td",{className:"py-3 px-3",onClick:e=>e.stopPropagation(),children:eS("tpsl")}),(0,w.jsx)("td",{className:"py-3 px-3",children:(0,w.jsxs)("div",{"data-compact-actions":!0,className:V.default.actions,children:[ee&&(0,w.jsx)(ry,{open:T,onOpenChange:M,activeCount:ek,children:["trailing","dca","rsi"].map(e=>(0,w.jsxs)("div",{className:V.default.strategyRow,children:[(0,w.jsxs)("div",{children:[(0,w.jsx)("strong",{children:"trailing"===e?j("columnTrailing"):"dca"===e?"DCA":j("columnIndicator")}
2),(0,w.jsx)("p",{children:j(c?"strategyOpenPositionHint":"dca"===e?"strategyAfterEntryHint":"trailing"===e?"strategyTrailingHint":"strategyIndicatorHint")})]}),eS(e)]},e))}),n&&"increase"===t.action&&(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("button",{onClick:()=>{e||n(t)},"aria-label":j("executeAtMarketPrice"),disabled:e||i||a,title:e?j("reviewTradingDisabled"):void 0,className:"p-1 text-muted-foreground hover:text-amber-400 hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",children:a?(0,w.jsx)(ep.Spinner,{className:"size-3.5"}):(0,w.jsx)(ed,{className:"w-3.5 h-3.5"})})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"text-xs px-2 py-1 whitespace-nowrap",showArrow:!1,children:j("executeAtMarketPrice")})]}),$&&(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("button",{onClick:()=>D(!0),"aria-label":j("editOrderTooltip"),disabled:e||i||a,title:e?j("reviewTradingDisabled"):void 0,className:"p-1 text-muted-foreground hover:text-blue-400 hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",children:(0,w.jsx)(eh.Pencil,{className:"w-3.5 h-3.5"})})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"text-xs px-2 py-1 whitespace-nowrap",showArrow:!1,children:j("editOrderTooltip")})]}),(0,w.jsxs)(k.Tooltip,{children:[(0,w.jsx)(k.TooltipTrigger,{asChild:!0,children:(0,w.jsx)("button",{onClick:()=>{e||r(t.orderPda,G,t.profileIndex??0,l)},"aria-label":j("cancelOrder"),disabled:e||i||a,title:e?j("reviewTradingDisabled"):void 0,className:"p-1 text-muted-foreground hover:text-destructive hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",children:i?(0,w.jsx)(ep.Spinner,{className:"size-3.5"}):(0,w.jsx)(ec,{className:"w-3.5 h-3.5"})})}),(0,w.jsx)(k.TooltipContent,{side:"top",className:"text-xs px-2 py-1 whitespace-nowrap",showArrow:!1,children:j("cancelOrder")})]})]})})]}),(0,w.jsx)(rs.Dialog,{open:!e&&_,onOpenChange:e=>{e||A(!1)},children:(0,w.jsxs)(rs.DialogContent,{children:[(0,w.jsxs)(rs.DialogHeader,{className:"flex-col items-start",children:[(0,w.jsx)(rs.DialogTitle,{children:"ratchet"===E?j("trailingStopLossTitle"):"rsi"===E?j("rsiOrderTitle"):"TP/SL"}),(0,w.jsxs)("div",{className:"flex flex-col gap-1 pt-1",children:[(0,w.jsxs)("div",{className:"flex items-center gap-2",children:[(0,w.jsx)("span",{className:"text-sm font-medium text-foreground",children:q.symbol}),(0,w.jsx)("span",{className:(0,H.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded",K?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"),children:K?j("long"):j("short")}),Z>0&&(0,w.jsxs)("span",{className:"text-[10px] text-muted-foreground bg-surface-raised px-1.5 py-0.5 rounded",children:[Math.round(Z),"x"]})]}),(0,w.jsxs)("div",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 text-[11px]",children:[(0,w.jsxs)("div",{children:[(0,w.jsx)("span",{className:"text-label-muted inline-block w-[62px]",children:j("entryPrice")})," ",(0,w.jsxs)("span",{className:"text-foreground",children:["$",en>0?P.number(en):"—"]})]}),s&&s>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("span",{className:"text-label-muted inline-block w-[62px]",children:j("markPrice")})," ",(0,w.jsxs)("span",{className:"text-foreground",children:["$",P.number(s)]})]})]})]})]}),(0,w.jsx)(rA,{order:t,closeOrders:l,livePrices:o,onClose:()=>A(!1),onPositionChange:d,defaultOrderType:E})]})}),!e&&R&&(0,w.jsx)(rp,{order:t,open:R,onOpenChange:D,livePrice:s,onSuccess:d}),B&&(0,w.jsx)(rx,{open:!!B,onOpenChange:e=>{e||U(null)},order:(y="indicator"===B.orderType||"indicator_ratchet"===B.orderType,{source:"jupiter_native"===B.source?"jupiter_native":"imperial_passthrough",orderType:B.orderType,triggerPriceUsd:B.triggerPriceUsd,sizeUsd:B.sizeUsd,closeBps:B.closeBps,orderPda:B.orderPda,triggerCondition:B.triggerCondition,worstPriceUsd:B.ratchet?.worstPrice!=null?String(B.ratchet.worstPrice):void 0,ratchetSizeUsd:y?void 0:B.ratchet?.ratchetSize!=null?String(B.ratchet.ratchetSize):void 0,stopTriggerPriceUsd:B.ratchet?.stopTriggerPrice?String(B.ratchet.stopTriggerPrice):void 0,profileIndex:B.profileIndex,currentBestPriceUsd:B.ratchet?.bestPriceSeen!=null?String(B.ratchet.bestPriceSeen):void 0,currentIndicatorValue:B.indicator?.currentValue,indicatorThreshold:B.indicator?.thresholdValue!=null?String(B.indicator.thresholdValue):void 0,indicatorCondition:B.indicator?.indicatorCondition===1?"above":B.indicator?.indicatorCondition===0?"below":void 0,indicatorTimeframe:B.indicator?.timeframeCode!=null?rw.TIMEFRAME_LABELS[B.indicator.timeframeCode]:void 0,indicatorRatchetSize:"indicator_ratchet"===B.orderType&&B.ratchet?.ratchetSize?String(B.ratchet.ratchetSize):void 0,isReverseFib:B.ratchet?.isReverseFib}),asset:q.symbol,underwriter:B.underwriter??t.underwriter,side:B.side??t.side??"long",positionSizeUsd:t.sizeUsd,livePrice
2s:o,onCancelPassthroughOrder:e?void 0:Y})]})}function rB({id:e,...t}){let{attributes:r,listeners:i,setNodeRef:s,transform:n,transition:a,isDragging:l}=t9({id:e,disabled:t.readOnly}),o={transform:eD.Transform.toString(n),transition:a,zIndex:l?10:void 0};return(0,w.jsx)(rO,{...t,sortableRef:s,sortableStyle:o,sortableAttributes:r,dragHandleListeners:i,isDragging:l})}e.s(["UnfundedOrderBadge",0,rR],736679),e.s(["PackPositionBreakdown",0,function({priceCents:e,basisCents:t,awardCents:r,pnlUsd:i,tradingCostsUsd:s}){let n=(0,S.useTranslations)("rip"),{usdNumber:a}=(0,F.useFormatters)(),l=e=>`${e>=0?"+":"−"}${a(Math.abs(e))}`;return(0,w.jsxs)("div",{className:"w-full space-y-1.5 text-xs",children:[(0,w.jsxs)("dl",{className:"space-y-1 font-mono tabular-nums",children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("dt",{children:n("packTotalPaid")}),(0,w.jsx)("dd",{children:a(e/100)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("dt",{children:n("packCollateral")}),(0,w.jsx)("dd",{children:a(t/100)})]}),void 0!==r&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("dt",{children:n("packPnlAtIssue")}),(0,w.jsx)("dd",{children:l((r-t)/100)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("dt",{children:n("packFunded")}),(0,w.jsx)("dd",{children:a(r/100)})]}),(0,w.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,w.jsx)("dt",{children:n("packTradingCosts")}),(0,w.jsx)("dd",{children:null==s?n("valueUnknown"):a(s)})]})]}),null!=i&&(0,w.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border pt-1",children:[(0,w.jsx)("dt",{children:n("packReturn")}),(0,w.jsx)("dd",{children:l(i+(t-e)/100)})]})]}),(0,w.jsx)("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:n("packReceiptNote")})]})}],800239)},712963,e=>{e.v({annotation:"compact-history-module__hwKC6G__annotation",detailButton:"compact-history-module__hwKC6G__detailButton",identity:"compact-history-module__hwKC6G__identity",identityPrimary:"compact-history-module__hwKC6G__identityPrimary",metadata:"compact-history-module__hwKC6G__metadata",numeric:"compact-history-module__hwKC6G__numeric",scroller:"compact-history-module__hwKC6G__scroller",side:"compact-history-module__hwKC6G__side",stack:"compact-history-module__hwKC6G__stack",table:"compact-history-module__hwKC6G__table",tradeTable:"compact-history-module__hwKC6G__tradeTable"})},616341,725452,e=>{"use strict";var t=e.i(394390),r=e.i(942553),i=e.i(153517),s=e.i(894771),n=e.i(889572),a=e.i(299959);let l="marginAccount";function o(e){switch((0,n.healthBand)(e)){case"healthy":return"text-emerald-400";case"caution":return"text-yellow-400";case"risk":return"text-red-400";default:return"text-muted-foreground"}}function d(e){switch((0,n.healthBand)(e)){case"healthy":return"bg-emerald-400";case"caution":return"bg-yellow-400";default:return"bg-red-400"}}function c(e,t){return`$${e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2})}`}function u(e,t){return null===e?"—":c(e,t)}function h({health:e,projected:r,size:s="md"}){if(null===e)return(0,t.jsx)("span",{className:(0,i.cn)("sm"===s?"text-[10.5px]":"text-xs","text-muted-foreground"),children:"—"});let n=Math.max(1,Math.round(10*e)),a=null==r?n:Math.max(1,Math.round(10*r)),l=Math.min(n,a),c=Math.max(n,a),u=a<=n,p=d(u?r??e:e),m=d(u?e:r??e);return(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"flex gap-[2px]",children:Array.from({length:10},(e,r)=>(0,t.jsx)("i",{className:(0,i.cn)("rounded-[1px]","sm"===s?"w-[3.5px] h-[10px]":"w-[4px] h-3",r<l?p:r<c?(0,i.cn)(m,"opacity-40"):"bg-border-strong")},r))}),(0,t.jsxs)("span",{className:(0,i.cn)("font-mono tabular-nums","sm"===s?"text-[10.5px]":"text-xs",o(e)),children:[Math.round(100*e),"%"]}),null!=r&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:(0,i.cn)("text-muted-foreground","sm"===s?"text-[10px]":"text-[11px]"),children:"→"}),(0,t.jsxs)("span",{className:(0,i.cn)("font-mono tabular-nums","sm"===s?"text-[10.5px]":"text-xs",o(r)),children:[Math.round(100*r),"%"]})]})]})}function p({balanceUsd:e,onAdd:i,onWithdraw:s}){let n=(0,r.useTranslations)("positions"),l=(0,a.useFormatters)();return(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums",children:c(e,l.intlTag)}),(i||s)&&(0,t.jsxs)("span",{className:"inline-flex rounded border border-border-strong overflow-hidden",children:[(0,t.jsx)("button",{onClick:s,disabled:!s,title:n("marginAccountRemoveTitle"),"aria-label":n("marginAccountRemoveAria"),className:"px-1.5 py-[2px] text-[11px] leading-none text-secondary-foreground bg-surface-interactive hover:bg-surface-raised disabled:opacity-40 cursor-pointer disabled:cursor-default",children:"−"}),(0,t.jsx)("button",{onClick:i,disabled:!i,title:n("marginAccountAddTitle"),"aria-label":n("marginAccountAddAria"),className:"px-1.5 py-[2px] text-[11px] leading-none text-secondary-foreground bg-surface-interactive hover:bg-surface-raised border-l border-border-strong disabled:opacity-40 cursor-pointer disabled:cursor-default",children:"+"})]})]})}function m(e){let t=(0,r.useTranslations)("positions"),{profiles:i}=(0,s.useProfile)();return null==e||i.length<=e?null:i[e]?.name??t("profileFallbackName",{index:e+1})}e.s(["MARGIN_ACCOUNT_LABEL_KEY",0,l,"marginModeLabelKey",0,function(e){return"unified"===e||"cross"===e?"marginModeCross":"marginModeIsolated"}],725452),e.s(["CrossSeatStrip",0,function({seat:e,onAddCollateral:i,onWithdrawCollateral:s}){let n=(0,r.useTranslations)("positions"),o=(0,r.useTranslations)("terms"),d=(0,a.useFormatters)(),f=m(e.profileIndex);return(0,t.jsxs)("div",{className:"flex items-center gap-0 px-4 py-2 bg-surface-raised border-b border-border font-mono tabular-nums",children:[(0,t.jsxs)("span",{className:"text-[10px] font-semibold text-primary bg-primary/15 rounded px-1.5 py-[3px] whitespace-nowrap",children:[e.venueLabel&&`${e.venueLabel} \xb7 `,o(l)]}),f&&(0,t.jsx)("span",{className:"text-[10px] font-medium text-secondary-foreground bg-surface-interactive rounded px-1.5 py-[3px] ml-2 whitespace-nowrap",children:f}),(0,t.jsx)("span",{className:"w-px self-stretch bg-border mx-4"}),(0,t.jsxs)("div",{className:"flex flex-col gap-px whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-[9px] text-label-muted",children:n("seatBalance")}),(0,t.jsx)(p,{balanceUsd:e.balanceUsd,onAdd:i&&(()=>i(e)),onWithdraw:s&&(()=>s(e))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-px whitespace-nowrap ml-6",children:[(0,t.jsx)("span",{className:"text-[9px] text-label-muted",children:n("seatUsed")}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:u(e.usedUsd,d.intlTag)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-px whitespace-nowrap ml-6",children:[(0,t.jsx)("span",{className:"text-[9px] text-label-muted",children:n("seatFree")}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:c(e.freeUsd,d.intlTag)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-px whitespace-nowrap ml-6",children:[(0,t.jsx)("span",{className:"text-[9px] text-label-muted",children:n("seatHealth")}),(0,t.jsx)(h,{health:e.health})]})]})},"HealthMeter",0,h,"MobileCrossSeatCard",0,function({seat:e,onAddCollateral:i,onWithdrawCollateral:s}){let n=(0,r.useTranslations)("positions"),o=(0,r.useTranslations)("terms"),d=(0,a.useFormatters)(),f=m(e.profileIndex);return(0,t.jsxs)("div",{className:"bg-surface border border-primary/40 rounded-lg overflow-hidden",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 pt-3 pb-1",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)("i",{className:"w-2 h-2 rounded-[2px] bg-primary"}),e.venueLabel&&`${e.venueLabel} \xb7 `,o(l)]}),f&&(0,t.jsx)("span",{className:"text-[10px] font-medium text-secondary-foreground bg-surface-interactive rounded px-1.5 py-0.5",children:f})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-y-2.5 gap-x-2 px-3 pb-3 pt-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:n("seatBalance")}),(0,t.jsx)(p,{balanceUsd:e.balanceUsd,onAdd:i&&(()=>i(e)),onWithdraw:s&&(()=>s(e))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:n("seatUsed")}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:u(e.usedUsd,d.intlTag)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:n("seatFree")}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:c(e.freeUsd,d.intlTag)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:n("seatHealth")}),(0,t.jsx)(h,{health:e.health})]})]})]})}],616341)},888245,e=>{e.v({actions:"desktop-positions-module__97CVUq__actions",automation:"desktop-positions-module__97CVUq__automation",automationButton:"desktop-positions-module__97CVUq__automationButton",closeButton:"desktop-positions-module__97CVUq__closeButton",expandButton:"desktop-positions-module__97CVUq__expandButton",feeLine:"desktop-positions-module__97CVUq__feeLine",feesCell:"desktop-positions-module__97CVUq__feesCell",identityDetails:"desktop-positions-module__97CVUq__identityDetails",identityLine:"desktop-positions-module__97CVUq__identityLine",leverage:"desktop-positions-module__97CVUq__leverage",marketButton:"desktop-positions-module__97CVUq__marketButton",ordersTable:"desktop-positions-module__97CVUq__ordersTable",overflowButton:"desktop-positions-module__97CVUq__overflowButton",receipt:"desktop-positions-module__97CVUq__receipt",scroll:"desktop-positions-module__97CVUq__scroll",shareButton:"desktop-positions-module__97CVUq__shareButton",strategyButton:"desktop-positions-module__97CVUq__strategyButton",strategyCount:"desktop-positions-module__97CVUq__strategyCount",strategyMenu:"desktop-positions-module__97CVUq__strategyMenu",strategyRow:"desktop-positions-module__97CVUq__strategyRow",table:"desktop-positions-module__97CVUq__table"})},20446,e=>{"use strict";e.s(["HistoryTab",()=>z],20446);var t=e.i(394390),r=e.i(183023),i=e.i(943494),s=e.i(845165),n=e.i(942553),a=e.i(268680),l=e.i(450358),o=e.i(305085),d=e.i(712963),c=e.i(299959);
2function u(e,t){return`+$${(e/1e6).toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2})}`}function h(e,t){return new Date(1e3*e).toLocaleDateString(t,{month:"short",day:"numeric"})}function p(e){return e&&e.split(" · ")[0].replace(/\s+\d{4}-\d{2}-\d{2}T\d{2}$/,"").trim()||null}function m({signature:e}){return(0,t.jsx)("a",{href:`https://solscan.io/tx/${e}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:(0,t.jsx)(s.ExternalLink,{className:"w-3.5 h-3.5"})})}function f({payout:e}){let r=(0,n.useTranslations)("positions"),i=(0,c.useFormatters)();return(0,t.jsxs)("tr",{className:"border-b border-border hover:bg-surface-interactive/50 transition-colors",children:[(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsxs)("div",{className:d.default.identity,children:[(0,t.jsxs)("div",{className:d.default.identityPrimary,children:[(0,t.jsx)("span",{className:`${d.default.side} bg-emerald-500/20 text-emerald-400`,children:r("rewardBadge")}),(0,t.jsx)("span",{"aria-hidden":"true",children:"🎉"}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground truncate max-w-[140px]",title:e.notes??void 0,children:p(e.notes)??r("rewardFallbackLabel")})]}),(0,t.jsx)("div",{className:d.default.metadata,children:r("rewardDepositedNote")})]})}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground",children:h(e.paidAt,i.intlTag)}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground",children:"—"}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground",children:"—"}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground",children:"—"}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-side-long font-mono tabular-nums",children:u(e.amountUsdcBase,i.intlTag)}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground",children:"—"}),(0,t.jsx)("td",{className:"py-3 px-3",children:e.transactionSignature?(0,t.jsx)(m,{signature:e.transactionSignature}):(0,t.jsx)("span",{className:"text-muted-foreground text-[10px]",children:r("rewardPending")})})]})}function x({payout:e}){let r=(0,n.useTranslations)("positions"),i=(0,c.useFormatters)();return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg p-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400",children:r("rewardBadge")}),(0,t.jsx)("span",{"aria-hidden":"true",children:"🎉"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:h(e.paidAt,i.intlTag)})]}),(0,t.jsx)("div",{className:"text-sm text-foreground mt-2 truncate",title:e.notes??void 0,children:p(e.notes)??r("rewardFallbackLabel")}),(0,t.jsxs)("div",{className:"mt-3 flex items-end justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:r("amountUsdc")}),(0,t.jsx)("div",{className:"text-2xl font-semibold text-side-long font-mono tabular-nums",children:u(e.amountUsdcBase,i.intlTag)})]}),e.transactionSignature&&(0,t.jsx)("div",{className:"shrink-0 pb-1",children:(0,t.jsx)(m,{signature:e.transactionSignature})})]}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground mt-3",children:r("rewardDepositedNote")})]})}var g=e.i(670374),b=e.i(26826),v=e.i(986759),y=e.i(894771),w=e.i(619966),j=e.i(153517),S=e.i(259048),k=e.i(679278),N=e.i(116082),P=e.i(803817),T=e.i(213076),C=e.i(623075),M=e.i(924416),_=e.i(740713),A=e.i(875574),E=e.i(566314),L=e.i(101735),F=e.i(510079);let R=(e,t)=>e.amountMicros===t.amountMicros&&e.amountUsd===t.amountUsd&&e.mint===t.mint&&e.treasury===t.treasury;function D({className:e,compact:s=!1,toolbarTarget:l}){let o=(0,n.useTranslations)("positions"),d=(0,r.useId)(),c=(0,r.useId)(),u=(0,P.useRouter)(),h=(0,_.useReportOwnerSession)(),{publicKey:p}=(0,A.useUnifiedWalletContext)(),m=(0,M.useReportEligibility)(),{data:f,isLoading:x}=m,g=(0,M.useGenerateReport)(),b=(0,M.useReportGenerating)(),{pay:v,quote:y,paying:w,canPay:S,mobileSessionCannotPay:I,paymentPhase:U,pendingPayment:O,paymentBlockedReason:B,completePayment:z}=(0,L.useReportPayment)(),[$,V]=(0,r.useState)(!1),[H,W]=(0,r.useState)(!1),[q,K]=(0,r.useTransition)(),[G,Y]=(0,r.useState)(null),X=(0,r.useRef)(!1),Q=(0,r.useRef)(null),J=(0,r.useRef)({session:h,quote:y});J.current={session:h,quote:y};let Z=m.error instanceof F.ReportApiError&&401===m.error.status||g.error instanceof F.ReportApiError&&401===g.error.status&&g.variables?.jwt===h;if(p&&(!h||Z)){let r=(0,t.jsx)(E.ReportOwnerVerification,{compact:s,className:e});return s?l?(0,k.createPortal)(r,l):null:r}if(x||!f?.eligible)return null;let ee=f.reports[0],et=f.credits>0,er=f.freeReportAvailable&&et,ei=y?.amountUsd??f.priceUsd,es=$||w||b||g.isPending,en=(!et||O)&&(!!B||
2!S),ea=!!G&&!!y&&G.session===h&&G.latestReportId===(ee?.id??null)&&R(G.quote,y),el=async e=>{if(X.current||es)return;X.current=!0,V(!0),W(!0),Y(null);let t=!1,r=null;try{let i=await m.refetch();if(i.isError||!i.data?.eligible)throw Error(o("reportEligibilityChanged"));if(J.current.session!==h)throw Error(o("reportSessionChanged"));if(W(!1),O||i.data.credits<1){if(!O&&(!e||!y||e.session!==h||!J.current.quote||!R(e.quote,J.current.quote)))throw Error(o("reportCreditUsed"));let i=await v(e?{expectedLatestReportId:e.latestReportId}:void 0);if(r=i.signature,t=!!i.signature,i.existingReportId)return void N.toast.info(o("reportPaymentNeedsReview"))}if(J.current.session!==h)throw Error(o("reportSessionChanged"));await g.mutateAsync(),r&&await z(r)}catch(e){e instanceof L.MobileSessionCannotPayError?N.toast.error(o("reportMobilePaymentUnavailable")):e instanceof F.ReportApiError&&e.needsPayment?N.toast.error(o(t?"reportPaidCreditUnavailable":"reportCreditUsed")):(console.error("[report] generate",e),N.toast.error(e instanceof Error?e.message:o("reportFailed")))}finally{X.current=!1,W(!1),V(!1)}},eo=()=>{if(!es&&!en){if(O||et)return el();y&&Y({quote:{...y},session:h,latestReportId:ee?.id??null})}},ed=()=>{ee&&!q&&K(()=>u.push(`/report/${ee.id}`))},ec=O?o("reportCheckPayment"):er?o("reportGenerate"):et?o("reportGenerateNew"):o("reportGeneratePaid",{price:ei.toFixed(2)}),eu=H?o("reportChecking"):"awaiting-wallet"===U?o("reportAwaitingWallet"):"confirming"===U?o("reportConfirmingPayment"):w?o("reportPreparingPayment"):o("reportReadingHistory"),eh=(en?B:null)||(et||O||!I?O?o("reportPendingPaymentHint"):es?o("reportWorkingHint"):null:o("reportMobilePaymentUnavailable")),ep=(0,t.jsx)(C.Dialog,{open:!!G,onOpenChange:e=>!e&&Y(null),children:(0,t.jsxs)(C.DialogContent,{className:"sm:max-w-md",onOpenAutoFocus:e=>{e.preventDefault(),Q.current?.focus()},children:[(0,t.jsx)(C.DialogHeader,{children:(0,t.jsx)(C.DialogTitle,{className:"pr-8",children:o("reportPaymentTitle")})}),(0,t.jsxs)("div",{className:"space-y-3 px-4",children:[(0,t.jsx)(C.DialogDescription,{children:o("reportDescription",{count:f.closedTrades})}),(0,t.jsx)("p",{className:"text-sm text-text-secondary",children:o("reportPaymentDescription")}),(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-[5px] border border-border bg-canvas px-3 py-3",children:[(0,t.jsx)("span",{className:"text-sm text-text-secondary",children:o("reportPaymentCost")}),(0,t.jsxs)("span",{className:"font-mono text-base font-semibold",children:[G?.quote.amountUsd.toFixed(2)," USDC"]})]}),(0,t.jsx)("p",{className:"text-sm text-text-secondary",children:o("reportPaymentWallet")}),(0,t.jsx)("p",{className:"text-xs text-text-muted",children:o("reportPaymentRecovery")}),!ea&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-amber-400",children:o("reportQuoteChanged")})]}),(0,t.jsxs)(C.DialogFooter,{children:[(0,t.jsx)(T.Button,{ref:Q,variant:"ghost",onClick:()=>Y(null),children:o("reportCancel")}),(0,t.jsx)(T.Button,{disabled:!ea||es||en,onClick:()=>G&&el(G),children:o("reportConfirmPurchase",{price:G?.quote.amountUsd.toFixed(2)??ei.toFixed(2)})})]})]})});return s?l?(0,k.createPortal)((0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:(0,j.cn)("relative inline-flex shrink-0 items-center py-1",e),"data-report-control":!0,children:[er&&!ee&&!es&&(0,t.jsx)("span",{id:d,className:"pointer-events-none absolute right-1 -top-px z-10 rounded-full border border-canvas bg-brand-orange px-1.5 text-[9px] font-medium leading-[11px] text-black",children:o("reportFree")}),(0,t.jsx)(a.TooltipProvider,{children:(0,t.jsxs)(a.Tooltip,{children:[(0,t.jsx)(a.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:!ee&&en&&eh?0:void 0,"aria-describedby":eh?c:void 0,className:"inline-flex rounded focus-visible:outline-2 focus-visible:outline-ring",children:(0,t.jsxs)(T.Button,{type:"button",onClick:ee?ed:eo,disabled:q||!ee&&(es||en),"aria-busy":q||!ee&&es,"aria-describedby":[er&&!ee&&!es?d:null,eh?c:null].filter(Boolean).join(" ")||void 0,className:"h-6 min-h-0 gap-1.5 rounded-[4px] px-2 py-1 text-xs",children:[(q||!ee&&es)&&(0,t.jsx)(i.Loader2,{className:"size-3 animate-spin"}),q?o("reportOpening"):ee?o("reportView"):es?eu:ec]})})}),eh&&(0,t.jsx)(a.TooltipContent,{id:c,side:"top",className:"max-w-64 text-xs",children:eh})]})}),ee&&(0,t.jsxs)(T.Button,{type:"button",variant:"outline",disabled:es||q||en,onClick:eo,"aria-busy":es,"aria-describedby":eh?c:void 0,className:"ml-1.5 h-6 min-h-0 rounded-[4px] px-2 py-1 text-xs",children:[es&&(0,t.jsx)(i.Loader2,{className:"size-3 animate-spin"}),es?eu:O?o("reportCheckPayment"):et?o("reportNew"):o("reportNewPaid",{price:ei.toFixed(2)})]}),es&&(0,t.jsxs)("span",{className:"sr-only",role:"status",children:[eu,". ",o("reportWorkingHint")]})]}),ep]}),l):null:(0,t.jsxs)("div",{className:(0,j.cn)("flex flex-col gap-4 roun
2ded-lg border border-brand-orange/30 bg-surface p-5",e),children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-base font-medium text-text-primary",children:"Your trading report"}),er&&(0,t.jsx)("span",{className:"rounded-full bg-brand-orange/15 px-2 py-0.5 text-[10px] text-brand-orange",children:o("reportFree")})]}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-text-secondary",children:`A scored read of every one of your ${f.closedTrades.toLocaleString()} closed trades — where the money actually went, the habit behind it, and what to change.`})]}),eh&&(0,t.jsx)("p",{className:"text-xs text-text-muted",children:eh}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)(T.Button,{onClick:ee?ed:eo,disabled:q||!ee&&(es||en),"aria-busy":q||!ee&&es,children:[(q||!ee&&es)&&(0,t.jsx)(i.Loader2,{className:"size-3 animate-spin"}),q?o("reportOpening"):ee?o("reportView"):es?eu:ec]}),ee&&(0,t.jsxs)(T.Button,{variant:"ghost",onClick:eo,disabled:es||en,"aria-busy":es,children:[es&&(0,t.jsx)(i.Loader2,{className:"size-3 animate-spin"}),es?eu:ec]})]}),ep]})}function I(e){let t=Date.parse(e.timestamp);return Number.isFinite(t)?Math.floor(t/1e3):0}function U({action:e}){let r=(0,n.useTranslations)("positions"),i=(0,c.useFormatters)(),a="buy"===e.actionType,l=r("liquidation"===e.actionType?"historyActionLiquidation":a?"historyActionBuy":"historyActionSell");return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg px-3 py-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:e.asset}),(0,t.jsx)("span",{className:(0,j.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded","liquidation"===e.actionType?"bg-amber-500/20 text-amber-400":a?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"),children:l}),(0,t.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-300",children:"Phoenix Direct"})]}),e.transactionSignature&&(0,t.jsx)("a",{href:`https://orbmarkets.io/tx/${e.transactionSignature}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:(0,t.jsx)(s.ExternalLink,{className:"w-3.5 h-3.5"})})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:r("historyColPrice")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:i.rawPrice(e.price)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:r("historyColBaseQty")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:e.baseQty})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:r("historyColQuoteQty")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:i.rawUsd(e.quoteQty)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:r("historyColRealizedPnl")}),(0,t.jsxs)("div",{className:(0,j.cn)("text-xs font-mono tabular-nums",(0,S.pnlColor)((0,b.parseRawValue)(e.realizedPnl))),children:[(0,b.parseRawValue)(e.realizedPnl)>=0?"+":"",i.rawUsd(e.realizedPnl)]})]})]}),(0,t.jsx)("div",{className:"mt-2 text-[10px] text-label-muted",children:i.dateTime(I(e))})]})}function O({action:e}){let r=(0,n.useTranslations)("positions"),i=(0,n.useTranslations)("terms"),a=(0,c.useFormatters)(),l="buy"===e.actionType,o=r("liquidation"===e.actionType?"historyActionLiquidation":l?"historyActionBuy":"historyActionSell");return(0,t.jsxs)("tr",{className:"border-b border-border/50",children:[(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:a.dateTime(I(e))}),(0,t.jsx)("td",{className:"px-3 py-2",children:(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:(0,j.cn)("text-xs font-medium",l?"text-side-long":"text-side-short"),children:o}),(0,t.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-300 whitespace-nowrap",children:"Phoenix Direct"})]})}),(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:e.instructionType||r("historyOrderTypeMarket")}),(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:a.rawPrice(e.price)}),(0,t.jsxs)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:[e.baseQty," ",e.asset]}
2),(0,t.jsxs)("td",{className:"px-3 py-2 text-xs font-mono tabular-nums",children:[(0,t.jsx)("div",{className:"text-foreground",children:a.rawUsd(e.quoteQty)}),(0,t.jsxs)("div",{className:(0,S.pnlColor)((0,b.parseRawValue)(e.realizedPnl)),children:[i("pnl")," ",(0,b.parseRawValue)(e.realizedPnl)>=0?"+":"",a.rawUsd(e.realizedPnl)]})]}),(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-amber-400 font-mono tabular-nums",children:a.rawUsd(e.fees)}),(0,t.jsx)("td",{className:"px-3 py-2",children:e.transactionSignature&&(0,t.jsx)("a",{href:`https://orbmarkets.io/tx/${e.transactionSignature}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:(0,t.jsx)(s.ExternalLink,{className:"w-3.5 h-3.5"})})})]})}function B({message:e,filtersActive:r,onResetFilters:i}){let s=(0,n.useTranslations)("positions");return(0,t.jsxs)("div",{className:"py-12 text-center space-y-3",children:[(0,t.jsx)("div",{className:"text-muted-foreground text-sm",children:e}),r&&(0,t.jsx)("button",{onClick:i,className:"px-4 py-1.5 text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors",children:s("historyResetFilters")})]})}function z({reportToolbarTarget:e,lifecycles:u,rewardPayouts:h=[],lifetimeStats:p,chainActions:m,chainLoading:k,phoenixDirectActions:N=[],dataSource:P="api",dbDown:T,isLoading:C,unverifiedRead:M=!1,filtersActive:_,onResetFilters:A,sideFilter:E,assetFilter:L,period:F,customDateFrom:R,customDateTo:$,hasMore:V,isFetchingNextPage:H,onLoadMore:W,phoenixDirectHasMore:q,phoenixDirectLoadingMore:K,phoenixDirectReadBlocked:G,onLoadMorePhoenixDirect:Y}){let X=(0,n.useTranslations)("positions"),Q=(0,n.useTranslations)("terms"),J=(0,c.useFormatters)(),{profiles:Z}=(0,y.useProfile)(),ee=(0,w.useIsDesktop)(),et=!1!==ee&&void 0!==e,er=p?parseFloat(p.pnlUsd):NaN,ei=(0,r.useMemo)(()=>{let e=u.map(e=>({kind:"position",at:e.closedAt??e.openedAt,lifecycle:e}));if("all"!==E||"all"!==L||0===h.length)return e;let t=e.length?Math.min(...e.map(e=>e.at)):0;return[...e,...h.filter(e=>e.paidAt>=t&&(e=>{let t;if("ALL"===F)return!0;if("CUSTOM"===F)return!(R&&e<new Date(R).getTime()/1e3||$&&e>=new Date($).getTime()/1e3+86400);let r=new Date;if("WTD"===F){let e=r.getDay();t=new Date(r.getFullYear(),r.getMonth(),r.getDate()-(0===e?6:e-1)).getTime()/1e3}else t="MTD"===F?new Date(r.getFullYear(),r.getMonth(),1).getTime()/1e3:new Date(r.getFullYear(),0,1).getTime()/1e3;return e>=t})(e.paidAt)).map(e=>({kind:"reward",at:e.paidAt,payout:e}))].sort((e,t)=>t.at-e.at)},[u,h,E,L,F,R,$]),es=(0,r.useMemo)(()=>[...(m??[]).map(e=>({kind:"jupiter_chain",timestamp:e.tx1Timestamp??0,action:e})),...N.map(e=>({kind:"phoenix_direct",timestamp:I(e),action:e}))].sort((e,t)=>t.timestamp-e.timestamp),[m,N]);if("chain"===P&&es.length>0)return(0,t.jsxs)("div",{className:"h-full overflow-y-auto",children:[(0,t.jsx)("div",{className:"px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-xs text-amber-400",children:X("historyChainDataNotice")}),!1===ee&&(0,t.jsx)("div",{className:"space-y-3 p-3",children:es.map(e=>{if("phoenix_direct"===e.kind)return(0,t.jsx)(U,{action:e.action},`phoenix-${e.action.id}`);let r=e.action,i="increase"===r.actionType,n=(0,b.parseRawValue)(r.collateralDelta),a=r.tx2Signature||r.tx1Signature;return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg px-3 py-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${i?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i?X("historyActionIncrease"):"liquidation"===r.actionType?X("historyActionLiquidation"):"max_payoff_close"===r.actionType?X("historyActionMaxPayoff"):X("historyActionDecrease")}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[r.asset??"SOL"," ",r.side??""]})]}),a&&(0,t.jsx)("a",{href:`https://orbmarkets.io/tx/${a}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400",children:(0,t.jsx)(s.ExternalLink,{className:"w-3.5 h-3.5"})})]}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:X("historyColPrice")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:J.rawPrice(r.entryPrice)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:Q("size.full")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:J.rawUsd(r.sizeDelta)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:X("historyColCollateral")}),(0,t.jsxs)("div",{className:`text-xs font-mono tabular-nums ${(0,S.pnlColor)(n)}`,children:[n>=0?"+":"",J.rawUsd(r.collateralDelta)]})]})]}),(0,t.jsx)("div",{className:"mt-2 text-[10px] text-label-muted",children:J.dateTime(r.tx1Timestamp)})]},`jupiter-${r.id}`)})}),ee&&(0,t.jsx)("div",{className:d.default.scroller,children:(0,t.jsxs)("table",{className:d.default.table,children:[(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColTime")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColSource")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColAction")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColPrice")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColSizeDelta")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyColCollateralDelta")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:X("historyRowFees")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left",children:"Tx"})]})}),(0,t.jsx)("tbody",{children:es.map(e=>{if("phoenix_direct"===e.kind)return(0,t.jsx)(O,{action:e.action},`phoenix-${e.action.id}`);let r=e.action,i="increase"===r.actionType,s=(0,b.parseRawValue)(r.jupiterFee),n=(0,b.parseRawValue)(r.interest),l=`$${(s+n).toLocaleStr
2ing(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`,o=(0,b.parseRawValue)(r.collateralDelta);return(0,t.jsxs)("tr",{className:"border-b border-border/50",children:[(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:J.dateTime(r.tx1Timestamp)}),(0,t.jsx)("td",{className:"px-3 py-2",children:(()=>{let e=r.source??"Direct",i=e.match(/^Profile (\d+)$/);if(i){let r=parseInt(i[1],10)-1,s=Z[r],n=s?.name??e,a=g.PROFILE_TAG_COLORS[r]??g.PROFILE_TAG_COLORS[0];return(0,t.jsx)("span",{className:(0,j.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded",a),children:n})}return(0,t.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-orange-500/20 text-orange-400",children:"Jupiter"})})()}),(0,t.jsx)("td",{className:"px-3 py-2",children:(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:`text-xs font-medium ${i?"text-side-long":"text-side-short"}`,children:i?X("historyActionIncrease"):"liquidation"===r.actionType?X("historyActionLiquidation"):"max_payoff_close"===r.actionType?X("historyActionMaxPayoff"):X("historyActionDecrease")}),(0,t.jsxs)("span",{className:"text-xs text-label-muted",children:[r.asset??"SOL"," ",r.side??""]})]})}),(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:J.rawPrice(r.entryPrice)}),(0,t.jsx)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:J.rawUsd(r.sizeDelta)}),(0,t.jsx)("td",{className:"px-3 py-2",children:(0,t.jsxs)("span",{className:`text-xs font-mono tabular-nums ${(0,S.pnlColor)(o)}`,children:[o>=0?"+":"",J.rawUsd(r.collateralDelta)]})}),(0,t.jsx)("td",{className:"px-3 py-2",children:(0,t.jsx)(a.TooltipProvider,{children:(0,t.jsxs)(a.Tooltip,{children:[(0,t.jsx)(a.TooltipTrigger,{className:"cursor-help",children:(0,t.jsx)("span",{className:"text-xs text-amber-400 font-mono tabular-nums underline decoration-dotted underline-offset-2",children:l})}),(0,t.jsx)(a.TooltipContent,{side:"top",className:"font-mono text-xs",children:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-semibold mb-2",children:X("historyFeeBreakdown")}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeOpenClose")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:null!=r.pairsImpactFee?J.usdNumber((0,g.openCloseFeeExImpact)(r.jupiterFee,r.pairsImpactFee)):J.rawUsd(r.jupiterFee)})]}),null!=r.pairsImpactFee&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeSkewImpact")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:J.rawUsd(r.pairsImpactFee)})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeInterest")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:J.rawUsd(r.interest)})]})]})})]})})}),(0,t.jsx)("td",{className:"px-3 py-2",children:(0,t.jsx)(v.TxLinks,{tx1Signature:r.tx1Signature,tx2Signature:r.tx2Signature,tx3Signature:r.tx3Signature})})]},`jupiter-${r.id}`)})})]})}),q&&Y&&(0,t.jsx)("div",{className:"p-3",children:(0,t.jsxs)("button",{onClick:Y,disabled:K||G,className:"w-full py-2.5 text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors flex items-center justify-center gap-2",children:[K&&(0,t.jsx)(i.Loader2,{className:"h-3.5 w-3.5 animate-spin"}),K?X("historyLoading"):X("historyLoadMorePhoenixFills")]})})]});let en=C?null:0===ei.length?null===p?X("accountReadTotalsUnavailable"):T&&k?X("historyEmptyChainLoading"):M?X("accountReadNoHistoryToDisplay"):T?X("historyEmptyDbUnavailable"):_?X("historyEmptyFiltered"):X("historyEmptyNoClosedPositions"):null;return C&&0===ei.length&&0===N.length?(0,t.jsxs)("div",{className:"flex items-center justify-center py-12",role:"status",children:[(0,t.jsx)(i.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground","aria-hidden":"true"}),(0,t.jsx)("span",{className:"sr-only",children:X("loadingEllipsis")})]}):null===p&&0===ei.length&&N.length>0?(0,t.jsxs)("div",{className:"space-y-3 p-3",children:[(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:X("accountReadTotalsUnavailable")}),N.map(e=>(0,t.jsx)(U,{action:e},e.id))]}):en?(0,t.jsx)(B,{message:en,filtersActive:_&&!T,onResetFilters:A}):(0,t.jsxs)("div",{className:"h-full overflow-y-auto",children:[(0,t.jsx)("div",{className:et?"contents":"p-3",children:(0,t.jsx)(D,{compact:et,toolbarTarget:e})}),!1===ee&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[(0,t.jsxs)("div",{className:`text-xs font-mono tabular-nums ${(0,S.pnlColor)(er)}`,children:[X("historyPnlLabel")," ",Number.isFinite(er)?`${er>=0?"+":""}
2$${er.toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"]}),(0,t.jsxs)("div",{className:"text-xs text-amber-400 font-mono tabular-nums",children:[X("historyFeesLabel")," ",p?`$${parseFloat(p.feesUsd).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"]})]}),(0,t.jsxs)("div",{className:"space-y-3 p-3",children:[ei.map(e=>"reward"===e.kind?(0,t.jsx)(x,{payout:e.payout},`reward-${e.payout.id}`):(0,t.jsx)(o.MobilePositionCard,{lifecycle:e.lifecycle,onClosePosition:()=>{},showDateColumn:!0,dcaGrouping:!0},e.lifecycle.id)),V&&W&&(0,t.jsxs)("button",{onClick:W,disabled:H,className:"w-full py-2.5 text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors flex items-center justify-center gap-2",children:[H?(0,t.jsx)(i.Loader2,{className:"h-3.5 w-3.5 animate-spin"}):null,H?X("historyLoading"):X("historyLoadMore")]})]})]}),ee&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:d.default.scroller,children:(0,t.jsxs)("table",{className:(0,j.cn)(d.default.table,d.default.tradeTable),children:[(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[130px] sticky left-0 z-20 bg-canvas",children:X("historyColPosition")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:X("historySectionDate")}),(0,t.jsxs)("th",{className:"py-2.5 px-3 text-left",children:[(0,t.jsx)("div",{children:X("historyColMaxSize")}),(0,t.jsx)("div",{className:"text-[10px] text-muted-foreground font-normal font-mono tabular-nums cursor-help",title:X("historyTitleCumulativeSize"),children:p?`$${parseFloat(p.cumulativeSizeUsd).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"})]}),(0,t.jsxs)("th",{className:"py-2.5 px-3 text-left",children:[(0,t.jsx)("div",{children:X("historyColMaxCollateral")}),(0,t.jsx)("div",{className:"text-[10px] text-muted-foreground font-normal font-mono tabular-nums cursor-help",title:X("historyTitleTotalCollateralDeposited"),children:p?`$${parseFloat(p.collateralUsd).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"})]}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:X("historyColAvgEntryExit")}),(0,t.jsxs)("th",{className:"py-2.5 px-3 text-left",children:[(0,t.jsx)("div",{children:Q("pnl")}),(0,t.jsx)("div",{className:`text-[10px] font-normal font-mono tabular-nums cursor-help ${(0,S.pnlColorDim)(er)}`,title:X("historyTitleTotalPnl"),children:Number.isFinite(er)?`${er>=0?"+":""}$${er.toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"})]}),(0,t.jsxs)("th",{className:"py-2.5 px-3 text-left",children:[(0,t.jsx)("div",{children:X("historyRowFees")}),p?(0,t.jsx)(a.TooltipProvider,{children:(0,t.jsxs)(a.Tooltip,{children:[(0,t.jsx)(a.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("div",{className:"text-[10px] text-yellow-500/70 font-normal font-mono tabular-nums cursor-help underline decoration-dotted underline-offset-2",children:["$",parseFloat(p.feesUsd).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})}),(0,t.jsx)(a.TooltipContent,{side:"top",className:"font-mono text-xs",children:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-semibold mb-2",children:X("historyTotalFeeBreakdown")}),parseFloat(p.feeBreakdown.proOrderFee)>0&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeProOrder")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",parseFloat(p.feeBreakdown.proOrderFee).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeImperial")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",parseFloat(p.feeBreakdown.platformFee).toLocaleStr
2ing(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeSlippage")}),(0,t.jsxs)("span",{className:(0,j.cn)("font-mono tabular-nums",0>parseFloat(p.feeBreakdown.slippage)?"text-side-long":void 0),children:[0>parseFloat(p.feeBreakdown.slippage)?"-":"","$",Math.abs(parseFloat(p.feeBreakdown.slippage)).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeInterest")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",parseFloat(p.feeBreakdown.interest).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeOpenCloseFees")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:null!=p.feeBreakdown.pairsImpactFee?J.usdNumber((0,g.openCloseFeeExImpact)(p.feeBreakdown.jupiterFee,p.feeBreakdown.pairsImpactFee)):`$${parseFloat(p.feeBreakdown.jupiterFee).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`})]}),null!=p.feeBreakdown.pairsImpactFee&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:X("historyFeeSkewImpact")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",parseFloat(p.feeBreakdown.pairsImpactFee).toLocaleString(J.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]})]})})]})}):(0,t.jsx)("span",{children:"—"})]}),(0,t.jsx)("th",{children:(0,t.jsx)("span",{className:"sr-only",children:X("columnActions")})})]})}),(0,t.jsx)("tbody",{children:ei.map(e=>"reward"===e.kind?(0,t.jsx)(f,{payout:e.payout},`reward-${e.payout.id}`):(0,t.jsx)(l.PositionRow,{lifecycle:e.lifecycle,onClosePosition:()=>{},showDateColumn:!0,dcaGrouping:!0},e.lifecycle.id))})]})}),V&&W&&(0,t.jsx)("div",{className:"flex justify-center py-3 border-t border-border",children:(0,t.jsxs)("button",{onClick:W,disabled:H,className:"px-6 py-2 text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors flex items-center gap-2",children:[H?(0,t.jsx)(i.Loader2,{className:"h-3.5 w-3.5 animate-spin"}):null,H?X("historyLoading"):X("historyLoadMore")]})})]})]})}},334281,691887,e=>{"use strict";e.s(["IncompletePosition",()=>b,"IncompletePositionIdentity",()=>g],334281),e.s(["useManualCloseTarget",()=>u],691887);var t=e.i(394390),r=e.i(183023),i=e.i(942553),s=e.i(116082),n=e.i(365221);e.i(875574);var a=e.i(142298),l=e.i(687229),o=e.i(432533),d=e.i(937505),c=e.i(631193);function u(e,t=100){let{publicKey:r}=(0,a.useUnifiedWallet)(),i=r?.toBase58()??null,{cache:s,auth:h,ready:p}=(0,o.useAccountReadSession)(),{blockedPartialIds:m,manualClosePriceObservations:f}=(0,l.useUnifiedPositions)(),{slippageBps:x}=(0,c.useSlippageBps)();if(!e)return{status:"unavailable",reason:"identity"};let g=(0,n.closeMarketFor)(e.row.underwriter,e.row.asset,"partial"===e.kind?e.row.marketMint:void 0),b=i?s.available((0,d.positionsKey)(i),h):null,v=g?f[g.marketMint]??null:null,y="full"===e.kind||b?.exits.some(t=>t===e.row);return(0,n.resolveManualClose)(e,{wallet:i,current:p&&!!y,visibility:b?.metadata?.visibility??null,market:g,price:v,sizePercent:t,slippageBps:x,contradicted:"partial"===e.kind&&m.has(e.row.lifecycleId)})}var h=e.i(727322),p=e.i(567978),m=e.i(473344),f=e.i(190459),x=e.i(936548);function g({row:e}){let r=(0,i.useTranslations)("positions");return(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("span",{className:"font-medium",children:[e.asset||r("accountReadUnknownMarket")," ","long"===e.side?r("long"):"short"===e.side?r("short"):"—"]}),(0,t.jsxs)("span",{className:"ml-2 text-xs text-muted-foreground",children:[e.underwriter||"—"," · ",r("accountReadDetailsUnavailable")]})]})}function b({row:e}){let d=(0,i.useTranslations)("positions"),c=u({kind:"partial",row:e}),{closePosition:v,getLastActionError:y}=(0,h.useTradeActions)(),{publicKey:w}=(0,a.useUnifiedWallet)(),{cache:j,auth:S}=(0,o.useAccountReadSession)(),{refreshPositions:k}=(0,l.useUnifiedPositions)(),{addPendingPosition:N,hasPendingCloseForPda:P}=(0,p.usePendingPositions)(),[T,C]=(0,r.useState)(!1),M=(0,r.useRef)(!1),_=(0,r.useRef)(!0);(0,r.useEffect)(()=>(_.current=!0,()=>{_.current=!1}),[]);let A=async()=>
2{if(!(!(0,n.manualCloseIsCurrent)(c)||M.current||!w||"available"!==c.status||"imperial"!==c.input.ownership||!j.isCurrent(S)||P(e.positionPda,e.asset))){M.current=!0,C(!0);try{let t=await v(c.input);if(!j.isCurrent(S))return;if(!t)return void s.toast.error((0,x.displayClientError)(y()));N({id:t,market:(0,m.pendingMarketKey)(c.input.marketMint),marketId:c.input.marketMint,owner:w,type:"closing",isLong:"long"===e.side,timestamp:Date.now(),status:"pending",positionPda:e.positionPda,asset:e.asset,profileIndex:e.profileIndex??void 0,venue:e.underwriter,sizeUsdAtIntent:c.input.sizeUsd,settledAtSubmit:(0,f.settlesSynchronously)(e.underwriter)}),k()}catch(e){j.isCurrent(S)&&s.toast.error((0,x.displayClientError)(e))}finally{M.current=!1,_.current&&j.isCurrent(S)&&C(!1)}}};return(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-border bg-surface px-3 py-3",children:[(0,t.jsx)(g,{row:e}),(0,t.jsxs)("div",{className:"flex flex-col items-end gap-1",children:[(0,t.jsx)("button",{type:"button",className:"rounded border border-border px-3 py-2 text-xs disabled:opacity-50",disabled:T||"available"!==c.status||P(e.positionPda,e.asset),onClick:()=>void A(),children:d(T?"accountReadClosing":"accountReadManualClose")}),"unavailable"===c.status&&(0,t.jsx)("span",{className:"max-w-64 text-right text-xs text-muted-foreground",children:d("accountReadCloseUnavailable")})]})]})}},61162,500665,e=>{"use strict";e.s(["InlineEditCollateralForm",()=>L],61162),e.s(["useCollateralEdit",()=>E],500665);var t=e.i(394390),r=e.i(943494),i=e.i(942553),s=e.i(153517),n=e.i(821043),a=e.i(299959),l=e.i(665757),o=e.i(546642),d=e.i(183023),c=e.i(116082),u=e.i(689384),h=e.i(727322),p=e.i(670374),m=e.i(26826),f=e.i(193568),x=e.i(76990),g=e.i(894771),b=e.i(142298),v=e.i(122097),y=e.i(856255),w=e.i(739835),j=e.i(936548),S=e.i(610021),k=e.i(508947),N=e.i(332608),P=e.i(795974),T=e.i(190459),C=e.i(494286),M=e.i(148974),_=e.i(308146),A=e.i(265724);function E({lifecycle:e,livePrices:t,onClose:r,onPositionChange:s,initialAmount:n}){let l=(0,i.useTranslations)("positions"),o=(0,a.useFormatters)(),[L,F]=(0,d.useState)(null),[R,D]=(0,d.useState)(n??""),[I,U]=(0,d.useState)(!1),[O,B]=(0,d.useState)(null),[z,$]=(0,d.useState)(!0),{depositCollateral:V,withdrawCollateral:H}=(0,h.useTradeActions)(),{awaitingReturn:W,submitWithArrivingWait:q}=(0,M.useArrivingWithdrawal)(),{publicKey:K,connection:G,signTransaction:Y,sendTransaction:X}=(0,b.useUnifiedWallet)(),{profiles:Q}=(0,g.useProfile)(),{balances:J}=(0,v.useAllProfileUsdcBalances)(Q),Z="long"===e.side,ee=(0,p.getMarketMintFromAsset)(e.asset,e.underwriter),et=(0,f.useTradingPreload)(ee??""),er="2"===e.underwriter?"phoenix":e.underwriter,ei="phoenix"===er,es=7===(0,T.underwriterByteFrom)(String(e.underwriter??"")),en=L??(es?"withdraw":"deposit"),ea=K?.toBase58()??null,el=null!=e.profileIndex?Number(e.profileIndex):null,eo=void 0!==e.sunriseMarginSeat,ed=e.sunriseMarginSeat??null,{data:ec,isLoading:eu,refetch:eh}=(0,C.useSunriseMargin)(ea,el,ed,es&&eo),ep=eo?(0,C.sunriseWithdrawableNowUsd)(ec):null,em=eo?(0,C.sunriseArrivingUsd)(ec):null,ef=Z&&!ei&&!es&&"deposit"===en,ex=Z&&!ei&&!es&&"withdraw"===en,{data:eg}=(0,x.usePhoenixMarkets)(),eb=(0,d.useMemo)(()=>ei?eg?.find(t=>t.symbol===e.asset)??null:null,[ei,eg,e.asset]),ev=(0,d.useMemo)(()=>et.feeSettings&&ef?Math.floor(Math.floor(1e6*(parseFloat(R)||0))*et.feeSettings.longSwapFeeBps/1e4):0,[R,et.feeSettings,ef]),ey=(0,d.useMemo)(()=>et.feeSettings&&ex?Math.floor(Math.floor(1e6*(parseFloat(R)||0))*et.feeSettings.longSwapFeeBps/1e4):0,[R,et.feeSettings,ex]);(0,d.useEffect)(()=>{let t=!1;return(async()=>{if(e.positionPda){$(!0);let r=await (0,u.fetchCollateralEditQuote)({positionPubkey:e.positionPda,side:e.side,source:"imperial",collateralUsd:0,sizeUsd:(0,m.parseRawValue)(e.sizeUsd),currentCollateralUsd:(0,m.parseRawValue)(e.collateralUsd),underwriter:er,assetSymbol:e.asset});t||(B(r),$(!1))}else $(!1)})(),()=>{t=!0}},[e.positionPda,e.side,er,e.asset,e.sizeUsd,e.collateralUsd]);let ew=eo&&"number"==typeof ec?.collateralUsd&&Number.isFinite(ec.collateralUsd)?ec.collateralUsd:null,ej=!es||null!==ew,eS=es?ew??0:(0,m.parseRawValue)(e.collateralUsd),ek=es?eu||!ej:z,eN=(0,m.parseRawValue)(e.sizeUsd),eP=(0,m.parseRawValue)(e.entryPrice),eT=(0,m.parseRawValue)((0,p.displayLiquidationPriceForLifecycle)(e)),eC=(0,p.getMarketMintFromAsset)(e.asset,e.underwriter),eM=eC?t?.[eC]:void 0,e_=ei?(0,m.parseRawValue)(e.markPrice)||eP:eM??((0,m.parseRawValue)(e.markPrice)||eP),eA=ei?(0,N.computePhoenixUnrealizedPnlUsd)({side:e.side,sizeUsd:eN,entryPrice:eP,collateralUsd:eS},e_):0,eE=es?eS>0?eN/eS:0:(0,m.parseRawValue)((0,A.displayPositionLeverage)(e)),eL=parseFloat(R)||0,eF=(0,d.useMemo)(()=>O?parseFloat(O.depositSwapFeeUsd):0,[O]),eR=(0,d.useMemo)(()=>O?parseFloat(O.withdrawSwapFeeUsd):0,[O]),eD=(0,d.useMemo)(()=>
2{if(es)return eu?null:ep;if(z)return null;let t=O?.maxWithdrawalUsd?parseFloat(O.maxWithdrawalUsd):null;if(ei&&eb&&eb.maxLeverage>0&&e_>0&&eP>0){let r=(0,N.computePhoenixMaxWithdrawUsd)({side:e.side,sizeUsd:eN,entryPrice:eP,collateralUsd:eS},{maxLeverage:eb.maxLeverage,takerFeeMicro:eb.takerFeeMicro},e_);return Math.max(0,(null!==t?Math.min(r,t):r)-eN*e_/eP*100/1e4)}return null!==t?t:Math.max(0,eS-eN/100)},[z,eS,eN,O,ei,eb,e_,eP,e.side,es,eu,ep]),eI=(0,d.useMemo)(()=>z?null:O?.maxDepositUsd?parseFloat(O.maxDepositUsd):null,[z,O]),eU=(0,d.useMemo)(()=>{let t,r=es?0:"deposit"===en?ef?ev/1e6:eF:ex?ey/1e6:eR;if(es&&ec?.primeBound)return{newCollateral:eS,newLeverage:eE,newLiqPrice:eT,swapFee:0,withdrawReceived:0,isValid:!1,error:"Close this Prime position in full to repay the loan and release your collateral.",isLoading:!1};if(ek||null===eD)return{newCollateral:eS,newLeverage:eE,newLiqPrice:eT,swapFee:0,withdrawReceived:0,isValid:!1,error:null,isLoading:!0};if(eL<=0)return{newCollateral:eS,newLeverage:eE,newLiqPrice:eT,swapFee:0,withdrawReceived:0,isValid:!1,error:null,isLoading:!1};let i="deposit"===en?eL-r:eL,s="deposit"===en?eS+i:eS-eL;if(!es&&s<=0)return{newCollateral:0,newLeverage:0,newLiqPrice:0,swapFee:r,withdrawReceived:"withdraw"===en?eL-r:void 0,isValid:!1,error:l("errorWithdrawExceedsCollateral"),isLoading:!1};let n=es?eN/Math.max(.01,s):eE*eS/Math.max(.01,s),a=eN/Math.max(.01,s+eA),d=ei&&eb&&eb.maxLeverage>0?(0,N.computePhoenixLiquidationPrice)({side:e.side,sizeUsd:eN,entryPrice:eP,collateralUsd:s},{maxLeverage:eb.maxLeverage,takerFeeMicro:eb.takerFeeMicro},e_):null;if(null!==d)t=d;else if(ei){let e=.9875/a;t=Z?eP*(1-e):eP*(1+e)}else t=(0,P.calculateLiquidationPrice)({entryPrice:eP,sizeUsd:eN,collateralUsd:s,isLong:Z});let c={newCollateral:s,newLeverage:n,newLiqPrice:Math.max(0,t),swapFee:r,withdrawReceived:"withdraw"===en?eL-r:void 0,isLoading:!1};return"withdraw"===en&&eL>eD?{...c,isValid:!1,error:l("errorMaxWithdrawal",{amount:o.number(eD)})}:"deposit"===en&&eI&&eL>eI?{...c,isValid:!1,error:l("errorMaxDeposit",{amount:o.number(eI)})}:!es&&"withdraw"===en&&a>100?{...c,isValid:!1,error:l("errorLeverageExceedsCap")}:{...c,isValid:!0,error:null}},[ec?.primeBound,eL,en,eS,eA,eN,eP,Z,eE,eT,ek,eD,eI,eF,eR,ef,ex,ev,ey,ei,es,eb,e_,e.side,e.asset]),eO=(0,d.useCallback)(e=>{F(e),D("")},[]),eB=(0,d.useCallback)(()=>{"withdraw"===en&&null!==eD&&D((0,_.percentToDecimalString)(eD,100,6))},[en,eD]),ez=(0,d.useCallback)(async()=>{if(!eU.isValid||eL<=0)return void c.toast.error(eU.error||l("errorEnterValidAmount"));U(!0);try{let t=es?e.asset:(0,p.getMarketMintFromAsset)(e.asset,e.underwriter);if(!t)return void c.toast.error(l("errorMarketDataUnavailable"));if("deposit"===en){let i=null!=e.profileIndex?Number(e.profileIndex):null;if(null!=i){let e=J.get(i);if(null==e)return void c.toast.error(l("errorBalanceStillLoading"));let t=function(e,t){let r=(0,_.numberToBaseUnits)(e,6),i=(0,_.floorNumberToBaseUnits)(t,6);if(null===r||null===i)throw Error("Invalid collateral amount or balance");return r<=i?0:Number((r-i+9999n)/10000n)/100}(eL,e);if(t>0){if(!K||!G||!Y||!X)return void c.toast.error(l("errorConnectWalletToFund"));let r=await (0,y.getWalletUsdcBalance)(G,K);if(r<t)return void c.toast.error(l("errorNotEnoughUsdc",{account:o.number(e),wallet:o.number(r)}));let s=c.toast.loading(l("toastMovingUsdcToAccount",{amount:o.number(t)}));try{await (0,y.fundProfileWithUsdc)({connection:G,publicKey:K,signTransaction:Y,sendTransaction:X,profileIndex:i,amountUsdc:t})}catch(e){c.toast.error((0,w.isUserRejection)(e)?l("toastDepositCancelled"):l("toastFundingTransferFailed"));return}finally{c.toast.dismiss(s)}}}await V({positionPubkey:e.positionPda,marketMint:t,side:e.side,collateralAmount:eL,currentPrice:e_,slippageBps:h.DEFAULT_SLIPPAGE_BPS,profileIndex:e.profileIndex,underwriter:e.underwriter,sunriseMarginMode:es?(0,k.parseSeatText)(ed).seat:void 0,preloadedData:ef?{protocolFeeRecipient:et.protocolFeeRecipient??void 0,feeSettings:et.feeSettings??void 0,userAccountExists:et.userAccountExists,projectAlt:et.projectAlt??void 0}:void 0})&&(es&&eh(),c.toast.success(l("toastCollateralDeposited")),r(),s?.())}else{let i=es&&ea&&null!==el?()=>(0,C.fetchSunriseMargin)(ea,el,ed):void 0;await q({requestedUsd:eL,readMargin:i,submit:()=>H({positionPubkey:e.positionPda,marketMint:t,side:e.side,collateralAmount:eL,currentPrice:e_,slippageBps:h.DEFAULT_SLIPPAGE_BPS,profileIndex:e.profileIndex,underwriter:e.underwriter,sunriseMarginMode:es?(0,k.parseSeatText)(ed).seat:void 0})})&&(es&&eh(),c.toast.success(l("toastCollateralWithdrawn")),r(),s?.())}}catch(e){if((0,S.isSunriseArriving)(e))return void c.toast.info((0,j.displayClientError)(e));console.error(`Failed to ${en} collateral:`,e),c.toast.error(l("toastCollateralEditFailed",{mode:en}))}finally{U(!1)}},[eU,eL,en,e,e_,ef,et,V,H,r,s,J,K,G,Y,X,es,ea,el,ed,q,eh]);return{mode:en,setMode:eO,isSunrise:es,sunriseWithdrawableNowUsd:ep,sunriseArrivingUsd:em,sunriseArrivingEtaSecs:ec?.arrivingEtaSecs??null,amount:R,setAmount:D,amountNum:eL,submitting:I,awaitingReturn:W,loadingLimits:ek,maxWithdraw:eD,maxDeposit:eI,currentCollateral:ej?eS:null,currentLeverage:eE,currentLiqPrice:eT,preview:eU,handleMax:eB,handleSubmit:ez}}
2function L({lifecycle:e,livePrices:d,onClose:c,onPositionChange:u,initialAmount:h}){let p,m=(0,i.useTranslations)("positions"),f=(0,i.useTranslations)("terms"),x=(0,i.useTranslations)("common"),g=(0,a.useFormatters)(),b=(0,a.useDecimalSeparator)(),{mode:v,setMode:y,amount:w,setAmount:j,amountNum:S,submitting:k,awaitingReturn:N,loadingLimits:P,maxWithdraw:T,currentCollateral:C,currentLeverage:M,currentLiqPrice:_,preview:A,handleMax:F,handleSubmit:R}=E({lifecycle:e,livePrices:d,onClose:c,onPositionChange:u,initialAmount:h});return(0,t.jsx)("div",{className:"flex justify-end px-4 py-3",children:(0,t.jsxs)("div",{className:"flex gap-8 max-w-[550px]",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-2 text-xs min-w-[200px]",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-label-muted",children:f("leverage.full")}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[g.fixed(M,2),"x",(0,t.jsx)("span",{className:"text-label-muted mx-1",children:"→"}
2),A.isLoading?(0,t.jsx)(r.Loader2,{className:"inline w-3 h-3 animate-spin text-muted-foreground"}):(0,t.jsxs)("span",{className:A.newLeverage>100?"text-red-400":"",children:[g.fixed(A.newLeverage,2),"x"]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("liquidationPrice")}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:["$",g.number(_),(0,t.jsx)("span",{className:"text-label-muted mx-1",children:"→"}),A.isLoading?(0,t.jsx)(r.Loader2,{className:"inline w-3 h-3 animate-spin text-muted-foreground"}):(0,t.jsxs)("span",{children:["$",g.number(A.newLiqPrice)]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("collateral")}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[null===C?"—":`$${g.number(C)}`,(0,t.jsx)("span",{className:"text-label-muted mx-1",children:"→"}),A.isLoading?(0,t.jsx)(r.Loa
2der2,{className:"inline w-3 h-3 animate-spin text-muted-foreground"}):(0,t.jsxs)("span",{className:A.newCollateral<=0?"text-red-400":"deposit"===v?"text-cyan-400":"text-amber-400",children:["$",g.number(A.newCollateral)]})]})]}),A.swapFee>0&&S>0&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("platformFee")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["-$",g.number(A.swapFee)]})]}),"withdraw"===v&&void 0!==A.withdrawReceived&&A.swapFee>0&&S>0&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("youReceive")}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:["$",g.number(A.withdrawReceived)]})]}),A.error&&(0,t.jsx)("div",{className:"text-red-400 text-xs mt-1",children:A.error})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"inline-flex gap-0.5 bg-surface-raised border border-border-strong rounded p-0.5 w-fit",children:[(0,t.jsx)("button",{onClick:()=>y("deposit"),className:(0,s.cn)("px-3 py-1 text-xs rounded transition-colors","deposit"===v?"bg-surface-interactive text-cyan-400":"text-muted-foreground hover:text-foreground"),children:m("depositMode")}),(0,t.jsx)("button",{onClick:()=>y("withdraw"),className:(0,s.cn)("px-3 py-1 text-xs rounded transition-colors","withdraw"===v?"bg-surface-interactive text-amber-400":"text-muted-foreground hover:text-foreground"),children:m("withdrawMode")})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded px-3 py-1.5 w-24",children:(0,t.jsx)(l.Input,{type:"text",inputMode:"decimal","data-keypad-unit":"money",placeholder:"0.00",value:w,onChange:e=>j((0,n.sanitizeDecimalInput)(e.target.value,b)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"USDC"}),"withdraw"===v&&(0,t.jsx)("button",{onClick:F,disabled:P||null===T,className:"px-2 py-0.5 text-xs text-muted-foreground hover:text-foreground rounded border border-border-strong hover:bg-surface-interactive disabled:opacity-50 disabled:cursor-not-allowed",children:m("maxAmount")})]}),(p=(0,o.pickMissingLabel)([[P||null===T,m("loadingLimits")],[S<=0,m("deposit"===v?"enterDepositAmount":"enterWithdrawAmount")]]),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("button",{onClick:c,disabled:k&&!N,className:"px-3 py-1 text-xs rounded border border-border-strong text-muted-foreground hover:text-foreground hover:bg-surface-interactive disabled:opacity-50",children:x("cancel")}),(0,t.jsx)("button",{onClick:R,disabled:k||null!==p||!A.isValid||A.isLoading,className:(0,s.cn)("px-3 py-1 text-xs rounded font-medium text-primary-foreground disabled:opacity-50 disabled:cursor-not-allowed","deposit"===v?"bg-cyan-500 hover:bg-cyan-600":"bg-amber-500 hover:bg-amber-600"),children:N?(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(r.Loa
2der2,{className:"h-3 w-3 animate-spin"}),m("sunriseWaitingForFunds")]}):k?(0,t.jsx)(r.Loader2,{className:"h-3 w-3 animate-spin"}):p??x("confirm")})]}))]})]})})}},97881,976955,e=>{"use strict";e.s(["ALL_ASSETS",()=>H,"AssetGroupLabel",()=>K,"OrdersAssetFilterBar",()=>G,"assetSymbolOf",()=>W,"groupOrdersByAsset",()=>q],976955),e.s(["MobilePassthroughOrderCard",()=>$],97881);var t=e.i(394390),r=e.i(183023),i=e.i(457058),s=e.i(169443),n=e.i(120911),a=e.i(695109),l=e.i(1169),o=e.i(984457),d=e.i(942553),c=e.i(687229),u=e.i(894771),h=e.i(153517),p=e.i(670374),m=e.i(852070);e.i(889723);var f=e.i(465217),x=e.i(599059),g=e.i(459),b=e.i(259048),v=e.i(943494),y=e.i(116082),w=e.i(685576),j=e.i(821043),S=e.i(299959),k=e.i(626074),N=e.i(665757),P=e.i(727322),T=e.i(993467),C=e.i(296228),M=e.i(734195),_=e.i(936548),A=e.i(26826),E=e.i(546642),L=e.i(227456);function F({open:e,onOpenChange:i,order:s,closeOrders:n,livePrices:a,onPositionChange:o,defaultOrderType:c}){let u,m,f=(0,d.useTranslations)("positions"),x=(0,d.useTranslations)("terms"),R=(0,d.useTranslations)("trading"),D=(0,d.useTranslations)("common"),I=(0,S.useFormatters)(),[U,O]=(0,r.useState)(c??"tp");(0,r.useEffect)(()=>{e&&c&&O(c)},[e,c]);let[B,z]=(0,r.useState)(""),[$,V]=(0,r.useState)("price"),[H,W]=(0,r.useState)(100),[q,K]=(0,r.useState)(!1),G=(0,r.useRef)(!1),Y=(0,r.useRef)(new Set),[,X]=(0,r.useState)(0),Q=(0,T.useOrderTpSlAttempt)(s,n),J="tp"===U||"sl"===U?Q.attempts[U]:null,Z="tp"===U||"sl"===U?null!==J:Y.current.has(U),[ee,et]=(0,r.useState)(""),[er,ei]=(0,r.useState)(""),[es,en]=(0,r.useState)(""),[ea,el]=(0,r.useState)(3),[eo,ed]=(0,r.useState)(0),[ec,eu]=(0,r.useState)("30"),[eh,ep]=(0,r.useState)(!1),[em,ef]=(0,r.useState)(""),{createPassthroughOrder:ex,createRatchetOrder:eg,createIndicatorCloseOrder:eb,wasLastErrorRejection:ev}=(0,P.useTradeActions)(),ey=()=>{("ratchet"===U||"rsi"===U)&&Y.current.add(U),X(e=>e+1),o?.()},ew="long"===s.side,ej=parseFloat(s.sizeUsd||"0"),eS="ratchet_entry"===s.orderType||"fib_ratchet_entry"===s.orderType?s.ratchet?.worstPrice??parseFloat(s.triggerPriceUsd||"0"):parseFloat(s.triggerPriceUsd||"0"),ek=s.marketMint||"",eN=a?.[ek]??eS,eP=s.collateralAmount??0,eT=ej*H/100,eC=eP*H/100,eM=parseFloat(B)||0,e_=eS>0?eS:eN,eA=(()=>{if(eM<=0)return eM;if("pct"===$&&e_>0)return"tp"===U?ew?e_*(1+eM/100):e_*(1-eM/100):ew?e_*(1-eM/100):e_*(1+eM/100);if("pnl"===$&&eS>0&&ej>0){let e="tp"===U?eM:-eM;return(0,A.priceForTargetPnlPct)({sizeUsd:ej,collateralUsd:eP,netCapital:null,entryPrice:eS,isLong:ew,targetPnlPct:e})??0}return eM})(),eE=eA>0&&(ew?eA>e_:eA<e_),eL=eA>0&&(ew?eA<e_:eA>e_),eF="rsi"===U||("tp"===U?eE:eL),eR=(0,r.useMemo)(()=>(0,A.calculatePnl)({size:eT,entryPrice:eS,execPrice:eA,isLong:ew})?.total??null,[eA,eS,eT,ew]),eD=(0,r.useMemo)(()=>{let e=parseFloat(ee)||0;return(0,A.calculatePnl)({size:eT,entryPrice:eS,execPrice:e,isLong:ew})?.total??null},[ee,eS,eT,ew]),eI=parseFloat(ee)||0,eU=parseFloat(er)||0,eO=eI>0&&eU>0&&H>0,eB=parseFloat(ec)||0,ez=eB>0&&eB<100&&H>0&&(!eh||(parseFloat(em)||0)>0),e$=()=>i(!1),eV=async()=>{if(!G.current&&Q.ready&&!Z){G.current=!0;try{await eH()}finally{G.current=!1}}},eH=async()=>{let e;try{e=(0,p.getCloseOrderTargetFromOrder)(s)}catch(e){y.toast.error((0,_.displayClientError)(e));return}if("rsi"===U){let t=parseFloat(ec)||0;if(t<=0||t>=100)return void y.toast.error((0,M.tradingValidationError)("invalidIndicatorThreshold"));if(eh&&0>=(parseFloat(em)||0))return void y.toast.error(f("mobileInvalidRsiTrailSize"));try{K(!0);let r=await eb({...e,sizeUsd:eT,closeBps:Math.round(100*H),indicatorType:0,timeframeCode:ea,period:14,indicatorCondition:eo,thresholdValue:t,ratchetSize:eh?parseFloat(em):void 0});if(!Q.isCurrent())return;r?(y.toast.success(f("mobileRsiOrderCreated")),e$(),o?.()):!0!==ev()&&ey()}catch(e){if(!Q.isCurrent())return;ey(),console.error("Error creating RSI close order:",e),y.toast.error(f("mobileRsiOrderFailed"))}finally{K(!1)}return}if("ratchet"===U){if(eI<=0)return void y.toast.error(f("mobileInvalidWorstPrice"));if(eU<=0)return void y.toast.error(f("mobileInvalidTrailSize"));try{K(!0);let t=await eg({...e,sizeUsd:eT,closeBps:Math.round(100*H),currentPrice:eN,worstPrice:eI,ratchetSize:eU});if(!Q.isCurrent())return;t?(y.toast.success(f("mobileTrailingOrderCreated")),e$(),o?.()):!0!==ev()&&ey()}catch(e){if(!Q.isCurrent())return;ey(),console.error("Error creating ratchet order:",e),y.toast.error(f("mobileTrailingOrderFailed"))}finally{K(!1)}return}if(!eA||eA<=0)return void y.toast.error((0,M.tradingValidationError)("invalidTriggerPrice"));try{K(!0);let t="tp"===U;await Q.submit(U,{triggerPrice:eA,closeBps:Math.round(100*H),sizeUsd:eT},()=>ex({...e,sizeUsd:eT,closeBps:Math.round(100*H),triggerPrice:eA,isTakeProfit:t}),ev)?(y.toast.success(t?f("mobileTakeProfitOrderCreated"):f("mobileStopLossOrderCreated")),e$(),o?.()):!0!==ev()&&o?.()}catch(e){o?.(),console.error("Error creating order:",e),y.toast.error(f("mobileOrderCreateFailed"))}finally{K(!1)}},eW={tp:{label:f("mobileOrderTypeTakeProfit"),color:"text-side-long"},sl:{label:f("mobileOrderTypeStopLoss"),color:"text-side-short"},ratchet:{label:f("historyOrderTypeTrailingSl"),color:"text-blue-400"},rsi:{label:"RSI",color:"text-amber-400"}},eq="ratchet"===U?eD:eR;return(0,t.jsx)(w.Sheet,{open:e,onOpenChange:i,children:(0,t.jsxs)(w.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4 overflow-y-auto overflow-x-hidden",children:[(0,t.jsx)(w.SheetTitle,{className:"text-foreground text-lg font-semibold mb-4",children:f("mobileAddCloseOrder")}),(0,t.jsx)("div",{className:"flex items-center gap-2 mb-4",children:(0,t.jsxs)(k.DropdownMenu,{children:[(0,t.jsx)(k.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 bg-surface-raised border border-border-strong rounded px-3 py-1.5 cursor-pointer hover:border-border-strong transition-colors",children:[(0,t.jsx)("span",{className:(0,h.cn)("text-sm font-medium",eW[U].color),children:eW[U].label}),(0,t.jsx)(l.ChevronDown,{className:"w-3.5 h-3.5 text-muted-foreground"})]})}),(0,t.jsxs)(k.DropdownMenuContent,{className:"min-w-0",children:[(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{O("tp"),z("")},className:"text-sm text-side-long hover:bg-surface-interactive cursor-pointer focus:bg-surface-interactive focus:text-side-long",children:f("mobileOrderTypeTakeProfit")}),(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{O("sl"),z("")},className:"text-sm text-side-short hover:bg-surface-interactive cursor-pointer focus:bg-surface-interactive focus:text-side-short",children:f("mobileOrderTypeStopLoss")}),(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{O("ratchet"),z(""),et(""),ei(""),en("")},className:"text-sm text-blue-400 hover:bg-surface-interactive cursor-pointer focus:bg-surface-interactive focus:text-blue-400",children:f("historyOrderTypeTrailingSl")}),(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{O("rsi"),z("")},className:"text-sm hover:bg-surface-interactive cursor-pointer focus:bg-surface-interactive",children:(0,t.jsx)("span",{className:"text-amber-400",children:"RSI"})})]})]})}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-2",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:x("size.full")}),(0,t.jsx)("input",{type:"range",...L.THUMB_ONLY_SLIDER,min:1,max:100,value:H,onChange:e=>W(parseInt(e.target.value)),className:(0,h.cn)(L.RANGE_SLIDER_CLASSES,"flex-1 [&::-webkit-slider-thumb]:bg-orange-500")}),(0,t.jsxs)("span",{className:"text-sm text-foreground font-mono tabular-nums w-10 text-right",children:[H,"%"]})]}),(0,t.jsx)("div",{className:"flex items-center gap-1",children:[25,50,75,100].map(e=>(0,t.jsxs)("button",{onClick:()=>W(e),className:(0,h.cn)("flex-1 py-1.5 text-xs rounded",H===e?"bg-surface-interactive text-foreground":"bg-surface text-label-muted hover:text-secondary-foreground"),children:[e,"%"]},e))})]}),"rsi"===U?(0,t.jsxs)("div",{className:"space-y-3 mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("mobileTimeframe")}),(0,t.jsx)("select",{value:ea,onChange:e=>el(Number(e.target.value)),className:"bg-surface-raised border border-border-strong rounded px-3 py-1.5 text-sm text-foreground",children:Object.entries(g.TIMEF
2RAME_LABELS).map(([e,r])=>(0,t.jsx)("option",{value:e,children:r},e))})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("historyRowCondition")}),(0,t.jsx)("select",{value:eo,onChange:e=>ed(Number(e.target.value)),className:"bg-surface-raised border border-border-strong rounded px-3 py-1.5 text-sm text-foreground",children:g.CONDITION_OPTIONS.map(e=>(0,t.jsx)("option",{value:e,children:R(g.CONDITION_LABEL_KEYS[e])},e))})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("mobileThreshold")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-24",children:(0,t.jsx)(N.Input,{type:"text",inputMode:"numeric",placeholder:"30",value:ec,onChange:e=>eu(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto text-right focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[(0,t.jsx)("input",{type:"checkbox",checked:eh,onChange:e=>ep(e.target.checked),className:"w-3.5 h-3.5 rounded border-border-strong bg-surface-raised text-amber-500 focus:ring-0"}),(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("historyOrderTypeRsiTrailing")})]}),eh&&(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-24",children:(0,t.jsx)(N.Input,{type:"text",inputMode:"decimal",placeholder:"0.5",value:em,onChange:e=>ef((0,j.sanitizeDecimalInput)(e.target.value,I.decimalSeparator)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto text-right focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]})]}):"ratchet"===U?(0,t.jsxs)("div",{className:"space-y-3 mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:ew?f("mobileMinPrice"):f("mobileMaxPrice")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-32",children:(0,t.jsx)(N.Input,{type:"text",inputMode:"decimal",placeholder:I.number(eS),value:ee,onChange:e=>{let t=(0,j.sanitizeDecimalInput)(e.target.value,I.decimalSeparator);et(t);let r=parseFloat(t),i=parseFloat(es);r>0&&i>0&&ei(parseFloat(Math.abs(i-r).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto text-right focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("mobileTrailSize")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-32",children:(0,t.jsx)(N.Input,{type:"text",inputMode:"decimal",placeholder:"0.50",value:er,onChange:e=>{let t=(0,j.sanitizeDecimalInput)(e.target.value,I.decimalSeparator);ei(t);let r=parseFloat(t),i=parseFloat(ee);if(r>0&&i>0){let e=parseFloat((ew?i+r:i-r).toPrecision(12));en(e>0?e.toString():"")}},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto text-right focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:f("mobileDragPrice")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-32",children:(0,t.jsx)(N.Input,{type:"text",inputMode:"decimal",placeholder:I.number(eN),value:es,onChange:e=>{let t=(0,j.sanitizeDecimalInput)(e.target.value,I.decimalSeparator);en(t);let r=parseFloat(t),i=parseFloat(ee);r>0&&i>0&&ei(parseFloat(Math.abs(r-i).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto text-right focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]})]}):(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-sm text-label-muted",children:"tp"===U?f("mobileOrderTypeTakeProfit"):f("mobileOrderTypeStopLoss")}),(0,t.jsxs)(k.DropdownMenu,{children:[(0,t.jsx)(k.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsxs)("button",{className:"flex items-center gap-0.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:["price"===$?f("historyColPrice"):"pct"===$?f("mobilePctPrice"):f("mobilePctPnl"),(0,t.jsx)(l.ChevronDown,{className:"w-3 h-3"})]})}),(0,t.jsxs)(k.DropdownMenuContent,{align:"start",className:"min-w-[100px]",children:[(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{V("price"),z("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:f("historyColPrice")}),(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{V("pct"),z("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:f("mobilePctPrice")}),(0,t.jsx)(k.DropdownMenuItem,{onClick:()=>{V("pnl"),z("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:f("mobilePctPnl")})]})]})]}),(0,t.jsx)("button",{onClick:()=>{"price"===$&&z((0,j.toDecimalInputValue)(eN))},className:"text-xs text-label-muted hover:text-foreground transition-colors",children:f("mobileLastPrice")})]}),(0,t.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2.5",children:[(0,t.jsx)(N.Input,{type:"text",inputMode:"decimal",placeholder:"pnl"===$?"tp"===U?f("mobilePctGainHint"):f("mobilePctLoss
2Hint"):"pct"===$?"tp"===U?f("historyActionIncrease"):f("historyActionDecrease"):"tp"===U?ew?`>${I.number(e_)}`:`<${I.number(e_)}`:ew?`<${I.number(e_)}`:`>${I.number(e_)}`,value:B,onChange:e=>z((0,j.sanitizeDecimalInput)(e.target.value,I.decimalSeparator)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,t.jsx)("span",{className:"text-xs text-label-muted ml-2",children:"price"===$?"USD":"%"})]}),"pnl"===$&&(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(E.PnlPctPresets,{value:B,onChange:z,orderType:"tp"===U?"tp":"sl"})}),("pct"===$||"pnl"===$)&&eA>0&&(0,t.jsxs)("div",{className:"text-[10px] text-label-muted mt-1",children:["≈ $",I.number(eA)]})]}),"rsi"!==U&&(0,t.jsxs)("div",{className:"space-y-2 mb-5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:"ratchet"===U?f("mobileEstPnlAt",{bound:ew?f("mobileBoundMin"):f("mobileBoundMax")}):f("mobileEstPnl")}),null!==eq?(0,t.jsxs)("span",{className:`${(0,b.pnlColor)(eq)} font-mono tabular-nums`,children:[eq>=0?"+":"",I.number(eq)," USD"]}):(0,t.jsx)("span",{className:"text-label-muted",children:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:f("mobileEstReturn")}),null!==eq?(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[I.number(eC+eq)," USD"]}):(0,t.jsx)("span",{className:"text-label-muted",children:"—"})]})]}),!Q.ready&&(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:f("tpslOrderWalletUnavailable")}),Z&&(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground mb-3",children:f("tpslSubmissionUncertain")}),J?.persistence==="memory"&&(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:f("tpslGuardMemoryOnly")}),J&&Q.scope&&Q.wallet&&("tp"===U||"sl"===U)&&(0,t.jsx)(C.TpSlAttemptRecovery,{scope:Q.scope,leg:U,attempt:J,wallet:Q.wallet,market:ek,onRecovered:()=>{z(""),Q.refresh(),o?.()}},J.attemptId),(u="rsi"===U?(0,E.pickMissingLabel)([[H<=0,f("mobileSetSize")],[eB<=0||eB>=100,f("mobileSetRsiThreshold")],[eh&&0>=(parseFloat(em)||0),f("mobileSetTrailSize")]]):"ratchet"===U?(0,E.pickMissingLabel)([[H<=0,f("mobileSetSize")],[eI<=0,ew?f("mobileSetMinPrice"):f("mobileSetMaxPrice")],[eU<=0,f("mobileSetTrailSize")]]):(0,E.pickMissingLabel)([[H<=0,f("mobileSetSize")],[!B,f("mobileSetTriggerPrice")]]),m=q||!Q.ready||Z||null!==u||("rsi"===U?!ez:"ratchet"===U?!eO:!eF),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("button",{onClick:e$,disabled:q,className:"flex-1 py-3 rounded-lg border border-border-strong text-muted-foreground font-medium text-sm hover:text-foreground hover:bg-surface-interactive transition-colors disabled:opacity-50",children:D("cancel")}),(0,t.jsx)("button",{onClick:eV,disabled:m,className:"flex-1 py-3 rounded-lg font-medium text-sm bg-orange-500 hover:bg-orange-600 text-primary-foreground disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:q?(0,t.jsx)(v.Loader2,{className:"h-4 w-4 animate-spin"}):u??f("mobileSubmit")})]}))]})})}var R=e.i(317629),D=e.i(917898),I=e.i(392836),U=e.i(441399),O=e.i(442150),B=e.i(687821),z=e.i(736679);function $({readOnly:e=!1,order:b,onCancel:v,isCanceling:y,livePrice:w,onExecuteNow:j,isExecuting:k,closeOrders:N,livePrices:P,onPositionChange:T,hasActivePosition:C,fundingShortfallUsd:M}){let _,A,E,L,V,H,W,q,K,G,Y,X=(0,d.useTranslations)("positions"),Q=(0,d.useTranslations)("terms"),J=(0,d.useTranslations)("trading"),Z=(0,S.useFormatters)(),[ee,et]=(0,r.useState)(!1),[er,ei]=(0,r.useState)("tp"),[es,en]=(0,r.useState)(!1),[ea,el]=(0,r.useState)(!1),[eo,ed]=(0,r.useState)(null),ec=eo?(N??[]).find(e=>e.orderPda===eo)??null:null,eu=!p.DCA_ORDER_TYPES.has(b.orderType)&&"imperial_passthrough"===b.source,{profiles:eh}=(0,u.useProfile)(),ep=(0,p.getTokenInfo)(b.marketMint||""),em="long"===b.side,ef=p.USDC_MINT.toBase58(),ex=parseFloat(b.sizeUsd),eg=b.collateralAmount??0,eb=eg>0?ex/eg:0,ev="decrease"===b.action&&"number"==typeof b.closeBps&&b.closeBps>0?b.closeBps/100:null,ey=b.profileIndex,ew="number"==typeof ey?(eh.length>ey?eh[ey]?.name:null)??X("profileFallbackName",{index:ey+1}):null,ej=async(t,r)=>{if(e)return!1;let i=await v(t,ef,r,void 0);return i&&ed(null),i},eS=("indicator"===b.orderType||"indicator_ratchet"===b.orderType)&&b.indicator,ek=("ratchet"===b.orderType||"ratchet_entry"===b.orderType||"fib_ratchet"===b.orderType||"fib_ratchet_entry"===b.orderType)&&b.ratchet,eN=(0,U.venueLivePrice)(P,b.underwriter,b.marketMint?(0,c.mintToMatchingKey)(b.marketMint):void 0,w),eP=(0,I.useRatchetPrices)([b],eN).get(b.orderPda)?.price,eT=ek?(0,D.getRatchetInfo)(b,eN,eP||void 0):null;if(eT)_=Z.price(eT.isTracking||eT.isStopArmed?eT.liveTrigger:eT.dragPrice);else if(eS&&0===b.indicator.phase){let e=J(g.CONDITION_LABEL_KEYS[b.indicator.indicatorCondition??0]);_=`RSI ${e} ${Z.fixed(b.indicator.thresholdValue,0)}`}else if(eS&&1===b.indicator.phase&&b.ratchet)_=b.ratchet.worstPrice>0?Z.price(b.ratchet.worstPrice):X("historyOrderTypeRsiTrailing");else{let e=parseFloat(b.triggerPriceUsd);_=e>0?Z.price(e):X("historyOrderTypeMarket")}let eC=e=>({executed:String(e.legsExecuted),total:String(e.numLegs)}),eM={landmine:{label:X("historyOrderTypeLandmine"),color:"bg-purple-500/20 text-purple-400"},ratchet:{label:X("historyOrderTypeTrailingSl"),color:"bg-blue-500/20 text-blue-400"},ratchet_entry:{label:X("historyOrderTypeTrailing"),color:"bg-blue-500/20 text-blue-400"},fib_ratchet:{label:X("historyOrderTypeFibTrailingSl"),color:"bg-fuchsia-500/20 text-fuchsia-400"},fib_ratchet_entry:{label:X("historyOrderTypeFibTrailing"),color:"bg-fuchsia-500/20 text-fuchsia-400"}
2,indicator:{label:"RSI",color:"bg-amber-500/20 text-amber-400"},indicator_ratchet:{label:X("historyOrderTypeRsiTrailing"),color:"bg-amber-500/20 text-amber-400"},dca:{label:b.dca?X("historyOrderBadgeDcaLegs",eC(b.dca)):"DCA",color:"bg-cyan-500/20 text-cyan-400"},dca_close:{label:b.dcaClose?X("historyOrderBadgeDcaCloseLegs",eC(b.dcaClose)):X("historyOrderTypeDcaClose"),color:"bg-cyan-500/20 text-cyan-400"},dca_time_close:{label:b.dcaTimeClose?X("historyOrderBadgeDcaTimeLegs",eC(b.dcaTimeClose)):X("mobileOrderTypeDcaTimeClose"),color:"bg-cyan-500/20 text-cyan-400"},dca_ratchet_close:{label:b.dcaRatchetClose?X("historyOrderBadgeDcaTrailingLegs",eC(b.dcaRatchetClose)):X("historyOrderTypeDcaTrailing"),color:"bg-teal-500/20 text-teal-400"},dca_time:{label:b.dcaTime?X("historyOrderBadgeDcaTimeLegs",eC(b.dcaTime)):X("historyOrderTypeDcaTime"),color:"bg-cyan-500/20 text-cyan-400"},dca_ratchet:{label:b.dcaRatchet?X("historyOrderBadgeDcaTrailingLegs",eC(b.dcaRatchet)):X("historyOrderTypeDcaTrailing"),color:"bg-teal-500/20 text-teal-400"},private_tpsl:{label:"TP/SL",color:"bg-side-long/20 text-side-long"},limit:{label:X("historyOrderTypeLimit"),color:"bg-blue-500/20 text-blue-400"},stop_limit:{label:X("historyOrderTypeStop"),color:"bg-side-short/20 text-side-short"},sl:{label:X("historyOrderTypeStop"),color:"bg-side-short/20 text-side-short"},tp:{label:X("mobileOrderTypeTakeProfit"),color:"bg-side-long/20 text-side-long"},market:{label:X("historyOrderTypeMarket"),color:"bg-side-long/20 text-side-long"}}[b.orderType];eM||(0,B.warnUnmapped)("order type",b.orderType);let e_=eM??{label:X("historyUnknownLabel"),color:B.UNMAPPED_BADGE_CLASS},eA=eM?void 0:X("historyUnknownRawTooltip",{value:b.orderType}),eE="increase"===b.action;return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg overflow-hidden",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-3 pt-3 pb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${em?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:em?X("historyLongUpper"):X("historyShortUpper")}),ep.image&&(0,t.jsx)(i.default,{src:ep.image,alt:ep.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:f.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground font-medium",children:ep.symbol}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:eb>0?`${Math.round(eb)}x`:""}),"jupiter"===b.underwriter&&(0,t.jsx)(i.default,{src:"/jupiter-logo.webp",alt:"Jupiter",width:12,height:12,className:"rounded-full",unoptimized:!0}),(A=b.underwriter?(0,x.getVenueIcon)(b.underwriter,b.hedgeVenue):null)&&"jupiter"!==b.underwriter?(0,t.jsx)(i.default,{src:A.src,alt:A.alt,width:12,height:12,className:"rounded-full",unoptimized:!0}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{title:eA,className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${e_.color}`,children:e_.label}),eT&&(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${eT.isTracking?"bg-cyan-500/20 text-cyan-400":eT.isStopArmed?"bg-emerald-500/20 text-emerald-400":"bg-amber-500/20 text-amber-400"}`,children:eT.isTracking?X("mobileRatchetTracking"):eT.isStopArmed?X("statusStopSet"):X("mobileRatchetWaiting")}),ew&&(0,t.jsx)("span",{className:(0,h.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded",(0,p.getProfileColorClass)(ey)),children:ew})]})]}),1===b.fundingStatus&&(0,t.jsx)("div",{className:"px-3 pb-1",children:(0,t.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-yellow-500/20 text-yellow-400 inline-flex items-center gap-1",children:X("mobilePendingFunding",{priority:b.priority??0})})}),(0,t.jsx)("div",{className:"px-3 pb-1 empty:hidden",children:(0,t.jsx)(z.UnfundedOrderBadge,{order:b,shortfallUsd:M,variant:"card"})}),(0,t.jsx)("div",{className:"px-3 pb-2",children:(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:Q("size.full")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:null!=ev?`${ev.toLocaleStr
2ing(Z.intlTag,{maximumFractionDigits:1})}%`:`$${ex.toLocaleString(Z.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:X("historyColCollateral")}),eE?(0,t.jsxs)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:["$",eg.toLocaleString(Z.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]}):(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:"-"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:X("mobileColTrigger")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:_})]}),(E="dca_time"===b.orderType?b.dcaTime:"dca_time_close"===b.orderType?b.dcaTimeClose:null)?(0,t.jsx)("div",{children:(0,t.jsx)(O.DcaTimeLegCountdown,{legsExecuted:E.legsExecuted,lastLegTimestamp:E.lastLegTimestamp,intervalSeconds:E.intervalSeconds,startAt:E.startAt??0,className:"text-xs",stackedLabel:!0})}):null]})}),eE&&(L={tpsl:["tp","sl"],trailing:["ratchet","fib_ratchet"],dca:["dca_close","dca_time_close","dca_ratchet_close"],rsi:["indicator","indicator_ratchet"]},V=N??[],H=["tpsl","trailing","dca","rsi"].filter(e=>V.some(t=>L[e]?.includes(t.orderType))),W={tpsl:"TP/SL",trailing:X("historyOrderTypeTrailing"),dca:"DCA",rsi:"RSI"},q=0===H.length?X("mobileCloseOrdersNone"):X("mobileCloseOrdersPending",{categories:H.map(e=>W[e]).join(", ")}),K={tpsl:"tp",trailing:"ratchet",rsi:"rsi"},G={tpsl:X("mobileNoTpSlSet"),trailing:X("mobileNoTrailingSet"),dca:X("mobileNoDcaSet"),rsi:X("mobileNoRsiSet")},(0,t.jsxs)("div",{className:"border-t border-border",children:[(0,t.jsxs)("button",{onClick:()=>el(e=>!e),className:"flex items-center justify-between px-3 py-1.5 w-full",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1 text-[10px] text-label-muted font-medium",children:[(0,t.jsx)(l.ChevronDown,{className:(0,h.cn)("w-3 h-3 transition-transform",!ea&&"-rotate-90")}),X("mobileCloseOrders")]}),(0,t.jsx)("span",{className:"text-[10px] text-muted-foreground",children:q})]}),ea&&(0,t.jsx)("div",{className:"divide-y divide-border/50",children:["tpsl","trailing","dca","rsi"].map(r=>{let i=V.filter(e=>L[r]?.includes(e.orderType)),s="dca"!==r&&!C;if("tpsl"===r){let r=i.filter(e=>"tp"===e.orderType),n=i.filter(e=>"sl"===e.orderType),a=r.length>0||n.length>0,l=(e,r,i)=>{let s=parseFloat(e.triggerPriceUsd||"0"),n=parseFloat(e.sizeUsd||"0"),a="number"==typeof e.closeBps&&e.closeBps>0?e.closeBps/1e4:ex>0?n/ex:0,l=a>0?Math.round(100*a):null;return(0,t.jsx)("button",{onClick:()=>e.orderPda&&ed(e.orderPda),className:"flex items-center justify-between px-3 py-1.5 w-full text-left hover:bg-surface-interactive transition-colors",children:(0,t.jsxs)("span",{className:(0,h.cn)("text-[10px] font-mono tabular-nums font-medium","tp"===r?"text-side-long":"text-side-short"),children:["tp"===r?"TP":"SL"," ",Z.price(s),null!==l&&(0,t.jsxs)("span",{className:"text-label-muted ml-0.5",children:["(",l,"%)"]})]})},i)},o=s?(0,t.jsxs)("div",{className:"flex items-center justify-between px-3 py-1.5",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:a?"":X("mobileNoTpSlSet")}),(0,t.jsx)("button",{disabled:e,title:e?X("reviewTradingDisabled"):void 0,onClick:()=>{e||(ei("tp"),et(!0))},className:"text-[10px] text-muted-foreground hover:text-foreground transition-colors ml-2 shrink-0",children:a?X("mobileAddTpSl"):X("mobileAdd")})]},"add-tpsl"):null;return[...r.map((e,t)=>l(e,"tp",`tp-${e.orderPda??t}`)),...n.map((e,t)=>l(e,"sl",`sl-${e.orderPda??t}`)),o]}return(0,t.jsxs)("div",{className:"flex items-center justify-between px-3 py-1.5",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 text-[10px] min-w-0 flex-1",children:i.length>0?(0,t.jsx)("span",{className:"font-mono tabular-nums font-medium flex items-center gap-1 flex-wrap",children:i.map((e,r)=>{let i="ratchet"===e.orderType||"fib_ratchet"===e.orderType,s="indicator"===e.orderType||"indicator_ratchet"===e.orderType,n=i?e.ratchet?.worstPrice??parseFloat(e.triggerPriceUsd||"0"):parseFloat(e.triggerPriceUsd||"0"),a=Z.price(n),l=s?"RSI":i?X("historyTrail",{distance:a}):`${e.orderType} ${a}`;return(0,t.jsxs)("span",{children:[r>0&&(0,t.jsx)("span",{className:"text-muted-foreground mr-1",children:"/"}),(0,t.jsx)("button",{onClick:()=>e.orderPda&&ed(e.orderPda),className:(0,h.cn)("hover:underline",s?"text-amber-400":i?"text-blue-400":"text-muted-foreground"),children:l})]},r)})}):(0,t.jsx)("span",{className:"text-label-muted",children:G[r]})}),s&&(0,t.jsx)("button",{disabled:e,title:e?X("reviewTradingDisabled"):void 0,onClick:()=>{e||(ei(K[r]),et(!0))},className:"text-[10px] text-muted-foreground hover:text-foreground transition-colors ml-2 shrink-0",children:i.length>0?X("mobileAddMore"):X("mobileAdd")})]},r)})})]})),(0,t.jsxs)("div",{className:"flex items-center justify-between px-3 pb-3 pt-1 border-t border-border",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:b.createdAt?Z.dateTime(b.createdAt):X("mobileNotAvailable")}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[j&&"increase"===b.action&&(0,t.jsx)("button",{onClick:()=>{e||j(b)},disabled:e||y||k,className:"p-1.5 text-muted-foreground hover:text-amber-400 hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",title:X("mobileExecuteAtMar
2ket"),children:k?(0,t.jsx)(o.Spinner,{className:"size-3.5"}):(0,t.jsx)(s.Play,{className:"w-3.5 h-3.5"})}),eu&&(0,t.jsx)("button",{onClick:()=>en(!0),disabled:e||y||k,className:"p-1.5 text-muted-foreground hover:text-blue-400 hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",title:X("mobileEditOrder"),children:(0,t.jsx)(a.Pencil,{className:"w-3.5 h-3.5"})}),(0,t.jsx)("button",{onClick:()=>{e||v(b.orderPda,ef,b.profileIndex??0,N)},disabled:e||y||k,className:"p-1.5 text-muted-foreground hover:text-destructive hover:bg-surface-interactive rounded disabled:opacity-50 disabled:cursor-not-allowed",title:e?X("reviewTradingDisabled"):X("mobileCancelOrder"),children:y?(0,t.jsx)(o.Spinner,{className:"size-3.5"}):(0,t.jsx)(n.Trash2,{className:"w-3.5 h-3.5"})})]})]}),!e&&ee&&(0,t.jsx)(F,{open:ee,onOpenChange:et,order:b,closeOrders:N,livePrices:P,onPositionChange:T,defaultOrderType:er}),!e&&es&&(0,t.jsx)(m.EditOrderDialog,{order:b,open:es,onOpenChange:en,livePrice:w,onSuccess:T}),ec&&(0,t.jsx)(R.OrderDetailSheet,{open:!!ec,onOpenChange:e=>{e||ed(null)},order:(Y="indicator"===ec.orderType||"indicator_ratchet"===ec.orderType,{source:"jupiter_native"===ec.source?"jupiter_native":"imperial_passthrough",orderType:ec.orderType,triggerPriceUsd:ec.triggerPriceUsd,sizeUsd:ec.sizeUsd,closeBps:ec.closeBps,orderPda:ec.orderPda,triggerCondition:ec.triggerCondition,worstPriceUsd:ec.ratchet?.worstPrice!=null?String(ec.ratchet.worstPrice):void 0,ratchetSizeUsd:Y?void 0:ec.ratchet?.ratchetSize!=null?String(ec.ratchet.ratchetSize):void 0,stopTriggerPriceUsd:ec.ratchet?.stopTriggerPrice?String(ec.ratchet.stopTriggerPrice):void 0,profileIndex:ec.profileIndex,currentBestPriceUsd:ec.ratchet?.bestPriceSeen!=null?String(ec.ratchet.bestPriceSeen):void 0,currentIndicatorValue:ec.indicator?.currentValue,indicatorThreshold:ec.indicator?.thresholdValue!=null?String(ec.indicator.thresholdValue):void 0,indicatorCondition:ec.indicator?.indicatorCondition===1?"above":ec.indicator?.indicatorCondition===0?"below":void 0,indicatorTimeframe:ec.indicator?.timeframeCode!=null?g.TIMEFRAME_LABELS[ec.indicator.timeframeCode]:void 0,indicatorRatchetSize:"indicator_ratchet"===ec.orderType&&ec.ratchet?.ratchetSize?String(ec.ratchet.ratchetSize):void 0,isReverseFib:ec.ratchet?.isReverseFib}),asset:ep.symbol,underwriter:ec.underwriter??b.underwriter,side:ec.side??b.side??"long",positionSizeUsd:b.sizeUsd,livePrices:P,onCancelPassthroughOrder:e?void 0:ej})]})}var V=e.i(305916);let H="all";function W(e){return(0,p.getTokenInfo)(e.marketMint||"").symbol||"Unknown"}function q(e){let t=new Map;for(let r of e){let e=(0,p.getTokenInfo)(r.marketMint||""),i=e.symbol||"Unknown",s=t.get(i)??{symbol:i,image:e.image,orders:[]};s.orders.push(r),t.set(i,s)}return Array.from(t.values()).sort((e,t)=>t.orders.length-e.orders.length||e.symbol.localeCompare(t.symbol))}function K({group:e}){return(0,t.jsxs)(t.Fragment,{children:[e.image&&(0,t.jsx)(i.default,{src:e.image,alt:e.symbol,width:14,height:14,className:"rounded-full",unoptimized:!0,onError:f.handleTokenImageError}),(0,t.jsx)("span",{className:"text-[10px] font-medium text-label-muted",children:e.symbol}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted/70",children:e.orders.length})]})}function G({groups:e,totalCount:r,value:s,onChange:n,className:a}){let l=(0,d.useTranslations)("positions"),o=e=>(0,h.cn)(V.CHIP,e?V.CHIP_SELECTED_RING:V.CHIP_IDLE);return(0,t.jsxs)("div",{className:(0,h.cn)(V.CHIP_RAIL,a),children:[(0,t.jsxs)("button",{onClick:()=>n(H),className:o(s===H),children:[l("filterAllAssets"),(0,t.jsx)("span",{className:"text-label-muted",children:r})]}),e.map(e=>(0,t.jsxs)("button",{onClick:()=>n(s===e.symbol?H:e.symbol),className:o(s===e.symbol),children:[e.image&&(0,t.jsx)(i.default,{src:e.image,alt:e.symbol,width:14,height:14,className:"rounded-full",unoptimized:!0,onError:f.handleTokenImageError}),e.symbol,(0,t.jsx)("span",{className:"text-label-muted",children:e.orders.length})]},e.symbol))]})}},305085,923469,e=>{"use strict";e.s(["MobilePositionCard",()=>O],305085),e.s(["MobileHistoryCard",()=>C],923469);var t=e.i(394390),r=e.i(800239),i=e.i(183023),s=e.i(457058),n=e.i(943494),a=e.i(1169),l=e.i(467290),o=e.i(409686),d=e.i(695109),c=e.i(942553),u=e.i(153517),h=e.i(259048),p=e.i(268680),m=e.i(679555),f=e.i(670374),x=e.i(26826);e.i(889723);var g=e.i(465217),b=e.i(43085),v=e.i(585457),y=e.i(894771),w=e.i(51314),j=e.i(255810),S=e.i(845165),k=e.i(756880),N=e.i(637226),P=e.i(594651),T=e.i(299959);function C({action:e,asset:r,side:i,dcaGroupLabel:n,underwriter:a,marketMint:l}){let o,d=(0,c.useTranslations)("positions"),u=(0,c.useTranslations)("terms"),p=(0,T.useFormatters)(),m=(0,f.getTokenInfo)(r),g="increase"===e.actionType||"add_collateral"===e.actionType||"open"===e.actionType,b=(0,x.depositedCapitalForLeg)(e),v=(0,x.computeActionFees)(e),y=v-(0,x.parseRawValue)(e.pairsImpactFee),w="liquidation"===e.actionType||!!e.forcedCloseReason,j=w?d("historyActionLiquidation"):"max_payoff_close"===e.actionType?d("historyActionMaxPayoff"):"dca"===e.orderType&&n?n:"key"in(o=function(e){switch(e){case"market":default:return{key:"historyOrderTypeMarket"};case"limit":return{key:"historyOrderTypeLimit"};case"stop_limit":return{key:"historyOrderTypeStop"};case"landmine":return{key:"historyOrderTypeLandmine"};case"ratchet":return{key:"historyOrderTypeTrailingSl"};case"ratchet_entry":return{key:"historyOrderTypeTrailing"};case"fib_ratchet":return{key:"historyOrderTypeFibTrailingSl"};case"fib_ratchet_entry":return{key:"historyOrderTypeFibTrailing"};case"indicator":return{text:"RSI"};case"indicator_ratchet":return{key:"historyOrderTypeRsiTrailing"};case"dca":return{text:"DCA"}}}(e.orderType))?d(o.key):o.text,M=null!=e.sizeDelta&&0===(0,x.parseRawValue)(e.sizeDelta),_=d(w?"historyActionLiquidation":"max_payoff_close"===e.actionType?"historyActionMaxPayoff":M?g?"historyActionAddCollateral":"historyActionRemoveCollateral":g?"historyActionIncrease":"historyActionDecrease"),A=e.tx2Signature||e.tx1Signature,E=(0,x.parseRawValue)(e.entryPrice),L=e.tx2Timestamp??e.tx1Timestamp,F=l??(0,P.assetToMint)(r,a);return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg overflow-hidden px-3 py-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[m.image?(0,t.jsx)(s.default,{src:m.image,alt:m.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0}):(0,t.jsx)("div",{className:"w-4 h-4 rounded-full bg-gradient-to-r from-green-500 to-teal-500"}),(0,t.jsx)("span",{className:"text-xs text-foreground font-medium",children:m.symbol}),(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${g?"bg-emerald-500/20 text-emerald-400":"liquidation"===e.actionType?"bg-amber-500/20 text-amber-400":"bg-red-500/20 text-red-400"}`,children:d("historyActionSide",{action:_,side:i})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[!M&&E>0&&!!L&&!!F&&(0,t.jsx)("button",{title:d("historyShowFillOnChart"),className:"text-blue-400 hover:text-blue-300",onClick:e=>{e.stopPropagation(),(0,N.showFillOnChart)({marketMint:F,symbol:m.symbol,venue:a,timestampSec:L,price:E,locale:p.intlTag})},children:(0,t.jsx)(k.ChartCandlestick,{className:"w-3.5 h-3.5"})}),A&&(0,t.jsx)("a",{href:`https://orbmarkets.io/tx/${A}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(S.ExternalLink,{className:"w-3.5 h-3.5"})})]})]}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:d("historyColOrderType")}),(0,t.jsx)("div",{className:"text-xs text-secondary-foreground",children:j})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:u("size.full")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:p.rawUsd(e.sizeDelta)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:d("historyColPrice")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:M?"-":p.rawPrice(e.entryPrice)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:d(g?"historyColDeposit":"historyColReceived")}),(0,t.jsx)("div",{className:`text-xs font-mono tabular-nums ${g?"text-side-short":"text-side-long"}`,children:g?b>0?`-${p.rawUsd(b.toFixed(6))}`:"—":e.userReceived?`+${p.rawUsd(e.userReceived)}`:"—"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:u("pnl")}),(()=>{let r=(0,x.parseRawValue)(e.pnlRealized),i=Math.abs(r),s=(e.pnlRealized?!1===e.hasProfit?-i:!0===e.hasProfit?i:r:0)-v;if(0===s)return(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:"-"});let n=s<0,a=p.rawUsd(Math.abs(s).toString());return(0,t.jsx)("div",{className:`text-xs font-mono tabular-nums ${(0,h.pnlColor)(s)}`,children:n?`-${a}`:`+${a}`})})()]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:d("historyColFee")}),(0,t.jsxs)("div",{className:"text-xs text-amber-400 font-mono tabular-nums",children:["$",y.toLocaleStr
2ing(p.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),null!=e.pairsImpactFee&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:d("historyColSkewImpact")}),(0,t.jsx)("div",{className:"text-xs text-amber-400 font-mono tabular-nums",children:p.rawUsd(e.pairsImpactFee)})]})]}),(0,t.jsx)("div",{className:"mt-2 text-[10px] text-label-muted",children:p.dateTime(e.tx1Timestamp)})]})}var M=e.i(955724),_=e.i(317629),A=e.i(725452);let E="text-[9.26px] font-medium leading-none text-label-muted",L="mt-[3px] font-mono text-[10.5px] font-semibold leading-none tabular-nums text-foreground",F="mt-[3px] font-mono text-[8.64px] font-medium leading-none tabular-nums text-label-muted",R="inline-flex h-[19.76px] shrink-0 items-center justify-center rounded-[4.94px] px-[6.2px] text-[9.88px] font-medium leading-none",D="bg-[var(--phone-hairline)] text-foreground",I="flex h-[29px] flex-1 items-center justify-center rounded-[5px] border-[0.926px] border-[var(--phone-control-edge)] bg-[var(--phone-control)] text-[9.88px] font-medium text-foreground transition-colors hover:bg-surface-interactive disabled:cursor-not-allowed disabled:opacity-50 focus-ring",U="flex w-[30px] shrink-0 items-center justify-center rounded-[4px] border-[0.926px] border-[var(--phone-control-edge)] bg-[var(--phone-control)] text-foreground transition-colors hover:bg-surface-interactive focus-ring";function O({readOnly:e=!1,lifecycle:S,isClosing:k,showDateColumn:N,onCancelPassthroughOrder:P,onCancelJupiterOrder:B,livePrices:z,orderbookMidPrice:$,dcaGrouping:V,onOpenCloseSheet:H,onOpenOrderSheet:W,onOpenTxnsSheet:q,onOpenEditCollateralSheet:K}){let G,Y,X,Q,J,Z,ee,et,er=(0,c.useTranslations)("positions"),ei=(0,c.useTranslations)("terms"),es=(0,T.useFormatters)(),[en,ea]=(0,i.useState)(!1),[el,eo]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[eu,eh]=(0,i.useState)(!1),[ep,em]=(0,i.useState)(null),ef=ep?(S.tpslOrders??[]).find(e=>e.orderPda===ep)??null:null,{setMarketMint:ex}=(0,v.useMarketContext)(),{setActiveProfileIndex:eg,profiles:eb}=(0,y.useProfile)(),{tokenInfo:ev,profileName:ey,profileIdx:ew,isLong:ej,isClosed:eS,feesLoading:ek,livePrice:eN,useLivePrice:eP,pnlValue:eT,packEntryPrice:eC,packOpenedAt:eM,packPnlUsd:e_,packPnlPercent:eA,pnlPercentValue:eE,feesPaidValue:eL,feesOwedValue:eF,pricePnl:eR,realizedPnl:eD,realizedInclOpenFees:eI,settledFunding:eU,settledCloseFees:eO,displaySize:eB,displayCollateral:ez,displayLeverage:e$,displayLiquidationPrice:eV,avgEntryPrice:eH,shareCardMarkPrice:eW,breakevenPrice:eq,displayActions:eK,dcaGroupLabels:eG}=(0,j.usePositionData)({lifecycle:S,livePrices:z,dcaGrouping:V}),eY="venue_direct"===S.ownership&&(0,x.isPhoenixUnderwriter)(S.underwriter),eX=(0,x.isCrossMarginLeg)(S),eQ=eX||eY&&eS&&!ez,eJ=ei((0,A.marginModeLabelKey)(S.directVenue?.marginMode)),eZ=eX?S.directVenue?.accountCollateralUsd:ez,e0=S.tpslOrders??[],e1=e=>e?es.price(parseFloat(e)):"-- / --",e2=(0,x.parseRawValue)(eH),e5=(0,x.parseRawValue)(eB),e3=S.sizeTokenAmount?parseFloat(S.sizeTokenAmount):e2>0?e5/e2:0,e4=e3>0?e3.toLocaleString(es.intlTag,{maximumFractionDigits:4}):null,e6=e3*(eP?eN:(0,x.parseRawValue)(S.markPrice)),e8=eS||!(e5>0)||eX?null:(0,x.parseRawValue)(S.collateralUsd)/e5*100,e9=0!==ew||eb[0]?.name?ey:er("mobileAccountMain"),e7=!eS&&"pairs"!==S.underwriter&&!eY&&!eX&&!!K;return(0,t.jsxs)("div",{className:"overflow-hidden rounded-[5px] border-[0.926px] border-[var(--phone-card-border)] bg-[var(--phone-band)]",children:[(0,t.jsxs)("div",{className:"relative",onClick:()=>ec(e=>!e),children:[(0,t.jsxs)("div",{className:"flex flex-col px-[12px] pb-[12px] pt-[11px]",children:[(0,t.jsxs)("div",{className:"flex items-center gap-[6px] pr-[36px]",children:[(0,t.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),null!=ew&&eg(ew),ex((0,w.fromUrlSlug)(S.asset))},className:"flex min-w-0 items-center gap-[4px] focus-ring rounded-[3px]",children:[ev.image?(0,t.jsx)(s.default,{src:ev.image,alt:ev.symbol,width:16,height:16,className:"h-4 w-4 shrink-0 rounded-full",unoptimized:!0,onError:g.handleTokenImageError}):(0,t.jsx)("span",{className:"h-4 w-4 shrink-0 rounded-full bg-gradient-to-r from-green-500 to-teal-500"}),(0,t.jsx)("span",{className:"truncate text-[12.35px] font-bold leading-none tracking-[0.12px] text-foreground",children:ev.symbol})]}),(0,t.jsx)("span",{className:(0,u.cn)(R,"ml-[12px] min-w-[39.5px]",ej?"bg-[var(--side-pad-long)] text-[var(--side-ink-long)]":"bg-[var(--side-pad-short)] text-[var(--side-short)]"),children:ej?er("historyLong"):er("historyShort")}),!eX&&(0,t.jsx)("span",{className:(0,u.cn)(R,D,"min-w-[39.5px] font-mono tabular-nums"),children:es.rawLeverage(e$)}),e9&&(0,t.jsx)("span",{className:(0,u.cn)(R,D,"min-w-[35.8px]"),children:e9}),eY&&(0,t.jsx)("span",{className:(0,u.cn)(R,"bg-primary/15 text-primary"),children:"Phoenix Direct"}),(eY||eX)&&(0,t.jsx)("span",{className:(0,u.cn)(R,D),children:eJ})]}),(0,t.jsxs)("div",{className:"mt-[6px] flex items-start",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col",children:[(0,t.jsx)("span",{className:E,
2children:er("mobilePnlUsd")}),ek?(0,t.jsx)(m.Skeleton,{className:"mt-[4px] h-[17px] w-24 rounded"}):(0,t.jsxs)(p.Tooltip,{children:[(0,t.jsx)(p.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{className:(0,u.cn)("mt-[4px] w-fit cursor-help font-mono text-[16.67px] font-bold leading-none tabular-nums underline decoration-dashed decoration-[1px] underline-offset-[5px]",(0,h.pnlColor)(e_??eT)),style:{textDecorationColor:"color-mix(in srgb, currentColor 80%, transparent)"},children:es.pnl(e_??eT)})}),(0,t.jsx)(p.TooltipContent,{side:"top",className:"font-mono text-xs",children:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-semibold mb-2",children:er("mobilePnlBreakdown")}),!eS&&0!==eR&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:er("mobilePnlUnrealized")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(eR)})]}),0!==eF&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:er("mobilePnlFeesOwed")}),(0,t.jsx)("span",{className:(0,u.cn)("font-mono tabular-nums",eF<0?"text-green-400":void 0),children:es.pnl(-eF)})]}),(0!==eD||eL>0)&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:er("mobilePnlRealized")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(eI)})]}),0!==eU&&(0,t.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,t.jsx)("span",{className:"pl-2",children:er("mobileInclSettledFunding")}),(0,t.jsx)("span",{className:(0,u.cn)("font-mono tabular-nums",eU<0?"text-green-400":void 0),children:es.pnl(-eU)})]}),0!==eO&&(0,t.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,t.jsx)("span",{className:"pl-2",children:er("mobileInclCloseFees")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(-eO)})]}),eL>0&&(0,t.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,t.jsx)("span",{className:"pl-2",children:er("mobileInclOpenFees")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(-eL)})]}),null!==e_&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:er("packPrizeLessPriceLabel")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(e_-eT)})]}),S.packPrize&&null!==(0,f.packIssueBasisUsd)(S.packPrize)&&(0,t.jsx)("div",{className:"border-t border-border pt-2 mt-2 max-w-[300px]",children:(0,t.jsx)(r.PackPositionBreakdown,{priceCents:100*Number(S.packPrize.stakeUsd),basisCents:100*(0,f.packIssueBasisUsd)(S.packPrize),awardCents:((0,f.packIssueBasisUsd)(S.packPrize)+Number(S.packPrize.pnlOffsetUsd))*100,pnlUsd:(0,f.packPnlVsIssueBasisUsd)(S.packPrize,eT),tradingCostsUsd:eL+eF})}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border pt-1 mt-1 font-semibold",children:[(0,t.jsx)("span",{className:"text-secondary-foreground",children:er("mobilePnlTotal")}),(0,t.jsx)("span",{className:"font-mono tabular-nums",children:es.pnl(e_??eT)})]}),(0,t.jsx)(b.LoanScoreboardRows,{lifecycle:S})]})})]})]}),(0,t.jsxs)("div",{className:"flex w-[115px] shrink-0 flex-col pt-[4px]",children:[(0,t.jsx)("span",{className:E,children:er("mobilePnlPercent")}),(0,t.jsx)("span",{className:(0,u.cn)("mt-[4px] font-mono text-[13.58px] font-semibold leading-none tabular-nums",(0,h.pnlColor)(e_??eT)),children:ek||eQ?"—":es.signedPercent(eA??eE,2)})]})]})]}),(0,t.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),ec(e=>!e)},"aria-expanded":ed,"aria-label":er(ed?"shelfCollapse":"shelfExpand"),className:(0,u.cn)(U,"absolute right-[12px] top-[9px] h-[23px] before:absolute before:-inset-[10px] before:content-['']"),children:(0,t.jsx)(a.ChevronDown,{className:(0,u.cn)("h-[10px] w-[10px] transition-transform",ed&&"rotate-180"),strokeWidth:2.5})})]}),ed&&(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"px-[12px]",children:[!eS&&0!==eI&&(0,t.jsxs)("div",{className:"flex items-baseline gap-[9px]",children:[(0,t.jsx)("span",{className:E,
2children:er("historyColRealizedPnl")}),(0,t.jsx)("span",{className:(0,u.cn)("font-mono text-[9.26px] font-medium leading-none tabular-nums",(0,h.pnlColor)(eI)),children:es.pnl(eI)})]}),(0,t.jsxs)("div",{role:!eS&&q?"button":void 0,onClick:!eS&&q?()=>q():void 0,className:(0,u.cn)("mt-[16px] grid grid-cols-[118.5px_118.5px_1fr] gap-y-[10px] pb-[6px] [&>*:nth-child(n+7)]:mt-[3px]",!eS&&q&&"cursor-pointer"),children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileQtyWithSymbol",{symbol:ev.symbol})}),(0,t.jsx)("div",{className:L,children:e4??"—"}),(0,t.jsxs)("div",{className:F,children:["≈ $",e6.toLocaleString(es.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),(0,t.jsxs)("div",{children:[e7?(0,t.jsxs)("button",{type:"button",onClick:t=>{t.stopPropagation(),e||K()},disabled:e,title:e?er("reviewTradingDisabled"):void 0,className:(0,u.cn)(E,"flex items-center gap-[4px] transition-colors hover:text-secondary-foreground"),children:[er("mobileCollateralUsd"),(0,t.jsx)(d.Pencil,{className:"h-[6px] w-[6px]"})]}):(0,t.jsx)("div",{className:E,children:eX?er("mobileShared"):er("mobileCollateralUsd")}),(0,t.jsx)("div",{className:L,children:es.rawUsd(eZ)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileCollateralRatio")}),(0,t.jsx)("div",{className:L,children:null!=e8?es.percent(e8,2):"—"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileEntryPrice")}),(0,t.jsx)("div",{className:L,children:es.rawPrice(eC??eH)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileMarkPrice")}),(0,t.jsx)("div",{className:L,children:eP?es.price(eN):es.rawPrice(S.markPrice)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileLiqPrice")}),(0,t.jsx)("div",{className:(0,u.cn)(L,"text-primary"),children:eS?"—":es.rawPrice(eV)}),!eS&&S.liqBandPriceUsd&&(0,t.jsxs)("div",{className:F,children:[er("mobileLiqFill")," ",ej?"≥":"≤"," ",es.rawPrice(S.liqBandPriceUsd)]})]}),eq&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileBreakeven")}),(0,t.jsx)("div",{className:L,children:es.rawPrice(eq)})]}),(0,x.parseRawValue)(S.totalFeesUsd)>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileFeesPaid")}),(0,t.jsx)("div",{className:L,children:es.rawUsd(S.totalFeesUsd)})]}),!eS&&S.feesOwed&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:E,children:er("mobileFeesOwed")}),(0,t.jsx)("div",{className:(0,u.cn)(L,eF<0&&"text-side-long"),children:eF<0?es.pnl(eF):es.rawUsd(S.feesOwed)})]})]})]}),!eS&&!eY&&W&&(G=e0.filter(e=>"tp"===e.orderType||"private_tp"===e.orderType),Y=e0.filter(e=>"sl"===e.orderType||"private_sl"===e.orderType),X=e0.filter(e=>"ratchet"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType),Q=e0.filter(e=>"dca_close"===e.orderType||"dca_time_close"===e.orderType||"dca_ratchet_close"===e.orderType),J=e0.filter(e=>"indicator"===e.orderType||"indicator_ratchet"===e.orderType),ee=0===(Z=G.length+Y.length+X.length+Q.length+J.length)?er("mobileCloseOrdersNone"):er("mobileOrdersPlacedCount",{amount:String(Z)}),et=(r,i,s,n,a,l)=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 px-[15px] py-2",children:[(0,t.jsx)("span",{className:"shrink-0 text-[10.5px] font-medium text-label-muted",children:r}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center justify-end gap-1.5",children:[0===n.length?(0,t.jsx)("span",{className:"font-mono text-[10.5px] tabular-nums text-secondary-foreground",children:"-- / --"}):n.map((n,o)=>(0,t.jsx)("button",{type:"button",onClick:()=>{n.orderPda?em(n.orderPda):e||W(i,n,s)},className:(0,u.cn)("rounded-[4.94px] bg-[var(--phone-hairline)] px-2 py-0.5 font-mono text-[10.5px] tabular-nums transition-colors hover:text-foreground",l?l(n):"text-foreground"),title:er("mobileViewLabel",{label:r}),children:a(n)},n.orderPda??o)),(0,t.jsx)("button",{type:"button",onClick:()=>{e||W(i,void 0,s)},disabled:e,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--phone-hairline)] text-secondary-foreground transition-colors hover:text-foreground",title:e?er("reviewTradingDisabled"):er("mobileAddLabel",{label:r}),children:(0,t.jsx)(o.Plus,{className:"h-3.5 w-3.5"})})]})]}),(0,t.jsxs)("div",{className:"border-t-[0.926px] border-[var(--phone-hairline)]",children:[(0,t.jsxs)("button",{type:"button",onClick:()=>eh(e=>!e),"aria-expanded":eu,className:"flex h-[26px] w-full items-center gap-[10px] pl-[15px] pr-[14px] text-[10.5px] font-medium leading-none transition-colors hover:bg-surface-interactive",children:[(0,t.jsx)(a.ChevronDown,{className:(0,u.cn)("h-[8px] w-[8px] text-secondary-foreground transition-transform",!eu&&"-rotate-90"),strokeWidth:2.5}),(0,t.jsx)("span",{className:"text-secondary-foreground",children:er("mobileCloseOrders")}),(0,t.jsx)("span",{className:"ml-auto text-label-muted",children:ee})]}),eu&&(0,t.jsxs)("div",{className:"divide-y divide-[var(--phone-hairline)] border-t-[0.926px] border-[var(--phone-hairline)]",children:[et("TP / SL","tpsl","tp",[...G,...Y],e=>e1(e.triggerPriceUsd),e=>{let t="private_tp"===e.orderType||"private_sl"===e.orderType,r="tp"===e.orderType||"private_tp"===e.orderType;return t?"text-purple-300":r?"text-side-long":"text-side-short"}),et(er("mobileTrailingStop"),"trailing","ratchet",X,e=>e1(e.worstPriceUsd)),et(er("historyOrderTypeDcaClose"),"dca","dca_close",Q,()=>er("mobilePlaced")),et(er("mobileIndicator"),"rsi","rsi",J,()=>er("mobilePlaced"))]})]})),(k||N)&&(0,t.jsxs)("div",{className:"space-y-1 px-[12px] pb-2",children:[k&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-amber-400",children:[(0,t.jsx)(n.Loader2,{className:"h-3 w-3 animate-spin"}),(0,t.jsx)("span",{children:er("mobileClosePositionQueued")})]}
2),N&&(0,t.jsxs)("div",{className:E,children:[new Date((eM??S.openedAt)*1e3).toLocaleDateString(es.intlTag,{month:"short",day:"numeric",year:"numeric"}),S.closedAt&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"mx-1 text-muted-foreground",children:"→"}),new Date(1e3*S.closedAt).toLocaleDateString(es.intlTag,{month:"short",day:"numeric",year:"numeric"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-end gap-[8px] border-t-[0.926px] border-[var(--phone-hairline)] px-[10px] pb-[13px] pt-[8px]",children:[!eS&&(0,t.jsxs)(t.Fragment,{children:[!eY&&(0,t.jsx)("button",{type:"button",onClick:()=>{e||W?.("tpsl",void 0,"tp")},title:e?er("reviewTradingDisabled"):void 0,disabled:e||!W,className:I,children:"TP/SL"}),(0,t.jsx)("button",{type:"button",onClick:()=>{e||H?.()},title:e?er("reviewTradingDisabled"):void 0,disabled:e||k||!H,className:I,children:k?(0,t.jsx)(n.Loader2,{className:"mx-auto h-3 w-3 animate-spin"}):er("mobileClose")})]}),(0,t.jsx)("button",{type:"button",onClick:()=>eo(!0),title:er("mobileSharePnl"),"aria-label":er("mobileSharePnl"),className:(0,u.cn)(U,"h-[27px]"),children:(0,t.jsx)(l.Share2,{className:"h-3 w-3"})})]}),eS&&(0,t.jsx)("div",{className:"px-3 pb-2 pt-1 border-t border-border",children:(0,t.jsxs)("button",{onClick:()=>ea(!en),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(a.ChevronDown,{className:(0,u.cn)("w-3 h-3 transition-transform",en&&"rotate-180")}),er("mobileTransactionHistory")]})}),en&&(0,t.jsx)("div",{className:"border-t border-border bg-surface p-3 space-y-2",children:0===eK.length?(0,t.jsx)("div",{className:"text-center text-label-muted text-xs py-3",children:er("mobileNoTransactions")}):eK.map(e=>(0,t.jsx)(C,{action:e,asset:S.asset,side:S.side,dcaGroupLabel:eG.get(e.id),underwriter:S.underwriter},e.id))}),(0,t.jsx)(M.SharePnlDialog,{open:el,onOpenChange:eo,lifecycle:S,pnlPercent:eA??eE,pnlUsd:e_??eT,leverage:e$??"1",entryPriceOverride:eC??eH,markPriceOverride:eW}),ef&&(0,t.jsx)(_.OrderDetailSheet,{open:!!ef,onOpenChange:e=>{e||em(null)},order:ef,asset:S.asset,underwriter:S.underwriter,side:S.side,positionSizeUsd:S.sizeUsd,livePrices:z,onCancelPassthroughOrder:e?void 0:P,onCancelJupiterOrder:e?void 0:B,onEditOrder:!e&&W?e=>{em(null),W({tp:"tpsl",sl:"tpsl",private_tp:"tpsl",private_sl:"tpsl",ratchet:"trailing",fib_ratchet:"trailing",fib_ratchet_entry:"trailing",dca_close:"dca",dca_time_close:"dca",dca_ratchet_close:"dca",indicator:"rsi",indicator_ratchet:"rsi"}[e.orderType]??"tpsl",e,{tp:"tp",private_tp:"tp",sl:"sl",private_sl:"sl",ratchet:"ratchet",fib_ratchet:"ratchet",fib_ratchet_entry:"ratchet",dca_close:"dca_close",dca_time_close:"dca_close",dca_ratchet_close:"dca_close",indicator:"rsi",indicator_ratchet:"rsi"}[e.orderType])}:void 0,lifecycle:S})]})}},247897,e=>{"use strict";e.s(["OrdersTab",()=>S]);var t=e.i(394390),r=e.i(51559),i=e.i(989714),s=e.i(984457),n=e.i(265172),a=e.i(183023),l=e.i(888245),o=e.i(546642),d=e.i(942553),c=e.i(326729),u=e.i(854553),h=e.i(687229),p=e.i(894771),m=e.i(24893),f=e.i(97881),x=e.i(670374),g=e.i(976955),b=e.i(728570),v=e.i(341296),y=e.i(124431),w=e.i(346731);function j({readOnly:e=!1,profileName:r,orders:i,matchedFor:s,activePositionKeys:n,cancelingOrderId:l,livePrices:o,executingOrderId:p,onExecuteNow:f,onCancelPassthroughOrder:x,onPositionChange:g,onUpdatePriority:b,onBatchUpdatePriorities:v}){let y=(0,d.useTranslations)("positions"),[w,S]=(0,a.useState)(()=>({source:i,ids:i.map(e=>e.orderPda)})),[k,N]=(0,a.useState)(!1),P=k||w.source===i?w.ids:i.map(e=>e.orderPda);k||w.source===i||S({source:i,ids:P});let T=(0,a.useMemo)(()=>{let e=new Map;for(let t of i)e.set(t.orderPda,t);return e},[i]),C=(0,a.useMemo)(()=>{let e=[];for(let t of P){let r=T.get(t);r&&e.push(r)}for(let t of i)P.includes(t.orderPda)||e.push(t);return e},[P,T,i]),M=(0,a.useCallback)(()=>{N(!0)},[]),_=(0,a.useCallback)(t=>{N(!1);let{active:r,over:s}=t;if(e||!s||r.id===s.id)return;let n=P.indexOf(String(r.id)),a=P.indexOf(String(s.id));if(-1===n||-1===a)return;let l=(0,u.arrayMove)(P,n,a);S({source:i,ids:l});let o=[];for(let e=0;e<l.length;e++){let t=T.get(l[e]);t&&(t.priority??0)!==e&&o.push({orderPda:t.orderPda,profileIndex:t.profileIndex??0,priority:e,underwriter:t.underwriter})}o.length>0&&v?.(o)},[e,P,i,T,v]);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("tr",{children:(0,t.jsx)("td",{colSpan:9,className:"py-2 px-4 text-[10px] font-medium text-yellow-500/70 bg-yellow-500/5 border-b border-border",children:y("deferredOrdersGroupHeader",{profile:r})})}),(0,t.jsx)(c.DndContext,{collisionDetection:c.closestCenter,onDragStart:M,onDragEnd:_,onDragCancel:()=>N(!1),children:(0,t.jsx)(u.SortableContext,{items:P,strategy:u.verticalListSortingStrategy,children:C.map(r=>{let i=`${(0,h.mintToMatchingKey)(r.marketMint||"")}:${r.side}:${r.profileIndex??""}`,a=s(r);return(0,t.jsx)(m.SortablePassthroughOrderRow,{readOnly:e,id:r.orderPda,order:r,onCancel:x,isCanceling:l===r.orderPda,livePrice:o?.[r.marketMint||""],onExecuteNow:f,isExecuting:p===r.orderPda,closeOrders:a,livePrice
2s:o,onPositionChange:g,hasActivePosition:n.has(i),onUpdatePriority:b},r.orderPda)})})})]})}function S({readOnly:e=!1,passthroughOrders:c,cancelingOrderId:u,onCancelPassthroughOrder:k,livePrices:N,executingOrderId:P,onExecuteNow:T,limitCloseOrders:C,onPositionChange:M,onUpdatePriority:_,onBatchUpdatePriorities:A}){let E=(0,d.useTranslations)("positions"),L=(0,d.useTranslations)("terms"),{positions:F,walletState:R,ordersAvailability:D,ordersLoading:I}=(0,h.useUnifiedPositions)(),{profiles:U,activeProfileIndex:O}=(0,p.useProfile)(),{balances:B}=(0,y.useProfileBalance)(),[z,$]=(0,a.useState)(g.ALL_ASSETS),V=c.length,H=(0,b.usePhoenixOrderbookFills)(c),{panelRef:W,isDesktop:q}=(0,v.usePanelLayout)(500),K=B.USDC,G=(0,a.useMemo)(()=>{let e=new Map;if(null===K||null===O)return e;for(let t of c){if(t.profileIndex!==O)continue;let r=(0,w.fundingShortfallUsd)(t,K);null!==r&&e.set(t.orderPda,r)}return e},[c,K,O]),Y=(0,a.useMemo)(()=>new Set(F.map(e=>`${(0,x.getMarketMintFromAsset)(e.asset)??""}:${e.side}:${e.profileIndex??""}`)),[F]),{closeOrdersByParentPda:X,closeOrdersByTriple:Q}=(0,a.useMemo)(()=>{let e=new Map,t=new Map;if(!C)return{closeOrdersByParentPda:e,closeOrdersByTriple:t};for(let r of C)if(r.parentOrderPda){let t=e.get(r.parentOrderPda)??[];t.push(r),e.set(r.parentOrderPda,t)}else{let e=`${(0,h.mintToMatchingKey)(r.marketMint||"")}:${r.side}:${r.profileIndex??""}`,i=t.get(e)??[];i.push(r),t.set(e,i)}return{closeOrdersByParentPda:e,closeOrdersByTriple:t}},[C]),J=(0,a.useCallback)(e=>{let t=X.get(e.orderPda)??[],r=`${(0,h.mintToMatchingKey)(e.marketMint||"")}:${e.side}:${e.profileIndex??""}`,i=[...t,...Q.get(r)??[]];return i.length>0?i:void 0},[X,Q]),Z=(0,a.useMemo)(()=>(0,g.groupOrdersByAsset)(c),[c]),ee=Z.some(e=>e.symbol===z)?z:g.ALL_ASSETS,et=(0,a.useMemo)(()=>ee===g.ALL_ASSETS?c:c.filter(e=>(0,g.assetSymbolOf)(e)===ee),[c,ee]),{deferredByProfile:er,normalOrders:ei}=(0,a.useMemo)(()=>{let e=new Map,t=[];for(let r of et)if(1===r.fundingStatus){let t=r.profileIndex??0,i=e.get(t)??[];i.push(r),e.set(t,i)}else t.push(r);for(let[,t]of e)t.sort((e,t)=>(e.priority??0)-(t.priority??0));return{deferredByProfile:e,normalOrders:t}},[et]),es=(0,a.useMemo)(()=>Array.from(er.keys()).sort((e,t)=>e-t),[er]),en=es.length>0,ea=(0,a.useMemo)(()=>(0,g.groupOrdersByAsset)(q?ei:[...ei,...es.flatMap(e=>er.get(e)??[])]),[q,ei,es,er]),el=1e3*(0,i.useTickingNowSecs)(),eo=null===D.lastReadAt||el-D.lastReadAt>=n.READ_STALE_MS;if(0===V)return"disconnected"===R?(0,t.jsx)(o.TabConnectEmptyState,{title:E("connectToViewOrders"),hint:E("connectToViewOrdersHint")}):I?(0,t.jsxs)("div",{className:"flex items-center justify-center py-12",role:"status",children:[(0,t.jsx)(s.Spinner,{className:"size-6 text-muted-foreground"}),(0,t.jsx)("span",{className:"sr-only",children:E("loadingEllipsis")})]}):(0,t.jsx)(t.Fragment,{children:"available"!==D.status||eo?(0,r.hasUnverifiedAccountUpdate)(D)&&(0,t.jsx)(o.TabEmptyState,{title:E("accountReadNoOrdersToDisplay"),hint:E("noPendingOrdersHint")}):(0,t.jsx)(o.TabEmptyState,{title:E("noPendingOrders"),hint:E("noPendingOrdersHint")})});let ed=Z.length>1;return(0,t.jsxs)("div",{ref:W,className:"h-full min-h-0 min-w-0",children:[!1===q&&(0,t.jsxs)(t.Fragment,{children:[ed&&(0,t.jsx)(g.OrdersAssetFilterBar,{groups:Z,totalCount:V,value:ee,onChange:$,className:"px-3 pt-3"}),(0,t.jsx)("div",{className:"space-y-5 p-3 overflow-y-auto",children:ea.map(r=>(0,t.jsxs)("div",{className:"space-y-3",children:[ea.length>1&&(0,t.jsxs)("div",{className:"flex items-center gap-2 px-1",children:[(0,t.jsx)(g.AssetGroupLabel,{group:r}),(0,t.jsx)("div",{className:"flex-1 h-px bg-border"})]}),r.orders.map(r=>{let i=`${(0,h.mintToMatchingKey)(r.marketMint||"")}:${r.side}:${r.profileIndex??""}`,s=J(r);return(0,t.jsx)(f.MobilePassthroughOrderCard,{readOnly:e,order:r,onCancel:k,isCanceling:u===r.orderPda,livePrice:N?.[r.marketMint||""],onExecuteNow:T,isExecuting:P===r.orderPda,closeOrders:s,livePrices:N,onPositionChange:M,hasActivePosition:Y.has(i),fundingShortfallUsd:G.get(r.orderPda)},r.orderPda)})]},r.symbol))})]}),q&&(0,t.jsxs)("div",{className:"flex flex-col h-full min-h-0 min-w-0",children:[ed&&(0,t.jsx)(g.OrdersAssetFilterBar,{groups:Z,totalCount:V,value:ee,onChange:$,className:"shrink-0 px-4 py-2 border-b border-border"}),(0,t.jsx)("div",{className:l.default.scroll,children:(0,t.jsxs)("table",{className:l.default.ordersTable,children:[(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[130px] sticky left-0 z-20 bg-canvas",children:E("columnOrder")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("columnType")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:L("size.full")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("collateral")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("columnTriggerPrice")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("columnPro")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("columnCreated")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-center w-[80px]",children:"TP/SL"}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left",children:E("columnActions")})]})}),(0,t.jsxs)("tbody",{children:[ea.map(r=>(0,t.jsxs)(a.Fragment,{children:[ea.length>1&&(0,t.jsx)("tr",{children:(0,t.jsx)("td",{colSpan:9,className:"py-1.5 px-4 bg-surface-raised/40 border-b border-border",children:(0,t.jsx)("div",{className:"flex items-center gap-2 sticky left-4 w-fit",children:(0,t.jsx)(g.AssetGroupLabel,{group:r})})})}),r.orders.map(r=>{let i=`${(0,h.mintToMatchingKey)(r.marketMint||"")}:${r.side}:${r.profileIndex??""}`,s=J(r);return(0,t.jsx)(m.PassthroughOrderRow,{readOnly:e,order:r,onCancel:k,isCanceling:u===r.orderPda,livePrice:N?.[r.marketMint||""],onExecuteNow:T,isExecuting:P===r.orderPda,closeOrders:s,livePrice
2s:N,onPositionChange:M,hasActivePosition:Y.has(i),onUpdatePriority:_,phoenixFill:H.get(r.orderPda),fundingShortfallUsd:G.get(r.orderPda)},r.orderPda)})]},r.symbol)),en&&es.map(r=>{let i=er.get(r),s=(U.length>r?U[r]?.name:null)??E("profileFallbackName",{index:r+1});return(0,t.jsx)(j,{readOnly:e,profileIndex:r,profileName:s,orders:i,matchedFor:J,activePositionKeys:Y,cancelingOrderId:u,livePrices:N,executingOrderId:P,onExecuteNow:T,onCancelPassthroughOrder:k,onPositionChange:M,onUpdatePriority:_,onBatchUpdatePriorities:A},r)})]})]})})]})]})}},526862,e=>{"use strict";e.s(["PairGroupCards",()=>x,"PairGroupRows",()=>f]);var t=e.i(394390),r=e.i(190459),i=e.i(183023),s=e.i(942553),n=e.i(227631),a=e.i(967090);e.i(670374);var l=e.i(26826),o=e.i(157157),d=e.i(601852),c=e.i(232024),u=e.i(375290),h=e.i(153517);function p(e){let t=Math.abs(e);return`${e<0?"-":""}$${t<10?t.toFixed(2):Math.round(t).toLocaleString()}`}function m({link:e,legs:f,onCloseAll:x,variant:g}){let b,{data:v}=(0,o.useFundingRates)(),y=(0,c.pairRepayment)(f.map(e=>{let t,i,s;return t=(0,l.parseRawValue)(e.sizeUsd),s=(i=(0,r.venueFromUnderwriter)(e.underwriter??"",e.hedgeVenue))?(0,d.signedCarryPctPerHour)(v?.get(e.asset.toUpperCase()),i,"long"===e.side?"long":"short"):null,{feesPaidUsd:(0,l.feesPaidForRemainingSize)(e),closeFeesUsd:(0,l.parseRawValue)(e.closeFeeOwed)+(0,l.parseRawValue)(e.swapFeeOwed),accruedFundingUsd:(0,l.parseRawValue)(e.borrowFeeOwed),fundingRateHourlyUsd:null!==s&&t>0?-s/100*t:null}}),(0,l.parseRawValue)(e.settledFundingNetUsd)),w=Math.round(100*y.progress),j=y.remainingUsd<=0,S=(0,s.useTranslations)("carry"),[k,N]=(0,i.useState)(!1),P=y.netRateHourlyUsd,T=!j&&null!==P&&P>0,C=!j&&null===P,M=j?100:Math.max(2,w);return(0,t.jsxs)("div",{className:(0,h.cn)("pair-group__strip","cards"===g&&"pair-group__strip--cards",T&&"pair-group__strip--paying"),children:[(0,t.jsxs)("div",{className:"pair-group__tab",children:[(0,t.jsx)(n.Link2,{className:"h-3 w-3 shrink-0"}),(0,t.jsx)("span",{className:"font-semibold whitespace-nowrap",children:e.label||"Pair"}),(0,t.jsx)("div",{className:"pair-group__bar",title:S("barTooltip",{earned:p(y.fundingEarnedUsd),total:p(y.totalFeesUsd)}),children:(0,t.jsx)("div",{className:(0,h.cn)("pair-group__bar-fill",j&&"pair-group__bar-fill--done"),style:{width:`${M}%`}})}),(0,t.jsx)("span",{className:"font-mono tabular-nums whitespace-nowrap",children:j?(0,t.jsx)("span",{className:"text-emerald-400",children:S("feesRepaid")}):T?(0,t.jsx)("span",{className:"text-amber-300",children:S("payingPerHour",{amount:(b=Math.abs(P))>=1?`$${b.toFixed(2)}`:b>=.01?`$${b.toFixed(3)}`:`$${b.toFixed(4)}`})}):C?(0,t.jsx)("span",{className:"opacity-70",children:S("rateUnavailable")}):(0,t.jsxs)(t.Fragment,{children:[S("amountLeft",{percent:w,amount:p(y.remainingUsd)}),null!==y.hoursToRepay&&(0,t.jsxs)("span",{className:"opacity-70",children:[" (~",(0,u.formatBreakEven)(y.hoursToRepay),")"]})]})}),x&&(k?(0,t.jsxs)("span",{className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-[10px] opacity-80",children:S("closeBothLegsConfirm")}),(0,t.jsx)("button",{type:"button",onClick:()=>{N(!1),x()},className:(0,h.cn)("rounded px-1.5 py-0.5 text-[10px] font-medium","bg-red-500/80 text-white transition-colors hover:bg-red-500"),children:S("yes")}),(0,t.jsx)("button",{type:"button",onClick:()=>N(!1),className:"rounded border border-[#e8c766]/40 px-1.5 py-0.5 text-[10px]",children:S("no")})]}):(0,t.jsxs)("button",{type:"button",onClick:()=>N(!0),title:S("closeBothLegsTooltip"),className:(0,h.cn)("ml-auto inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5","border border-[#e8c766]/40 text-[10px] whitespace-nowrap","transition-colors hover:bg-[#e8c766]/20"),children:[(0,t.jsx)(a.X,{className:"h-2.5 w-2.5"}),S("closeAll")]}))]}),"rows"===g&&(0,t.jsx)("div",{className:"pair-group__rail"})]})}function f({link:e,legs:r,colSpan:i,onCloseAll:s,children:n}){return(0,t.jsxs)("tbody",{className:"pair-group",children:[(0,t.jsx)("tr",{className:"pair-group__tab-row",children:(0,t.jsx)("td",{colSpan:i,className:"p-0",children:(0,t.jsx)(m,{link:e,legs:r,onCloseAll:s,variant:"rows"})})}),n]})}function x({link:e,legs:r,onCloseAll:i,children:s}){return(0,t.jsxs)("div",{className:"pair-group pair-group--cards",children:[(0,t.jsx)(m,{link:e,legs:r,onCloseAll:i,variant:"cards"}),(0,t.jsx)("div",{className:"flex flex-col gap-2 p-1.5 pt-0",children:s})]})}},26826,e=>{"use strict";function t(e){return e&&parseFloat(e)||0}function r(e){return"phoenix"===e||"2"===e}function i(e){let t=(e??"").toLowerCase();return"flash_trade"===t||"flash"===t||"1"===t||"flash_v2"===t||"4"===t}function s(e){let r="increase"===e.actionType||"add_collateral"===e.actionType||"open"===e.actionType;return(r?t(e.platformFee)-t(e.proOrderFee):t(e.tx3SwapFee))+(r?0:t(e.tx3PlatformFee)-t(e.tx3SwapFee)-t(e.proOrderFee))+(r?t(e.swapSlippage):t(e.tx3SweepSlippage))+t(e.jupiterFee)+t(e.interest)+t(e.proOrderFee)}function n(e){let i=t(e.ownedCollateralUsd),s=t(e.borrowedCollateralUsd);if(i<=0&&s<=0)return null;if(r(e.underwriter)){let r=t(e.collateralUsd);return r>0?r:null}return i>0?i:null}function a(e){return e.directVenue?.marginMode==="cross"||!0===e.isPhoenixCrossSeat}function l(e){if("increase"!==e.actionType&&"add_collateral"!==e.actionType&&"open"!==e.actionType)return 0;let r=t(e.collateralDeposited);if(r>0)return r;let i=Math.abs(t(e.collateralDelta));return i<=0?0:i+("increase"===e.actionType?t(e.jupiterFee):0)}function o(e){if(a(e)||"sunrise"===e.underwriter||!e.actions?.length)return null;let r=0,i=0,s=!1;for(let n of e.actions){let e=l(n);e>0&&(r+=e,s=!0),n.userReceived&&(i+=t(n.userReceived))}if(!s)return null;let o=n(e),d=r-i;return null!==o&&(d=Math.min(d,o)),d>0?d:null}function d(e){let{size:t,entryPrice:r,execPrice:i,isLong:s,feesPaid:n=0,feesOwed:a=0,jupSwapFee:l=0,imperialSwapFee:o=0}=e;if(i<=0||r<=0||t<=0)return null;let d=s?t*(i-r)/r:t*(r-i)/r,c=d-n,u=c-(a-o+l);return{pricePnl:d,afterFeesPaid:c,afterFeesOwed:u,total:u}}function c(e,t){let r=t.pricePnl-t.afterFeesPaid;return e+t.total+r}function u(e,t,r){return null!==r?c(t,e)-r:e.total}function h(e){let r=o(e);if(null===r||i(e.underwriter))return null;if(e.actions?.length){let r=t(e.sizeUsd);if(Math.abs(e.actions.reduce((e,r)=>e+t(r.sizeDelta),0)-r)>Math.max(1,.01*r))return null}return r}function p(e,r,i){let s=u(r,t(e.collateralUsd),i);
2return null!==i?s:s+x(e)}function m(e){if("decrease"!==e.actionType&&"liquidation"!==e.actionType||null==e.pnlRealized)return null;let r=t(e.pnlRealized),i=Math.abs(r);return!1===e.hasProfit?-i:!0===e.hasProfit?i:r}function f(e){let t=m(e);return null===t?null:t-s(e)}function x(e){if(!e.actions?.length)return 0;let t=0;for(let r of e.actions)t+=f(r)??0;return t}function g(e){if(!e.actions?.length)return t(e.totalFeesUsd);let r=0;for(let t of e.actions)("increase"===t.actionType||"open"===t.actionType||"add_collateral"===t.actionType)&&(r+=s(t));if("sunrise"===e.underwriter)return r;let i=t(e.sizeUsd),n=t(e.maxSizeUsd);return n<=0||i<=0?r:r*Math.min(1,i/n)}function b(e,r){let{execPrice:i,closeFraction:s,isJupNative:n=!1}=r,a=t(e.sizeUsd),l=t(e.entryPrice),o=t(e.collateralUsd),c="long"===e.side;if(i<=0||l<=0||a<=0||s<=0)return null;let u=o*s,h=g(e)*s,p=t(e.borrowFeeOwed),m=(t(e.feesOwed)-p)*s+p,f=n?t(e.swapFeeOwed)*s:0;return d({size:a*s,collateral:u,entryPrice:l,execPrice:i,isLong:c,feesPaid:h,feesOwed:m,jupSwapFee:n?28*u/1e4:0,imperialSwapFee:f})}
2function v(e,t){let r=b(e,t);if(!r)return null;let i=r.total,s=t.closeFraction>=1?r:b(e,{...t,closeFraction:1}),n=h(e);return{netPnl:s?p(e,s,n):i,legPnl:i,divergent:Math.abs(x(e))>=1||t.closeFraction<1,breakdown:r}}let y=e=>Math.round(1e6*e),w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,j=e=>e&&w.test(e)?e:void 0,S=e=>j(e.lifecycleId)??j(e.id),k=e=>Math.round(1e9*e);e.s(["QUOTE_FORMULA_VERSION",0,2,"buildQuoteSnapshot",0,function(e,r){let i=v(e,{execPrice:r.execPrice,closeFraction:r.closeFraction,isJupNative:r.isJupNative});if(!i||!((...e)=>e.every(Number.isFinite))(i.netPnl,i.legPnl,i.breakdown.pricePnl,i.breakdown.afterFeesPaid,i.breakdown.afterFeesOwed,r.execPrice,r.markPrice,r.lastPrice))return null;let s=h(e);return{leg:r.leg,netPnlMicro:y(i.netPnl),legPnlMicro:y(i.legPnl),pricePnlMicro:y(i.breakdown.pricePnl),afterFeesPaidMicro:y(i.breakdown.afterFeesPaid),afterFeesOwedMicro:y(i.breakdown.afterFeesOwed),execPriceNano:k(r.execPrice),entryPriceNano:k(t(e.entryPrice)),sizeUsdMicro:y(t(e.sizeUsd)),collateralUsdMicro:y(t(e.collateralUsd)),closeBps:r.closeBps,feesPaidMicro:y(g(e)),feesOwedMicro:y(t(e.feesOwed)),borrowFeeOwedMicro:y(t(e.borrowFeeOwed)),closeFeeOwedMicro:y(t(e.closeFeeOwed)),swapFeeOwedMicro:y(t(e.swapFeeOwed)),...null!==s?{netCapitalMicro:y(s)}:{},markPriceNano:k(r.markPrice),lastPriceNano:k(r.lastPrice),priceRef:r.priceRef,inputMode:r.inputMode,formulaVersion:2,...S(e)?{lifecycleId:S(e)}:{},...e.asset?{assetSymbol:e.asset}:{},...r.identity??{}}},"calculateLockInitialsPercent",0,function(e,r){let i=o(e);if(null===i||i<=0)return null;let s=t(e.collateralUsd),n=b(e,{execPrice:r,closeFraction:1});if(!n)return null;let a=c(s,n);if(a-i<10)return null;let l=Math.round(Math.min(99,Math.max(1,i/a*100))),d=a*l/100,u=a-d;return u<10?null:{percent:l,netCapital:i,receiving:d,remaining:u}},"calculatePnl",0,d,"closedDisplayPnl",0,function(e){if(null!=e.netCashPnlUsd)return t(e.netCashPnlUsd);let r=t(e.pnlUsd);return"jupiter"===e.underwriter&&"long"===e.side?r:r-t(e.totalFeesUsd)},"computeActionFees",0,s,"depositedCapitalForLeg",0,l,"estimateClosePnl",0,b,"estimateOrderPnl",0,v,"feesPaidForRemainingSize",0,g,"getDisplayPnl",0,u,"getEstimatedReturn",0,c,"getGrossDepositedCapital",0,function(e){if(a(e)||!e.actions?.length)return null;let r=0,i=0,s=!1;for(let n of e.actions){let e=l(n);e>0&&(r+=e,s=!0),n.userReceived&&(i+=t(n.userReceived))}let o=n(e);return null!==o&&s&&(r=Math.min(r,o+i)),s&&r>0?r:null},"isCrossMarginLeg",0,a,"isFlashUnderwriter",0,i,"isPhoenixUnderwriter",0,r,"legGrossPnl",0,m,"legRealizedPnl",0,f,"netCapitalForDisplay",0,h,"parseRawValue",0,t,"phoenixCashBasisBreakeven",0,function(e){if(!r(e.underwriter))return null;let i=t(e.sizeUsd),s=t(e.entryPrice);if(i<=0||s<=0)return null;let n=t(e.feesOwed),a=h(e),l=(null!==a?a+n-t(e.collateralUsd):g(e)+n-x(e))/i,o="long"===e.side?s*(1+l):s*(1-l);return isFinite(o)&&o>0?o:null},"priceForTargetPnlPct",0,function(e){let{sizeUsd:t,collateralUsd:r,netCapital:i,entryPrice:s,feesPaid:n=0,feesOwed:a=0,isLong:l,targetPnlPct:o,realizedPnl:d=0}=e;if(t<=0||s<=0)return null;let c=o/100,u=(null!==i?i*(1+c)-r+a:r*c+n+a-d)/t,h=l?s*(1+u):s*(1-u);return h>0?h:null},"quotableLiquidationPrice",0,function(e){if(!e)return null;let t=parseFloat(e);return Number.isFinite(t)&&t>0?e:null},"settledCloseFeesFromActions",0,function(e){if(!e.actions?.length)return 0;let r=0;for(let i of e.actions)("decrease"===i.actionType||"liquidation"===i.actionType)&&(r+=s(i)-t(i.interest));return r},"settledFundingFromActions",0,function(e){if(!e.actions?.length)return 0;let r=0;for(let i of e.actions)("decrease"===i.actionType||"liquidation"===i.actionType)&&(r+=t(i.interest));return r},"sumRealizedPnlFromActions",0,x,"wholeTradeNetPnl",0,p])},877933,e=>{e.v({actionRow:"pnl-share-dialog-module__vYQ-Xa__actionRow",artGrid:"pnl-share-dialog-module__vYQ-Xa__artGrid",artOption:"pnl-share-dialog-module__vYQ-Xa__artOption",body:"pnl-share-dialog-module__vYQ-Xa__body",controlSection:"pnl-share-dialog-module__vYQ-Xa__controlSection",controls:"pnl-share-dialog-module__vYQ-Xa__controls",customGrid:"pnl-share-dialog-module__vYQ-Xa__customGrid",customItem:"pnl-share-dialog-module__vYQ-Xa__customItem",customOption:"pnl-share-dialog-module__vYQ-Xa__customOption",dialog:"pnl-share-dialog-module__vYQ-Xa__dialog",error:"pnl-share-dialog-module__vYQ-Xa__error",fallback:"pnl-share-dialog-module__vYQ-Xa__fallback",feedback:"pnl-share-dialog-module__vYQ-Xa__feedback",footer
2:"pnl-share-dialog-module__vYQ-Xa__footer",header:"pnl-share-dialog-module__vYQ-Xa__header",hint:"pnl-share-dialog-module__vYQ-Xa__hint",imageActions:"pnl-share-dialog-module__vYQ-Xa__imageActions",linkActions:"pnl-share-dialog-module__vYQ-Xa__linkActions",nativeAction:"pnl-share-dialog-module__vYQ-Xa__nativeAction",preview:"pnl-share-dialog-module__vYQ-Xa__preview",previewArea:"pnl-share-dialog-module__vYQ-Xa__previewArea",previewStatus:"pnl-share-dialog-module__vYQ-Xa__previewStatus",primaryAction:"pnl-share-dialog-module__vYQ-Xa__primaryAction",removePhoto:"pnl-share-dialog-module__vYQ-Xa__removePhoto",secondaryAction:"pnl-share-dialog-module__vYQ-Xa__secondaryAction",segmented:"pnl-share-dialog-module__vYQ-Xa__segmented",upload:"pnl-share-dialog-module__vYQ-Xa__upload"})},232675,e=>{"use strict";e.s(["PnlTab",()=>D],232675);var t=e.i(394390),r=e.i(183023),i=e.i(288204),s=e.i(457058),n=e.i(465217),a=e.i(942553),l=e.i(463547),o=e.i(153517),d=e.i(259048),c=e.i(845165),u=e.i(682768),h=e.i(943494),p=e.i(467290),m=e.i(670374),f=e.i(26826),x=e.i(986759),g=e.i(955724),b=e.i(299959),v=e.i(619966);let y=e=>null==e?0:Number(e),w=e=>e.tx2Timestamp??e.tx1Timestamp;var j=e.i(457395),S=e.i(988462),k=e.i(623075),N=e.i(831979),P=e.i(107481),T=e.i(114787);async function C(e,t,r){await document.fonts.ready;let i=document.createElement("canvas");i.width=2400,i.height=1350;let s=i.getContext("2d");if(!s)throw Error("Canvas unavailable");s.fillStyle="#0b0d0e",s.fillRect(0,0,i.width,i.height);let n=e=>{s.strokeStyle="#272a2d",s.lineWidth=2,s.beginPath(),s.moveTo(100,e),s.lineTo(2300,e),s.stroke()},a=(e,t,i,n,a,l=500,o=2200)=>{s.font=`${l} ${n}px ${r}`,s.fillStyle=a;let d=e;for(;s.measureText(d).width>o&&d.length>1;)d=d.slice(0,-2);d!==e&&(d=`${d.trimEnd()}…`),s.fillText(d,t,i)};a("IMPERIAL",100,140,48,"#f5f5f5",700),s.textAlign="right",a(t.title,2300,140,36,"#9ca2a9",500,1300),s.textAlign="left",n(190),a(t.realized,100,290,38,"#a2a7ae");let l=e.stats.totalPnl>0?"#4ebc91":e.stats.totalPnl<0?"#ed6a64":"#e4e6e8";a(t.pnl,100,445,142,l,600,1450),s.textAlign="right",a(t.period,2300,310,38,"#e4e6e8",500,780),a(t.scope,2300,370,30,"#a2a7ae",500,780),s.textAlign="left";let o=[{time:e.chart[0]?.time??0,value:0},...e.chart],d=0,c=0;for(let e of o)d=Math.min(d,e.value),c=Math.max(c,e.value);let u=c-d||1,h=o[0].time,p=o[o.length-1].time-h||1,m=e=>865-(e-d)/u*310,f=e=>100+(e-h)/p*2200;s.strokeStyle="#272a2d",s.setLineDash([6,8]),s.beginPath(),s.moveTo(100,m(0)),s.lineTo(2300,m(0)),s.stroke(),s.setLineDash([]),s.strokeStyle=l,s.lineWidth=5,s.beginPath(),o.forEach((e,t)=>{0===t?s.moveTo(f(e.time),m(e.value)):s.lineTo(f(e.time),m(e.value))}),s.stroke();let x=o[o.length-1];return s.fillStyle=l,s.beginPath(),s.arc(f(x.time),m(x.value),7,0,2*Math.PI),s.fill(),n(945),t.metrics.forEach((e,t)=>{let r=100+550*t;a(e.label,r,1015,30,"#a2a7ae",500,505),a(e.value,r,1090,53,"#edf0f2",600,505)}),n(1150),a(t.basis,100,1210,26,"#a2a7ae"),a(t.asOf,100,1265,24,"#858c94",500,1450),s.textAlign="right",a(t.captured,2300,1265,24,"#858c94",500,720),i.toDataURL("image/png")}let M="focus-ring inline-flex min-h-10 items-center justify-center gap-2 rounded border border-border px-3 text-xs text-foreground hover:bg-surface-interactive disabled:cursor-not-allowed disabled:opacity-40",_="imperial-performance.png";function A({snapshot:e,onClose:i}){let s=(0,a.useTranslations)("positions"),n=(0,a.useTranslations)("common"),l=(0,b.useFormatters)(),o=(0,r.useRef)(0),d=(0,r.useRef)(!1);(0,r.useLayoutEffect)(()=>()=>{o.current++},[]);let[c,u]=(0,r.useState)(null),[m,f]=(0,r.useState)(null),[x,g]=(0,r.useState)(0),[v]=(0,r.useState)(()=>({copy:!!navigator.clipboard?.write&&"u">typeof ClipboardItem,share:!!navigator.share})),y=(0,r.useMemo)(()=>{let t=e=>new Intl.DateTimeFormat(l.intlTag,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e);return{title:s("sharePerformance"),realized:s("performanceRealized"),pnl:l.pnl(e.stats.totalPnl),scope:e.profiles,period:e.period,metrics:[{label:s("performanceCompleted"),value:String(e.stats.totalTrades)},{label:s("winRate"),value:null==e.stats.profitPercent?"—":l.percent(e.stats.profitPercent,1)},{label:s("columnFeesPaid"),value:l.usdNumber(e.stats.totalFees)},{label:s("funding"),value:l.pnl(e.stats.totalFunding)}],basis:s("performanceShareBasis"),asOf:s("performanceAsOf",{time:t(e.dataUpdatedAt)}),captured:s("performanceCaptured",{time:t(e.capturedAt)})}},[l,e,s]),w=c?.text===y?c.url:void 0,E=(0,r.useMemo)(()=>w?(0,P.dataUrlToPngBlob)(w):null,[w]),L=s("performancePost",{pnl:y.pnl,period:e.period}),F=`https://x.com/intent/tweet?${new URLSearchParams({text:L,url:"https://www.imperial.space"})}`;(0,r.useEffect)(()=>{let t=++o.current;return C(e,y,getComputedStyle(document.body).getPropertyValue("--font-bai-jamjuree").trim()||getComputedStyle(document.body).fontFamily).then(e=>{t===o.current&&u({text:y,url:e})},()=>{t===o.current&&u({text:y,error:!0})}),()=>{o.current++}},[e,y,x]);let R=e=>{if(!E||d.current)return;d.current=!0;
2let t=o.current,r=()=>t===o.current;if(f("opening"),e)(0,T.copyImageToX)(E,F,r).then(e=>{r()&&"retired"!==e&&f("opened"===e?"opened":"popup-blocked")},()=>{r()&&f("error")}).finally(()=>{r()&&(d.current=!1)});else try{navigator.clipboard.write([new ClipboardItem({"image/png":E})]).then(()=>{r()&&f("copied")},()=>{r()&&f("error")}).finally(()=>{r()&&(d.current=!1)})}catch{r()&&(d.current=!1,f("error"))}};return(0,t.jsx)(k.Dialog,{open:!0,onOpenChange:e=>{e||(o.current++,i())},children:(0,t.jsxs)(k.DialogContent,{className:"gap-0 overflow-hidden border-border bg-[#101213] p-0 sm:max-w-[760px]",children:[(0,t.jsx)(k.DialogTitle,{className:"sr-only",children:s("sharePerformance")}),(0,t.jsx)(k.DialogDescription,{className:"sr-only",children:s("performanceShareBasis")}),(0,t.jsx)("div",{className:"aspect-[16/9] w-full overflow-hidden",children:w?(0,t.jsx)("img",{src:w,alt:`${y.realized}: ${y.pnl}. ${y.period}. ${y.scope}`,className:"block h-full w-full object-contain"}):(0,t.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[!c?.error&&(0,t.jsx)(h.Loader2,{className:"size-4 animate-spin"}),s(c?.error?"performanceShareError":"performanceSharePreparing"),c?.error&&(0,t.jsx)("button",{type:"button",className:M,onClick:()=>g(e=>e+1),children:n("retry")})]})}),(0,t.jsxs)("div",{className:"border-t border-border px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,t.jsxs)("button",{type:"button",className:M,disabled:!w,onClick:()=>{if(!w)return;let e=document.createElement("a");e.href=w,e.download=_,e.click()},children:[(0,t.jsx)(S.Download,{className:"size-4"}),s("downloadImage")]}),v.copy&&(0,t.jsxs)("button",{type:"button",className:M,disabled:!E||"opening"===m,onClick:()=>R(!1),children:[(0,t.jsx)(j.Copy,{className:"size-4"}),s("copyImage")]}),v.share&&(0,t.jsxs)("button",{type:"button",className:M,disabled:!E||"opening"===m,onClick:()=>{if(!E)return;let e=o.current,t=new File([E],_,{type:"image/png"});navigator.canShare?.({files:[t]})?navigator.share({files:[t],text:L}).catch(t=>{e!==o.current||t instanceof Error&&"AbortError"===t.name||f("error")}):f("error")},children:[(0,t.jsx)(p.Share2,{className:"size-4"}),s("shareImage")]}),(0,t.jsxs)("button",{type:"button",className:M,disabled:!E||!v.copy||"opening"===m,onClick:()=>R(!0),children:[(0,t.jsx)(N.XIcon,{className:"size-3.5"}),s("shareCopyOpenX")]})]}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"mt-2 flex h-10 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)("span",{className:"line-clamp-2",children:s("opening"===m?"shareCopyingImage":"copied"===m||"opened"===m?"shareXCopied":"popup-blocked"===m?"shareXPopupBlocked":"error"===m?"performanceShareError":"performanceShareHint")}),"popup-blocked"===m&&(0,t.jsx)("a",{className:"shrink-0 text-primary underline",href:F,target:"_blank",rel:"noopener noreferrer",children:s("shareOpenX")})]})]})]})})}function E(){let e=(0,a.useTranslations)("positions");return(0,t.jsxs)("div",{className:"absolute top-3 left-3 flex items-center gap-3 text-[10px] text-muted-foreground font-mono pointer-events-none",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"inline-block w-3 h-[2px] bg-emerald-500"}),e("netPnl")]}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"inline-block w-3 h-[1px] border-t border-dashed border-red-500"}),e("columnFeesPaid")]}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"inline-block w-3 h-[1px] border-t border-dashed border-sky-400"}),e("funding")]})]})}function L(){let e=(0,a.useTranslations)("positions");return(0,t.jsx)("span",{className:"text-[9px] font-medium px-1 py-0.5 rounded bg-amber-500/20 text-amber-400",children:e("partialBadge")})}function F({row:e}){let i=(0,a.useTranslations)("positions"),l=(0,b.useFormatters)(),{lifecycle:c}=e,[u,h]=(0,r.useState)(!1),v=(0,m.getTokenInfo)(c.asset),y=(0,d.pnlColor)(e.pnl),w=l.shortDate(e.time),j="settlement"===e.kind;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("tr",{className:"h-11 border-b border-border/50 hover:bg-surface-interactive/20",children:[(0,t.jsx)("td",{className:"px-3 py-1.5",children:(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[v.image&&(0,t.jsx)(s.default,{unoptimized:!0,onError:n.handleTokenImageError,src:v.image,alt:v.symbol,width:14,height:14,className:"rounded-full"}),(0,t.jsx)("span",{className:(0,o.cn)("text-xs font-medium","long"===c.side?"text-side-long":"text-side-short"),children:i("long"===c.side?"longUpper":"shortUpper")}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:c.asset}),"partial"===e.kind&&(0,t.jsx)(L,{})]})}),(0,t.jsxs)("td",{className:"px-3 py-1.5 text-xs text-muted-foreground",children:[(0,t.jsx)("div",{children:w}),(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:i("cost"===e.kind?"performanceCostEvent":"partial"===e.kind?"performancePartialEvent":"performanceSettlementEvent")})]}),(0,t.jsx)("td",{className:"px-3 py-1.5 text-xs text-foreground font-mono tabular-nums",children:l.rawLeverage(c.maxLeverageX)}),(0,t.jsx)("td",{className:"px-3 py-1.5 text-xs text-foreground font-mono tabular-nums",children:l.usdNumber(e.volume)}),(0,t.jsx)("td",{className:(0,o.cn)("px-3 py-1.5 text-xs font-medium font-mono tabular-nums",y),children:l.pnl(e.pnl)}),(0,t.jsx)("td",{className:"px-3 py-1.5 text-xs text-amber-400 font-mono tabular-nums",children:l.usdNumber(e.fees)}),(0,t.jsx)("td",{className:"px-3 py-1.5",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[e.txAction&&(0,t.jsx)(x.TxLinks,{tx1Signature:e.txAction.tx1Signature,tx2Signature:e.txAction.tx2Signature,tx3Signature:e.txAction.tx3Signature}),j&&(0,t.jsxs)("button",{onClick:e=>{e.stopPropagation(),h(!0)},className:"focus-ring inline-flex min-h-7 items-center gap-1 rounded border border-border px-1.5 text-xs text-label-muted hover:text-secondary-foreground transition-colors cursor-pointer",title:i("shareTradeTitle"),children:[(0,t.jsx)(p.Share2,{className:"w-3.5 h-3.5"}),i("shareAction")]})]})})]}),j&&(0,t.jsx)(g.SharePnlDialog,{open:u,onOpenChange:h,lifecycle:c,pnlPercent:(0,f.parseRawValue)(c.pnlPercent),pnlUsd:(0,f.closedDisplayPnl)(c),leverage:c.maxLeverageX??c.leverageX??"1",entryPriceOverride:(0,m.closedAvgEntryPrice)(c),markPriceOverride:(0,m.closedAvgExitPrice)(c)})]})}function R({row:e}){let i,l=(0,a.useTranslations)("positions"),u=(0,b.useFormatters)(),{lifecycle:h}=e,[x,v]=(0,r.useState)(!1),y=(0,m.getTokenInfo)(h.asset),w=(0,d.pnlColor)(e.pnl),j=u.shortDate(e.time),S="settlement"===e.kind;return(0,t.jsxs)("div",{className:"flex items-center justify-between py-2 border-b border-border/50",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[y.image&&(0,t.jsx)(s.default,{unoptimized:!0,onError:n.handleTokenImageError,src:y.image,alt:y.symbol,width:14,height:14,className:"rounded-full flex-shrink-0"}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:(0,o.cn)("text-xs font-medium","long"===h.side?"text-side-long":"text-side-short"),children:l("long"===h.side?"longUpper":"shortUpper")}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:h.asset}),(0,t.jsx)("span",{className:"text-xs text-label-muted font-mono tabular-nums",children:u.rawLeverage(h.maxLeverageX)}),"partial"===e.kind&&(0,t.jsx)(L,{})]}),(0,t.jsxs)("div",{className:"text-[10px] text-label-muted",children:[j," · ",l("cost"===e.kind?"performanceCostEvent":"partial"===e.kind?"performancePartialEvent":"performanceSettlementEvent")]})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:(0,o.cn)("text-xs font-medium font-mono tabular-nums",w),children:u.pnl(e.pnl)}),(0,t.jsx)("div",{className:"text-[10px] text-label-muted font-mono tabular-nums",children:u.usdNumber(e.volume)})]}),S&&(0,t.jsx)("button",{onClick:e=>{e.stopPropagation(),v(!0)},className:"text-label-muted hover:text-secondary-foreground transition-colors cursor-pointer",title:l("shareTradeTitle"),children:(0,t.jsx)(p.Share2,{className:"w-3.5 h-3.5"})}),e.txAction&&((i=e.txAction.tx2Signature||e.txAction.tx1Signature)?(0,t.jsx)("a",{href:`https://orbmarkets.io/tx/${i}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(c.ExternalLink,{className:"w-3 h-3"})}):null)]}),S&&(0,t.jsx)(g.SharePnlDialog,{open:x,onOpenChange:v,lifecycle:h,pnlPercent:(0,f.parseRawValue)(h.pnlPercent),pnlUsd:(0,f.closedDisplayPnl)(h),leverage:h.maxLeverageX??h.leverageX??"1",entryPriceOverride:(0,m.closedAvgEntryPrice)(h),markPriceOverride:(0,m.closedAvgExitPrice)(h)})]})}function D(e){return(0,t.jsx)(I,{...e},e.historyScopeKey??"unverified")}function I({lifecycles:e,createdProfiles:s,hasMore:n,isFetchingNextPage:c,onLoadMore:x,historyReady:g=!1,historyError:j=!1,historyScopeKey:S="",dataUpdatedAt:k=0}){let N=(0,a.useTranslations)("positions"),P=(0,a.useTranslations)("terms"),[T,C]=(0,r.useState)(null),M=(0,b.useFormatters)(),[_,L]=(0,r.useState)(()=>{let e=localStorage.getItem("pnl-tab-period");return"ALL"===e||"WTD"===e||"MTD"===e||"YTD"===e||"CUSTOM"===e?e:"ALL"}),[D,U]=(0,r.useState)(()=>{try{let e=localStorage.getItem("pnl-source-filter");if(e)return new Set(JSON.parse(e))}catch{}return new Set(["all"])}),[O,B]=(0,r.useState)(()=>localStorage.getItem("pnl-custom-date-from")||null),[z,$]=(0,r.useState)(()=>localStorage.getItem("pnl-custom-date-to")||null);(0,r.useEffect)(()=>{localStorage.setItem("pnl-tab-period",_)},[_]),(0,r.useEffect)(()=>{localStorage.setItem("pnl-source-filter",JSON.stringify([...D]))},[D]),(0,r.useEffect)(()=>{O?localStorage.setItem("pnl-custom-date-from",O):localStorage.removeItem("pnl-custom-date-from")},[O]),(0,r.useEffect)(()=>{z?localStorage.setItem("pnl-custom-date-to",z):localStorage.removeItem("pnl-custom-date-to")},[z]);let V=(0,r.useRef)(null),H=(0,r.useRef)(null),W=(0,r.useRef)(null),q=(0,r.useRef)(null),K=(0,r.useRef)(null),G=(0,v.useIsDesktop)()??!0,Y=(0,r.useMemo)(()=>(function(e,t,r,i,s,n=new Date){let a=function(e,t,r,i=new Date){let s=null,n=null;if("CUSTOM"===e){let e=(e,t)=>
2{if(!e||!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let[r,i,s]=e.split("-").map(Number),n=new Date(r,i-1,s);return n.getFullYear()!==r||n.getMonth()!==i-1||n.getDate()!==s?null:(t&&n.setDate(n.getDate()+1),n.getTime()/1e3)};return{from:s=e(t,!1),to:n=e(r,!0),valid:!!t&&!!r&&null!==s&&null!==n&&s<n}}return"WTD"===e?s=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(i.getDay()+6)%7).getTime()/1e3:"MTD"===e?s=new Date(i.getFullYear(),i.getMonth(),1).getTime()/1e3:"YTD"===e&&(s=new Date(i.getFullYear(),0,1).getTime()/1e3),{from:s,to:n,valid:!0}}(t,i,s,n),l=e=>a.valid&&(null==a.from||e>=a.from)&&(null==a.to||e<a.to),o=[],d=0,c=0,u=0,h=new Set;for(let t of e){if(!r.has("all")&&!r.has(`profile_${t.profileIndex??0}`))continue;let e=t.lifecycleId??t.id;if(h.has(e))continue;h.add(e);let i="closed"===t.status||"liquidated"===t.status,s=[...t.actions??[]].sort((e,t)=>w(e)-w(t)||e.sequenceNumber-t.sequenceNumber),n=s.length>0,a=[],p=new Set;for(let r of s){if(p.has(r.id)||(p.add(r.id),"failed"===r.status))continue;if("completed"!==r.status){n=!1;continue}let s=w(r),l=[r.platformFee,r.proOrderFee,r.tx3SwapFee,r.tx3PlatformFee,r.swapSlippage,r.tx3SweepSlippage,r.jupiterFee,r.interest,r.sizeDelta,r.pnlRealized];if(!Number.isFinite(s)||s<=0||l.some(e=>null!=e&&!Number.isFinite(Number(e)))){n=!1;continue}let o="decrease"===r.actionType||"liquidation"===r.actionType,d=(0,f.legGrossPnl)(r);o&&null===d&&(n=!1),!i&&o&&null!=r.positionSizeAfter&&0===Number(r.positionSizeAfter)&&(n=!1);let c=-y(r.interest),u=(0,f.computeActionFees)(r)+c;a.push({key:`${e}:${r.id}`,lifecycle:t,time:s,fees:u,funding:c,pnl:(d??0)-u+c,volume:Math.abs(y(r.sizeDelta)),kind:o?"partial":"cost",txAction:r})}if(i){let r=null!=t.netCashPnlUsd&&Number.isFinite(Number(t.netCashPnlUsd)),i=t.directVenue?.marginMode==="cross"&&null!=t.pnlUsd&&Number.isFinite(Number(t.pnlUsd))&&Number.isFinite(Number(t.totalFeesUsd)),s=(0,f.closedDisplayPnl)(t);if(r||i||(n=!1),Number.isFinite(s)&&null!=t.closedAt&&Number.isFinite(t.closedAt)){let r=a.findLastIndex(e=>"partial"===e.kind),i=r>=0?a[r]:void 0,o=a.reduce((e,t,i)=>e+(i===r?0:t.pnl),0);i?(i.pnl=s-o,i.kind="settlement",i.time=t.closedAt):(n=!1,a.push({key:`${e}:settlement`,lifecycle:t,pnl:s-o,volume:0,fees:0,funding:0,time:t.closedAt,kind:"settlement",txAction:null})),l(t.closedAt)&&(c++,s>0&&u++)}else n=!1}!n&&d++,o.push(...a.filter(e=>l(e.time)))}o.sort((e,t)=>e.time-t.time||e.key.localeCompare(t.key));let p=[],m=[],x=[],g={totalPnl:0,totalVolume:0,totalFees:0,totalFunding:0,totalTrades:c,profitableTrades:u,profitPercent:c?u/c*100:null},b=(e,t,r)=>{let i=e[e.length-1];i?.time===t?i.value=r:e.push({time:t,value:r})};for(let e of o)g.totalPnl+=e.pnl,g.totalVolume+=e.volume,g.totalFees+=e.fees,g.totalFunding+=e.funding,b(p,e.time,g.totalPnl),b(m,e.time,-g.totalFees),b(x,e.time,g.totalFunding);return{rows:o,stats:g,chartData:p,feesData:m,fundingData:x,unverifiedLifecycles:d,validRange:a.valid}})(e,_,D,O,z),[e,_,D,O,z]),{chartData:X,feesData:Q,fundingData:J,stats:Z,rows:ee}=Y,et=g&&!n&&!c&&!j&&0===Y.unverifiedLifecycles&&Y.validRange&&ee.length>0&&!!S&&k>0,er=`${_}:${[...D].sort().join(",")}:${O}:${z}`,ei=`${S}:${er}`,es=(0,r.useMemo)(()=>[...ee].reverse(),[ee]),en=(0,r.useRef)(null);(0,r.useEffect)(()=>{n&&x&&!c&&!j&&en.current!==e.length&&(en.current=e.length,x())},[n,x,c,j,e.length]),(0,r.useEffect)(()=>{let e=V.current;if(!e)return;let t=(0,l.createChart)(e,{autoSize:!0,layout:{background:{color:"transparent"},textColor:"#A6ADB7"},grid:{vertLines:{visible:!1},horzLines:{color:i.CHART_GRID}},rightPriceScale:{borderColor:i.CHART_GRID},timeScale:{borderColor:i.CHART_GRID,timeVisible:!0},crosshair:{horzLine:{color:"#A6ADB7",style:3},vertLine:{color:"#A6ADB7",style:3}}}),r=t.addSeries(l.BaselineSeries,{baseValue:{type:"price",price:0},topLineColor:"#22c55e",topFillColor1:"rgba(34, 197, 94, 0.35)",topFillColor2:"rgba(34, 197, 94, 0.05)",bottomLineColor:"#ef4444",bottomFillColor1:"rgba(239, 68, 68, 0.05)",bottomFillColor2:"rgba(239, 68, 68, 0.35)",baseLineVisible:!0,baseLineColor:"rgba(100, 116, 139, 0.3)",lineWidth:2,priceFormat:{type:"custom",formatter:e=>M.pnl(e)}}),s=t.addSeries(l.LineSeries,{color:"#ef4444",lineWidth:1,lineStyle:2,priceFormat:{type:"custom",formatter:e=>M.pnl(e)}}),n=t.addSeries(l.LineSeries,{color:"#38bdf8",lineWidth:1,lineStyle:2,priceFormat:{type:"custom",formatter:e=>M.pnl(e)}});if(0===e.clientWidth){let e=t.timeScale(),r=t=>{0!==t&&(e.unsubscribeSizeChange(r),e.fitContent())};e.subscribeSizeChange(r)}return H.current=t,W.current=r,q.current=s,K.current=n,()=>{t.remove(),H.current=null,W.current=null,q.current=null,K.current=null}},[M]),(0,r.useEffect)(()=>{W.current&&(W.current.setData(X),q.current?.setData(Q),K.current?.setData(J),H.current&&X.length>0&&H.current.timeScale().fitContent())},[X,Q,J]);let ea=(0,d.pnlColor)(Z.totalPnl),el=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:"text-[11px] text-label-muted",children:N("periodLabel")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:[["ALL","filterAll"],["WTD","periodWtd"],["MTD","periodMtd"],["YTD","periodYtd"],["CUSTOM","periodCustom"]].map(([e,r])=>(0,t.jsx)("button",{onClick:()=>L(e),className:(0,o.cn)("focus-ring min-h-7 px-2 text-[11px] rounded transition-colors",_===e?"bg-surface-interactive text-foreground":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:N(r)},e))}),"CUSTOM"===_&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5 mt-1.5",children:[(0,t.jsx)("input",{type:"date","aria-label":N("performanceDateFrom"),value:O??"",onChange:e=>B(e.target.value||null),className:"bg-surface-raised text-foreground text-[11px] px-1.5 py-0.5 rounded border border-border-strong outline-none [color-scheme:dark] w-[110px]"}),(0,t.jsx)("span",{className:"text-[11px] text-label-muted",children:N("dateRangeTo")}),(0,t.jsx)("input",{type:"date","aria-label":N("performanceDateTo"),value:z??"",onChange:e=>$(e.target.value||null),className:"bg-surface-raised text-foreground text-[11px] px-1.5 py-0.5 rounded border border-border-strong outline-none [color-scheme:dark] w-[110px]"})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:"text-[11px] text-label-muted",children:N("profileLabel")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>U(new Set(["all"])),className:(0,o.cn)("focus-ring min-h-7 px-2 text-[11px] rounded transition-colors",D.has("all")?"bg-surface-interactive text-foreground":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:N("filterAll")}),s.map(e=>
2{let r=`profile_${e.index}`,i=m.PROFILE_TAG_COLORS[e.index%m.PROFILE_TAG_COLORS.length],s=i.split(" ")[1];return(0,t.jsx)("button",{onClick:()=>{let e=new Set(D);e.delete("all"),e.has(r)?e.delete(r):e.add(r),U(0===e.size?new Set(["all"]):e)},className:(0,o.cn)("focus-ring min-h-7 px-2 text-[11px] rounded transition-colors",D.has(r)?i:(0,o.cn)("bg-surface-raised",s)),children:e.name},r)})]})]})]}),eo=[{label:N("performanceCompleted"),value:String(Z.totalTrades)},{label:N("winRate"),value:null==Z.profitPercent?"—":M.percent(Z.profitPercent,1)},{label:N("performanceVolume"),value:M.usdNumber(Z.totalVolume)},{label:N("columnFeesPaid"),value:M.usdNumber(Z.totalFees)},{label:N("funding"),value:M.pnl(Z.totalFunding)}],ed=Y.validRange?j?"performanceHistoryError":n||c?"performanceLoadingHistory":!g||Y.unverifiedLifecycles>0?"performanceUnverified":"performanceBasis":"performanceInvalidRange";return(0,t.jsxs)("div",{className:"flex h-full min-h-0 flex-col overflow-y-auto bg-canvas","data-pnl-performance":!0,children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-5 gap-y-2 border-b border-border px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex items-baseline gap-3",children:[(0,t.jsx)("h3",{className:"text-xs text-muted-foreground",children:N("performanceRealized")}),(0,t.jsx)("span",{className:(0,o.cn)("font-mono text-xl font-semibold tabular-nums",ea),children:M.pnl(Z.totalPnl)})]}),(0,t.jsxs)("button",{type:"button",onClick:()=>{var e;let t="CUSTOM"===_?`${O} – ${z}`:N({ALL:"performanceAllTime",WTD:"periodWtd",MTD:"periodMtd",YTD:"periodYtd",CUSTOM:"periodCustom"}[_]),r=D.has("all")?N("performanceAllProfiles"):s.filter(e=>D.has(`profile_${e.index}`)).map(e=>e.name||`${N("profileLabel")} ${e.index}`).join(", ");C(!(e={data:Y,historyReady:et,scopeKey:ei,period:t,profiles:`${N("performanceScope")} \xb7 ${r}`,dataUpdatedAt:k}).historyReady||!e.scopeKey||!e.data.validRange||e.data.unverifiedLifecycles>0||Object.values(e.data.stats).some(e=>null!==e&&!Number.isFinite(e))||!e.data.rows.length||!Number.isFinite(e.dataUpdatedAt)||e.dataUpdatedAt<=0?null:Object.freeze({scopeKey:e.scopeKey,period:e.period,profiles:e.profiles,capturedAt:e.capturedAt??Date.now(),dataUpdatedAt:e.dataUpdatedAt,stats:Object.freeze({...e.data.stats}),chart:Object.freeze(e.data.chartData.map(e=>Object.freeze({...e})))}))},disabled:!et,title:et?void 0:N(ed),className:"focus-ring inline-flex min-h-8 items-center gap-1.5 rounded border border-border px-2.5 text-xs hover:bg-surface-interactive disabled:cursor-not-allowed disabled:opacity-40",children:[(0,t.jsx)(p.Share2,{className:"size-3.5"}),N("sharePerformance")]})]}),(0,t.jsx)("div",{className:"border-b border-border px-3 py-2",children:el}),(0,t.jsx)("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-2 border-b border-border px-3 py-2 sm:grid-cols-3 xl:grid-cols-5",children:eo.map(e=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-2 xl:block",children:[(0,t.jsx)("dt",{className:"text-[11px] text-label-muted",children:e.label}),(0,t.jsx)("dd",{className:"font-mono text-xs tabular-nums text-foreground xl:mt-0.5",children:e.value})]},e.label))}),(0,t.jsx)("p",{className:(0,o.cn)("px-3 pt-2 text-[10px]","performanceBasis"===ed?"text-label-muted":"text-amber-400"),role:"status",children:N(ed)}),(0,t.jsxs)("div",{className:"relative h-[180px] min-h-[160px] shrink-0 border-b border-border p-2 lg:h-[200px]",children:[(0,t.jsx)("div",{ref:V,className:"h-full w-full"}),X.length>0&&(0,t.jsx)(E,{}),0===X.length&&(0,t.jsxs)("div",{className:"pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 text-sm text-label-muted",children:[(0,t.jsx)(u.BarChart3,{className:"size-5"}),N(n||c?"loadingEllipsis":"noRealizedTrades")]})]}),(0,t.jsxs)("div",{className:"min-h-[88px] flex-1 overflow-auto",children:[G?(0,t.jsxs)("table",{className:"w-full min-w-[620px] text-xs",children:[(0,t.jsx)("thead",{className:"sticky top-0 z-10 border-b border-border bg-canvas text-label-muted",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("columnPosition")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("performanceEvent")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:P("leverage.abbrev")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("performanceVolume")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("netPnl")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("columnFees")}),(0,t.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:N("columnActions")})]})}),(0,t.jsx)("tbody",{children:es.map(e=>(0,t.jsx)(F,{row:e},e.key))})]}):(0,t.jsx)("div",{className:"px-3",children:es.map(e=>(0,t.jsx)(R,{row:e},e.key))}),0===ee.length&&(0,t.jsx)("div",{className:"py-6 text-center text-xs text-label-muted",children:N("noRealizedTrades")}
2),n&&x&&(0,t.jsxs)("button",{onClick:x,disabled:c,className:"focus-ring flex min-h-10 w-full items-center justify-center gap-2 border-t border-border text-xs text-muted-foreground hover:text-foreground",children:[c&&(0,t.jsx)(h.Loader2,{className:"size-3.5 animate-spin"}),N(c?"loadingEllipsis":"loadMore")]})]}),T&&T.scopeKey===ei&&et&&(0,t.jsx)(A,{snapshot:T,onClose:()=>C(null)},`${ei}:${T.capturedAt}`)]})}},450358,429238,955724,e=>{"use strict";let t;e.s(["PositionRow",()=>eT],450358),e.s(["SharePnlDialog",()=>ew],955724);var r=e.i(394390),i=e.i(800239),s=e.i(183023),n=e.i(457058),a=e.i(943494),l=e.i(967090),o=e.i(695109),d=e.i(467290),c=e.i(308294),u=e.i(199472),h=e.i(1169),p=e.i(942553),m=e.i(153517),f=e.i(259048),x=e.i(268680),g=e.i(670374),b=e.i(26826),v=e.i(328188);e.i(889723);var y=e.i(465217),w=e.i(599059),j=e.i(585457),S=e.i(25158),k=e.i(894771),N=e.i(51314),P=e.i(255810),T=e.i(633441),C=e.i(43085),M=e.i(980333),_=e.i(815109),A=e.i(443048),E=e.i(725747),L=e.i(870020),F=e.i(161568),R=e.i(61162),D=e.i(457395),I=e.i(202647),U=e.i(409686),O=e.i(988462),B=e.i(401382),z=e.i(273297);e.i(875574);var $=e.i(142298),V=e.i(43690),H=e.i(514049),W=e.i(242132),q=e.i(616861),K=e.i(689384);function G(){let{publicKey:e,signMessage:t}=(0,$.useUnifiedWallet)(),{jwt:r}=(0,q.useMobileAuth)(),i=(0,H.useQueryClient)(),n=e?.toBase58()??"",{data:a=[],isPlaceholderData:l}=(0,V.useQuery)({queryKey:["share-card-backgrounds",n],queryFn:()=>(0,K.listShareCardBackgrounds)(n),enabled:!!n,staleTime:6e4,placeholderData:W.keepPreviousData}),[o,d]=(0,s.useState)(!1),[c,u]=(0,s.useState)(null),h=(0,s.useCallback)(()=>{i.invalidateQueries({queryKey:["share-card-backgrounds",n]})},[i,n]),p=(0,s.useCallback)(async e=>{if(!n)throw Error("No wallet connected");d(!0);try{let i=await (0,K.createShareCardBackground)(n,e,t,r);return h(),i}finally{d(!1)}},[n,t,r,h]),m=(0,s.useCallback)(async e=>{if(!n)throw Error("No wallet connected");u(e);try{await (0,K.deleteShareCardBackground)(n,e,t,r),h()}finally{u(null)}},[n,t,r,h]),f=a.length>=K.MAX_SHARE_CARD_BACKGROUNDS;return{savedBackgrounds:a,isPlaceholderData:l,saveBackground:p,removeBackground:m,isSaving:o,deletingId:c,atCapacity:f,maxBackgrounds:K.MAX_SHARE_CARD_BACKGROUNDS}}e.s(["useShareCardBackgrounds",0,G],429238);var Y=e.i(623075),X=e.i(440094),Q=e.i(159179);let J=["/share/pnl/obsidian.png","/share/pnl/colosseum.png","/share/pnl/golden.png","/share/pnl/chrome.png"];function Z(e){return(0,Q.isValidReferralCode)(e)?e:null}function ee(e){if(!Number.isFinite(e)||e<=0)return"—";let t=new Date(1e3*e);if(!Number.isFinite(t.getTime()))return"—";let r=e=>String(e).padStart(2,"0");return`${r(t.getUTCDate())}/${r(t.getUTCMonth()+1)}/${r(t.getUTCFullYear()%100)} ${r(t.getUTCHours())}:${r(t.getUTCMinutes())}:${r(t.getUTCSeconds())}`}let et={[J[0]]:"#4b2a13",[J[1]]:"#8d4934",[J[2]]:"#382719",[J[3]]:"#4f2440"};var er=e.i(406470),ei=e.i(517616);let es="Imperial PnL";function en(e){return new Promise((t,r)=>{let i=new Image;i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>r(Error("Card artwork could not be loaded")),i.src=e})}function ea(e){if(e.startsWith("/")&&!e.startsWith("//")||e.startsWith("blob:")||e.startsWith("https://"))return e;throw Error("Unsupported card image source")}function el(e,t,r,i,s,n,a,l=0){e.letterSpacing=`${l}px`,e.font=`${n} ${s}px '${es}'`;let o=e.measureText(t).width;o>a&&(e.font=`${n} ${s*a/o}px '${es}'`),e.fillText(t,r,i,a),e.letterSpacing="0px"}async function eo(e,r){var i;let s,n,a,l=e.backgroundImage??J[0],o=J.includes(l),[d,c,u]=await Promise.all([en(ea(l)),o?Promise.resolve(null):en(J[0]),e.tokenImage?en(ea(e.tokenImage)).catch(()=>null):Promise.resolve(null),t??=Promise.all([400,500,600,700].map(async e=>{let t=new FontFace(es,`url('/share/pnl/bai-${e}.ttf')`,{weight:String(e)});document.fonts.add(await t.load())})).then(async()=>{let e=new FontFace("Imperial PnL Mono","url('/share/pnl/mono-500.ttf')",{weight:"500"});document.fonts.add(await e.load())}).catch(e=>{throw t=void 0,e})]),h=document.createElement("canvas");h.width=2772,h.height=1564;let p=h.getContext("2d");if(!p)throw Error("Image export is unavailable");if(p.scale(4,4),p.save(),p.beginPath(),p.roundRect(0,0,693,391,10),p.clip(),o)p.drawImage(d,0,0,693,391);else{let e,t,r;
2e=Math.max(693/d.naturalWidth,391/d.naturalHeight),t=d.naturalWidth*e,r=d.naturalHeight*e,p.drawImage(d,(693-t)/2,(391-r)/2,t,r);let i=p.createLinearGradient(0,0,693,0);i.addColorStop(0,"#000000da"),i.addColorStop(1,"#00000018"),p.fillStyle=i,p.fillRect(0,0,693,391),c&&(p.save(),p.beginPath(),p.moveTo(0,0),p.lineTo(693,0),p.lineTo(693,10),p.lineTo(208,10),p.lineTo(136,58),p.lineTo(0,58),p.clip(),p.drawImage(c,0,0,693,391),p.restore()),p.fillStyle="#929da4",p.font=`400 16px '${es}'`,p.fillText("Entry Price",27,250),p.fillText("Mark price",237,250)}let m=(s=Z(e.referralCode))?`https://www.imperial.space/refer/${encodeURIComponent(s)}`:null;m&&o||(i=!!m,n=new Path2D("M11 335H339Q346 335 350 330L383 287Q388 281 397 281H680Q691 281 691 292V380Q691 390 680 390H12Q1 390 1 379V346Q1 335 11 335Z"),(a=p.createLinearGradient(0,335,693,391)).addColorStop(0,"#131416"),a.addColorStop(1,et[J.find(e=>e===l)??J[0]]),p.fillStyle=a,p.fill(n),p.strokeStyle="#ffffff30",p.lineWidth=.7,p.stroke(n),p.strokeStyle="#ffffff20",p.beginPath(),p.moveTo(132,362.5),p.lineTo(i?489:580,362.5),p.stroke(),p.font=`400 13px '${es}'`,p.fillStyle="#858a91",p.textAlign="right",p.fillText("imperial.space",i?582:677,366),p.textAlign="left",i&&p.fillText("Referral",535,334)),u?(p.save(),p.beginPath(),p.arc(31.5,125,15.5,0,2*Math.PI),p.clip(),p.drawImage(u,16,109.5,31,31),p.restore()):(p.fillStyle="#26282a",p.beginPath(),p.arc(31.5,125,15.5,0,2*Math.PI),p.fill(),p.fillStyle="#f2f3f6",el(p,e.tokenSymbol.slice(0,2),20,130,12,600,23)),p.fillStyle="#f2f3f6",el(p,`${e.tokenSymbol}-PERP`,57,131.5,18,700,195,.4),p.font=`700 18px '${es}'`,p.letterSpacing=".4px";let f=57+Math.min(p.measureText(`${e.tokenSymbol}-PERP`).width,195)+12;p.letterSpacing="0px";let x=Number.parseFloat(e.leverage),g=`${e.isLong?"LONG":"SHORT"} ${Number.isFinite(x)&&x>0?Math.round(x):"—"}x`;p.font=`400 12px '${es}'`;let b=p.measureText(g).width+18;p.fillStyle=e.isLong?"#17382c":"#412328",p.beginPath(),p.roundRect(f,114,b,23,3),p.fill(),p.fillStyle=e.isLong?"#65e0b3":"#ff7575",p.fillText(g,f+9,130),e.boosted&&(p.fillStyle="#f79929",el(p,"Boosted by Imperial",f+b+12,130,12,500,200));let v=e.displayMode??"percent",y=Number.isFinite(e.pnlPercent)?(0,er.formatSignedPercent)(e.pnlPercent,2,r):"—",w=Number.isFinite(e.pnlUsd)?(0,er.formatPnlNumber)(e.pnlUsd,r):"—",j=("dollar"===v?e.pnlUsd:e.pnlPercent)>=0,S=p.createLinearGradient(110,0,275,0);if(S.addColorStop(0,"#65e0b3"),S.addColorStop(1,"#34d399"),p.fillStyle=j?S:"#ff595c",el(p,"dollar"===v?w:y,22,214,72,700,649,-.5),"both"===v&&(p.fillStyle=e.pnlUsd>=0?"#65e0b3":"#ff595c",el(p,w,28,312,24,500,305)),p.fillStyle="#eef1f3",p.font="500 19px 'Imperial PnL Mono'",p.letterSpacing="-.5px",p.fillText((0,er.formatRawPrice)(e.entryPrice,r),29,271,188),p.fillText((0,er.formatRawPrice)(e.markPrice,r),234,271,210),p.fillStyle="#858a91",el(p,ee(e.timestamp),14,366,13,400,112,-.05),m){p.fillStyle="#eef1f3",p.textAlign="right",el(p,m.replace("https://www.",""),582,350,13,400,420,.13),p.textAlign="left";let e=(0,ei.create)(m,{errorCorrectionLevel:"M"}).modules;p.save(),p.setTransform(1,0,0,1,0,0);p.fillStyle="#fff",p.beginPath(),p.roundRect(2392,1192,320,320,20),p.fill();let t=Math.max(1,Math.floor(320/(e.size+8))),r=Math.floor((320-e.size*t)/2);p.fillStyle="#0b0c0e";for(let i=0;i<e.size;i++)for(let s=0;s<e.size;s++)e.get(i,s)&&p.fillRect(2392+r+s*t,1192+r+i*t,t,t);p.restore()}return p.restore(),h.toDataURL("image/png")}let ed=(0,s.forwardRef)(function({onReadyChange:e,...t},i){let n=(0,X.useLocale)(),a=(0,p.useTranslations)("positions"),l=(0,p.useTranslations)("common"),o=JSON.stringify([t,n]),[d,c]=(0,s.useState)(null),[u,h]=(0,s.useState)(null),[m,f]=(0,s.useState)(0),x=d?.key===o?d.url:null;(0,s.useImperativeHandle)(i,()=>({getDataUrl:()=>x}),[x]),(0,s.useEffect)(()=>{let t=!1;e?.(!1);let[r,i]=JSON.parse(o);return eo(r,i).then(r=>{t||(c({key:o,url:r}),h(null),e?.(!0))}).catch(()=>{t||(h(o),e?.(!1))}),()=>{t=!0}},[o,m,e]);let g=u===o,b=t.displayMode??"percent",v=Number.isFinite(t.pnlPercent)?(0,er.formatSignedPercent)(t.pnlPercent,2,n):"—",y=Number.isFinite(t.pnlUsd)?(0,er.formatPnlNumber)(t.pnlUsd,n):"—",w=[`${t.tokenSymbol}-PERP`,a(t.isLong?"longUpper":"shortUpper"),"dollar"!==b?v:null,"percent"!==b?y:null,`${a("entryPrice")}: ${(0,er.formatRawPrice)(t.entryPrice,n)}`,`${a("markPrice")}: ${(0,er.formatRawPrice)(t.markPrice,n)}`,`${ee(t.timestamp)}
2 UTC`].filter(Boolean).join(" · ");return(0,r.jsx)("div",{"data-pnl-card":!0,"aria-busy":!x&&!g,className:"relative w-full overflow-hidden rounded-[10px] bg-surface",style:{aspectRatio:"693/391"},children:x?(0,r.jsx)("img",{"data-pnl-card-image":!0,src:x,width:693,height:391,alt:w,className:"block h-auto w-full"}):(0,r.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 text-center text-sm text-muted-foreground",role:"status",children:[(0,r.jsx)("span",{children:g?a("shareExportFailed"):l("loading")}),g&&(0,r.jsx)("button",{type:"button",className:"focus-ring min-h-11 rounded-md border border-border px-4 text-foreground",onClick:()=>{h(null),f(e=>e+1)},children:l("retry")})]})})});var ec=e.i(831979),eu=e.i(114787),eh=e.i(107481),ep=e.i(492728),em=e.i(299959),ef=e.i(877933);let ex=[{value:"both",labelKey:"displayModeBoth"},{value:"percent",labelKey:"displayModePercent"},{value:"dollar",labelKey:"displayModeDollar"}],eg=["Obsidian","Colosseum","Golden","Chrome"],eb=()=>()=>{},ev=()=>"u">typeof navigator&&"function"==typeof navigator.share,ey=()=>!1;function ew(e){let{publicKey:t}=(0,$.useUnifiedWallet)(),i=t?.toBase58()??"";return(0,r.jsx)(ej,{...e,walletAddress:i},i)}function ej({open:e,onOpenChange:t,lifecycle:i,pnlPercent:n,pnlUsd:o,leverage:c,entryPriceOverride:u,markPriceOverride:h,walletAddress:m}){let f=(0,p.useTranslations)("positions"),x=(0,p.useTranslations)("common"),b=(0,em.useFormatters)(),v=(0,s.useRef)(null),y=(0,s.useRef)(null),w=(0,s.useRef)(null),j=(0,s.useRef)(!1),S=(0,s.useRef)(0),k=(0,s.useRef)(!1),[N,P]=(0,s.useState)(!1),[T,C]=(0,s.useState)(null),M=null!==T,[_,A]=(0,s.useState)(null),[E,L]=(0,s.useState)(!1),[F,R]=(0,s.useState)(!1),[$,V]=(0,s.useState)(null),[H,W]=(0,s.useState)(null),[q,K]=(0,s.useState)(J[0]),[X,Q]=(0,s.use
2State)(null),[ee,et]=(0,s.useState)(null),[er,ei]=(0,s.useState)("percent"),[es,en]=(0,s.useState)(null),ea=(0,s.useSyncExternalStore)(eb,ev,ey),[el,eo]=(0,s.useState)(null),ew=(0,z.useReferralCode)(m,e),eS=!m||ew.isSuccess&&!ew.isFetching,ek=e&&m&&ew.isSuccess&&!ew.isFetching?Z(ew.data?.wallet===m?ew.data.code:null):null,{savedBackgrounds:eN,isPlaceholderData:eP,saveBackground:eT,removeBackground:eC,isSaving:eM,deletingId:e_,maxBackgrounds:eA}=G(),eE=eP?[]:eN,eL=eE.length>=eA,eF=J.some(e=>e===q)||X===m?q:J[0],eR=X===m?_:null,eD=!J.some(e=>e===eF),eI=(0,g.getTokenInfo)(i.asset),eU="long"===i.side,eO=!!i.borrowedCollateralUsd&&parseFloat(i.borrowedCollateralUsd)>0,eB=u??i.entryPrice,ez=h??null,e$=i.lastActionAt||i.openedAt,eV=JSON.stringify([e,m,eI.symbol,eI.image,eU,c,n,o,eB,ez,e$,eF,er,ek,eS,eO,b.intlTag]),[eH,eW]=(0,s.useState)(eV);eH!==eV&&(eW(eV),C(null),L(!1),R(!1),eo(null),V(null),W(null)),(0,s.useLayoutEffect)(()=>(S.current+=1,k.current=!1,()=>{S.current+=1}),[eV]);let eq=e&&eS&&es===eV,eK=(0,s.useCallback)(e=>{en(e?eV:null)},[eV]),[eG,eY]=(0,s.useState)(e);eG!==e&&(eY(e),e||(eo(null),C(null),L(!1),R(!1),et(null),en(null),A(null),K(e=>e.startsWith("blob:")?J[0]:e))),(0,s.useLayoutEffect)(()=>(e||(w.current=null),()=>{w.current=null}),[e]),(0,s.useEffect)(()=>()=>{_&&URL.revokeObjectURL(_)},[_]);let eX=(0,s.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;if(e.target.value="",!t.type.startsWith("image/"))return void et(f("sharePhotoFailed"));if(eL)return void console.warn(`Saved photo limit reached (${eA}). Remove one first.`);et(null),Q(m),w.current=t;let r=URL.createObjectURL(t);A(r),K(r)},[eL,eA,m,f]),eQ=(0,s.useCallback)(async()=>{let e=w.current;if(e&&!j.current){j.current=!0,P(!0);try{et(null);let t=await (0,eh.resizeImageForBackground)(e);if(w.current!==e)return;let r=await eT(t);if(w.current!==e)return;w.current=null,A(null),K(r.url)}
2catch(t){console.error("Failed to save share card background:",t),w.current===e&&et(f("sharePhotoFailed"))}finally{j.current=!1,P(!1)}}},[eT,f]),eJ=(0,s.useCallback)(()=>{w.current=null,A(null),K(J[0])},[]),eZ=(0,s.useCallback)(async(e,t)=>{try{await eC(e),K(e=>e===t?J[0]:e)}catch(e){console.error("Failed to remove saved background:",e),et(f("sharePhotoFailed"))}},[eC,f]),e0=(0,s.useCallback)(()=>eq?v.current?.getDataUrl()??null:null,[eq]),e1=(0,s.useCallback)(()=>{let e=new URLSearchParams;e.set("token",eI.symbol),eI.image&&e.set("tokenImage",eI.image),e.set("isLong",String(eU)),e.set("leverage",c),"dollar"!==er&&e.set("pnl",n.toFixed(2)),"percent"!==er&&e.set("pnlUsd",o.toFixed(2)),eB&&e.set("entryPrice",eB),ez&&e.set("markPrice",ez),ek&&e.set("ref",ek),e.set("display",er),e.set("ts",String(e$));let t=J.find(e=>e===eF)??J[0];return e.set("bg",t),eO&&e.set("boosted","true"),`https://www.imperial.space/share/position?${e.toString()}`},[eI,eU,c,n,o,eB,ez,ek,eO,er,e$,eF]),e2=(0,s.useCallback)(()=>{if(M||k.current)return;let e=e0();if(!e)return;let t=S.current;k.current=!0,C("image"),L(!1),V(null),W(null),et(null);try{let r=(0,eh.dataUrlToPngBlob)(e);navigator.clipboard.write([new ClipboardItem({"image/png":r})]).then(()=>{t===S.current&&(L(!0),setTimeout(()=>{t===S.current&&L(!1)},2e3))}).catch(e=>{console.error("Clipboard write failed:",e),t===S.current&&et(f("shareCopyFailed"))}).finally(()=>{t===S.current&&(k.current=!1,C(null))})}catch(e){console.error("Failed to copy PnL card image:",e),et(f("shareCopyFailed")),k.current=!1,C(null)}},[M,e0,f]),e5=(0,s.useCallback)(()=>{let e=S.current,t=e0();if(t){et(null);try{if((0,eh.isWalletInAppBrowser)()){let r=new File([(0,eh.dataUrlToPngBlob)(t)],"imperial-pnl.png",{type:"image/png"});if(navigator.canShare?.({files:[r]}))return void navigator.share({files:[r]}).catch(r=>{"AbortError"!==r.name&&e===S.current&&eo(t)});eo(t);return}let r=document.createElement("a");r.href=t,r.download="imperial-pnl.png",r.click()}catch(e){console.error("Failed to save PnL card image:",e),(0,eh.isWalletInAppBrowser)()?eo(t):et(f("shareExportFailed"))}}},[e0,f]),e3=(0,s.useCallback)(()=>{if(!eS||k.current)return;let e=S.current,t=e1();k.current=!0,C("link"),L(!1),R(!1),V(null),W(null),et(null);try{navigator.clipboard.writeText(t).then(()=>{e===S.current&&(R(!0),setTimeout(()=>{e===S.current&&R(!1)},2e3))}).catch(t=>{console.error("Failed to copy PnL card link:",t),e===S.current&&et(f("shareCopyFailed"))}).finally(()=>{e===S.current&&(k.current=!1,C(null))})}catch(e){console.error("Failed to copy PnL card link:",e),et(f("shareCopyFailed")),k.current=!1,C(null)}},[e1,eS,f]),e4=(0,s.useCallback)(()=>{if(!eS||M||k.current)return;let e=e0();if(!e)return;let t=S.current,r=e1(),i=eU?f("long"):f("short"),s=n>=0?"+":"",a="dollar"===er?f("nativeShareText"):f("shareToXText",{direction:i,symbol:eI.symbol,leverage:Math.round(parseFloat(c)),pnl:`${s}${n.toFixed(2)}`,handle:ep.X_HANDLE}),l=`https://x.com/intent/tweet?text=${encodeURIComponent(a)}&url=${encodeURIComponent(r)}`;k.current=!0,C("image"),L(!1),R(!1),V(null),W(null),et(null);try{(0,eu.copyImageToX)((0,eh.dataUrlToPngBlob)(e),l,()=>t===S.current).then(e=>{t===S.current&&"retired"!==e&&(V(e),"popup-blocked"===e&&W(l))}).catch(()=>{t===S.current&&(et(f("shareCopyFailed")),W(l))}).finally(()=>{t===S.current&&(k.current=!1,C(null))})}catch{k.current=!1,C(null),et(f("shareCopyFailed")),W(l)}},[e1,M,e0,er,eU,n,eI.symbol,c,eS,f]),e6=(0,s.useCallback)(()=>{let e=S.current;if(!navigator.share)return;let t=e0();if(t){et(null);try{let r=new File([(0,eh.dataUrlToPngBlob)(t)],"imperial-pnl.png",{type:"image/png"}),i=e1(),s=f("nativeShareText"),n=navigator.canShare?.({files:[r]})?{files:[r],text:s,url:i}:{text:s,url:i};navigator.share(n).catch(t=>{"AbortError"!==t.name&&e===S.current&&(console.error("Failed to share:",t),et(f("shareExportFailed")))})}catch(e){console.error("Failed to share PnL card image:",e),et(f("shareExportFailed"))}}},[e0,e1,f]);return(0,r.jsx)(Y.Dialog,{open:e,onOpenChange:t,children:(0,r.jsxs)(Y.DialogContent,{className:ef.default.dialog,"aria-describedby":void 0,children:[(0,r.jsx)(Y.DialogHeader,{className:ef.default.header,children:(0,r.jsx)(Y.DialogTitle,{children:f("shareTradeTitle")})}),(0,r.jsxs)("div",{className:ef.default.body,children:[(0,r.jsxs)("div",{className:ef.default.previewArea,children:[(0,r.jsx)("div",{className:ef.default.preview,style:{maxWidth:693},children:(0,r.jsx)(ed,{ref:v,tokenSymbol:eI.symbol,tokenImage:eI.image,isLong:eU,leverage:c,pnlPercent:n,pnlUsd:o,entryPrice:eB,markPrice:ez,timestamp:e$,backgroundImage:eF,displayMode:er,referralCode:ek,boosted:eO,onReadyChange:eK})}),eS?!eq&&(0,r.jsx)("p",{className:ef.default.previewStatus,role:"status",children:f("shareImageNotReady")}):(0,r.jsxs)("div",{className:ef.default.previewStatus,children:[(0,r.jsx)("p",{role:ew.isError?"alert":"status",children:f(ew.isError?"shareReferralFailed":"shareReferralLoading")}),ew.isError&&(0,r.jsx)("button",{type:"button",className:ef.default.secondaryAction,onClick:()=>void ew.refetch(),disabled:ew.isFetching,children:x("retry")})]})]}),(0,r.jsxs)("div",{className:ef.default.controls,children:[(0,r.jsxs)("fieldset",{className:ef.default.controlSection,children:[(0,r.jsx)("legend",{children:f("shareDisplayLabel")}),(0,r.jsx)("div",{className:ef.default.segmented,children:ex.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>ei(e.value),"aria-pressed":er===e.value,children:f(e.labelKey)},e.value))})]}),(0,r.jsxs)("fieldset",{className:ef.default.controlSection,children:[(0,r.jsx)("legend",{children:f("shareDesignLabel")}),(0,r.jsx)("div",{className:ef.default.artGrid,children:J.map((e,t)=>(0,r.jsxs)("button",{type:"button",className:ef.default.artOption,onClick:()=>K(e),"aria-pressed":eF===e,"aria-label":eg[t]??`${f("shareDesignLabel")} ${t+1}`,children:[(0,r.jsx)("img",{src:e,alt:""}),(0,r.jsxs)("span",{children:[eg[t],eF===e&&(0,r.jsx)(I.Check,{size:14,"aria-hidden":"true"})]})]},e))})]}),(0,r.jsxs)("fieldset",{className:ef.default.controlSection,children:[(0,r.jsx)("legend",{children:f("sharePhotosLabel")}),(eE.length>0||eR)&&(0,r.jsxs)("div",{className:ef.default.customGrid,children:[eE.map((e,t)=>(0,r.jsxs)("div",{className:ef.default.customItem,children:[(0,r.jsx)("button",{type:"button",className:ef.default.customOption,onClick:()=>{Q(m),K(e.url)},"aria-label":f("shareSavedPhotoLabel",{index:t+1}),"aria-pressed":eF===e.url,children:(0,r.jsx)("img",{src:e.url,alt:""})}),(0,r.jsx)("button",{type:"button",className:ef.default.removePhoto,onClick:()=>void eZ(e.id,e.url),disabled:e_===e.id,"aria-label":`${f("removeSavedPhoto")} — ${f("shareSavedPhotoLabel",{index:t+1})}`,children:e_===e.id?(0,r.jsx)(a.Loader2,{className:"animate-spin",size:15}):(0,r.jsx)(l.X,{size:15})})]},e.id)),eR&&(0,r.jsxs)("div",{className:ef.default.customItem,children:[(0,r.jsx)("button",{type:"button",className:ef.default.customOption,onClick:()=>K(eR),"aria-label":f("unsavedPhotoHint"),"aria-pressed":eF===eR,children:(0,r.jsx)("img",{src:eR,alt:"",onError:()=>{eJ(),et(f("sharePhotoFailed"))}})}),(0,r.jsx)("button",{type:"button",className:ef.default.removePhoto,onClick:eJ,"aria-label":f("discardPhoto"),children:(0,r.jsx)(l.X,{size:15})})]})]}),!eL&&(0,r.jsxs)("button",{type:"button",className:ef.default.upload,onClick:()=>y.current?.click(),children:[(0,r.jsx)(U.Plus,{size:16}),f("uploadPhoto")]}),eR&&(0,r.jsxs)("button",{type:"button",className:ef.default.upload,onClick:()=>void eQ(),disabled:eM||N||!m,title:f("savePhotoHint"),children:[eM||N?(0,r.jsx)(a.Loader2,{className:"animate-spin",size:16}):(0,r.jsx)(B.Save,{size:16}),f("shareSavePhoto")]}),(0,r.jsx)("input",{ref:y,type:"file",accept:"image/*",onChange:eX,className:"hidden"}),eL&&!eR&&(0,r.jsx)("p",{className:ef.default.hint,children:f("savedPhotosAtCapacity",{saved:eA,max:eA})})]})]})]}),(0,r.jsxs)("div",{className:ef.default.footer,children:[(0,r.jsx)("div",{className:ef.default.feedback,children:(0,r.jsxs)("p",{role:ee?"alert":"status",className:ee?ef.default.error:ef.default.hint,children:[ee||(M?f("link"===T?"shareCopyingLink":"shareCopyingImage"):"popup-blocked"===$?f("shareXPopupBlocked"):"opened"===$?f("shareXCopied"):E||F?f("copied"):eD?f("shareCustomLinkHint"):f("shareCopyOpenXHint")),H&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("a",{href:H,target:"_blank",rel:"noopener noreferrer",children:f("shareOpenX")})]})]})}),(0,r.jsxs)("div",{className:ef.default.actionRow,children:[(0,r.jsxs)("div",{className:ef.default.imageActions,children:[(0,r.jsxs)("button",{type:"button",className:ef.default.primaryAction,onClick:e5,disabled:M||!eq,children:[(0,r.jsx)(O.Download,{size:17}),f("shareSaveImage")]}),(0,r.jsxs)("button",{type:"button",className:ef.default.secondaryAction,onClick:e2,disabled:M||!eq,"aria-busy":M,children:[E?(0,r.jsx)(I.Check,{size:17}):M?(0,r.jsx)(a.Loader2,{className:"animate-spin",size:17}):(0,r.jsx)(D.Copy,{size:17}
2),f("copyImage")]})]}),(0,r.jsxs)("div",{className:ef.default.linkActions,children:[(0,r.jsxs)("button",{type:"button",className:ef.default.secondaryAction,onClick:e4,disabled:M||!eq,"aria-busy":M,children:[(0,r.jsx)(ec.XIcon,{className:"size-4"}),f("shareCopyOpenX")]}),(0,r.jsxs)("button",{type:"button",className:ef.default.secondaryAction,onClick:e3,disabled:M||!eS,"aria-busy":"link"===T,children:[F?(0,r.jsx)(I.Check,{size:16}):(0,r.jsx)(D.Copy,{size:16}),f("copyLink")]}),ea&&(0,r.jsx)("button",{type:"button",className:ef.default.nativeAction,onClick:e6,disabled:M||!eq,"aria-label":f("shareAction"),title:f("shareAction"),children:(0,r.jsx)(d.Share2,{size:17})})]})]})]}),(0,r.jsx)(Y.Dialog,{open:!!el,onOpenChange:e=>{e||eo(null)},children:(0,r.jsxs)(Y.DialogContent,{className:ef.default.fallback,"aria-describedby":void 0,children:[(0,r.jsx)(Y.DialogHeader,{children:(0,r.jsx)(Y.DialogTitle,{children:f("shareSaveImage")})}),(0,r.jsx)("p",{children:f.rich("longPressSaveHint",{b:e=>(0,r.jsx)("b",{children:e})})}),el&&(0,r.jsx)("img",{src:el,alt:f("pnlCardAlt")})]})})]})})}var eS=e.i(725452),ek=e.i(888245),eN=e.i(702021),eP=e.i(626074);function eT({readOnly:e=!1,lifecycle:t,onClosePosition:D,isClosing:I,showDateColumn:U,onCancelPassthroughOrder:O,onCancelJupiterOrder:B,onPositionChange:z,livePrices:$,orderbookMidPrice:V,dcaGrouping:H,otherOpenLegs:W=0,autoOpenClose:q=!1,desktopLayout:K=!1}){let G,X,Q,J=(0,p.useTranslations)("positions"),Z=(0,p.useTranslations)("terms"),ee=(0,em.useFormatters)(),[et,er]=(0,s.useState)(!1),[ei,es]=(0,s.useState)(!1),[en,ea]=(0,s.useState)(!1),[el,eo]=(0,s.useState)(!1),[ed,ec]=(0,s.useState)(!1),[eu,eh]=(0,s.use
2State)(q&&!e),[ep,ef]=(0,s.useState)(!1),[ex,eg]=(0,s.useState)(!1),[eb,ev]=(0,s.useState)(!1),[ey,ej]=(0,s.useState)(void 0),[eC,eM]=(0,s.useState)("entire"),[e_,eA]=(0,s.useState)("ratchet"),[eE,eL]=(0,s.useState)(null),[eF,eR]=(0,s.useState)(q);eF!==q&&(eR(q),q&&!e&&eh(!0));let eD=t.tpslOrders?.length??0,eI=null!==eE&&eD<=eE;null===eE||eI||eL(null),(0,s.useEffect)(()=>{if(!eI)return;let e=setTimeout(()=>eL(null),8e3);return()=>clearTimeout(e)},[eI]);let{tokenInfo:eU,profileName:eO,profileIdx:eB,isLong:ez,isClosed:e$,isPhoenixPosition:eV,isPairsPosition:eH,feesLoading:eW,livePrice:eq,useLivePrice:eK,feesPaidValue:eG,feesOwedValue:eY,pricePnl:eX,realizedPnl:eQ,realizedInclOpenFees:eJ,settledFunding:eZ,settledCloseFees:e0,pnlValue:e1,openPnl:e2,openPnlPercent:e5,packEntryPrice:e3,packOpenedAt:e4,packPnlUsd:e6,packPnlPercent:e8,pnlPercentValue:e9,displaySize:e7,displayCollateral:te,displayLeverage:tt,avgEntryPrice:tr,shareCardMarkPrice:ti,displayLiquidationPrice:ts,breakevenPrice:tn,displayActions:ta,dcaGroupLabels:tl,groupedDisplayActions:to,showBorrowRate:td,borrowRateHourlyUsd:tc}=(0,P.usePositionData)({lifecycle:t,livePrices:$,dcaGrouping:H}),tu="venue_direct"===t.ownership&&(0,b.isPhoenixUnderwriter)(t.underwriter),th=(0,b.isCrossMarginLeg)(t),tp=e6??e2??e1,tm=th||tu&&e$&&!te?null:e8??(null!==e2?e5:e9),tf=Math.round(100*eJ)/100,{mode:tx}=(0,T.usePnlDisplayMode)(),tg=!e$&&"percent"===tx&&null!==tm,tb=Z((0,eS.marginModeLabelKey)(t.directVenue?.marginMode)),tv=eO??((K||e$)&&null!=eB?0===eB?J("mobileAccountMain"):J("profileFallbackName",{index:eB+1}):null),ty=th?t.directVenue?.accountCollateralUsd:te,tw=Object.values({tpsl:ei,trailing:en,dca:el,rsi:ed,close:eu,editCollateral:ep,share:ex}).some(Boolean),tj=!!t.borrowedCollateralUsd&&parseFloat(t.borrowedCollateralUsd)>0,tS=(()=>{if("liquidated"!==t.status||!t.liqTriggerPriceUsd)return null;let e=parseFloat(t.liqTriggerPriceUsd);if(!Number.isFinite(e)||e<=0)return null;let r=ta.find(e=>"liquidation"===e.actionType)?.entryPrice??[...ta].reverse().find(e=>"decrease"===e.actionType)?.entryPrice,i=r?parseFloat(r):NaN,s=null,n=!1;if(Number.isFinite(i)&&i>0){let t=ez?e-i:i-e;n=t<=0;let r=Math.abs(t);s=`$${ee.fixed(r,2)} (${ee.fixed(r/e*1e4,0)} bps)`}return{trigger:t.liqTriggerPriceUsd,fill:r??null,slippage:s,favorable:n}})(),tk=e3?ta.reduce((e,t)=>"increase"!==t.actionType||null!==e&&e.sequenceNumber<=t.sequenceNumber?e:t,null):null,{setMarketMint:tN}=(0,j.useMarketContext)(),{setActiveProfileIndex:tP}=(0,k.useProfile)(),tT=(0,S.useQuickTrade)(),tC=!e&&tT&&"pairs"!==t.underwriter?(0,g.getMarketMintFromAsset)(t.asset,t.underwriter):null,tM=(0,r.jsx)(x.TooltipProvider,{children:(0,r.jsxs)(x.Tooltip,{children:[(0,r.jsx)(x.TooltipTrigger,{className:"cursor-help",children:(0,r.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums underline decoration-dotted underline-offset-2",children:ee.rawUsd(t.totalFeesUsd)})}),(0,r.jsx)(x.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("div",{className:"font-semibold mb-2",children:J("totalFeesPaidLabel")}),parseFloat(t.fees.proOrderFee||"0")>0&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("proOrderFeesLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.fees.proOrderFee)})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("imperialFeeLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.fees.platformFee)})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("slippageLabel")}),(0,r.jsxs)("span",{className:t.fees.slippage&&0>parseFloat(t.fees.slippage)?"text-green-400":void 0,children:[t.fees.slippage&&0>parseFloat(t.fees.slippage)?"-":"",ee.rawUsd(t.fees.slippage?Math.abs(parseFloat(t.fees.slippage)).toString():"0")]})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:eV||eH?J("fundingLabel"):J("interestLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.fees.interest)})]}),td&&null!==tc&&(0,r.jsxs)("div",{className:tc<0?"text-green-400":"text-label-muted",children:["(",tc<0?"-":"",`$${ee.number(Math.abs(tc))}/hr`,")"]}),tj&&t.fees.loanInterest&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("loanInterestLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.fees.loanInterest)})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("openCloseFeesLabel")}),(0,r.jsx)("span",{children:null!=t.fees.pairsImpactFee?ee.usdNumber((0,g.openCloseFeeExImpact)(t.fees.jupiterFee,t.fees.pairsImpactFee)):ee.rawUsd(t.fees.jupiterFee)})]}),null!=t.fees.pairsImpactFee&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("skewImpactLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.fees.pairsImpactFee)})]}),(0,r.jsx)(C.LoanScoreboardRows,{lifecycle:t})]})})]})}),t_=(0,r.jsx)(x.TooltipProvider,{children:(0,r.jsxs)(x.Tooltip,{children:[(0,r.jsx)(x.TooltipTrigger,{asChild:!0,children:(0,r.jsx)("span",{className:(0,m.cn)("text-xs font-mono tabular-nums cursor-help underline decoration-dotted underline-offset-2",0>(0,b.parseRawValue)(t.feesOwed)?"text-side-long":"text-foreground"),children:t.feesOwed?(G=(0,b.parseRawValue)(t.feesOwed))<0?ee.pnl(G):`$${G.toLocaleStr
2ing(ee.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"-"})}),(0,r.jsx)(x.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("div",{className:"font-semibold mb-2",children:J("feesOwedOnCloseLabel")}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("platformFeeLabel")}),(0,r.jsx)("span",{children:t.swapFeeOwed&&parseFloat(t.swapFeeOwed)>0?ee.rawUsd(t.swapFeeOwed):"-"})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("slippageLabel")}),(0,r.jsx)("span",{children:"-"})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:eV||eH?J("fundingLabel"):J("interestLabel")}),(0,r.jsx)("span",{className:(eV||eH)&&t.borrowFeeOwed&&0>parseFloat(t.borrowFeeOwed)?"text-green-400":void 0,children:t.borrowFeeOwed?ee.rawUsd(t.borrowFeeOwed):"-"})]}),td&&null!==tc&&(0,r.jsxs)("div",{className:tc<0?"text-green-400":"text-label-muted",children:["(",tc<0?"-":"",`$${ee.number(Math.abs(tc))}/hr`,")"]}),tj&&t.accruedInterestUsd&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("loanInterestLabel")}),(0,r.jsx)("span",{children:ee.rawUsd(t.accruedInterestUsd)})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("openCloseLabel")}),(0,r.jsx)("span",{children:t.closeFeeOwed?ee.rawUsd(t.closeFeeOwed):"-"})]}),(0,r.jsx)(C.LoanScoreboardRows,{lifecycle:t})]})})]})}),tA=(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),e||(eh(!eu),es(!1),er(!1))},disabled:I||e,className:(0,m.cn)(K?ek.default.closeButton:"p-1.5 rounded border border-border-strong",I?"text-muted-foreground cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-surface-interactive"),title:e?J("reviewTradingDisabled"):J("closePositionTitle"),"aria-label":J("closePositionTitle"),children:I?(0,r.jsx)(a.Loader2,{className:"w-3.5 h-3.5 animate-spin"}):K?J("columnClose"):(0,r.jsx)(l.X,{className:"w-3.5 h-3.5"})}),tE=(t.tpslOrders??[]).filter(e=>["ratchet","fib_ratchet","fib_ratchet_entry","dca_close","dca_time_close","dca_ratchet_close","indicator","indicator_ratchet"].includes(e.orderType)),tL=i=>(0,r.jsx)(A.TpSlHoverPopover,{readOnly:e,lifecycle:t,desktopLayout:K,livePrices:$,waitingForOrder:eI,filterCategory:i,suppressTooltips:tw,onOpenTpSlTab:t=>{e||(eM(t),ev(!1),ej(void 0),eh(!1),er(!1),es(!0))},onOpenPopover:t=>{e||(t?({tpsl:es,trailing:ea,dca:eo,rsi:ec})[t](!0):es(!0),ev(!1),ej(void 0),eh(!1),er(!1))},onCancelPassthroughOrder:O,onCancelJupiterOrder:B,onEditOrder:r=>{if(e)return;ev(!1),ej(r);let i=r.orderType;"ratchet"===i||"fib_ratchet"===i||"fib_ratchet_entry"===i?ea(!0):"dca_close"===i||"dca_time_close"===i||"dca_ratchet_close"===i?eo(!0):"indicator"===i||"indicator_ratchet"===i?ec(!0):(eM((0,v.isEntirePositionOrder)(r,(0,b.parseRawValue)(t.sizeUsd))?"entire":"partial"),es(!0)),eh(!1),er(!1)}});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("tr",{"data-desktop-position":K||void 0,"data-history-row":e$||void 0,className:(0,m.cn)("border-b border-border cursor-pointer hover:bg-surface-interactive/50 transition-colors",et&&"bg-surface-raised/30"),onClick:()=>{let e=!et;er(e),e&&(es(!1),eh(!1))},children:[(0,r.jsx)("td",{className:"py-3 px-3 w-[130px] sticky left-0 z-[5] bg-canvas",children:(0,r.jsxs)("div",{className:"flex items-start gap-2",children:[(K||e$)&&(0,r.jsx)("button",{type:"button",className:ek.default.expandButton,"aria-label":J("transactionHistoryHeading"),"aria-expanded":et,onClick:e=>{e.stopPropagation(),er(!et),es(!1),eh(!1)},children:(0,r.jsx)(h.ChevronDown,{className:"size-3"})}),(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsxs)("div",{className:(0,m.cn)("flex items-center gap-2",(K||e$)&&ek.default.identityLine),children:[(0,r.jsx)("span",{className:`text-xs font-medium px-2 py-0.5 rounded ${ez?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:ez?J("longUpper"):J("shortUpper")}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),null!=eB&&tP(eB),tN((0,N.fromUrlSlug)(t.asset))},className:(0,m.cn)("flex items-center gap-2 hover:opacity-80 transition-opacity",(K||e$)&&ek.default.marketButton),children:[eU.image?(0,r.jsx)(n.default,{src:eU.image,alt:eU.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:y.handleTokenImageError}):(0,r.jsx)("div",{className:"w-4 h-4 rounded-full bg-gradient-to-r from-green-500 to-teal-500"}),(0,r.jsx)("span",{className:"text-xs text-foreground",children:eU.symbol})]}),K&&!th&&(0,r.jsx)("span",{className:ek.default.leverage,children:ee.rawLeverage(tt)}),!K&&tC&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),null!=eB&&tP(eB),tT.openQuickTrade(tC)},className:"flex items-center justify-center w-5 h-5 rounded bg-primary/10 hover:bg-primary/25 transition-colors","aria-label":J("trade
2Symbol",{symbol:eU.symbol}),children:(0,r.jsx)(c.Zap,{className:"w-3 h-3 text-primary"})})]}),(0,r.jsxs)("div",{className:(0,m.cn)("flex items-center gap-2",(K||e$)&&ek.default.identityDetails),children:[t.packPrize&&(0,r.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-imperial-gold/15 text-imperial-gold",children:J("packPrizeBadge")}),tu&&(0,r.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-300",children:J("phoenixDirectBadge")}),(tu||th)&&(0,r.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-surface-raised text-secondary-foreground",children:tb}),tv&&(0,r.jsx)("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-surface-raised text-secondary-foreground",children:tv}),!K&&!th&&(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:ee.rawLeverage(tt)}),(Q=(X="2"===t.underwriter?"phoenix":t.underwriter)?(0,w.getVenueIcon)(X,t.hedgeVenue):null)?(0,r.jsxs)("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[(0,r.jsx)(n.default,{src:Q.src,alt:Q.alt,title:Q.alt,width:14,height:14,className:"rounded-full",unoptimized:!0}),(K||e$)&&(0,r.jsx)("span",{children:Q.alt})]}):null]})]})]})}),U&&(0,r.jsx)("td",{className:"py-3 px-3",children:(0,r.jsxs)("span",{className:"text-xs text-muted-foreground",children:[ee.shortDate(e4??t.openedAt),t.closedAt&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-muted-foreground mx-1",children:"→"}),ee.shortDate(t.closedAt)]})]})}),(0,r.jsx)("td",{className:"py-3 px-3 w-[100px]",children:(0,r.jsxs)("div",{className:"flex flex-col",children:[(0,r.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums",children:ee.rawUsd(e7)}),t.sizeTokenAmount&&(0,r.jsx)("span",{className:"text-xs text-muted-foreground font-mono tabular-nums",children:ee.sizeTokens(t.sizeTokenAmount,t.asset)})]})}),(0,r.jsx)("td",{className:"py-3 px-3 w-[100px]",children:(0,r.jsx)("div",{className:"flex flex-col gap-0.5",children:e$||"pairs"===t.underwriter||tu||th?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-xs font-medium text-foreground font-mono tabular-nums",children:ee.rawUsd(ty)}),th&&(0,r.jsx)("span",{className:"text-[9px] text-muted-foreground",children:J("sharedCollateral")})]}):(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),e||(ef(!ep),eh(!1),es(!1),er(!1))},disabled:e,title:e?J("reviewTradingDisabled"):void 0,className:"flex items-center gap-1 cursor-pointer hover:bg-surface-interactive/50 rounded px-1 -mx-1 self-start disabled:cursor-not-allowed",children:[(0,r.jsx)("span",{className:"text-xs font-medium text-foreground font-mono tabular-nums",children:ee.rawUsd(te)}),(0,r.jsx)(o.Pencil,{className:"w-3 h-3 text-muted-foreground"})]})})}),(0,r.jsx)("td",{className:"py-3 px-3 w-[100px]",children:(0,r.jsx)(x.TooltipProvider,{children:(0,r.jsxs)(x.Tooltip,{children:[(0,r.jsx)(x.TooltipTrigger,{className:"cursor-help",children:(0,r.jsx)("span",{className:"text-[11px] text-secondary-foreground font-mono tabular-nums underline decoration-dotted underline-offset-2",children:ee.rawPrice(e3??tr)})}),(0,r.jsx)(x.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs max-w-xs",children:(0,r.jsxs)("div",{className:"space-y-1",children:[tn&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 border-b border-border pb-1 mb-1",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("labelBreakeven")}),(0,r.jsx)("span",{children:ee.rawPrice(tn)})]}),tS&&(0,r.jsxs)("div",{className:"border-b border-border pb-1 mb-1 space-y-0.5",children:[(0,r.jsx)("div",{className:"font-semibold text-destructive",children:J("liquidation")}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("labelTrigger")}),(0,r.jsx)("span",{children:ee.rawPrice(tS.trigger)})]}),tS.fill&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("labelFilledAt")}),(0,r.jsx)("span",{children:ee.rawPrice(tS.fill)})]}),tS.slippage&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:tS.favorable?J("labelPriceImprovement"):J("labelSlippage")}),(0,r.jsx)("span",{children:tS.slippage})]}),"phoenix"===t.underwriter&&(0,r.jsx)("div",{className:"text-[10px] text-muted-foreground",children:J("venueOrderbookCloseNote")})]}),(0,r.jsx)("div",{className:"font-semibold mb-2",children:J("positionActions
2Heading")}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 text-label-muted text-[10px] border-b border-border pb-1 mb-1",children:[(0,r.jsx)("span",{className:"w-8 shrink-0",children:J("columnType")}),(0,r.jsx)("span",{children:Z("size.full")}),(0,r.jsx)("span",{children:J("inputModePrice")})]}),ta.filter(e=>e.entryPrice&&e.sizeDelta).map((e,t)=>{let i="increase"===e.actionType?J("actionEntry"):"liquidation"===e.actionType?J("actionLiq"):J("actionExit"),s="increase"===e.actionType?"text-side-long":"liquidation"===e.actionType?"text-destructive":"text-primary",n=e3&&e===tk?e3:e.entryPrice;return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:(0,m.cn)("w-8 text-3xs shrink-0",s),children:i}),(0,r.jsx)("span",{className:"text-muted-foreground",children:ee.rawUsd(e.sizeDelta)}),(0,r.jsx)("span",{children:ee.rawPrice(n)})]},e.id||t)})]})})]})})}),!e$&&(0,r.jsx)("td",{className:"py-3 px-3 w-[100px]",children:(0,r.jsx)("span",{className:"text-[11px] text-foreground font-mono tabular-nums",children:eK?`$${ee.number(eq)}`:ee.rawPrice(t.markPrice)})}),!e$&&(0,r.jsx)("td",{className:"py-3 px-3 w-[90px]",children:t.liqTriggerPriceUsd||t.liqBandPriceUsd?(0,r.jsx)(x.TooltipProvider,{children:(0,r.jsxs)(x.Tooltip,{children:[(0,r.jsx)(x.TooltipTrigger,{className:"cursor-help",children:(0,r.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums underline decoration-dotted underline-offset-2",children:ee.rawPrice(ts)})}),(0,r.jsx)(x.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs max-w-xs",children:(0,r.jsxs)("div",{className:"space-y-1",children:[t.liqTriggerPriceUsd&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("labelEstFill")}),(0,r.jsx)("span",{children:ee.rawPrice(t.liqTriggerPriceUsd)})]}),t.liqBandPriceUsd&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:ez?J("labelWorstFillFloor"):J("labelWorstFillCap")}),(0,r.jsx)("span",{children:ee.rawPrice(t.liqBandPriceUsd)})]}),(0,r.jsx)("div",{className:"text-[10px] text-muted-foreground pt-1 border-t border-border",children:J("liquidationOrderbookNote")})]})})]})}):(0,r.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums",children:ee.rawPrice(ts)})}),(0,r.jsx)("td",{className:"py-3 px-3 w-[150px]",children:eW?(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsx)("div",{className:"h-4 w-16 rounded bg-surface-interactive animate-pulse"}),(0,r.jsx)("div",{className:"h-3 w-12 rounded bg-surface-interactive/60 animate-pulse"})]}):(0,r.jsxs)("div",{className:"flex items-start gap-1.5",children:[(0,r.jsx)(x.TooltipProvider,{children:(0,r.jsxs)(x.Tooltip,{children:[(0,r.jsx)(x.TooltipTrigger,{className:"cursor-help",children:(0,r.jsxs)("div",{className:"flex flex-col items-start",children:[(0,r.jsx)("span",{className:`text-xs font-bold font-mono tabular-nums whitespace-nowrap ${(0,f.pnlColor)(tp)}`,children:tg?ee.signedPercent(tm,2):ee.pnl(tp)}),e$&&(0,r.jsx)("span",{className:`text-xs font-mono tabular-nums ${(0,f.pnlColorDim)(tp)}`,children:null===tm?"—":ee.signedPercent(tm,2)}),!e$&&(0,r.jsxs)("span",{className:"flex items-baseline gap-1 whitespace-nowrap text-[11px] font-mono tabular-nums",children:[(0,r.jsx)("span",{className:"text-label-muted",children:J("columnRpnl")}),(0,r.jsx)("span",{className:(0,f.pnlColorDim)(tf),children:0===tf?ee.usdNumber(0):ee.pnl(tf)})]})]})}),(0,r.jsx)(x.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("div",{className:"font-semibold mb-2",children:J("pnlBreakdownLabel")}),!e$&&0!==eX&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("unrealizedLabel")}),(0,r.jsx)("span",{children:ee.pnl(eX)})]}),0!==eY&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("feesOwedLabel")}),(0,r.jsx)("span",{className:eY<0?"text-green-400":void 0,children:ee.pnl(-eY)})]}),(0!==eQ||eG>0)&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("realizedLabel")}),(0,r.jsx)("span",{children:ee.pnl(eJ)})]}),0!==eZ&&(0,r.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,r.jsx)("span",{className:"pl-2",children:J("inclSettledFunding")}),(0,r.jsx)("span",{className:eZ<0?"text-green-400":void 0,children:ee.pnl(-eZ)})]}),0!==e0&&(0,r.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,r.jsx)("span",{className:"pl-2",children:J("inclCloseFees")}),(0,r.jsx)("span",{children:ee.pnl(-e0)})]}),eG>0&&(0,r.jsxs)("div",{className:"flex justify-between gap-4 text-muted-foreground",children:[(0,r.jsx)("span",{className:"pl-2",children:J("inclOpenFees")}),(0,r.jsx)("span",{children:ee.pnl(-eG)})]}),null!==e6&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:J("packPrizeLessPriceLabel")}),(0,r.jsx)("span",{children:ee.pnl(e6-e1)})]}),t.packPrize&&null!==(0,g.packIssueBasisUsd)(t.packPrize)&&(0,r.jsx)("div",{className:"border-t border-border pt-2 mt-2 max-w-[300px]",children:(0,r.jsx)(i.PackPositionBreakdown,{priceCents:100*Number(t.packPrize.stakeUsd),basisCents:100*(0,g.packIssueBasisUsd)(t.packPrize),awardCents:((0,g.packIssueBasisUsd)(t.packPrize)+Number(t.packPrize.pnlOffsetUsd))*100,pnlUsd:(0,g.packPnlVsIssueBasisUsd)(t.packPrize,e1),tradingCostsUsd:eG+eY})}),(0,r.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border pt-1 mt-1 font-semibold",children:[(0,r.jsx)("span",{className:"text-secondary-foreground",children:J("totalLabel")}),(0,r.jsx)("span",{children:ee.pnl(e6??e1)})]}),!e$&&(0,r.jsx)("div",{className:"pt-1 max-w-[240px] whitespace-normal font-sans text-muted-foreground",children:J("rpnlUnsettledNote")})]})})]})}),!K&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),eg(!0)},className:"mt-0.5 p-0.5 rounded text-muted-foreground hover:text-secondary-foreground transition-colors cursor-pointer",title:J("sharePnlTitle"),children:(0,r.jsx)(d.Share2,{className:"w-3 h-3"})})]})}),K?(0,r.jsxs)("td",{className:ek.default.feesCell,children:[(0,r.jsxs)("div",{className:ek.default.feeLine,children:[(0,r.jsx)("span",{children:J("feesPaidShort")}),tM]}),(0,r.jsxs)("div",{className:ek.default.feeLine,children:[(0,r.jsx)("span",{children:J("feesOwedShort")}),t_]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("td",{className:"py-3 px-3 w-[85px]",children:tM}),!e$&&(0,r.jsx)("td",{className:"py-3 px-3 w-[85px]",children:t_})]}),!e$&&!K&&(0,r.jsx)("td",{className:"py-3 px-3 w-[70px]",children:tA}),!e$&&!tu&&O&&B&&(0,r.jsx)(r.Fragment,{children:(K?["tpsl"]:["tpsl","trailing","dca","rsi"]).map(e=>(0,r.jsx)("td",{className:"py-3 px-3 w-[80px]",onClick:e=>e.stopPropagation(),children:tL(e)},e))}),!e$&&(tu||K&&(!O||!B))&&(0,r.jsx)(r.Fragment,{children:(K?["tpsl"]:["tpsl","trailing","dca","rsi"]).map(e=>{let t="tpsl"===e?"TP/SL":"dca"===e?"DCA":"trailing"===e?J("columnTrailing"):J("columnIndicator");return(0,r.jsx)("td",{className:"py-3 px-3 w-[80px] text-center",children:(0,r.jsx)("span",{className:"text-xs text-muted-foreground",title:tu?J("categoryUnavailableDirectVenue",{category:t}):void 0,children:"—"})},e)})}),!e$&&K&&(0,r.jsx)("td",{onClick:e=>e.stopPropagation(),children:(0,r.jsxs)("div",{"data-compact-actions":!0,className:ek.default.actions,children:[!tu&&O&&B&&(0,r.jsx)(eN.StrategyDisclosure,{open:eb,onOpenChange:ev,activeCount:tE.length,children:["trailing","dca","rsi"].map(e=>(0,r.jsxs)("div",{className:ek.default.strategyRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:"trailing"===e?J("columnTrailing"):"dca"===e?"DCA":J("columnIndicator")}
2),(0,r.jsx)("p",{children:J("trailing"===e?"strategyTrailingHint":"dca"===e?"strategyDcaHint":"strategyIndicatorHint")})]}),tL(e)]},e))}),(0,r.jsxs)("button",{type:"button",className:ek.default.shareButton,onClick:()=>eg(!0),disabled:eW,"aria-label":J("sharePnlTitle"),children:[(0,r.jsx)(d.Share2,{className:"size-3.5"}),J("shareAction")]}),tA,(0,r.jsxs)(eP.DropdownMenu,{children:[(0,r.jsx)(eP.DropdownMenuTrigger,{asChild:!0,children:(0,r.jsx)("button",{type:"button",className:ek.default.overflowButton,"aria-label":J("columnActions"),children:(0,r.jsx)(u.Ellipsis,{className:"size-4"})})}),(0,r.jsxs)(eP.DropdownMenuContent,{align:"end",children:[tC&&(0,r.jsxs)(eP.DropdownMenuItem,{onSelect:()=>{null!=eB&&tP(eB),tT.openQuickTrade(tC)},children:[(0,r.jsx)(c.Zap,{className:"size-3.5"}),J("tradeSymbol",{symbol:eU.symbol})]}),(0,r.jsx)(eP.DropdownMenuItem,{onSelect:()=>{er(!et),es(!1),eh(!1)},children:J("transactionHistoryHeading")})]})]})]})}),e$&&(0,r.jsx)("td",{onClick:e=>e.stopPropagation(),children:(0,r.jsx)("div",{className:ek.default.actions,children:(0,r.jsxs)("button",{type:"button",className:ek.default.shareButton,onClick:()=>eg(!0),disabled:eW,"aria-label":J("sharePnlTitle"),children:[(0,r.jsx)(d.Share2,{className:"size-3.5"}),J("shareAction")]})})})]}),et&&(0,r.jsx)("tr",{"data-detail-row":!0,children:(0,r.jsx)("td",{colSpan:K?10:e$?U?8:7:U?15:14,className:"bg-surface border-b border-border",children:(0,r.jsxs)("div",{className:ek.default.receipt,children:[(0,r.jsx)("div",{className:"text-sm text-muted-foreground mb-3",children:J("transactionHistoryHeading")}),(0,r.jsx)("div",{className:"overflow-x-auto",children:(0,r.jsxs)("table",{className:"w-full",children:[(0,r.jsx)("thead",{className:"border-b border-border text-xs text-label-muted",children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("columnTime")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("receiptEvent")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("labelTrigger")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("inputModePrice")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("receiptSizeChange")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("receiptCapitalMovement")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:J("columnFees")}),(0,r.jsx)("th",{className:"px-3 py-2 text-left",children:"Tx"})]})}),(0,r.jsx)("tbody",{children:0===ta.length?(0,r.jsx)("tr",{children:(0,r.jsx)("td",{colSpan:8,className:"px-3 py-4 text-center text-label-muted text-sm",children:J("noTransactionsRecorded")})}):to?to.map(e=>"dca_group"===e.type?(0,r.jsx)(_.DcaSummaryRow,{group:e.group,dcaLabels:tl},e.group.groupKey):(0,r.jsx)(M.ActionRow,{action:e.action,asset:e.asset,side:e.side,dcaGroupLabel:tl.get(e.action.id),underwriter:t.underwriter},e.action.id)):ta.map(e=>(0,r.jsx)(M.ActionRow,{action:e,asset:t.asset,side:t.side,dcaGroupLabel:tl.get(e.id),underwriter:t.underwriter},e.id))})]})})]})})}),(0,r.jsx)(Y.Dialog,{open:!e&&ei&&!e$&&!tu,onOpenChange:e=>{e||(es(!1),ej(void 0))},children:(0,r.jsx)(Y.DialogContent,{className:"gap-0 sm:max-w-md",children:(0,r.jsx)(F.TpSlModal,{lifecycle:t,symbol:t.asset,iconSrc:eU?.image,leverage:tt,initialTab:eC,editOrder:ey,livePrices:$,onClose:()=>{es(!1),ej(void 0)},onPositionChange:z,onOrderSubmitted:e=>{eL(e??eD)},onCancelPassthroughOrder:O,onCancelJupiterOrder:B})})}),(0,r.jsx)(Y.Dialog,{open:!e&&en&&!e$&&!tu,onOpenChange:e=>{e||(ea(!1),ej(void 0))},children:(0,r.jsx)(Y.DialogContent,{className:"gap-0 sm:max-w-md",children:(0,r.jsx)(L.InlineTpSlForm,{lifecycle:t,livePrices:$,orderbookMidPrice:V,editOrder:ey,defaultOrderType:"ratchet",title:J("trailingStopLossTitle"),subtitle:"fib_ratchet"===e_?J("fibTrailingSubtitle"):J("trailingSubtitle"),onOrderTypeChange:eA,onCancelPassthroughOrder:O,onCancelJupiterOrder:B,onClose:()=>{ea(!1),ej(void 0)},onPositionChange:z,onOrderSubmitted:e=>{eL(e??eD)}})})}),(0,r.jsx)(Y.Dialog,{open:!e&&el&&!e$&&!tu,onOpenChange:e=>{e||(eo(!1),ej(void 0))},children:(0,r.jsx)(Y.DialogContent,{className:"gap-0 sm:max-w-md",children:(0,r.jsx)(L.InlineTpSlForm,{lifecycle:t,livePrice
2s:$,orderbookMidPrice:V,editOrder:ey,defaultOrderType:"dca_close",title:J("orderTypeDcaClose"),subtitle:J("dcaCloseSubtitle"),onCancelPassthroughOrder:O,onCancelJupiterOrder:B,onClose:()=>{eo(!1),ej(void 0)},onPositionChange:z,onOrderSubmitted:e=>{eL(e??eD)}})})}),(0,r.jsx)(Y.Dialog,{open:!e&&ed&&!e$&&!tu,onOpenChange:e=>{e||(ec(!1),ej(void 0))},children:(0,r.jsx)(Y.DialogContent,{className:"gap-0 sm:max-w-md",children:(0,r.jsx)(L.InlineTpSlForm,{lifecycle:t,livePrices:$,orderbookMidPrice:V,editOrder:ey,defaultOrderType:"rsi",title:J("indicatorCloseTitle"),subtitle:J("indicatorCloseSubtitle"),onCancelPassthroughOrder:O,onCancelJupiterOrder:B,onClose:()=>{ec(!1),ej(void 0)},onPositionChange:z,onOrderSubmitted:e=>{eL(e??eD)}})})}),(0,r.jsx)(Y.Dialog,{open:!e&&eu&&!e$,onOpenChange:e=>{e||I||eh(!1)},children:(0,r.jsx)(Y.DialogContent,{className:"gap-0 sm:max-w-md",children:(0,r.jsx)(E.InlineCloseForm,{lifecycle:t,symbol:t.asset,iconSrc:eU?.image,leverage:tt,livePrices:$,otherOpenLegs:W,isClosing:I,onClose:()=>eh(!1),onSubmit:t=>{e||D(t)},onPositionChange:z,onOrderSubmitted:e=>{eL(e??eD)}})})}),(0,r.jsx)(Y.Dialog,{open:!e&&ep&&!e$&&!tu,onOpenChange:e=>{e||ef(!1)},children:(0,r.jsxs)(Y.DialogContent,{children:[(0,r.jsx)(Y.DialogHeader,{children:(0,r.jsx)(Y.DialogTitle,{children:J("editCollateralTitle")})}),(0,r.jsx)(R.InlineEditCollateralForm,{lifecycle:t,livePrices:$,onClose:()=>ef(!1),onPositionChange:z})]})}),(0,r.jsx)(ew,{open:ex,onOpenChange:eg,lifecycle:t,pnlPercent:e8??e9,pnlUsd:e6??e1,leverage:tt??"1",entryPriceOverride:e3??tr,markPriceOverride:ti})]})}},521186,e=>{"use strict";e.s(["PositionsTab",()=>er],521186);var t=e.i(394390),r=e.i(989714),i=e.i(334281),s=e.i(265172),n=e.i(183023),a=e.i(888245),l=e.i(984457),o=e.i(546642),d=e.i(942553),c=e.i(859394),u=e.i(341296),h=e.i(633441);e.i(875574);var p=e.i(142298),m=e.i(687229),f=e.i(387445),x=e.i(526862),g=e.i(894771),b=e.i(450358),v=e.i(616341),y=e.i(275683),w=e.i(190459),j=e.i(879630),S=e.i(786911),k=e.i(305085),N=e.i(259048),P=e.i(494286),T=e.i(685576),C=e.i(153517),M=e.i(670374),_=e.i(26826),A=e.i(752717),E=e.i(172581),L=e.i(91525),F=e.i(665757),R=e.i(299959),D=e.i(227456);function I({open:e,onOpenChange:r,lifecycle:i,livePrices:s,isClosing:n,onSubmit:a,otherOpenLegs:c=0,onPositionChange:u}){let h,p,m=(0,d.useTranslations)("positions"),f=(0,R.useFormatters)(),x="long"===i.side,g="sunrise"===i.underwriter||"7"===i.underwriter,{data:b}=(0,P.useSunriseMargin)(i.wallet,i.profileIndex??0,i.sunriseMarginSeat??null,g&&void 0!==i.sunriseMarginSeat),v=b?.primeBound===!0,w=(0,_.parseRawValue)(i.collateralUsd),j=(0,_.parseRawValue)(i.entryPrice),S=(0,M.getMarketMintFromAsset)(i.asset,i.underwriter),{sizePercent:k,amountInput:U,amountUnit:O,canToggleUnit:B,handleSizePercent:z,handleAmountTyped:$,toggleAmountUnit:V}=(0,E.useCloseAmount)(i),H=S?s?.[S]:void 0,W=H??((0,_.parseRawValue)(i.markPrice)||j),q=v?null:(0,_.calculateLockInitialsPercent)(i,W),K=(0,L.useLimitClose)(i,W),G=(0,L.canPlaceLimitClose)(i),Y=G&&"limit"===K.mode,X=k/100,Q=w*X,J=(0,_.netCapitalForDisplay)(i),Z=null!==J?J*X:null,ee=(0,_.estimateClosePnl)(i,{execPrice:Y?K.execPrice:W,closeFraction:X}),et=ee?(0,_.getEstimatedReturn)(Q,ee):Q,er=ee?(0,_.getDisplayPnl)(ee,Q,Z):0,ei=ee?ee.total:null,es=null!==ei&&Math.abs((0,_.sumRealizedPnlFromActions)(i))>=1&&Math.abs(er-ei)>=.01,en=(0,y.closeProceedsDestination)({marginMode:i.directVenue?.marginMode,sizePercent:k,otherOpenLegs:c}),ea=Z??Q,el=ea>0?er/ea*100:0;return(0,t.jsx)(T.Sheet,{open:e,onOpenChange:r,children:(0,t.jsxs)(T.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4 overflow-x-hidden flex flex-col",children:[(0,t.jsx)(T.SheetTitle,{className:"text-foreground text-lg font-semibold mb-2 shrink-0",children:m("mobileClosePositionTitle")}),(0,t.jsxs)("div",{className:"flex-1 overflow-y-auto min-h-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-3",children:[(0,t.jsx)("span",{className:"text-sm text-foreground font-medium",children:i.asset}),(0,t.jsx)("span",{className:`text-[11px] font-medium px-1.5 py-0.5 rounded ${x?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:x?m("historyLong"):m("historyShort")}),(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground px-1.5 py-0.5 rounded bg-surface-raised",children:f.rawLeverage(i.leverageX)})]}),G&&(0,t.jsx)("div",{className:"flex items-center gap-1 mb-3",children:["market","limit"].map(e=>(0,t.jsx)("button",{onClick:()=>K.setMode(e),className:(0,C.cn)("flex-1 py-1.5 text-xs font-medium rounded transition-colors",K.mode===e?"bg-surface-interactive text-foreground":"bg-surface text-label-muted hover:text-secondary-foreground"),children:"market"===e?m("closeTypeMarket"):m("closeTypeLimit")},e))}),v&&(0,t.jsx)("p",{className:"text-xs text-label-muted mb-3",children:"Proceeds from a partial close stay in this position until it is fully closed and Prime is repaid."}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm mb-1",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("mobileLastPriceUsd")}),(0,t.jsx)("span",{className:"text-foreground font-mono tabular-nums",children:H?`$${f.number(H)}`:f.rawPrice(i.markPrice)})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm mb-3",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("mobileEntryPriceUsd")}),(0,t.jsx)("span",{className:"text-foreground font-mono tabular-nums",children:f.rawPrice(i.entryPrice)})]}),(0,t.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2.5 mb-3",children:[(0,t.jsx)(F.Input,{type:"text",inputMode:"decimal",value:U,onChange:e=>$(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),B?(0,t.jsx)("button",{type:"button",onClick:V,className:"text-xs text-muted-foreground ml-2 px-2 py-1 rounded border border-border-strong bg-surface hover:text-foreground hover:border-border-strong transition-colors",title:m("mobileSwitchUnit",{unit:"usd"===O?i.asset:"USDC"}),children:"usd"===O?"USDC":i.asset}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USDC"})]}),Y&&(0,t.jsxs)("div",{className:"mb-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:m("limitClosePriceLabel")}),(0,t.jsxs)("button",{type:"button",onClick:()=>K.handlePriceTyped(String(W)),className:"text-[11px] text-label-muted",children:[m("priceRefMark")," $",f.number(W)]})]}),(0,t.jsxs)("div",{className:(0,C.cn)("flex items-center bg-surface-raised border rounded-lg px-3 py-2.5",K.hasPrice&&!K.isValidPrice?"border-destructive/60":"border-border-strong"),children:[(0,t.jsx)(F.Input,{type:"text",inputMode:"decimal",value:K.priceInput,onChange:e=>K.handlePriceTyped(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USD"})]}),K.isValidPrice&&(0,t.jsxs)("div",{className:"flex items-center gap-2 mt-1.5",children:[(0,t.jsx)("span",{className:(0,C.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded","tp"===K.leg?"bg-side-long/15 text-side-long":"bg-side-short/15 text-side-short"),children:"tp"===K.leg?m("takeProfit"):m("stopLoss")}),(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:m(K.movesUp?"limitCloseRisesTo":"limitCloseFallsTo",{percent:k,asset:i.asset,price:f.number(K.price)})})]})]}),(0,t.jsxs)("div",{className:"mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-2",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted w-12",children:m("mobileAmount")}),(0,t.jsx)("input",{type:"range",...D.THUMB_ONLY_SLIDER,min:1,max:100,value:k,onChange:e=>z(parseInt(e.target.value)),className:(0,C.cn)(D.RANGE_SLIDER_CLASSES,"flex-1 [&::-webkit-slider-thumb]:bg-primary")}),(0,t.jsxs)("span",{className:"text-sm text-foreground w-12 text-right font-mono tabular-nums",children:[k,"%"]})]}),(0,t.jsx)("div",{className:"flex items-center gap-1",children:[25,50,75,100].map(e=>(0,t.jsxs)("button",{onClick:()=>z(e),className:(0,C.cn)("flex-1 py-1.5 text-xs rounded",k===e?"bg-surface-interactive text-foreground":"bg-surface text-label-muted hover:text-secondary-foreground"),children:[e,"%"]},e))}),q&&(0,t.jsx)("button",{onClick:()=>z(q.percent),className:(0,C.cn)("w-full py-1.5 mt-2 text-xs rounded",k===q.percent?"bg-cyan-500/20 text-cyan-400 border border-cyan-500/30":"bg-surface text-cyan-600 hover:text-cyan-400 border border-transparent"),children:m("mobileInitialCapitalPercent",{percent:q.percent})}),q&&k===q.percent&&(0,t.jsx)("div",{className:"text-[10px] text-cyan-400/70",children:m("mobileInitialCapitalSplit",{initial:f.number(q.receiving),profit:f.number(q.remaining)})})]}),(0,t.jsxs)("div",{className:"space-y-2 mb-3 mt-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:en?.kind==="account"?m("mobileSettles"):m("mobileReceiving")}),(0,t.jsxs)("span",{className:et>=0?"text-cyan-400 font-mono tabular-nums":"text-destructive font-mono tabular-nums",children:["$",f.number(Math.max(0,et))," USDC"]})]}),en&&(0,t.jsx)("div",{className:"text-[11px] text-muted-foreground -mt-1",children:en.note}),(0,t.jsx)(A.CloseFeeBreakdown,{lifecycle:i,sizePercent:k}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:m("mobileNetPnl")}),(0,t.jsxs)("span",{className:(0,C.cn)("font-mono tabular-nums",(0,N.pnlColor)(er)),children:[er>=0?"+":"",f.number(er)," USD",(0,t.jsxs)("span",{className:(0,N.pnlColorDim)(er),children:[" ","(",f.signedPercent(el,2),")"]})]})]}
2),es&&null!==ei&&(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs ml-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:m("mobileLegPnl")}),(0,t.jsxs)("span",{className:(0,C.cn)("font-mono tabular-nums",(0,N.pnlColorDim)(ei)),children:[ei>=0?"+":"",f.number(ei)," USD"]})]}),Y&&K.isValidPrice&&(0,t.jsx)("div",{className:"text-[11px] text-label-muted",children:m("limitCloseEstimateNote")})]})]}),(0,t.jsx)("div",{className:"shrink-0 pt-3",children:(h=Y?K.missingLabel(k):(0,o.pickMissingLabel)([[k<=0,m("mobileSetSize")]]),p=Y?K.submitting:n,(0,t.jsx)("button",{onClick:async()=>{if(!Y){a(k),r(!1);return}await K.submit(k)&&(r(!1),u?.())},disabled:p||null!==h,className:"w-full py-3 rounded-lg border border-primary/40 text-primary bg-primary/10 hover:bg-primary/20 font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:p?(0,t.jsx)(l.Spinner,{className:"size-5"}):h??(Y?m("limitCloseAction"):m("mobileConfirm"))}))})]})})}var U=e.i(328188),O=e.i(870020),B=e.i(161568);let z={tpsl:"tp",trailing:"ratchet",dca:"dca_close",rsi:"rsi"},$={trailing:"mobileTrailingStop",dca:"historyOrderTypeDcaClose",rsi:"mobileIndicator"};function V({open:e,onOpenChange:r,lifecycle:i,livePrices:s,orderbookMidPrice:n,editOrder:a,onPositionChange:l,category:o,defaultSubType:c,onCancelPassthroughOrder:u,onCancelJupiterOrder:h}){let p=(0,d.useTranslations)("positions"),m=(0,M.getTokenInfo)(i.asset),f="tpsl"===o&&(!a||"tp"===a.orderType||"sl"===a.orderType||"private_tp"===a.orderType||"private_sl"===a.orderType);return(0,t.jsx)(T.Sheet,{open:e,onOpenChange:r,children:(0,t.jsx)(T.SheetContent,{side:"bottom",className:"bg-canvas px-0 pt-2 max-h-[90dvh] overflow-y-auto",children:f?(0,t.jsx)(B.TpSlModal,{lifecycle:i,symbol:i.asset,iconSrc:m?.image,leverage:i.leverageX,initialTab:!a||(0,U.isEntirePositionOrder)(a,(0,_.parseRawValue)(i.sizeUsd))?"entire":"partial",editOrder:a,livePrices:s,onClose:()=>r(!1),onPositionChange:l,onCancelPassthroughOrder:u,onCancelJupiterOrder:h}):(0,t.jsx)(O.InlineTpSlForm,{lifecycle:i,livePrices:s,orderbookMidPrice:n,editOrder:a,defaultOrderType:c??(o?z[o]:void 0),title:a?p("mobileEditOrderTitle"):o?"tpsl"===o?"TP/SL":p($[o]):void 0,onClose:()=>r(!1),onPositionChange:l,onOrderSubmitted:()=>r(!1),onCancelPassthroughOrder:u,onCancelJupiterOrder:h})})})}var H=e.i(255810),W=e.i(923469);function q({open:e,onOpenChange:r,lifecycle:i,livePrices:s}){let n=(0,d.useTranslations)("positions"),a=(0,R.useFormatters)(),l="long"===i.side,{displayActions:o,dcaGroupLabels:c}=(0,H.usePositionData)({lifecycle:i,livePrices:s});return(0,t.jsx)(T.Sheet,{open:e,onOpenChange:r,children:(0,t.jsxs)(T.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4 max-h-[80dvh] overflow-y-auto",children:[(0,t.jsx)(T.SheetTitle,{className:"text-foreground text-lg font-semibold mb-1",children:n("mobileTransactions")}),(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,t.jsx)("span",{className:"text-sm text-foreground font-medium",children:i.asset}),(0,t.jsx)("span",{className:`text-[11px] font-medium px-1.5 py-0.5 rounded ${l?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:n(l?"historyLong":"historyShort")}),(0,t.jsx)("span",{className:"text-[11px] font-mono tabular-nums text-muted-foreground px-1.5 py-0.5 rounded bg-surface-raised",children:a.rawLeverage(i.leverageX)})]}),0===o.length?(0,t.jsx)("div",{className:"text-center text-label-muted text-sm py-8",children:n("mobileNoTransactions")}):(0,t.jsx)("div",{className:"space-y-2",children:o.map(e=>(0,t.jsx)(W.MobileHistoryCard,{action:e,asset:i.asset,side:i.side,dcaGroupLabel:c.get(e.id),underwriter:i.underwriter},e.id))})]})})}var K=e.i(943494),G=e.i(821043),Y=e.i(500665),X=e.i(122097),Q=e.i(308146);let J=[10,20,50,80,100];function Z({open:e,onOpenChange:r,lifecycle:i,livePrices:s,onPositionChange:n}){let a=(0,d.useTranslations)("positions"),l=(0,d.useTranslations)("terms"),c=(0,d.useTranslations)("common"),u=(0,R.useFormatters)(),{mode:h,setMode:p,amount:m,setAmount:f,amountNum:x,submitting:b,awaitingReturn:v,loadingLimits:y,maxWithdraw:w,maxDeposit:j,
2currentCollateral:S,currentLeverage:k,currentLiqPrice:N,preview:P,handleSubmit:M}=(0,Y.useCollateralEdit)({lifecycle:i,livePrices:s,onClose:()=>r(!1),onPositionChange:n}),{profiles:_}=(0,g.useProfile)(),{balances:A}=(0,X.useAllProfileUsdcBalances)(_),E=null!=i.profileIndex?Number(i.profileIndex):null,L=null!=E?A.get(E):void 0,F="long"===i.side,D="deposit"===h,I=null==L?0:null!=j?Math.min(L,j):L,U=D?I:w??0,O=y||U<=0,B=(0,o.pickMissingLabel)([[y||null===w,a("mobileLoadingLimits")],[x<=0,a("mobileEnterAmount")]]);return(0,t.jsx)(T.Sheet,{open:e,onOpenChange:r,children:(0,t.jsxs)(T.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4 overflow-y-auto overflow-x-hidden",children:[(0,t.jsx)(T.SheetTitle,{className:"text-foreground text-lg font-semibold mb-1",children:a("mobileAdjustCollateral")}),(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,t.jsx)("span",{className:"text-sm text-foreground font-medium",children:i.asset}),(0,t.jsx)("span",{className:(0,C.cn)("text-[11px] font-medium px-1.5 py-0.5 rounded",F?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"),children:F?a("historyLong"):a("historyShort")}),(0,t.jsxs)("span",{className:"text-[11px] text-muted-foreground px-1.5 py-0.5 rounded bg-surface-raised",children:[u.fixed(k,2),"x"]})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-2 mb-4 bg-surface border border-border rounded-lg p-1",children:[(0,t.jsx)("button",{onClick:()=>p("deposit"),className:(0,C.cn)("py-2 text-sm font-medium rounded-md transition-colors",D?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-foreground"),children:a("mobileAddMargin")}),(0,t.jsx)("button",{onClick:()=>p("withdraw"),className:(0,C.cn)("py-2 text-sm font-medium rounded-md transition-colors",D?"text-muted-foreground hover:text-foreground":"bg-surface-interactive text-foreground"),children:a("mobileRemoveMargin")})]}),(0,t.jsxs)("div",{"data-keypad-reveal":!0,className:"flex items-center gap-2 bg-surface border border-border rounded-lg px-3 py-3 mb-2",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",placeholder:a("mobileAmount"),value:m,onChange:e=>f((0,G.sanitizeDecimalInput)(e.target.value,u.decimalSeparator)),className:"flex-1 min-w-0 bg-transparent border-none text-foreground text-base font-mono tabular-nums placeholder:text-label-muted focus:outline-none"}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground shrink-0",children:"USDC"})]}),(0,t.jsx)("div",{className:"grid grid-cols-5 gap-1.5 mb-2",children:J.map(e=>(0,t.jsxs)("button",{onClick:()=>{f((0,Q.percentToDecimalString)(U,e,6))},disabled:O,className:"py-1.5 text-xs rounded-full bg-surface text-muted-foreground hover:text-foreground hover:bg-surface-interactive transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[e,"%"]},e))}),(()=>{if(y||null===w)return(0,t.jsx)("div",{className:"text-[11px] text-label-muted mb-4",children:a("mobileLoadingLimitsEllipsis")});if(D&&null==L)return(0,t.jsx)("div",{className:"text-[11px] text-label-muted mb-4",children:a("mobileLoadingBalance")});if(U<=0){let e=D?null!=L&&L<=0?a("mobileNoUsdcInAccount"):a("mobileMaxCollateralReached"):a("mobileAlreadyMaxLeverage");return(0,t.jsx)("div",{className:"text-[11px] text-amber-400/80 mb-4",children:e})}return(0,t.jsx)("div",{className:"text-[11px] text-label-muted mb-4 tabular-nums",children:D?a("mobileAvailableUsdc",{amount:u.fixed(L??0,2)}):a("mobileMaxWithdrawable",{amount:u.number(w)})})})(),(0,t.jsxs)("div",{className:"space-y-2 mb-5",children:[(0,t.jsx)(ee,{label:a("historyColCollateral"),current:null===S?"—":`$${u.number(S)}`,isLoading:P.isLoading,next:`$${u.number(P.newCollateral)}`,nextClass:P.newCollateral<=0?"text-destructive":D?"text-cyan-400":"text-amber-400"}),(0,t.jsx)(ee,{label:a("mobileLiqPrice"),current:`$${u.number(N)}`,isLoading:P.isLoading,next:`$${u.number(P.newLiqPrice)}`}),(0,t.jsx)(ee,{label:l("leverage.full"),current:`${u.fixed(k,2)}x`,isLoading:P.isLoading,next:`${u.fixed(P.newLeverage,2)}x`,nextClass:P.newLeverage>100?"text-destructive":void 0}),P.swapFee>0&&x>0&&(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:a("mobilePlatformFee")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["-$",u.number(P.swapFee)]})]}),!D&&void 0!==P.withdrawReceived&&P.swapFee>0&&x>0&&(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:a("mobileYouReceive")}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:["$",u.number(P.withdrawReceived)]})]}),P.error&&(0,t.jsx)("div",{className:"text-destructive text-xs",children:P.error})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,t.jsx)("button",{onClick:()=>r(!1),disabled:b&&!v,className:"py-3 rounded-lg border border-border-strong text-sm font-medium text-secondary-foreground hover:text-foreground hover:bg-surface-interactive disabled:opacity-50",children:c("cancel")}),(0,t.jsx)("button",{onClick:M,disabled:b||null!==B||!P.isValid||P.isLoading,className:(0,C.cn)("py-3 rounded-lg text-sm font-medium text-primary-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",D?"bg-cyan-500 hover:bg-cyan-600":"bg-amber-500 hover:bg-amber-600"),children:v?(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[(0,t.jsx)(K.Loader2,{className:"h-5 w-5 animate-spin"}),a("sunriseWaitingForFunds")]}):b?(0,t.jsx)(K.Loader2,{className:"h-5 w-5 animate-spin"}):B??a("mobileConfirm")})]})]})})}function ee({label:e,current:r,next:i,nextClass:s,isLoading:n}){return(0,t.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,t.jsx)("span",{className:"text-label-muted",children:e}),(0,t.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[r,null!=i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-label-muted mx-1.5",children:"→"}),n?(0,t.jsx)(K.Loader2,{className:"inline w-3 h-3 animate-spin text-muted-foreground"}):(0,t.jsx)("span",{className:s,children:i})]})]})]})}function et(e,t){let r=t.directVenue?.traderAccount;if(t.directVenue?.marginMode!=="cross"||!r)return 0;let i=e.find(e=>e.traderAccount===r);return i?Math.max(0,i.openLegs-1):0}function er({readOnly:e=!1,desktopEmptyState:N=!1,positions:P,isLoading:T,isPositionClosing:C,livePrice
2s:M,orderbookMidPrice:_,orderbookSymbol:A,onClosePosition:E,createPassthroughCancelHandler:L,createJupiterCancelHandler:F,onPositionChange:R}){let D=(0,d.useTranslations)("positions"),U=1e3*(0,r.useTickingNowSecs)(),O=(0,d.useTranslations)("terms"),[B,z]=(0,n.useState)(null),$=B?.type==="editCollateral"?P.find(e=>e.id===B.lifecycle.id):void 0,[H,W]=(0,n.useState)(null),K=(0,n.useRef)(null),{panelRef:G,isDesktop:Y}=(0,u.usePanelLayout)(600),{mode:X,setMode:Q}=(0,h.usePnlDisplayMode)(),J=(0,y.deriveCrossSeats)(P.filter(e=>7!==(0,w.underwriterByteFrom)(String(e.underwriter??"")))),{publicKey:ee}=(0,p.useUnifiedWallet)(),ei=ee?.toBase58(),es=B?.type==="tpsl"?P.find(e=>e.id===B.lifecycle.id&&e.wallet===B.lifecycle.wallet&&e.profileIndex===B.lifecycle.profileIndex&&e.positionPda===B.lifecycle.positionPda&&e.underwriter===B.lifecycle.underwriter&&e.side===B.lifecycle.side&&"open"===e.status&&e.wallet===ei):void 0;B?.type!=="tpsl"||es||z(null);let{walletState:en,partialPositions:ea,positionsAvailability:el,phoenixAvailability:eo}=(0,m.useUnifiedPositions)(),ed=null===el.lastReadAt||U-el.lastReadAt>=s.READ_STALE_MS,ec=(0,t.jsx)("div",{className:"space-y-2 p-3",children:ea.map(e=>(0,t.jsx)(i.IncompletePosition,{row:e},e.lifecycleId))}),{linkByLifecycle:eu}=(0,f.usePairLinks)(ee?.toBase58(),P.length>
20),eh=(0,c.useSearchParams)().get("close"),[ep,em]=(0,n.useState)(null),[ef,ex]=(0,n.useState)(null);if(!e&&eh&&void 0!==Y&&ep!==eh){let e=P.find(e=>e.id===eh);e&&(em(eh),Y?ex(eh):z({type:"close",lifecycle:e}))}let eg=(0,n.useMemo)(()=>{let e=[],t=new Set;for(let r of P){if(t.has(r.id))continue;let i=r.lifecycleId?eu.get(r.lifecycleId):void 0;if(!i){t.add(r.id),e.push({link:null,items:[r]});continue}let s=P.filter(e=>e.lifecycleId&&eu.get(e.lifecycleId)?.id===i.id);s.forEach(e=>t.add(e.id)),e.push({link:s.length>1?i:null,items:s})}return e},[P,eu]);return 0===P.length?"disconnected"===en?(0,t.jsx)(o.TabConnectEmptyState,{desktop:N&&!0===Y,title:D("connectToViewPositions"),hint:D("connectToViewPositionsHint")}):(0,t.jsxs)(t.Fragment,{children:[ea.length>0&&ec,!e&&(0,t.jsx)(j.SunriseMarginAccounts,{positions:P,desktop:!0===Y,onPositionChange:R}),T?(0,t.jsxs)("div",{className:"flex items-center justify-center py-12",role:"status",children:[(0,t.jsx)(l.Spinner,{className:"size-6 text-muted-foreground"}),(0,t.jsx)("span",{className:"sr-only",children:D("loadingEllipsis")})]}):0===ea.length?(0,t.jsx)(o.TabEmptyState,{desktop:N&&!0===Y,title:D("available"!==el.status||"available"!==eo.status||ed?"accountReadNoPositionsToDisplay":"noOpenPositions"),hint:D("noOpenPositionsHint")}):null]}):(0,t.jsxs)("div",{ref:G,className:"h-full min-h-0 min-w-0",children:[ea.length>0&&ec,!1===Y&&(0,t.jsxs)("div",{className:"overflow-y-auto px-[10px] pb-3 pt-3 space-y-[9px]",children:[!e&&(0,t.jsx)(j.SunriseMarginAccounts,{positions:P,desktop:!1,onPositionChange:R}),J.map(r=>(0,t.jsx)(v.MobileCrossSeatCard,{seat:r,onAddCollateral:!e&&r.anchor?e=>W({seat:e,mode:"add"}):void 0,onWithdrawCollateral:!e&&r.anchor?e=>W({seat:e,mode:"withdraw"}):void 0},r.traderAccount)),eg.map(r=>{let i=r.items.map(r=>(0,t.jsx)(k.MobilePositionCard,{readOnly:e,lifecycle:r,onClosePosition:e=>E(r,e),isClosing:C(r),onCancelPassthroughOrder:L(r.side,(0,g.normalizeUnderwriter)(r.underwriter)),onCancelJupiterOrder:F(r.positionPda,r.source,r.profileIndex,(0,g.normalizeUnderwriter)(r.underwriter)),livePrices:M,orderbookMidPrice:r.asset===A?_:void 0,onOpenCloseSheet:()=>z({type:"close",lifecycle:r}),onOpenOrderSheet:(e,t,i)=>z({type:"tpsl",lifecycle:r,orderCategory:e,editOrder:t,defaultSubType:i}),onOpenTxnsSheet:()=>z({type:"txns",lifecycle:r}),onOpenEditCollateralSheet:()=>z({type:"editCollateral",lifecycle:r})},r.id));return r.link?(0,t.jsx)(x.PairGroupCards,{link:r.link,legs:r.items,onCloseAll:e?void 0:()=>r.items.forEach(e=>E(e,100)),children:i},r.link.id):i})]}),Y&&(0,t.jsxs)("div",{className:"flex flex-col h-full min-w-0 relative",children:[!e&&(0,t.jsx)(j.SunriseMarginAccounts,{positions:P,desktop:!0===Y,onPositionChange:R}),J.map(r=>(0,t.jsx)(v.CrossSeatStrip,{seat:r,onAddCollateral:!e&&r.anchor?e=>W({seat:e,mode:"add"}):void 0,onWithdrawCollateral:!e&&r.anchor?e=>W({seat:e,mode:"withdraw"}):void 0},r.traderAccount)),(0,t.jsx)("div",{ref:K,className:N?a.default.scroll:"overflow-x-auto overflow-y-auto max-h-full",children:(0,t.jsxs)("table",{className:N?a.default.table:"w-full table-fixed min-w-[1150px]",children:[(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[130px] sticky left-0 z-20 bg-canvas",children:D("columnPosition")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[100px]",children:O("size.full")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[100px]",children:D("collateral")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[100px]",children:D("avgEntry")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[100px]",children:D("columnMark")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[90px]",children:D("liquidationPrice")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[150px]",children:(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[N?O("pnl"):D("columnUpnlRpnl"),(0,t.jsx)("span",{role:"group","aria-label":D("pnlDisplayModeLabel"),className:"flex rounded border border-border overflow-hidden font-mono",children:["usd","percent"].map(e=>(0,t.jsx)("button",{type:"button","aria-pressed":X===e,onClick:()=>Q(e),className:`px-1.5 leading-5 cursor-pointer transition-colors ${X===e?"bg-surface-interactive text-foreground":"hover:text-secondary-foreground"}`,children:"usd"===e?"$":"%"},e))})]})}),N?(0,t.jsx)("th",{className:"text-left",children:D("columnFees")}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[85px]",children:D("columnFeesPaid")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[85px]",children:D("columnFeesOwed")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-left w-[70px]",children:D("columnClose")})]}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-center w-[80px]",children:"TP/SL"}),!N&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("th",{className:"py-2.5 px-3 text-center w-[80px]",children:D("columnTrailing")}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-center w-[80px]",children:"DCA"}),(0,t.jsx)("th",{className:"py-2.5 px-3 text-center w-[80px]",children:D("columnIndicator")}
2)]}),N&&(0,t.jsx)("th",{children:D("columnActions")})]})}),eg.map(r=>{let i=r.items.map(r=>(0,t.jsx)(b.PositionRow,{readOnly:e,desktopLayout:N,lifecycle:r,onClosePosition:e=>E(r,e),isClosing:C(r),onCancelPassthroughOrder:L(r.side,(0,g.normalizeUnderwriter)(r.underwriter)),onCancelJupiterOrder:F(r.positionPda,r.source,r.profileIndex,(0,g.normalizeUnderwriter)(r.underwriter)),onPositionChange:R,livePrices:M,otherOpenLegs:et(J,r),orderbookMidPrice:r.asset===A?_:void 0,autoOpenClose:r.id===ef},r.id));return r.link?(0,t.jsx)(x.PairGroupRows,{link:r.link,legs:r.items,colSpan:N?10:15,onCloseAll:e?void 0:()=>r.items.forEach(e=>E(e,100)),children:i},r.link.id):(0,t.jsx)("tbody",{children:i},r.items[0].id)})]})})]}),!e&&B?.type==="close"&&(0,t.jsx)(I,{open:!0,onOpenChange:e=>{e||z(null)},lifecycle:B.lifecycle,livePrices:M,otherOpenLegs:et(J,B.lifecycle),isClosing:C(B.lifecycle),onPositionChange:R,onSubmit:e=>{E(B.lifecycle,e),z(null)}}),!e&&B?.type==="tpsl"&&es&&(0,t.jsx)(V,{open:!0,onOpenChange:e=>{e||z(null)},lifecycle:es,livePrices:M,orderbookMidPrice:es.asset===A?_:void 0,onPositionChange:R,category:B.orderCategory,editOrder:B.editOrder,defaultSubType:B.defaultSubType,onCancelPassthroughOrder:L(es.side,(0,g.normalizeUnderwriter)(es.underwriter)),onCancelJupiterOrder:F(es.positionPda,es.source,es.profileIndex,(0,g.normalizeUnderwriter)(es.underwriter))}),B?.type==="txns"&&(0,t.jsx)(q,{open:!0,onOpenChange:e=>{e||z(null)},lifecycle:B.lifecycle,livePrices:M}),!e&&H&&(0,t.jsx)(S.MarginAccountSheet,{open:!0,onOpenChange:e=>{e||W(null)},seat:H.seat,initialMode:H.mode,onPositionChange:R}),!e&&$&&(0,t.jsx)(Z,{open:!0,onOpenChange:e=>{e||z(null)},lifecycle:$,livePrices:M,onPositionChange:R})]})}},341296,e=>{"use strict";var t=e.i(183023),r=e.i(619966);e.s(["usePanelLayout",0,function(e){let i=(0,r.useIsDesktop)(),[s,n]=(0,t.useState)(null),[a,l]=(0,t.useState)({width:null,railGrowth:0}),o=(0,t.useCallback)(e=>n(e),[]);return(0,t.useLayoutEffect)(()=>{if(!s)return;let e=new Set,t=new Set,r=()=>{let r=new Set([s]),n=new Map;for(let e of s.querySelectorAll("[data-compact-actions]")){let t=e.closest("td"),i=e.closest("table");if(!t||!i)continue;let s=n.get(i),a=s?.baseline??parseFloat(getComputedStyle(i).getPropertyValue("--actions-min-width"));if(!Number.isFinite(a)||a<=0)continue;let l=t.getBoundingClientRect().width;l<=0||(r.add(t),n.set(i,{width:Math.max(s?.width??0,l),baseline:a}))}let a=0;for(let[e,t]of n){let r=`${t.width}px`;e.style.getPropertyValue("--actions-width")!==r&&e.style.setProperty("--actions-width",r),a=Math.max(a,t.width-t.baseline)}for(let e of t)n.has(e)||e.style.removeProperty("--actions-width");for(let s of(t=new Set(n.keys()),e))r.has(s)||(i.unobserve(s),e.delete(s));for(let t of r)e.has(t)||(i.observe(t),e.add(t));let o=s.getBoundingClientRect().width;l(e=>{let t=n.size?a:e.railGrowth;return e.width===o&&e.railGrowth===t?e:{width:o,railGrowth:t}})},i=new ResizeObserver(r),n=new MutationObserver(r);return r(),n.observe(s,{childList:!0,subtree:!0}),()=>{for(let e of(i.disconnect(),n.disconnect(),t))e.style.removeProperty("--actions-width")}},[s]),{panelRef:o,isDesktop:void 0===i?void 0:i&&(null===a.width||a.width>=e+a.railGrowth)}}])},255810,633441,43085,815109,468602,161568,e=>{"use strict";e.s(["TpSlModal",()=>ec],161568),e.s(["DcaSummaryRow",()=>C],815109),e.s(["LoanScoreboardRows",()=>k],43085),e.s(["usePositionData",()=>h],255810);var t=e.i(183023),r=e.i(43690),i=e.i(689384),s=e.i(894771);e.i(889723);var n=e.i(49332),a=e.i(824088);e.i(965155);var l=e.i(22156),o=e.i(26826),d=e.i(670374),c=e.i(979804),u=e.i(265724);function h({lifecycle:e,livePrices:p,dcaGrouping:m}){(0,c.useTokenIconsVersion)();let{profiles:f}=(0,s.useProfile)(),x="closed"===e.status||"liquidated"===e.status,g=(0,l.useTimestampForSymbol)(x?void 0:e.asset),b=(0,d.getTokenInfo)(e.asset),v=(0,o.isFlashUnderwriter)(e.underwriter),y="gmtrade"===e.underwriter,{getMarketFees:w,getClosePrice:j}=(0,a.useGmTradeWs)(),S="false"!==localStorage.getItem("showBorrowRate"),k=(0,d.getMarketMintFromAsset)(e.asset),{data:N}=(0,r.useQuery)({queryKey:["jupiter-pool-info",k],queryFn:()=>(0,i.fetchJupiterPoolInfo)(k),staleTime:3e4,enabled:S&&!v&&!y&&!!k&&(0,n.isJupiterMarket)(k)}),P="phoenix"===e.underwriter||"2"===e.underwriter,T="pairs"===e.underwriter||"5"===e.underwriter,C="sunrise"===e.underwriter||"7"===e.underwriter,M=y?w(e.asset):void 0,_=(0,t.useMemo)(()=>
2{if(v)return null;if(y){if(!e.sizeUsd)return null;let t=(0,o.parseRawValue)(e.sizeUsd);return t<=0?null:M?("long"===e.side?M.longNetRatePerHourPercent:M.shortNetRatePerHourPercent)/100*t:null}if(P||C){if(!e.fundingRateHourlyPercent||!e.sizeUsd)return null;let t=parseFloat(e.fundingRateHourlyPercent),r=(0,o.parseRawValue)(e.sizeUsd);return isNaN(t)||r<=0?null:t/100*r}if(!N||!e.sizeUsd)return null;let t=(0,o.parseRawValue)(e.sizeUsd),r=parseFloat("long"===e.side?N.longBorrowRatePercent:N.shortBorrowRatePercent);return isNaN(r)||t<=0?null:r/100*t/8760},[N,e.sizeUsd,e.side,v,y,P,C,e.fundingRateHourlyPercent,M]),A=null!=e.profileIndex?Number(e.profileIndex):null,E=null!=A&&f.length>A?f[A]?.name??`Profile ${A+1}`:null,L="long"===e.side,F=!x&&null==e.feesOwed,R=(0,d.getMarketMintFromAsset)(e.asset,e.underwriter),D=y?j(e.asset,L):void 0,I=null==g||Date.now()-g>3e4,U=D??(P?void 0:(R?p?.[R]:void 0)??p?.[e.asset]),O=I&&null==D?void 0:U,B=x?0:(0,o.parseRawValue)(e.markPrice),z=O??(B>0?B:void 0),$=!x&&z,V=$?(0,d.calculateLivePnl)(e,z):null,H=F&&null==V,W=V?.realizedPnl??(0,o.sumRealizedPnlFromActions)(e),q=(0,o.settledFundingFromActions)(e),K=(0,o.settledCloseFeesFromActions)(e),G=V?.feesPaid??(0,o.feesPaidForRemainingSize)(e),Y=V?.feesOwed??(0,o.parseRawValue)(e.feesOwed),X=V?.unrealizedPnl??0,Q=(0,o.parseRawValue)(e.pnlUsd),J=V?.pnlUsd??(x?(0,o.closedDisplayPnl)(e):Q+W),Z=V?.pricePnl??0,ee=(0,o.parseRawValue)(e.maxCollateralUsd)||(0,o.parseRawValue)(e.collateralUsd),et=(0,o.getGrossDepositedCapital)(e),er=(0,o.parseRawValue)(e.collateralUsd),ei=et??er,es=V?.pnlPercent??(x?ee>0?J/ee*100:(0,o.parseRawValue)(e.pnlPercent):0!==W&&ei>0?J/ei*100:(0,o.parseRawValue)(e.pnlPercent)),en=x?null:V?.unrealizedPnl??Q,ea=e.packPrize??null,el=ea?.backdatedEntryPrice??null,eo=ea?.backdatedOpenedAt??null,ed=null===ea?0:(0,d.packCapitalBase)(ea,ei),ec=V?.packPnlUsd??(null===ea?null:(0,d.packPnlVsPriceUsd)(ea,J)),eu=V?.packPnlPercent??(null===ec||ed<=0?null:ec/ed*100),eh=(ec??J)>=0,ep=x?e.maxSizeUsd:e.sizeUsd,em=x?e.maxCollateralUsd:e.collateralUsd,ef=(0,u.displayPositionLeverage)(e),ex=(0,t.useMemo)(()=>{let t=e.actions?.findLast(e=>"increase"===e.actionType&&e.entryPrice);return t?.entryPrice??e.entryPrice},[e.actions,e.entryPrice]),eg=(0,t.useMemo)(()=>{if(!x&&P)return e.entryPrice;if(x)return(0,d.closedAvgEntryPrice)(e);let t=e.actions?.filter(e=>("increase"===e.actionType||"decrease"===e.actionType)&&e.sizeDelta).slice().sort((e,t)=>e.sequenceNumber-t.sequenceNumber);if(!t||0===t.length)return e.entryPrice;let r=0,i=0;for(let e of t){let t=Math.abs((0,o.parseRawValue)(e.sizeDelta));if("increase"===e.actionType){let s=e.entryPrice?(0,o.parseRawValue)(e.entryPrice):0;if(t>0&&s>0){let e=r+t;i=(r*i+t*s)/e,r=e}}else 0===(r=Math.max(0,r-t))&&(i=0)}return r>0?i.toString():e.entryPrice},[x,P,e.actions,e.entryPrice]),eb=(0,t.useMemo)(()=>x?(0,d.closedAvgExitPrice)(e):null,[x,e]),ev=(0,t.useMemo)(()=>x?eb:void 0!==O?O.toString():!y&&e.markPrice?e.markPrice:null,[x,eb,O,y,e.markPrice]),ey=(0,t.useMemo)(()=>e.actions&&e.actions.length>0?e.actions:e.sizeUsd||e.collateralUsd?[{id:`synthetic-${e.positionPda}`,actionType:"increase",status:"completed",sequenceNumber:1,failureReason:null,tx1Signature:"",tx1Timestamp:e.openedAt,collateralDeposited:e.collateralUsd,platformFee:null,hadSwap:!1,swapSlippage:null,tx2Signature:null,tx2Timestamp:e.openedAt,sizeDelta:e.sizeUsd,sizeDeltaTokens:e.sizeTokenAmount,collateralDelta:e.collateralUsd,jupiterFee:null,interest:null,entryPrice:e.entryPrice,tx3Signature:null,tx3Timestamp:null,pnlRealized:null,hasProfit:null,userReceived:null,tx3PlatformFee:null,tx3SwapFee:null,tx3SweepSlippage:null,proOrderFee:null,collateralAfter:e.collateralUsd,positionSizeAfter:null,postLiquidationPriceUsd:null,orderType:null,triggerPrice:null,triggerCondition:null,orderSizeUsd:null,orderSlippageBps:null,orderCreatedAt:null,orderWaitPrice:null,orderWaitDurationSecs:null,orderWorstPrice:null,orderRatchetSize:null,orderExecutionTriggerPrice:null,orderIndicatorConfig:null,orderThresholdValue:null,orderTriggerDelaySecs:null,orderDcaNumLegs:null,orderDcaLegNumber:null,orderDcaLegTrigger:null,orderDcaStartPrice
2:null,orderDcaEndPrice:null,orderDcaPriceLimit:null,orderDcaIntervalSeconds:null}]:[],[e]),ew=(0,d.displayLiquidationPriceForLifecycle)(e),ej=P?(0,o.phoenixCashBasisBreakeven)(e)?.toString()??e.breakevenPriceUsd:null,eS=(0,t.useMemo)(()=>(0,d.buildDcaGroupLabels)(ey),[ey]),ek=(0,t.useMemo)(()=>{if(!m)return null;let t=ey.map(t=>({action:t,asset:e.asset,side:e.side,underwriter:e.underwriter}));return(0,d.groupDcaActions)(t)},[m,ey,e.asset,e.side,e.underwriter]);return{tokenInfo:b,profileName:E,profileIdx:A,isLong:L,isClosed:x,isPhoenixPosition:P,isPairsPosition:T,feesLoading:H,livePrice:z,useLivePrice:$,livePnlUsd:J,livePnlPercent:es,feesPaidValue:G,feesOwedValue:Y,pricePnl:Z,realizedPnl:W,realizedInclOpenFees:W-G,settledFunding:q,settledCloseFees:K,unrealizedPnl:X,pnlValue:J,openPnl:en,openPnlPercent:null!==en&&er>0?en/er*100:null,packEntryPrice:el,packOpenedAt:eo,packPnlUsd:ec,packPnlPercent:eu,pnlPercentValue:es,isProfit:eh,displaySize:ep,displayCollateral:em,displayLeverage:ef,avgEntryPrice:eg,avgExitPrice:eb,shareCardMarkPrice:ev,initialEntryPrice:ex,displayLiquidationPrice:ew,breakevenPrice:ej,displayActions:ey,dcaGroupLabels:eS,groupedDisplayActions:ek,showBorrowRate:S,borrowRateHourlyUsd:_,collateral:ee}}let p="imperial_positions_pnl_mode",m="usd",f=!1,x=new Set;function g(e){if(!f){f=!0;try{"percent"===localStorage.getItem(p)&&(m="percent")}catch{}}return x.add(e),()=>x.delete(e)}function b(e){m=e;try{localStorage.setItem(p,e)}catch{}for(let e of x)e()}e.s(["usePnlDisplayMode",0,function(){return{mode:(0,t.useSyncExternalStore)(g,()=>m,()=>"usd"),setMode:b}}],633441);var v=e.i(394390),y=e.i(942553),w=e.i(299959),j=e.i(406470);function S(e,t){return`${(0,j.formatFixed)(e,e>=10?0:1,t)}x`}function k({lifecycle:e}){let t,r,i,s,n=(0,y.useTranslations)("positions"),a=(0,w.useFormatters)(),l=e.borrowedCollateralUsd;if(!(l&&parseFloat(l)>0))return null;let o=e.effectiveLeverageX?parseFloat(e.effectiveLeverageX):null,c=e.baseLeverageX?parseFloat(e.baseLeverageX):null;return(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)("div",{className:"mt-2 pt-2 border-t border-border text-sky-400 font-semibold",children:n("imperialLoan")}),null!==o&&null!==c&&(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:n("leverageLabel")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:[S(o,a.intlTag)," ",(0,v.jsx)("span",{className:"text-label-muted",children:n("leverageYours")})," ·"," ",S(c,a.intlTag)," ",(0,v.jsx)("span",{className:"text-label-muted",children:n("leverageVenue")})]})]}),(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:n("yourCollateralLabel")}),(0,v.jsx)("span",{className:"font-mono tabular-nums",children:a.rawUsd(e.collateralUsd)})]}),(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:n("borrowedLabel")}),(0,v.jsx)("span",{className:"font-mono tabular-nums",children:a.rawUsd(l)})]}),e.ourLiquidationPriceUsd&&(t=parseFloat(e.ourLiquidationPriceUsd),i=(r=(0,d.venueLiquidationPriceForLifecycle)(e))?parseFloat(r):NaN,s=Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0&&Math.abs(t-i)>=.005,(0,v.jsxs)(v.Fragment,{children:[(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:n("yourLiquidationLabel")}),(0,v.jsx)("span",{className:"font-mono tabular-nums",children:a.rawPrice(e.ourLiquidationPriceUsd)})]}),s&&(0,v.jsxs)("div",{className:"flex justify-between gap-4 text-[11px] text-label-muted",children:[(0,v.jsx)("span",{children:n("venueLiqLabel")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:[a.rawPrice(r),(0,v.jsxs)("span",{className:"text-muted-foreground",children:[" ","· ",n("weCloseEarlier",{amount:a.number(Math.abs(t-i))})]})]})]})]})),null!=e.loanRateBps&&(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:n("loanRateLabel")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:[a.apr(e.loanRateBps)," APR"]})]})]})}var N=e.i(491135),P=e.i(268680),T=e.i(980333);function C({group:e,dcaLabels:r}){let i=(0,y.useTranslations)("positions"),s=(0,w.useFormatters)(),[n,a]=(0,t.useState)(!1),l=s.price(e.avgEntryPrice),o=`$${Math.abs(e.totalSizeDelta).toLocaleStr
2ing(s.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=`$${e.totalFees.toLocaleString(s.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=e.totalCollateralDeposited>0,u=e.totalUserReceived>0;return(0,v.jsxs)(v.Fragment,{children:[(0,v.jsxs)("tr",{className:"border-b border-border/50 border-l-2 border-l-cyan-500/50 cursor-pointer hover:bg-surface-interactive/50",onClick:()=>a(!n),children:[(0,v.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:s.dateTime(e.mostRecentTimestamp)}),(0,v.jsx)("td",{className:"px-3 py-2",children:(0,v.jsx)(P.TooltipProvider,{children:(0,v.jsxs)(P.Tooltip,{children:[(0,v.jsx)(P.TooltipTrigger,{className:"cursor-help",children:(0,v.jsxs)("div",{className:"flex items-center gap-1",children:[(0,v.jsx)(N.ChevronRight,{className:`h-3 w-3 text-cyan-400 transition-transform ${n?"rotate-90":""}`}),(0,v.jsx)("span",{className:"text-xs text-cyan-400 underline decoration-dotted underline-offset-2",children:i("dcaLegsCount",{executed:e.numLegs,total:e.dcaNumLegs??"?"})})]})}),(0,v.jsx)(P.TooltipContent,{side:"top",className:"font-mono tabular-nums text-xs",children:(0,v.jsxs)("div",{className:"space-y-1",children:[(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:i("assetLabel")}),(0,v.jsx)("span",{children:i("assetAndSide",{asset:e.asset,side:e.side})})]}),e.dcaStartPrice&&e.dcaEndPrice&&(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:i("rangeLabel")}),(0,v.jsxs)("span",{children:[s.rawPrice(e.dcaStartPrice)," → ",s.rawPrice(e.dcaEndPrice)]})]}),(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:i("createdLabel")}),(0,v.jsx)("span",{children:s.dateTime(e.orderCreatedAt)})]})]})})]})})}),(0,v.jsx)("td",{className:"px-3 py-2 text-xs text-muted-foreground",children:"—"}),(0,v.jsx)("td",{className:"px-3 py-2 text-xs text-foreground font-mono tabular-nums",children:l}),(0,v.jsx)("td",{className:"px-3 py-2",children:(0,v.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums",children:o})}),(0,v.jsx)("td",{className:"px-3 py-2",children:(0,v.jsxs)("div",{className:"flex flex-col",children:[c&&(0,v.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:i("receiptCapitalAdded",{amount:`+$${e.totalCollateralDeposited.toLocaleString(s.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`})}),u&&(0,v.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums",children:i("receiptCapitalReturned",{amount:`$${e.totalUserReceived.toLocaleString(s.intlTag,{minimumFractionDigits:2,maximumFractionDigits:2})}`})})]})}),(0,v.jsx)("td",{className:"px-3 py-2",children:(0,v.jsx)("span",{className:"text-xs text-amber-400 font-mono tabular-nums",children:d})}),(0,v.jsx)("td",{className:"px-3 py-2 text-xs text-label-muted",children:"—"}),(0,v.jsx)("td",{className:"px-3 py-2 text-xs text-label-muted",children:"—"})]}),n&&e.actions.map(({action:e,asset:t,side:i,underwriter:s})=>(0,v.jsx)(T.ActionRow,{action:e,asset:t,side:i,dcaGroupLabel:r.get(e.id),indented:!0,underwriter:s},e.id))]})}var M=e.i(475274),_=e.i(734195),A=e.i(441399);e.i(875574);var E=e.i(142298),L=e.i(416627),F=e.i(1169),R=e.i(120911),D=e.i(984457),I=e.i(116082),U=e.i(936548),O=e.i(858007),B=e.i(153517),z=e.i(259048),$=e.i(821043),V=e.i(296228),H=e.i(379966),W=e.i(943494),q=e.i(409686),K=e.i(967090),G=e.i(328188);function Y({orders:e,positionSizeUsd:t,selectedPda:r,cancelingPda:i,canCancel:s,onSelect:n,onCancel:a}){let l=(0,y.useTranslations)("positions"),d=(0,w.useFormatters)();return 0===e.length?null:(0,v.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,v.jsx)("span",{className:"text-xs text-muted-foreground",children:l("existingPartialOrders")}),(0,v.jsxs)("div",{className:"flex flex-col gap-1.5",children:[e.map((e,c)=>{let u=G.TP_ORDER_TYPES.includes(e.orderType),h=e.orderType.startsWith("private_"),p=(0,G.closeFractionOf)(e,t),m=!!e.orderPda&&e.orderPda===r,f=!!e.orderPda&&e.orderPda===i;return(0,v.jsxs)("div",{className:(0,B.cn)("flex items-center rounded-lg border pr-1 transition-colors",m?"border-orange-500/60 bg-orange-500/5":"border-border-strong bg-surface-raised"),children:[(0,v.jsxs)("button",{onClick:()=>n(e),disabled:!e.orderPda,className:"flex flex-1 items-center gap-2 px-3 py-1.5 text-left text-xs disabled:cursor-not-allowed",children:[(0,v.jsx)("span",{className:(0,B.cn)("w-6 font-semibold",u?"text-side-long":"text-side-short"),children:u?"TP":"SL"}),h&&(0,v.jsx)("span",{className:"rounded bg-purple-500/15 px-1.5 py-0.5 text-[10px] font-medium text-purple-300",children:l("privateOrderBadge")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums text-foreground",children:["$",d.number((0,o.parseRawValue)(e.triggerPriceUsd))]}),(0,v.jsxs)("span",{className:"ml-auto font-mono tabular-nums text-label-muted",children:[Math.round(100*p),"% · $",d.number(t*p)]})]}),s(e)&&(0,v.jsx)("button",{onClick:()=>a(e),disabled:f,title:l("cancelOrder"),className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-red-500/10 hover:text-red-400 disabled:opacity-50",children:f?(0,v.jsx)(W.Loader2,{className:"h-3 w-3 animate-spin"}):(0,v.jsx)(K.X,{className:"h-3.5 w-3.5"})})]},e.orderPda||`partial-${c}`)}),(0,v.jsxs)("button",{onClick:()=>n(void 0),className:(0,B.cn)("flex items-center justify-center gap-1 rounded-lg border border-dashed px-3 py-1.5 text-xs transition-colors",r?"border-border-strong text-label-muted hover:border-border-strong hover:text-foreground":"border-orange-500/60 bg-orange-500/5 text-foreground"),children:[(0,v.jsx)(q.Plus,{className:"h-3 w-3"}),l("addNewOrder")]})]})]})}var X=e.i(626074),Q=e.i(665757),J=e.i(727322);let Z=(e,t,r,i)=>`${e.toUpperCase()}|${t}|${r}|${i}`,ee=["phoenix-depth-summary"],et="/api/v1/phoenix/depth";async function er(){let e=await fetch(`https://api.imperial.space${et}`);if(!e.ok)throw console.error(`Phoenix depth fetch failed: ${e.status} ${et}`),Error(`Failed to fetch Phoenix depth (${e.status})`);return e.json()}function ei(){return(0,r.useQuery)({queryKey:ee,queryFn:er,staleTime:15e3,refetchInterval:3e4,placeholderData:{snapshots:{}}})}e.s(["usePhoenixDepthSummary",0,ei],468602);var es=e.i(362221),en=e.i(227456),ea=e.i(905843);
2class el extends Error{}let eo={price:"inputModePrice",pct:"inputModePctPrice",pnl:"inputModePctPnl"},ed=e=>JSON.stringify([e.id,e.asset,e.wallet,e.positionPda,e.profileIndex,e.underwriter,e.side,e.sunriseMarginSeat,e.source,e.ownership]);function ec(e){let{publicKey:t}=(0,E.useUnifiedWallet)(),r=t?.toBase58()??"";return(0,v.jsx)(eu,{...e},`${ed(e.lifecycle)}:${r}`)}function eu({lifecycle:e,symbol:i,iconSrc:n,leverage:a,initialTab:l="entire",editOrder:c,livePrices:u,onClose:h,onPositionChange:p,onOrderSubmitted:m,onCancelPassthroughOrder:f,onCancelJupiterOrder:x}){let g=(0,y.useTranslations)("positions"),{publicKey:b}=(0,E.useUnifiedWallet)(),j=!!e.wallet&&b?.toBase58()===e.wallet,S=(0,y.useTranslations)("common"),k=(0,w.useFormatters)(),N=(0,w.useDecimalSeparator)(),{createTriggerOrder:P,updateTriggerOrder:T,updatePassthroughOrder:C,wasLastErrorRejection:W}=(0,J.useTradeActions)(),{bandFor:q}=function(){let{data:e,isLoading:t}=(0,r.useQuery)({queryKey:["close-slippage"],queryFn:async()=>{let e=await fetch("https://api.imperial.space/api/v1/close-slippage");if(!e.ok)throw Error(`close-slippage ${e.status}`);return e.json()},staleTime:18e5,gcTime:36e5,retry:1}),i=new Map;for(let t of e?.bands??[])i.set(Z(t.assetSymbol,t.underwriter,t.leg,t.formulaVersion),t);return{isLoading:t,bandFor:(e,t,r,s)=>e&&t?i.get(Z(e,t,r,s))??null:null}}(),{data:K}=ei(),ee="long"===e.side,et=(0,o.parseRawValue)(e.sizeUsd),er=e=>k.number(et*e/100,{useGrouping:!1}),ec=(0,o.parseRawValue)(e.entryPrice),em=(0,o.parseRawValue)(e.collateralUsd),ef=(0,d.getMarketMintFromAsset)(e.asset,e.underwriter),ex=(0,A.venueLivePrice)(u,(0,s.normalizeUnderwriter)(e.underwriter),e.asset,ef?u?.[ef]:u?.[e.asset]),eg=ex??((0,o.parseRawValue)(e.markPrice)||ec),eb=ex??eg,ev=(0,o.netCapitalForDisplay)(e),ey=(0,o.sumRealizedPnlFromActions)(e),ew=Math.abs(ey)>=1,ej=(0,o.feesPaidForRemainingSize)(e),eS=(0,o.parseRawValue)(e.feesOwed),ek=e=>G.TP_ORDER_TYPES.includes(e.orderType),eN=(0,t.useMemo)(()=>(e.tpslOrders??[]).filter(e=>G.TP_ORDER_TYPES.includes(e.orderType)||G.SL_ORDER_TYPES.includes(e.orderType)),[e.tpslOrders]),eP=eN.find(e=>ek(e)&&(0,G.isEntirePositionOrder)(e,et)),eT=eN.find(e=>!ek(e)&&(0,G.isEntirePositionOrder)(e,et)),eC=eN.filter(e=>!(0,G.isEntirePositionOrder)(e,et)),eM=(e,t)=>({tp:"entire"===e?eP:t&&ek(t)?t:void 0,sl:"entire"===e?eT:t&&!ek(t)?t:void 0}),e_=e=>{let t=(0,o.parseRawValue)(e?.triggerPriceUsd);return t>0?t.toString():""},eA=(e,t)=>{let r=(0,o.parseRawValue)(t?.triggerPriceUsd);return r<=0||eb<=0?"":(("tp"===e===ee?r-eb:eb-r)/eb*100).toFixed(2)},eE=(e,t)=>"entire"!==e&&t?Math.min(100,Math.max(1,Math.round(100*(0,G.closeFractionOf)(t,et)))):100,eL=c?.orderPda&&!(0,G.isEntirePositionOrder)(c,et)?c:void 0,eF=eM(l,eL),eR=eE(l,eF.tp??eF.sl),[eD,eI]=(0,t.useState)(l),[eU,eO]=(0,t.useState)(eL?.orderPda),[eB,ez]=(0,t.useState)(!1),e$=(0,t.useRef)(!1),eV=(0,t.useRef)(null),eH=ed(e);(0,t.useEffect)(()=>(eV.current=eH,()=>{eV.current=null}),[eH]);let eW=JSON.stringify(["position",e.wallet,e.positionPda,e.asset,e.profileIndex,(0,J.underwriterToNum)(e.underwriter),e.side,e.sunriseMarginSeat??null]),eq=(0,t.useSyncExternalStore)(L.subscribeTpSlAttempts,()=>(0,L.getTpSlAttempt)(eW,"tp"),()=>null),eK=(0,t.useSyncExternalStore)(L.subscribeTpSlAttempts,()=>(0,L.getTpSlAttempt)(eW,"sl"),()=>null),eG=e=>
2"tp"===e?eq:eK,eY=["tp","sl"].filter(e=>{let t=(0,L.getTpSlAttempt)(eW,e);return t?.status==="submitted"&&t.intent?.kind!=="cancel"}),eX=(0,t.useRef)(new Set(eY)),[eQ,eJ]=(0,t.useState)(eY),eZ=eQ.length>0,e0=!!(eq||eK),e1=[eq,eK].some(e=>e?.intent?.kind==="cancel"&&e.ownerReviewedAt),e2=[eq,eK].some(e=>e?.intent?.kind==="cancel"),e5=[eq,eK].some(e=>e&&"submitted"!==e.status),e3=[eq,eK].some(e=>e?.persistence==="memory");(0,t.useEffect)(()=>{for(let e of["tp","sl"]){let t=(0,L.getTpSlAttempt)(eW,e);(0,L.reconcileTpSlAttempt)(eW,e,eN)&&t?.intent?.kind!=="cancel"&&(eX.current.add(e),eJ([...eX.current]))}},[eW,eN,eq,eK]);let[e4,e6]=(0,t.useState)(null),[e8,e9]=(0,t.useState)(!1),[e7,te]=(0,t.useState)(eq?.intent?.kind==="cancel"?"":eq?.intent?String(eq.intent.triggerPrice):e_(eF.tp)),[tt,tr]=(0,t.useState)(eK?.intent?.kind==="cancel"?"":eK?.intent?String(eK.intent.triggerPrice):e_(eF.sl)),[ti,ts]=(0,t.useState)(eA("tp",eF.tp)),[tn,ta]=(0,t.useState)(eA("sl",eF.sl)),[tl,to]=(0,t.useState)("price"),[td,tc]=(0,t.useState)("price"),[tu,th]=(0,t.useState)("last"),[tp,tm]=(0,t.useState)("last"),[tf,tx]=(0,t.useState)({tp:!1,sl:!1}),[tg,tb]=(0,t.useState)(eR),[tv,ty]=(0,t.useState)("partial"===l&&et>0?er(eR):""),{tp:tw,sl:tj}=eM(eD,eU?eC.find(e=>e.orderPda===eU):void 0),tS=(e,t)=>{let{tp:r,sl:i}=eM(e,t);te(e_(r)),tr(e_(i)),ts(eA("tp",r)),ta(eA("sl",i)),to("price"),tc("price");let s=eE(e,r??i);tb(s),ty("partial"===e&&et>0?er(s):""),e9(!1)},tk=e=>"last"===e?eb:eg,tN=e=>{let t=parseFloat("tp"===e?e7:tt)||0,r="tp"===e?tl:td;if(t<=0)return 0;if("price"===r)return t;let i=ec>0?ec:eg;return"pct"===r&&i>0?"tp"===e?ee?i*(1+t/100):i*(1-t/100):ee?i*(1-t/100):i*(1+t/100):"pnl"===r&&ec>0&&et>0?(0,o.priceForTargetPnlPct)({sizeUsd:et,collateralUsd:em,netCapital:ev,realizedPnl:ey,entryPrice:ec,feesPaid:ej,feesOwed:eS,isLong:ee,targetPnlPct:"tp"===e?t:-t})??0:t},tP=()=>(0,M.stopLossLiquidationError)(ee,tN("sl"),e.liquidationPrice),tT=e=>{if("sl"===e&&tP())return!1;let t=tN(e);return!!Number.isFinite(t)&&!(t<=0)&&!!Number.isFinite(eg)&&!(eg<=0)&&("tp"===e?ee?t>eg:t<eg:ee?t<eg:t>eg)},tC="entire"===eD?1:Math.max(0,Math.min(1,tg/100)),tM=e=>(0,G.uncoveredPctFor)({orders:eN,leg:e,positionSizeUsd:et,targetPda:("tp"===e?tw:tj)?.orderPda}),t_="entire"===eD?100:tg,tA=(t,r,i,s)=>{let n=tN(t);if(!Number.isFinite(n)||n<=0)throw I.toast.error(g("errorEnterTpOrSlPrice")),new el("invalid price");let a="sl"===t?tP():null;if(a)throw I.toast.error((0,_.tradingValidationError)(a)),new el("invalid stop-loss");if(!tT(t)){let e=k.number(eg);throw I.toast.error("tp"===t?ee?g("takeProfitMustBeAboveMark",{price:e}):g("takeProfitMustBeBelowMark",{price:e}):ee?g("stopLossMustBeBelowMark",{price:e}):g("stopLossMustBeAboveMark",{price:e})),new el("invalid leg")}let l="entire"===eD?1e4:!e8&&"number"==typeof r?.closeBps&&r.closeBps>0?r.closeBps:Math.round(1e4*tC),d=l/1e4*et,c="tp"===t,u=(0,o.buildQuoteSnapshot)(e,{leg:t,execPrice:n,closeFraction:l/1e4,closeBps:l,priceRef:"tp"===t?tu:tp,inputMode:"tp"===t?tl:td,markPrice:eg,lastPrice:eb,identity:{side:+!ee,orderType:ea.PassthroughOrderType.StopLimit,underwriter:(0,J.underwriterToNum)(i.underwriter),marketMint:s}});return{intent:{triggerPrice:n,closeBps:l,sizeUsd:d,targetOrderPda:r?.orderPda,baselineOrderPdas:eN.flatMap(e=>e.orderPda?[e.orderPda]:[])},submit:async()=>{if(r?.orderPda){if("jupiter_native"===r.source){let t=await T({positionPubkey:e.positionPda,positionRequestPubkey:r.orderPda,marketMint:s,sizeUsd:d,triggerPrice:n,positionSource:"imperial",profileIndex:e.profileIndex,underwriter:e.underwriter,quote:u});return{ok:!!t,created:!1,signature:t}}let t=await C({orderPda:r.orderPda,profileIndex:r.profileIndex??i.profileIndex,triggerPrice:n,sizeUsd:d,underwriter:i.underwriter,closeBps:l,quote:u});return{ok:!!t,created:!1,signature:t}}let t=await P({positionPubkey:e.positionPda,...i,sizeUsd:d,triggerPrice:n,isTakeProfit:c,positionSource:"imperial",closeBps:l,quote:u});return{ok:!!t,created:!!t,signature:t}}}},tE=e=>!!e?.orderPda&&("jupiter_native"===e.source&&!!x||"jupiter_native"!==e.source&&void 0!==e.profileIndex&&!!f),tL=async e=>{let t=ek(e)?"tp":"sl";
2if(!j)return I.toast.error(g("tpslWalletUnavailable")),!1;if(!tE(e)||!e.orderPda||e$.current||(0,L.getTpSlAttempt)(eW,t))return!1;let r=(0,L.beginTpSlAttempt)(eW,t,{kind:"cancel",targetOrderPda:e.orderPda,triggerPrice:(0,o.parseRawValue)(e.triggerPriceUsd),sizeUsd:(0,o.parseRawValue)(e.sizeUsd),closeBps:Math.round(1e4*(0,G.closeFractionOf)(e,et)),baselineOrderPdas:eN.flatMap(e=>e.orderPda?[e.orderPda]:[])});if(!r)return!1;e$.current=!0,e6(e.orderPda);try{let i="jupiter_native"===e.source?await x(e.orderPda):await f(e.orderPda,e.profileIndex);if((0,L.settleTpSlAttempt)(eW,t,r.attemptId,i?"submitted":"uncertain"),!i||eV.current!==eH)return!1;return eU===e.orderPda&&eO(void 0),p?.(),!0}catch(e){if((0,L.settleTpSlAttempt)(eW,t,r.attemptId,"uncertain"),eV.current!==eH)return!1;return I.toast.error((0,U.displayClientError)(e)),!1}finally{e$.current=!1,eV.current===eH&&e6(null)}},tF=async e=>{let t="tp"===e?tw:tj;!t||await tL(t)&&("tp"===e?(te(""),ts("")):(tr(""),ta("")))},tR=async()=>{let t,r,i;if(!j)return void I.toast.error(g("tpslWalletUnavailable"));if(e$.current)return;let s=(parseFloat(e7)||0)>0,n=(parseFloat(tt)||0)>0;if(!s&&!n)return void I.toast.error(g("errorEnterTpOrSlPrice"));if(!Number.isFinite(et)||et<=0||!Number.isFinite(tC)||tC<=0)return void I.toast.error(g("errorSetAmountToClose"));if(s&&!eX.current.has("tp")&&!(0,L.getTpSlAttempt)(eW,"tp")&&t_>tM("tp"))return void I.toast.error(g("errorTakeProfitOverCovers"));if(n&&!eX.current.has("sl")&&!(0,L.getTpSlAttempt)(eW,"sl")&&t_>tM("sl"))return void I.toast.error(g("errorStopLossOverCovers"));try{t=(0,d.getCloseOrderTargetFromLifecycle)(e)}catch(t){console.error("[position-exit] Could not resolve close target",{buildId:"a99c7ad",asset:e.asset,underwriter:e.underwriter,profileIndex:e.profileIndex},t),(0,O.reportTradeError)(t,{stage:"close_target",action:"tpsl",wallet:e.wallet,positionPda:e.positionPda,asset:e.asset,underwriter:e.underwriter,profileIndex:e.profileIndex}),I.toast.error((0,U.displayClientError)(t));return}let a=t.marketMint??(0,d.getMarketMintFromAsset)(e.asset,e.underwriter);if(!a)return void I.toast.error(g("errorMarketDataUnavailable"));e$.current=!0,ez(!0);let l=e.tpslOrders?.length??0,o=[];try{let e=[];for(let{leg:l,intent:d,submit:c}of(!s||eX.current.has("tp")||(0,L.getTpSlAttempt)(eW,"tp")||e.push({leg:"tp",...tA("tp",tw,t,a)}),!n||eX.current.has("sl")||(0,L.getTpSlAttempt)(eW,"sl")||e.push({leg:"sl",...tA("sl",tj,t,a)}),e)){if(eV.current!==eH)break;let e=(0,L.beginTpSlAttempt)(eW,l,d);if(!e)break;r=l,i=e.attemptId;let t=await c();if(o.push({leg:l,...t}),t.ok?(eX.current.add(l),(0,L.settleTpSlAttempt)(eW,l,e.attemptId,"submitted",t.signature??void 0)):!0===W()?(0,L.rejectTpSlAttempt)(eW,l,e.attemptId):(0,L.settleTpSlAttempt)(eW,l,e.attemptId,"uncertain"),r=void 0,i=void 0,!t.ok)break}}catch(s){if(s instanceof el)return;r&&i&&(0,L.settleTpSlAttempt)(eW,r,i,"uncertain"),console.error("[position-exit] TP/SL submission interrupted",{buildId:"a99c7ad",asset:e.asset,underwriter:t.underwriter,profileIndex:t.profileIndex},s),(0,O.reportTradeError)(s,{stage:"submission",action:"tpsl",wallet:e.wallet,positionPda:e.positionPda,asset:e.asset,marketMint:t.marketMint,underwriter:t.underwriter,profileIndex:t.profileIndex,sunriseSeat:t.sunriseSeat}),eV.current===eH&&I.toast.error((0,U.displayClientError)(s))}finally{if(eV.current!==eH){e$.current=!1;return}eJ([...eX.current]);let e=o.filter(e=>e.ok);if(e.length){let t=(!s||eX.current.has("tp"))&&(!n||eX.current.has("sl"));I.toast.success(t&&s&&n?g("toastTpSlSubmitted"):"tp"===e[0].leg?g("toastTakeProfitSubmitted"):g("toastStopLossSubmitted")),e.some(e=>e.created)&&m?.(l),t&&h()}(e.length||(0,L.getTpSlAttempt)(eW,"tp")||(0,L.getTpSlAttempt)(eW,"sl"))&&p?.(),e$.current=!1,ez(!1)}},tD=t=>{let r="tp"===t?e7:tt,i="tp"===t?ti:tn,s="tp"===t?tl:td,n="tp"===t?to:tc,a="tp"===t?tu:tp,l="tp"===t?th:tm,d="tp"===t?"TP":"SL",c=""!==r&&!tT(t),u="tp"===t?tw:tj,h=u?.orderType.startsWith("private_")??!1,m=!!u?.orderPda&&e4===u.orderPda,f=eG(t);return(0,v.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,v.jsxs)("fieldset",{disabled:eB||!!f||eQ.includes(t),className:"flex min-w-0 flex-col gap-2 border-0 p-0",children:[(0,v.jsxs)("div",{className:"flex items-center justify-between",children:[(0,v.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,v.jsx)("span",{children:g("legTriggerPriceBy",{leg:d})}),(0,v.jsxs)(X.DropdownMenu,{children:[(0,v.jsx)(X.DropdownMenuTrigger,{asChild:!0,children:(0,v.jsxs)("button",{className:"flex items-center gap-0.5 text-foreground border-b border-dashed border-border-strong hover:border-border-strong transition-colors",children:[g(eo[s]),(0,v.jsx)(F.ChevronDown,{className:"w-3 h-3"})]})}),(0,v.jsx)(X.DropdownMenuContent,{align:"start",className:"min-w-[110px]",children:["price","pct","pnl"].map(e=>(0,v.jsx)(X.DropdownMenuItem,{onClick:()=>{n(e),"tp"===t?(te(""),ts("")):(tr(""),ta(""))},className:"text-xs text-foreground hover:bg-surface-interactive",children:g(eo[e])},e))})]})]}),u&&(0,v.jsxs)("div",{className:"flex items-center gap-2",children:[h&&(0,v.jsx)("span",{className:"rounded bg-purple-500/15 px-1.5 py-0.5 text-[10px] font-medium text-purple-300",children:g("privateOrderBadge")}),tE(u)&&(0,v.jsxs)("button",{onClick:()=>tF(t),disabled:m||eB,title:g("removeLeg",{leg:d}),className:"flex items-center gap-1 text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50",children:[m?(0,v.jsx)(D.Spinner,{className:"size-3"}):(0,v.jsx)(R.Trash2,{className:"h-3.5 w-3.5"}),g("removeAction")]})]})]}),(0,v.jsxs)("div",{className:"flex items-stretch gap-2",children:[(0,v.jsxs)("div",{className:(0,B.cn)("flex-[2] flex items-center bg-surface-raised border rounded-lg px-3 py-2",c?"border-destructive/60":"border-border-strong"),children:[(0,v.jsx)(Q.Input,{type:"text",inputMode:"decimal",value:r,onChange:e=>((e,t)=>{if(e$.current||eX.current.has(e)||(0,L.getTpSlAttempt)(eW,e))return;let r=(0,$.sanitizeDecimalInput)(t,N);if("tp"===e?te(r):tr(r),"price"!==("tp"===e?tl:td))return;let i=tk("tp"===e?tu:tp),s=parseFloat(r);if(i>0&&s>0){let t=("tp"===e===ee?(s-i)/i:(i-s)/i)*100;"tp"===e?ts(t.toFixed(2)):ta(t.toFixed(2))}else"tp"===e?ts(""):ta("")})(t,e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"price"===s?"0.00":"pct"===s?g("placeholderPctFromEntry"):"tp"===t?g("placeholderPctGain"):g("placeholderPctLoss"),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,v.jsxs)(X.DropdownMenu,{children:[(0,v.jsx)(X.DropdownMenuTrigger,{asChild:!0,children:(0,v.jsxs)("button",{className:"flex items-center gap-0.5 text-xs text-secondary-foreground hover:text-foreground transition-colors whitespace-nowrap ml-2",children:["last"===a?g("priceRefLast"):g("priceRefMark"),(0,v.jsx)(F.ChevronDown,{className:"w-3 h-3"})]})}),(0,v.jsxs)(X.DropdownMenuContent,{align:"end",className:"min-w-[80px]",children:[(0,v.jsx)(X.DropdownMenuItem,{onClick:()=>l("last"),className:"text-xs text-foreground hover:bg-surface-interactive",children:g("priceRefLast")}),(0,v.jsx)(X.DropdownMenuItem,{onClick:()=>l("mark"),className:"text-xs text-foreground hover:bg-surface-interactive",children:g("priceRefMark")})]})]})]}),(0,v.jsxs)("div",{className:(0,B.cn)("flex-1 flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2","price"!==s&&"opacity-40"),children:[(0,v.jsx)(Q.Input,{type:"text",inputMode:"decimal",value:i,disabled:"price"!==s,onChange:e=>((e,t)=>{if(e$.current||eX.current.has(e)||(0,L.getTpSlAttempt)(eW,e))return;let r=(0,$.sanitizeSignedDecimalInput)(t,N);"tp"===e?ts(r):ta(r);let i=tk("tp"===e?tu:tp),s=parseFloat(r);if(i>0&&!isNaN(s)){let t=parseFloat((i*("tp"===e===ee?1+s/100:1-s/100)).toPrecision(12));"tp"===e?te(t>0?t.toString():""):tr(t>0?t.toString():"")}})(t,e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:g("placeholderChange"),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,v.jsx)("span",{className:"text-xs text-label-muted ml-1",children:"%"})]})]}),"sl"===t&&tP()&&(0,v.jsx)("span",{className:"text-3xs text-destructive",children:(0,_.tradingValidationError)(tP())}),(parseFloat("tp"===t?e7:tt)||0)>0&&!eX.current.has(t)&&t_>tM(t)&&(0,v.jsx)("span",{className:"text-3xs text-destructive",children:0>=tM(t)?g("legFullyCovered",{leg:d}):g("legUncoveredPct",{pct:tM(t),leg:d})}),eG(t)?(0,v.jsx)("p",{className:"text-xs text-muted-foreground",children:g("tpslLegPending",{leg:d})}):(t=>{let r=tN(t);if(r<=0||!tT(t))return(0,v.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:g.rich("triggerExplainer",{ref:("tp"===t?tu:tp)==="last"?g("priceRefLast"):g("priceRefMark"),price:"-- USD",pnl:"-- USD",strong:e=>(0,v.jsx)("span",{className:"font-medium text-foreground",children:e}),pnlStyle:e=>(0,v.jsx)("span",{className:"font-medium text-foreground",children:e})})});let i=(0,o.estimateClosePnl)(e,{execPrice:r,closeFraction:tC}),s=(0,o.estimateClosePnl)(e,{execPrice:r,closeFraction:1}),n=i?.total??null,a=s?(0,o.wholeTradeNetPnl)(e,s,ev):n,l=tC<1,d=(ew||l)&&null!==a&&null!==n&&Math.abs(a-n)>=.01,c=(0,o.parseRawValue)(e.borrowFeeOwed)*tC,u=(0,o.parseRawValue)(e.closeFeeOwed)*tC,h=(0,o.parseRawValue)(e.swapFeeOwed)*tC,p=ej*tC,m=c+u+h+p,f=tf[t],x=("tp"===t?tu:tp)==="last"?g("priceRefLast"):g("priceRefMark"),b=(0,o.isPhoenixUnderwriter)(e.underwriter)?K?.snapshots[(0,es.canonicalToPhoenixSymbol)(e.asset)]:void 0,y=q(e.asset,e.underwriter,t,o.QUOTE_FORMULA_VERSION),w=et*tC,j=function(e){let{isLong:t,notionalUsd:r,depth:i,band:s}=e,n=null,a=0;if(i&&i.mid>0&&r>0){n=function(e,t,r){if(!e.length||t<=0||r<=0)return null;let i=[...e].sort((e,r)=>
2Math.abs(e.price-t)-Math.abs(r.price-t)),s=r,n=0,a=0;for(let e of i){if(e.price<=0||e.sizeBase<=0)continue;let t=Math.min(s,e.price*e.sizeBase);if(n+=t*e.price,a+=t,(s-=t)<=0)break}return a<=0?null:{bps:Math.abs(n/a-t)/t*1e4,exceeded:s>0}}((t?i.bids:i.asks)??[],i.mid,r);let e=i.sigmaBpsPerSqrtSec;n&&e&&e>0&&(a=e*Math.sqrt(3))}let l=n?n.bps+a:null,o=s?Math.abs(s.adverseBps):null;return null===l&&null===o?null:null!==o&&(null===l||o>l)?{bps:o,impactBps:o,latencyBps:0,source:"band",exceedsBook:!1,bookBps:l,bandBps:o}:{bps:l,impactBps:n.bps,latencyBps:a,source:"book",exceedsBook:n.exceeded,bookBps:l,bandBps:o}}({isLong:ee,notionalUsd:w,depth:b,band:y}),S=null===a?null:function(e,t,r){if(!r||r<=0||t<=0)return null;let i=e-t*r/1e4;return{low:Math.min(i,e),high:Math.max(i,e)}}(a,w,j?.bps),N=e=>`${e>=0?"+":""}${k.number(e)}`;return(0,v.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,v.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:g.rich("triggerExplainer",{ref:x,price:`$${k.number(r)} USD`,pnl:null!==a?`${a>=0?"+":""}${k.number(a)} USD`:"-- USD",strong:e=>(0,v.jsx)("span",{className:"font-medium text-foreground",children:e}),pnlStyle:e=>(0,v.jsx)("span",{className:(0,B.cn)("font-medium",(0,z.pnlColor)(a)),children:e})})}),i&&(0,v.jsxs)("div",{className:"bg-surface-raised border border-border-strong rounded-lg overflow-hidden",children:[(0,v.jsxs)("div",{role:"button",tabIndex:0,onClick:()=>tx(e=>({...e,[t]:!e[t]})),className:"flex items-center justify-between text-xs px-3 py-1.5 cursor-pointer select-none",children:[(0,v.jsxs)("span",{className:"flex items-center gap-1 text-label-muted",children:[g("netPnl"),(0,v.jsx)(F.ChevronDown,{className:(0,B.cn)("w-3 h-3 transition-transform",f&&"rotate-180")})]}),(0,v.jsxs)("div",{className:"flex flex-col items-end",children:[(0,v.jsx)("span",{className:(0,B.cn)("font-mono tabular-nums",(0,z.pnlColor)(a)),children:null===a?"—":S?`${N(S.low)} … ${N(S.high)} USD`:`${N(a)} USD`}),d&&null!==n&&(0,v.jsx)("span",{className:(0,B.cn)("text-[10px] mt-0.5 font-mono tabular-nums",(0,z.pnlColorDim)(n)),children:g("legPnlAmount",{amount:`${n>=0?"+":""}${k.number(n)}`})}),S&&j&&(0,v.jsx)("span",{className:"text-[10px] mt-0.5 text-label-muted",children:"book"===j.source?g("slippageBookNote"):g("slippageBandNote",{count:y?.sampleCount??0})})]})]}),f&&(0,v.jsxs)("div",{className:"px-3 pb-2 space-y-1 text-xs font-mono border-t border-border-strong",children:[(0,v.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1",children:g("pnlBreakdownLabel")}),(0,v.jsx)(eh,{label:g("pricePnlLabel"),v:i.pricePnl}),(0,v.jsx)(eh,{label:g("afterFeesPaidLabel"),v:i.afterFeesPaid}),(0,v.jsx)(eh,{label:g("afterFeesOwedLabel"),v:i.afterFeesOwed}),null!==ev&&s&&(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1 border-t border-border-strong",children:g("costBasisLabel")}),(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:g("netDepositedLabel")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:["$",k.number(ev)]})]}),(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:g("valueAtTriggerLabel")}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:["$",k.number((0,o.getEstimatedReturn)(em,s))]})]})]}),m>=.01&&(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1 border-t border-border-strong",children:g("feeBreakdownLabel")}),p>=.005&&(0,v.jsx)(ep,{label:g("entryFeesLabel"),v:p}),c>=.005&&(0,v.jsx)(ep,{label:g("borrowFeeLabel"),v:c}),u>=.005&&(0,v.jsx)(ep,{label:g("closeFeeLabel"),v:u}),h>=.005&&(0,v.jsx)(ep,{label:g("platformFeeLabel"),v:h}),(0,v.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border-strong pt-1",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:g("totalFeesLabel")}),(0,v.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",k.number(m)]})]})]})]})]})]})})(t)]}),f&&(0,v.jsx)(V.TpSlAttemptRecovery,{scope:eW,leg:t,attempt:f,wallet:e.wallet,market:e.asset,onRecovered:()=>{eX.current.delete(t),eJ([...eX.current]),"tp"===t?(te(""),ts(""),to("price")):(tr(""),ta(""),tc("price")),p?.()}},f.attemptId)]})};return(0,v.jsxs)(H.TpSlModalShell,{title:"TP/SL",lifecycle:e,symbol
2:i,iconSrc:n,leverage:a,livePrices:u,tab:eD,onTabChange:e=>{e$.current||eX.current.size||(0,L.getTpSlAttempt)(eW,"tp")||(0,L.getTpSlAttempt)(eW,"sl")||(eI(e),eO(void 0),tS(e,void 0))},tabsDisabled:eB||eZ||e0,confirmLabel:S("confirm"),onCancel:h,onConfirm:tR,submitting:eB,disabled:!j||!!e4||!(Number(e7)>0&&!eq&&!eQ.includes("tp")||Number(tt)>0&&!eK&&!eQ.includes("sl")),footerExtra:j?e0||eZ?(0,v.jsxs)("p",{role:"status",className:"text-xs text-muted-foreground",children:[g(e1?"tpslCancelReviewed":e2?"tpslCancelPending":e5?"tpslSubmissionUncertain":"tpslPartialSubmission"),e3&&(0,v.jsxs)(v.Fragment,{children:[" ",g("tpslGuardMemoryOnly")]})]}):void 0:(0,v.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:g("tpslWalletUnavailable")}),children:["partial"===eD&&!eZ&&!e0&&(0,v.jsx)(Y,{orders:eC,positionSizeUsd:et,selectedPda:eU,cancelingPda:e4,canCancel:tE,onSelect:e=>{e$.current||eX.current.size||(0,L.getTpSlAttempt)(eW,"tp")||(0,L.getTpSlAttempt)(eW,"sl")||(eO(e?.orderPda),tS("partial",e))},onCancel:tL}),tD("tp"),tD("sl"),"partial"===eD&&(0,v.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,v.jsx)("span",{className:"text-xs text-muted-foreground",children:g("amountLabel")}),(0,v.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2",children:[(0,v.jsx)(Q.Input,{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:tv,disabled:eB||eZ||e0,onChange:e=>(e=>{if(e$.current||eX.current.size||(0,L.getTpSlAttempt)(eW,"tp")||(0,L.getTpSlAttempt)(eW,"sl"))return;let t=(0,$.sanitizeDecimalInput)(e,N);ty(t),e9(!0);let r=parseFloat(t)||0;et>0&&tb(Math.max(0,Math.min(100,Math.round(r/et*100))))})(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),(0,v.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USDC"})]}),(0,v.jsx)("input",{type:"range",...en.THUMB_ONLY_SLIDER,min:1,max:100,value:tg,disabled:eB||eZ||e0,onChange:e=>{var t;return t=parseInt(e.target.value),void(!(e$.current||eX.current.size||(0,L.getTpSlAttempt)(eW,"tp")||(0,L.getTpSlAttempt)(eW,"sl"))&&(tb(t),e9(!0),ty(et>0?er(t):"")))},className:(0,B.cn)(en.RANGE_SLIDER_CLASSES,"w-full [&::-webkit-slider-thumb]:bg-white")}),(0,v.jsxs)("div",{className:"flex items-center justify-between text-xs text-label-muted",children:[(0,v.jsx)("span",{className:"text-foreground font-medium",children:g("closingPercent",{percent:tg})}),(0,v.jsx)("span",{children:g("ofAmountUsdc",{amount:k.number(et)})})]})]})]})}function eh({label:e,v:t}){let r=(0,w.useFormatters)();return(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:e}),(0,v.jsxs)("span",{className:"font-mono tabular-nums",children:[t>=0?"+":"",r.number(t)]})]})}function ep({label:e,v:t}){let r=(0,w.useFormatters)();return(0,v.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,v.jsx)("span",{className:"text-muted-foreground",children:e}),(0,v.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",r.number(t)]})]})}},670374,e=>{"use strict";e.s(["DCA_ORDER_TYPES",()=>x,"PROFILE_TAG_COLORS",()=>g,"USDC_MINT",()=>m,"WSOL_MINT",()=>f,"buildDcaGroupLabels",()=>L,"calculateLivePnl",()=>T,"closedAvgEntryPrice",()=>F,"closedAvgExitPrice",()=>R,"displayLiquidationPriceForLifecycle",()=>C,"exportLifecyclesToCsv",()=>U,"getCloseOrderTargetFromLifecycle",()=>_,"getCloseOrderTargetFromOrder",()=>A,"getMarketMintFromAsset",()=>E,"getProfileColorClass",()=>b,"getTokenInfo",()=>y,"groupDcaActions",()=>D,"openCloseFeeExImpact",()=>w,"packCapitalBase",()=>j,"packIssueBasisUsd",()=>P,"packPnlVsIssueBasisUsd",()=>N,"packPnlVsPriceUsd",()=>k,"venueLiquidationPriceForLifecycle",()=>M]);var t=e.i(915402),r=e.i(508947),i=e.i(828047),s=e.i(799227),n=e.i(653982);e.i(889723);var a=e.i(49332),l=e.i(465217),o=e.i(643459),d=e.i(622463),c=e.i(362221),u=e.i(722732),h=e.i(613448),p=e.i(26826);let m=new s.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),f=new s.PublicKey("So11111111111111111111111111111111111111112"),x=new Set(["dca","dca_close","dca_time_close","dca_ratchet_close","dca_time","dca_ratchet"]),g=["bg-surface-raised text-secondary-foreground","bg-surface-raised text-secondary-foreground","bg-surface-raised text-secondary-foreground","bg-surface-raised text-secondary-foreground","bg-surface-raised text-secondary-foreground","bg-surface-raised text-secondary-foreground"];function b(e){return null==e?"":"bg-surface-raised text-secondary-foreground"}let v={SOL:"So11111111111111111111111111111111111111112",ETH:"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",BTC:"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh"};function y(e){if(a.JUPITER_MARKETS[e])return a.JUPITER_MARKETS[e];let t=v[e];if(t&&a.JUPITER_MARKETS[t])return a.JUPITER_MARKETS[t];let r=(0,i.sunriseSymbolFromAssetMint)(e);
2if(r)return{symbol:r,name:r,image:(0,l.getFlashTokenImage)(r)};let s=(0,o.resolveMintSymbol)(e);if(s)return{symbol:s,name:s,image:(0,l.getFlashTokenImage)(s)};if((0,o.mintForSymbol)(e)){let t=e.toUpperCase();return{symbol:t,name:t,image:(0,l.getFlashTokenImage)(t)}}let n=(0,d.getGlobalPhoenixRegistry)();if(n){let t=n.getSymbolByOrderbook(e);if(t)return{symbol:t,name:t,image:(0,l.getFlashTokenImage)(t)}}let p=(0,u.getGlobalGmTradeRegistry)();if(p){let t=p.getSymbolByIndexMint(e);if(t)return{symbol:t,name:t,image:(0,l.getFlashTokenImage)(t)}}let m=(0,h.pairsMarketByMint)(e)??(0,h.pairsMarketBySymbol)(e);if(m)return{symbol:m.symbol,name:(0,h.pairsDisplayName)(m.symbol),image:(0,l.getFlashTokenImage)(m.symbol)};let f=e.toUpperCase(),x=(0,c.phoenixToCanonicalSymbol)(f);if(x!==f)return{symbol:x,name:x,image:(0,l.getFlashTokenImage)(x)};let g=f.match(/^(.+?)TOUCH\d*$/)?.[1];return g?{symbol:e,name:e,image:(0,l.getFlashTokenImage)(g)}:{symbol:e,name:e,image:(0,l.getFlashTokenImage)(e)}}function w(e,t){return(0,p.parseRawValue)(e)-(0,p.parseRawValue)(t)}function j(e,r){return(0,t.packCapitalUsd)((0,p.parseRawValue)(e.stakeUsd),S(e),r)}function S(e){return(P(e)??(0,p.parseRawValue)(e.stakeUsd))+(0,p.parseRawValue)(e.pnlOffsetUsd)}function k(e,r){return(0,t.packReturnUsd)(r,S(e),(0,p.parseRawValue)(e.stakeUsd))}function N(e,t){return t+(0,p.parseRawValue)(e.pnlOffsetUsd)}function P(e){if(!e)return null;if(null!=e.storyCollateralUsd)return(0,p.parseRawValue)(e.storyCollateralUsd);let t=(0,p.parseRawValue)(e.ripFeeUsd);return t>0?(0,p.parseRawValue)(e.stakeUsd)-t:null}function T(e,t){let r=(0,p.parseRawValue)(e.entryPrice),i=(0,p.parseRawValue)(e.sizeUsd),s=(0,p.feesPaidForRemainingSize)(e),n=(0,p.parseRawValue)(e.feesOwed),a=(0,p.parseRawValue)(e.collateralUsd),l=(0,p.sumRealizedPnlFromActions)(e),o="long"===e.side;if(!r||!i)return{pnlUsd:0,pnlPercent:0,pricePnl:0,feesPaid:0,feesOwed:0,realizedPnl:0,unrealizedPnl:0,packPnlUsd:null,packPnlPercent:null};let d=(0,p.calculatePnl)({size:i,entryPrice:r,execPrice:t,isLong:o,feesPaid:s,feesOwed:n});if(!d)return{pnlUsd:0,pnlPercent:0,pricePnl:0,feesPaid:0,feesOwed:0,realizedPnl:0,unrealizedPnl:0,packPnlUsd:null,packPnlPercent:null};let c=(0,p.netCapitalForDisplay)(e),u=(0,p.wholeTradeNetPnl)(e,d,c),h=d.pricePnl-n,m=(0,p.getGrossDepositedCapital)(e)??a,f=m>0?u/m*100:0,x=e.packPrize??null,g=null===x?null:k(x,u),b=null===x?0:j(x,m);return{pnlUsd:u,pnlPercent:f,pricePnl:d.pricePnl,feesPaid:s,feesOwed:n,realizedPnl:l,unrealizedPnl:h,packPnlUsd:g,packPnlPercent:null===g||b<=0?null:g/b*100}}function C(e){return e.ourLiquidationPriceUsd?(0,p.quotableLiquidationPrice)(e.ourLiquidationPriceUsd):(0,p.isPhoenixUnderwriter)(e.underwriter)&&e.partialLiquidationPriceUsd?(0,p.quotableLiquidationPrice)(e.partialLiquidationPriceUsd):(0,p.quotableLiquidationPrice)(e.liquidationPrice)}function M(e){return(0,p.isPhoenixUnderwriter)(e.underwriter)&&e.partialLiquidationPriceUsd?(0,p.quotableLiquidationPrice)(e.partialLiquidationPriceUsd):(0,p.quotableLiquidationPrice)(e.liquidationPrice)}function _(e,t){if(void 0===e.profileIndex||null===e.profileIndex)throw Error("This position was opened before profiles existed and can't host advanced exit orders — close it manually instead.");let i=e.underwriter??"jupiter",s=E(e.asset,i)??t?.marketMintFallback;if(!s)throw Error(`Couldn't resolve a market for ${e.asset}.`);return{marketMint:s,side:e.side,underwriter:i,profileIndex:e.profileIndex,..."sunrise"===i?{sunriseSeat:(0,r.sunriseSeatFromPosition)(e.sunriseMarginSeat)}:{}}}function A(e){if(!e.marketMint||!e.side)throw Error("Order is missing market or side — refresh and try again.");if(void 0===e.profileIndex||null===e.profileIndex)throw Error("Order is missing a profile — refresh and try again.");return{marketMint:e.marketMint,side:e.side,underwriter:e.underwriter??"jupiter",profileIndex:e.profileIndex,parentOrderPda:e.orderPda}}function E(e,t){let r=e.toUpperCase();switch(r){case"SOL":return n.SOL_MINT.toBase58();case"SOLBTC":return(0,h.pairsMintBySymbol)(r);case"BTC":return n.BTC_MINT.toBase58();case"ETH":return n.ETH_MINT.toBase58();
2default:{if(t){let i=function(e,t,r){let i=r.toLowerCase();if("sunrise"===i||"7"===i)return t;if("gmtrade"===i||"3"===i){let t=(0,u.getGlobalGmTradeRegistry)()?.getMarketBySymbol(e);return t?t.indexTokenMint.toBase58():null}if("phoenix"===i||"2"===i){let t=(0,d.resolvePhoenixSymbol)(e),r=t?(0,d.getGlobalPhoenixRegistry)()?.getMarketBySymbol(t):null;return r?r.orderbook.toBase58():null}return"pairs"===i||"5"===i?(0,h.pairsMintBySymbol)(t):null}(e,r,t);if(i)return i}let i=(0,o.mintForSymbol)(r);if(i)return i;let s=(0,d.getGlobalPhoenixRegistry)();if(s){let t=(0,d.resolvePhoenixSymbol)(e);if(t){let e=s.getMarketBySymbol(t);if(e)return e.orderbook.toBase58()}}let n=(0,u.getGlobalGmTradeRegistry)();if(n){let t=n.getMarketBySymbol(e);if(t)return t.indexTokenMint.toBase58()}return(0,h.pairsMintBySymbol)(r)}}}function L(e){let t=new Map,r=e.filter(e=>null!==e.orderType&&x.has(e.orderType)&&null!==e.orderCreatedAt),i=[...new Set(r.map(e=>e.orderCreatedAt))];if(i.length<=1)return t;i.sort((e,t)=>e-t);let s=new Map(i.map((e,t)=>[e,t+1]));for(let e of r)t.set(e.id,`DCA-${s.get(e.orderCreatedAt)}`);return t}function F(e){let t=e.actions?.filter(e=>"increase"===e.actionType&&e.entryPrice&&e.sizeDelta);if(!t||0===t.length)return e.entryPrice??null;let r=0,i=0;for(let e of t){let t=Math.abs((0,p.parseRawValue)(e.sizeDelta)),s=(0,p.parseRawValue)(e.entryPrice);t>0&&s>0&&(r+=t,i+=t*s)}return r>0?(i/r).toString():e.entryPrice??null}function R(e){let t=e.actions?.filter(e=>"decrease"===e.actionType&&e.entryPrice&&e.sizeDelta);if(!t||0===t.length)return e.markPrice??null;let r=0,i=0;for(let e of t){let t=Math.abs((0,p.parseRawValue)(e.sizeDelta)),s=(0,p.parseRawValue)(e.entryPrice);t>0&&s>0&&(r+=t,i+=t*s)}return r>0?(i/r).toString():e.markPrice??null}function D(e){let t=new Map,r=[];for(let i of e)if(null!==i.action.orderType&&x.has(i.action.orderType)&&null!==i.action.orderCreatedAt){let e=`${i.asset}_${i.side}_${i.action.orderCreatedAt}`;t.has(e)||t.set(e,[]),t.get(e).push(i)}else r.push({type:"action",...i});let i=[...r];for(let[e,r]of t){if(r.length<2){i.push({type:"action",...r[0]});continue}let t=0,s=0,n=0,a=0,l=0,o=0,d=0;for(let e of r){let r=(0,p.parseRawValue)(e.action.entryPrice),i=Math.abs((0,p.parseRawValue)(e.action.sizeDelta));t+=r*i,s+=i,n+=(0,p.parseRawValue)(e.action.sizeDelta),a+=(0,p.parseRawValue)(e.action.collateralDeposited),l+=(0,p.parseRawValue)(e.action.userReceived),o+=(0,p.computeActionFees)(e.action);let c=e.action.tx1Timestamp;c>d&&(d=c)}let c=r[0].action;i.push({type:"dca_group",group:{type:"dca_group",groupKey:e,actions:r,asset:r[0].asset,side:r[0].side,mostRecentTimestamp:d,avgEntryPrice:s>0?t/s:0,totalSizeDelta:n,totalCollateralDeposited:a,totalUserReceived:l,totalFees:o,numLegs:r.length,dcaNumLegs:c.orderDcaNumLegs,dcaStartPrice:c.orderDcaStartPrice,dcaEndPrice:c.orderDcaEndPrice,orderCreatedAt:c.orderCreatedAt}})}return i.sort((e,t)=>{let r="dca_group"===e.type?e.group.mostRecentTimestamp:e.action.tx1Timestamp;return("dca_group"===t.type?t.group.mostRecentTimestamp:t.action.tx1Timestamp)-r}),i}function I(e){return(0,p.parseRawValue)(e).toFixed(2)}function U(e,t){var r,i;let s,n,a,l=e.map(e=>{let r,i=(r=new Date(1e3*(e.closedAt??e.lastActionAt)),`${r.getMonth()+1}/${r.getDate()}/${r.getFullYear()} - ${r.getHours().toString().padStart(2,"0")}:${r.getMinutes().toString().padStart(2,"0")}:${r.getSeconds().toString().padStart(2,"0")}`),s=t?.get(e.profileIndex??0),n="venue_direct"===e.ownership?"Phoenix Direct":s??`Profile ${(e.profileIndex??0)+1}`,a="open"===e.status?"":I(e.markPrice),l=0;return e.fees&&(l=(0,p.parseRawValue)(e.fees.platformFee)+(0,p.parseRawValue)(e.fees.swapFee)+(0,p.parseRawValue)(e.fees.slippage)+(0,p.parseRawValue)(e.fees.jupiterFee)+(0,p.parseRawValue)(e.fees.interest)+(0,p.parseRawValue)(e.fees.proOrderFee)),[i,e.asset,e.side,n.includes(",")||n.includes('"')||n.includes("\n")?`"${n.replace(/"/g,'""')}"`:n,I(e.maxSizeUsd),I(e.maxCollateralUsd),I(e.entryPrice),a,I(e.pnlUsd),null==e.pnlPercent?"":(0,p.parseRawValue)(e.pnlPercent).toFixed(2),l.toFixed(2),e.status].join(",")}),o=new Date().toISOString().slice(0,10);r=["Time,Asset,Side,Source,Max Size (USD),Max Collateral (USD),Avg Entry,Avg Exit,PnL (USD),PnL (%),Fees (USD),Status",...l].join("\n"),i=`imperial-positions-${o}.csv`,s=new Blob([r],{type:"text/csv;charset=utf-8;"}),n=URL.createObjectURL(s),(a=document.createElement("a")).href=n,a.download=i,a.click(),URL.revokeObjectURL(n)}}
2,752717,172581,328188,91525,631193,e=>{"use strict";e.s(["canPlaceLimitClose",()=>S,"useLimitClose",()=>k],91525),e.s(["useCloseAmount",()=>m],172581),e.s(["CloseFeeBreakdown",()=>u],752717);var t=e.i(394390),r=e.i(183023),i=e.i(1169),s=e.i(942553),n=e.i(153517),a=e.i(406470),l=e.i(299959),o=e.i(670374),d=e.i(26826);let c=(e,t)=>`$${(0,a.formatNumber)(e,{minimumFractionDigits:2,maximumFractionDigits:2},t)}`;function u({lifecycle:e,sizePercent:a,compact:o}){let h=(0,s.useTranslations)("trading"),p=(0,l.useFormatters)(),[m,f]=(0,r.useState)(!1),x=a/100,g=(0,d.parseRawValue)(e.borrowFeeOwed)*x,b=(0,d.parseRawValue)(e.closeFeeOwed)*x,v=(0,d.parseRawValue)(e.swapFeeOwed)*x,y=(0,d.feesPaidForRemainingSize)(e)*x,w=(0,d.parseRawValue)(e.sizeUsd)*x,j=b+v+g;if(j+y<.01)return null;let S=o?"text-xs":"text-sm",k=e=>w>0?`${p.fixed(e/w*1e4,1)} bps`:null,N=[];return b>=.005&&N.push({labelKey:"closeFee",value:b}),v>=.005&&N.push({labelKey:"imperialFee",value:v,bps:!0}),g>=.005&&N.push({labelKey:"accruedBorrow",value:g}),(0,t.jsxs)("div",{role:"button",tabIndex:0,onClick:e=>{e.stopPropagation(),f(!m)},className:(0,n.cn)("select-none cursor-pointer touch-manipulation",S),children:[(0,t.jsxs)("div",{className:"flex items-center justify-between py-0.5",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1 text-label-muted",children:[h("dueOnClose"),(0,t.jsx)(i.ChevronDown,{className:(0,n.cn)("w-3 h-3 transition-transform",m&&"rotate-180")})]}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:[c(j,p.intlTag),k(j)&&(0,t.jsxs)("span",{className:"text-amber-400/60",children:[" / ",k(j)]})]})]}),m&&(0,t.jsxs)("div",{className:(0,n.cn)("ml-2 mt-1 space-y-2",S),children:[(0,t.jsx)("div",{className:"space-y-0.5",children:N.map(({labelKey:e,value:r,bps:i})=>(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:h(e)}),(0,t.jsxs)("span",{className:"text-muted-foreground font-mono tabular-nums",children:[c(r,p.intlTag),i&&k(r)&&(0,t.jsxs)("span",{className:"text-muted-foreground",children:[" / ",k(r)]})]})]},e))}),y>=.005&&(0,t.jsxs)("div",{className:"space-y-0.5",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:h("alreadyPaidNote")}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:h("entryFee")}),(0,t.jsx)("span",{className:"text-muted-foreground font-mono tabular-nums",children:c(y,p.intlTag)})]})]})]})]})}var h=e.i(821043);let p="sizeDisplayUnit";function m(e,t=100){let i=(0,l.useFormatters)(),s=(0,l.useDecimalSeparator)(),n=(0,d.parseRawValue)(e.sizeUsd),a=(0,d.parseRawValue)(e.sizeTokenAmount),o=a>0,[c,u]=(0,r.useState)(()=>"base"===localStorage.getItem(p)?"base":"usd"),f="base"===c&&o?"base":"usd",x=e=>"base"===e?a:n,g=(e,t)=>{let r=x(t);return r>0?i.number(r*e/100,{useGrouping:!1}):""},[b,v]=(0,r.useState)(t),[y,w]=(0,r.useState)(()=>t>0?g(t,f):"");return{sizePercent:b,amountInput:y,amountUnit:f,canToggleUnit:o,handleSizePercent:e=>{v(e),w(g(e,f))},handleAmountTyped:e=>{let t=(0,h.sanitizeDecimalInput)(e,s);w(t);let r=parseFloat(t)||0,i=x(f);i>0&&v(Math.max(0,Math.min(100,Math.round(r/i*100))))},toggleAmountUnit:()=>{let e="usd"===f?"base":"usd";u(e),localStorage.setItem(p,e),w(g(b,e))}}}var f=e.i(116082),x=e.i(936548),g=e.i(727322),b=e.i(905843);let v=["tp","private_tp"],y=["sl","private_sl"];function w(e,t){if("number"==typeof e.closeBps&&e.closeBps>0)return Math.min(1,e.closeBps/1e4);let r=parseFloat(e.sizeUsd||"0")||0;return t<=0||r<=0?0:Math.min(1,r/t)}function j(e){let{orders:t,leg:r,positionSizeUsd:i,targetPda:s}=e;if(i<=0)return 100;let n="tp"===r?v:y;return Math.max(0,Math.min(100,Math.round(100-100*t.filter(e=>n.includes(e.orderType)&&!(s&&e.orderPda===s)).reduce((e,t)=>e+w(t,i),0))))}function S(e){return!("venue_direct"===e.ownership&&(0,d.isPhoenixUnderwriter)(e.underwriter))&&void 0!==e.profileIndex&&null!==e.profileIndex}function k(e,t){let i=(0,s.useTranslations)("positions"),n=(0,l.useDecimalSeparator)(),{createTriggerOrder:a}=(0,g.useTradeActions)(),[c,u]=(0,r.useState)("market"),[p,m]=(0,r.useState)(""),[v,y]=(0,r.useState)(!1),w="long"===e.side,S=(0,d.parseRawValue)(e.sizeUsd),k=parseFloat(p)||0,N=k>0,P=N&&t>0&&k!==t,T=k>t,C=w===T?"tp":"sl",M=j({orders:e.tpslOrders??[],leg:C,positionSizeUsd:S}),_="limit"===c&&P?k:t,A=e=>e<=0?i("setSize"):N?P?e>M?M<=0?i("limitCloseFullyCovered"):i("limitCloseUncoveredPct",{pct:M}):null:i("limitClosePriceAtMark"):i("limitCloseSetPrice"),E=async r=>{let s;if(null!==A(r))return!1;try{s=(0,o.getCloseOrderTargetFromLifecycle)(e)}catch(e){return f.toast.error((0,x.displayClientError)(e)),!1}let n=Math.max(1,Math.min(1e4,Math.round(100*r))),l=s.marketMint??(0,o.getMarketMintFromAsset)(e.asset),c=(0,d.buildQuoteSnapshot)(e,{leg:C,execPrice:k,closeFraction:n/1e4,closeBps:n,priceRef:"mark",inputMode:"price",markPrice:t,lastPrice:t,...l?{identity:{side:+!w,orderType:b.PassthroughOrderType.StopLimit,underwriter:(0,g.underwriterToNum)(s.underwriter),marketMint:l}}:{}});y(!0);try{let t=!!await a({positionPubkey:e.positionPda,...s,sizeUsd:n/1e4*S,triggerPrice:k,isTakeProfit:"tp"===C,positionSource:"imperial",closeBps:n,quote:c});return t&&f.toast.success(i("limitCloseSubmitted")),t}finally{y(!1)}};return{mode:c,setMode:u,priceInput:p,handlePriceTyped:e=>m((0,h.sanitizeDecimalInput)(e,n)),price:k,hasPrice:N,isValidPrice:P,movesUp:T,leg:C,remainingPct:M,execPrice:_,missingLabel:A,submitting:v,submit:E}}e.s(["SL_ORDER_TYPES",0,y,"TP_ORDER_TYPES",0,v,"closeFractionOf",0,w,"isEntirePositionOrder",0,function(e,t){return w(e,t)>=.995},"uncoveredPctFor",0,j],328188);let N="imperial-slippage-bps",P="imperial-slippage-bps-changed";function T(e){return window.addEventListener(P,e),window.addEventListener("storage",e),()=>{window.removeEventListener(P,e),window.removeEventListener("storage",e)}}function C(){let e=localStorage.getItem(N);if(e){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1&&t<=5e3)return t}return 100}function M(){return 100}e.s(["useSlippageBps",0,function(){return{slippageBps:(0,r.useSyncExternalStore)(T,C,M),setSlippageBps:e=>{let t=Math.max(1,Math.min(5e3,Math.round(e)));localStorage.setItem(N,t.toString()),window.dispatchEvent(new CustomEvent(P))}}}],631193)},466134,e=>{"use strict";e.s(["DepositWithdrawDialog",()=>_]);var t=e.i(394390),r=e.i(183023),i=e.i(942553),s=e.i(145314),n=e.i(803817),a=e.i(116082),l=e.i(695109),o=e.i(401382),d=e.i(967090),c=e.i(394802),u=e.i(623075),h=e.i(213076),p=e.i(153517),m=e.i(299959),f=e.i(872429),x=e.i(843276),g=e.i(673028),b=e.i(87602),v=e.i(987363),y=e.i(679758),w=e.i(894771),j=e.i(580873),S=e.i(100555),k=e.i(419636),N=e.i(987752),P=e.i(822371),T=e.i(657645),C=e.i(742503);let M={noProfile:"finishAccountBeforeDeposit",loanBlocksWithdraw:"withdrawBlockedByLoan",loanBlocksTransfer:"transferBlockedByLoan",jwtWithdraw:"mobileSessionCannotWithdraw",jwtTransfer:"mobileSessionCannotTransfer"};function _({open:e,onOpenChange:A,initialMode:E}){let L=(0,i.useTranslations)("wallet"),F=(0,i.useTranslations)("common"),R=(0,m.useFormatters)(),D=(0,C.useWithdrawSettlingText)(),{renameProfile:I}=(0,w.useProfile)(),{activeProfileIndex:U,activeProfilePda:O,activeProfile:B,profileLabel:z,createdProfiles:$,allProfileBalances:V,publicKey:H,mode:W,switchMode:q,amount:K,onAmountInput:G,destProfileIndex:Y,setDestProfileIndex:X,isProcessing:Q,armadaStep:J,walletBalance:Z,profileBalance:ee,maxAmount:et,settlingLine:er,amountNote:ei,fetchTokenBalance:es,lockedBattle:en,receiveOnlyDeposit:ea,notices:el,amountRef:eo,focusAmount:ed,handleMax:ec,handleSubmit:eu,submitDisabled:eh}=(0,S.useProfileFunding)({open:e,initialMode:E}),ep=(0,N.useOnboarding)(),em=(0,r.useRef)(!1),ef=(0,r.useRef)(null),ex=(0,r.useRef)(!1),eg=(0,k.useFundingEntry
2)(q,()=>{em.current=!0,ep.open({intent:"funding",ownerWallet:H?.toBase58()??null,returnFocus:ef.current}),A(!1)}),eb=H?.toBase58()??null,[ev,ey]=(0,r.useState)(()=>e?{wallet:eb}:null);e!==(null!==ev)&&ey(e?{wallet:eb}:null);let ew=e&&(E??"deposit")==="deposit"&&ev?.wallet===eb&&eg.needsSetup&&!eg.disabled;(0,r.useLayoutEffect)(()=>{if(!e){ex.current=!1,ef.current=null;return}ew&&!ex.current&&(ex.current=!0,ef.current??=document.activeElement instanceof HTMLElement?document.activeElement:null,eg.startFunding("deposit"))},[e,ew,eg]);let{excluded:ej,isUpdating:eS,handleExclusionsChange:ek,pendingGmEnable:eN,confirmGmEnable:eP,cancelGmEnable:eT}=(0,j.useVenueExclusionEditor)(),[eC,eM]=(0,r.useState)(!1),[e_,eA]=(0,r.useState)(""),eE=()=>{eM(!1),eA("")},eL=async()=>{if(e_.trim()&&null!==U)try{await I(U,e_.trim()),eM(!1),eA(""),a.toast.success(L("profileRenamed"))}catch(e){console.error("Failed to rename profile:",e),a.toast.error(L("profileRenameFailed"))}};if(ew)return null;if(!B){let r=(E??"deposit")==="deposit";return(0,t.jsx)(u.Dialog,{open:e,onOpenChange:A,children:(0,t.jsxs)(u.DialogContent,{className:"overflow-hidden shadow-xl sm:max-w-[420px]",onOpenAutoFocus:()=>{em.current=!1,ef.current=document.activeElement instanceof HTMLElement?document.activeElement:null},onCloseAutoFocus:e=>{em.current&&(e.preventDefault(),em.current=!1)},children:[(0,t.jsxs)("div",{className:"border-b px-5 py-4",children:[(0,t.jsx)("div",{className:"text-[11px] font-medium text-label-muted",children:L("profileFunds")}),(0,t.jsx)(u.DialogTitle,{className:"mt-1 text-base font-semibold text-foreground",children:L(r?"fundYourProfile":"selectProfileFirst")})]}),(0,t.jsx)("div",{className:"px-5 py-6 text-center",children:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:L(r?"depositSetupHint":"selectProfileFirstBody")})}),(0,t.jsx)(u.DialogFooter,{className:"border-t border-border px-5 pb-5 pt-4",children:(0,t.jsx)(h.Button,{onClick:()=>r?void eg.startFunding("deposit"):A(!1),disabled:r&&eg.disabled,className:"h-11 w-full rounded-md bg-primary text-sm font-medium text-primary-foreground hover:bg-primary/90",children:r?L(eg.pending?"creating":eg.disabled?"loadingEllipsis":"deposit"):F("close")})})]})})}return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(x.GmTradeWarningDialog,{open:null!==eN,onConfirm:()=>void eP(),onCancel:eT}),(0,t.jsx)(u.Dialog,{open:e,onOpenChange:A,children:(0,t.jsxs)(u.DialogContent,{className:"overflow-hidden shadow-xl sm:max-w-[460px] gap-0",onOpenAutoFocus:e=>{ed()&&e.preventDefault()},children:[(0,t.jsx)("div",{className:"px-6 pt-6 pb-4",children:eC?(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{type:"text",value:e_,onChange:e=>eA(e.target.value),className:"flex-1 h-9 px-3 rounded-lg bg-surface border border-border text-foreground text-sm font-semibold focus:outline-none focus:border-[rgba(251,146,60,0.5)] transition-colors",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&eL(),"Escape"===e.key&&eE()}}),(0,t.jsx)("button",{onClick:eE,className:"p-1.5 rounded-lg hover:bg-surface-interactive text-muted-foreground hover:text-foreground transition-colors",children:(0,t.jsx)(d.X,{className:"w-4 h-4"})}),(0,t.jsx)("button",{onClick:eL,className:"p-1.5 rounded-lg hover:bg-surface-interactive text-green-400 hover:text-green-300 transition-colors",children:(0,t.jsx)(o.Save,{className:"w-4 h-4"})})]}):(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:z}),(0,t.jsx)("button",{onClick:()=>{eA(B?.name??""),eM(!0)},className:"p-1 rounded-lg hover:bg-surface-interactive text-label-muted hover:text-foreground transition-colors",children:(0,t.jsx)(l.Pencil,{className:"w-3.5 h-3.5"})})]})}),(0,t.jsxs)("div",{className:"px-6 pb-5 space-y-4",children:[(0,t.jsx)(f.UnderwriterSelector,{excluded:ej,onChange:e=>void ek(e),disabled:eS}),(0,t.jsx)(g.UsdtHintRow,{onSwapSuccess:es}),(0,t.jsx)("div",{className:"flex p-0.5 bg-surface rounded-lg",children:(0,y.fundSegmentsFor)($.length).map(e=>(0,t.jsx)("button",{onPointerDown:T.holdKeypadFocus,onClick:()=>q(e),className:`flex-1 h-9 rounded-md text-sm font-medium transition-colors ${W===e?"bg-surface-raised text-foreground shadow-sm":"text-label-muted hover:text-secondary-foreground"}`,children:L(e)},e))}),"transfer"===W&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-muted-foreground",children:L("transferTo")}),(0,t.jsx)("div",{className:"space-y-1.5",children:$.filter(e=>e.index!==U).map(e=>{let r;return(0,t.jsxs)("button",{onPointerDown:T.holdKeypadFocus,onClick:()=>X(e.index),className:(0,p.cn)("w-full flex items-center gap-3 px-3 py-2 rounded-lg transition-colors border",Y===e.index?"border-[rgba(251,146,60,0.5)] bg-[rgba(255,138,61,0.06)]":"border-border bg-surface hover:border-border-strong"),children:[(0,t.jsx)("div",{className:(0,p.cn)("w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-medium",Y===e.index?"bg-primary text-primary-foreground":"bg-surface-interactive text-secondary-foreground"),children:e.index+1}),(0,t.jsx)("span",{className:"text-sm font-medium text-foreground flex-1 text-left",children:e.name}),(0,t.jsxs)("span",{className:"text-xs font-mono tabular-nums text-label-muted",children:[null==(r=V.get(e.index))?"—":R.fixed(r,2)," USDC"]})]},e.index)})})]}),!ea&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-muted-foreground",children:L("amount")}),(0,t.jsx)("span",{className:"text-xs text-label-muted",children:"deposit"===W?L("usdcAvailable",{amount:null==et?"—":R.fixed(et,2)}):L("withdraw"===W?"availableToWithdraw":"availableToTransfer",{amount:null==et?"—":D.usd(et)})})]}),(0,t.jsxs)("div",{"data-keypad-reveal":!0,className:"flex items-center h-11 bg-surface border border-border rounded-lg px-4 gap-3 focus-within:border-[rgba(251,146,60,0.5)] transition-colors",children:[(0,t.jsx)("input",{ref:eo,...P.DECIMAL_INPUT_PROPS,"data-keypad-unit":"money",enterKeyHint:"go",value:K,onChange:e=>G(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),eu())},onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"flex-1 text-sm font-mono tabular-nums text-foreground bg-transparent border-none focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none placeholder:text-muted-foreground"}),(0,t.jsx)("button",{type:"button",onPointerDown:T.holdKeypadFocus,onClick:ec,className:"text-xs font-medium text-orange-400 hover:text-orange-300 transition-colors",children:L("maxUpper")}),(0,t.jsx)("span",{className:"text-xs text-label-muted",children:"USDC"})]}),ei?(0,t.jsx)("p",{role:"status",className:"px-1 text-xs text-amber-300/90",children:D.note(ei)}):er&&(0,t.jsxs)("div",{className:"flex items-center justify-end gap-1 px-1 text-xs text-label-muted",children:[(0,t.jsx)("span",{children:D.line(er)}),"settling"===er.kind&&(0,t.jsx)(C.SettlingInfo,{})]}),"transfer"!==W&&(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs text-label-muted px-1",children:[(0,t.jsx)("span",{children:L("walletAmountUsdc",{amount:null==Z?"—":R.fixed(Z,2)})}),(0,t.jsx)("span",{children:L("profileAmountUsdc",{amount:null==ee?"—":R.fixed(ee,2)})})]})]}),"deposit"===W&&O&&(0,t.jsx)(b.ProfileAddressCard,{address:O,defaultExpanded:ea}),el.map(e=>"battleLock"!==e&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2.5",children:[(0,t.jsx)(c.AlertTriangle,{className:"w-3.5 h-3.5 text-amber-400 shrink-0 mt-0.5"}),(0,t.jsx)("p",{className:"text-[11px] text-amber-200/90 leading-relaxed",children:L(M[e])})]},e))]}),"withdraw"===W&&O&&H&&(0,t.jsx)(v.ProfileTokenRescueList,{profilePda:O,profileIndex:U,walletPubkey:H,isActive:e,onRescueDone:es}),el.includes("battleLock")&&en&&(0,t.jsxs)("div",{className:"mx-6 mb-3 flex items-start gap-2.5 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2.5",children:[(0,t.jsx)(s.Sword,{className:"w-4 h-4 mt-0.5 text-amber-400 shrink-0"}),(0,t.jsx)("div",{className:"text-xs text-secondary-foreground leading-relaxed",children:L.rich("depositLockedByBattle",{battle:en.title,link:e=>(0,t.jsx)(n.Link,{href:"/competition",className:"text-amber-300 underline-offset-2 hover:underline",children:e})})})]}),(0,t.jsx)(u.DialogFooter,{className:(0,p.cn)("px-6 pb-6 pt-0",ea&&"hidden"),children:(0,t.jsx)("button",{onClick:eu,disabled:eh,className:"w-full h-10 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:J?L("transfer"===W?"movingFundsArmadaWait":"withdrawingArmadaWait"):Q?"transfer"===W?L("transferring"):L("deposit"===W?"depositing":"withdrawing"):"transfer"===W?L("transferAmountUsdc",{amount:K||"0"}):L("deposit"===W?"depositAmountUsdc":"withdrawAmountUsdc",{amount:K||"0"})})})]})})]})}},721680,e=>{e.v({accountName:"desktop-market-ticker-module__VaB1OW__accountName",accountRow:"desktop-market-ticker-module__VaB1OW__accountRow",accountTab:"desktop-market-ticker-module__VaB1OW__accountTab",accountTabs:"desktop-market-ticker-module__VaB1OW__accountTabs",accountsHint:"desktop-market-ticker-module__VaB1OW__accountsHint",accountsTrigger:"desktop-market-ticker-module__VaB1OW__accountsTrigger",connectAccounts:"desktop-market-ticker-module__VaB1OW__connectAccounts",cycle:"desktop-market-ticker-module__VaB1OW__cycle",empty:"desktop-market-ticker-module__VaB1OW__empty",footer
2:"desktop-market-ticker-module__VaB1OW__footer",iconLink:"desktop-market-ticker-module__VaB1OW__iconLink",inactiveAccountTab:"desktop-market-ticker-module__VaB1OW__inactiveAccountTab",manual:"desktop-market-ticker-module__VaB1OW__manual",market:"desktop-market-ticker-module__VaB1OW__market",marketIcon:"desktop-market-ticker-module__VaB1OW__marketIcon",motionButton:"desktop-market-ticker-module__VaB1OW__motionButton",negative:"desktop-market-ticker-module__VaB1OW__negative",positive:"desktop-market-ticker-module__VaB1OW__positive",price:"desktop-market-ticker-module__VaB1OW__price",repeat:"desktop-market-ticker-module__VaB1OW__repeat",symbol:"desktop-market-ticker-module__VaB1OW__symbol",ticker:"desktop-market-ticker-module__VaB1OW__ticker",track:"desktop-market-ticker-module__VaB1OW__track",unknown:"desktop-market-ticker-module__VaB1OW__unknown",utilities:"desktop-market-ticker-module__VaB1OW__utilities",utilityLink:"desktop-market-ticker-module__VaB1OW__utilityLink",utilityRow:"desktop-market-ticker-module__VaB1OW__utilityRow",viewport:"desktop-market-ticker-module__VaB1OW__viewport"})},160480,e=>{e.v({footer:"desktop-pro-order-form-module__3fdQdq__footer",form:"desktop-pro-order-form-module__3fdQdq__form"})},257355,e=>{e.v({footer:"desktop-shell-module__84MFgG__footer",shell:"desktop-shell-module__84MFgG__shell",viewport:"desktop-shell-module__84MFgG__viewport"})},331037,e=>{e.v({actionHost:"desktop-ticket-module__7OuUgG__actionHost",actions:"desktop-ticket-module__7OuUgG__actions",body:"desktop-ticket-module__7OuUgG__body",feeRow:"desktop-ticket-module__7OuUgG__feeRow",footer:"desktop-ticket-module__7OuUgG__footer",info:"desktop-ticket-module__7OuUgG__info",inputField:"desktop-ticket-module__7OuUgG__inputField",proFooter:"desktop-ticket-module__7OuUgG__proFooter",summary:"desktop-ticket-module__7OuUgG__summary",ticket:"desktop-ticket-module__7OuUgG__ticket"})},632588,486212,885484,828533,235361,915487,811321,646318,146911,115887,966275,927646,116668,206015,775062,167488,221784,485103,917404,168537,933657,e=>{"use strict";e.s(["DesktopWorkspaceActivity",()=>rU,"DesktopWorkspaceTicket",()=>rI],632588),e.s(["JupiterPerpsBottomPanel",()=>rF],168537),e.s([],486212),e.s(["OrderHistoryRow",()=>e2,"indicatorConditionSummary",()=>e0,"priceConditionSummary",()=>e1],235361),e.s(["OrderHistoryMobileCard",()=>e5],915487),e.s(["OrderHistoryDetailSheet",()=>ta,"OrderHistoryDetailView",()=>tl],811321),e.s(["OrderHistoryFilterBar",()=>tx,"orderHistoryFiltersActive",()=>tf],646318),e.s(["FundingHistoryRow",()=>tU],966275),e.s(["FundingHistoryMobileCard",()=>tO],927646),e.s(["FundingHistoryDetailSheet",()=>tB],116668),e.s(["FundingHistoryFilterBar",()=>tH,"fundingHistoryFiltersActive",()=>tV],206015),e.s(["DepositHistoryRow",()=>rr],167488),e.s(["DepositHistoryMobileCard",()=>ri],221784),e.s(["DepositHistoryDetailSheet",()=>rs],485103),e.s(["DepositHistoryFilterBar",()=>ro,"depositHistoryFiltersActive",()=>rl],917404);var t=e.i(394390),r=e.i(807956),i=e.i(585457),s=e.i(710729),n=e.i(581285),a=e.i(51559),l=e.i(718177),o=e.i(979804),d=e.i(183023),c=e.i(799227),u=e.i(994754),h=e.i(988462),p=e.i(943494),m=e.i(942553),f=e.i(116082),x=e.i(567978),g=e.i(291953),b=e.i(438495),v=e.i(875574),y=e.i(142298),w=e.i(739835),j=e.i(586569),S=e.i(687229),k=e.i(727322),N=e.i(631193),P=e.i(275813),T=e.i(298913),C=e.i(524536),M=e.i(7658),_=e.i(711451),A=e.i(263424),E=e.i(894771),L=e.i(670374);e.i(725747),e.i(870020),e.i(980333),e.i(443048),e.i(24893),e.i(450358);var F=e.i(521186),R=e.i(247897),D=e.i(20446);e.i(232675);var I=e.i(26826),U=e.i(596331),O=e.i(451720),B=e.i(546642),z=e.i(43690);let $="https://api.imperial.space",V={market:"all",underwriter:"all",side:"all",status:"all",category:"all",period:"ALL",customDateFrom:null,customDateTo:null};function H(e,t,r,i){if("CUSTOM"===e){let e={};if(t){let r=new Date(t).getTime()/1e3;isNaN(r)||(e.from=Math.floor(r))}if(r){let t=new Date(r).getTime()/1e3+86400;isNaN(t)||(e.to=Math.floor(t))}return e}if("WTD"===e){let e=i.getDay();return{from:Math.floor(new Date(i.getFullYear(),i.getMonth(),i.getDate()-(0===e?6:e-1)).getTime()/1e3)}}return"MTD"===e?{from:Math.floor(new Date(i.getFullYear(),i.getMonth(),1).getTime()/1e3)}:"YTD"===e?{from:Math.floor(new Date(i.getFullYear(),0,1).getTime()/1e3)}:{}}function W(e,t=new Date){let r={},i=(e,t)=>{t&&"all"!==t&&(r[e]=t)};i("market",e.market),i("underwriter",e.underwriter),i("side",e.side),i("status",e.status),i("category",e.category);let{from:s,to:n}=H(e.period,e.customDateFrom,e.customDateTo,t);return null!=s&&(r.from=String(s)),null!=n&&(r.to=String(n)),r}function q(e,t){if(null==e||""===e)return null;let r=Number(e);return Number.isFinite(r)?String(r/t):null}function K(e){return{...e,sizeUsd:q(e.sizeUsd,1e6),filledSizeUsd:q(e.filledSizeUsd,1e6),avgFillPrice:q(e.avgFillPrice,1e9),triggerPrice:q(e.triggerPrice,1e9),executionTriggerPrice:q(e.executionTriggerPrice,1e9),bestPriceSeen:q(e.bestPriceSeen,1e9),dca:e.dca?{...e.dca,avgFillPrice:q(e.dca.avgFillPrice,1e9)}:e.dca,ratchet:e.ratchet?{...e.ratchet,trailDistance:q(e.ratchet.trailDistance,1e9),referencePrice:q(e.ratchet.referencePrice,1e9)}:e.ratchet}}function G(e){return{...e,sizeUsd:q(e.sizeUsd,1e6),price:q(e.price,1e9),feesUsd:q(e.feesUsd,1e6)}}function Y(e){return{...e,price:q(e.price,1e9)}}async function X(e,t={}){let r=new URLSearchParams({walletAddress:e,limit:String(t.limit??50),offset:String(t.offset??0)});for(let[e,i]of Object.entries(t.params??{}))r.set(e,i);let i=await fetch(`${$}/api/v1/order-history?${r}`,{cache:"no-store"});if(!i.ok)throw Error(`Failed to fetch order history: ${i.status}`);let s=await i.json();return{orders:(s.orders??[]).map(K),totalCount:s.totalCount??0}}async function Q(e){let t=await fetch(`${$}/api/v1/order-history/${encodeURIComponent(e)}`,{cache:"no-store"});if(!t.ok)throw Error(`Failed to fetch order detail: ${t.status}`);let r=await t.json();return{...r,...K(r),feesUsd:q(r.feesUsd,1e6),children:(r.children??[]).map(K),fills:(r.fills??[]).map(G),events:(r.events??[]).map(Y)}}e.s(["DEFAULT_ORDER_HISTORY_FILTERS",0,V,"MICRO_USD",0,1e6,"buildOrderHistoryParams",0,W,"fetchOrderHistory",0,X,"fetchOrderHistoryDetail",0,Q,"periodRange",0,H,"scaleFixedPoint",0,q],885484);var J=e.i(242132),Z=e.i(175701),ee=e.i(514049);function et({queryKey:e,enabled:t,fetchPage:r,pageItems:i,pageTotalCount:s,itemId:n}){let a=(0,ee.useQueryClient)(),l=(0,Z.useInfiniteQuery)({queryKey:e,queryFn:({pageParam:e})=>r(e,50),initialPageParam:0,getNextPageParam:(e,t)=>{let r=t.reduce((e,t)=>
2e+i(t).length,0);if(!(r>=s(e)))return r},enabled:t,staleTime:3e4,refetchOnWindowFocus:!1}),o=(0,d.useRef)(e);o.current=e;let c=(0,J.hashKey)(e);(0,d.useEffect)(()=>{if(!t)return;let e=()=>{let e=o.current,t=a.getQueryState(e);!t?.dataUpdatedAt||Date.now()-t.dataUpdatedAt<3e4||(a.setQueryData(e,e=>e&&e.pages.length>1?{pages:e.pages.slice(0,1),pageParams:e.pageParams.slice(0,1)}:e),a.invalidateQueries({queryKey:e,exact:!0}))};return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[a,t,c]);let u=(0,d.useRef)({pageItems:i,itemId:n});return u.current={pageItems:i,itemId:n},{items:(0,d.useMemo)(()=>{let e=l.data?.pages;if(!e)return[];let t=new Set,r=[];for(let i of e)for(let e of u.current.pageItems(i)){let i=u.current.itemId(e);t.has(i)||(t.add(i),r.push(e))}return r},[l.data]),firstPage:l.data?.pages[0],hasMore:l.hasNextPage??!1,isFetchingNextPage:l.isFetchingNextPage,fetchNextPage:l.fetchNextPage,isLoading:l.isLoading,error:l.error?.message??null,refetch:l.refetch}}let er={orders:[],totalCount:0},ei=e=>e.orders,es=e=>e.totalCount,en=e=>e.orderPda;function ea(e,t){let[r,i]=(0,d.useState)(()=>{let r={...t};for(let t of Object.keys(e)){let i=localStorage.getItem(e[t]);i&&(r[t]=i)}return r});return(0,d.useEffect)(()=>{for(let t of Object.keys(e)){let i=r[t];"string"==typeof i&&i?localStorage.setItem(e[t],i):localStorage.removeItem(e[t])}},[r,e]),{filters:r,setFilters:(0,d.useCallback)(e=>{i(t=>{let r={...t};for(let t of Object.keys(e)){let i=e[t];void 0!==i&&(r[t]=i)}return r})},[]),resetFilters:(0,d.useCallback)(()=>i(t),[t])}}var el=e.i(619966);let eo="px-4 py-1.5 text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors";function ed({label:e}){let r=(0,m.useTranslations)("positions");return(0,t.jsx)("div",{className:"py-12 text-center text-muted-foreground text-sm",children:r("historyDbDownNotice",{label:e})})}function ec({onClick:e,isFetching:r,fullWidth:i}){let s=(0,m.useTranslations)("positions");return(0,t.jsxs)("button",{onClick:e,disabled:r,className:`${i?"w-full py-2.5 justify-center":"px-6 py-2"} text-xs text-muted-foreground hover:text-foreground bg-surface-raised hover:bg-surface-interactive rounded transition-colors flex items-center gap-2`,children:[r?(0,t.jsx)(p.Loader2,{className:"h-3.5 w-3.5 animate-spin"}):null,s(r?"historyLoading":"historyLoadMore")]})}function eu({isLoading:e,error:r,isEmpty:i,filtersActive:s,onRetry:n,onReset:a,errorText:l,emptyFilteredText:o,emptyText:d}){return e?(0,t.jsx)(eh,{}):r?(0,t.jsx)(ep,{errorText:l,onRetry:n}):i?s?(0,t.jsx)(em,{emptyFilteredText:o,onReset:a}):(0,t.jsx)("div",{className:"py-12 px-6 text-center text-muted-foreground text-sm",children:d}):null}function eh(){let e=(0,m.useTranslations)("positions");return(0,t.jsxs)("div",{role:"status",className:"flex items-center justify-center py-12",children:[(0,t.jsx)(p.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"}),(0,t.jsx)("span",{className:"sr-only",children:e("historyLoading")})]})}function ep({errorText:e,onRetry:r}){let i=(0,m.useTranslations)("positions");return(0,t.jsxs)("div",{className:"py-12 text-center space-y-3",children:[(0,t.jsx)("div",{className:"text-xs text-red-400/80",children:e}),(0,t.jsx)("button",{onClick:r,className:eo,children:i("historyRetry")})]})}function em({emptyFilteredText:e,onReset:r}){let i=(0,m.useTranslations)("positions");return(0,t.jsxs)("div",{className:"py-12 text-center space-y-3",children:[(0,t.jsx)("div",{className:"text-muted-foreground text-sm",children:e}),(0,t.jsx)("button",{onClick:r,className:eo,children:i("historyReset")})]})}var ef=e.i(457058),ex=e.i(491135),eg=e.i(268680),eb=e.i(406470);e.i(889723);var ev=e.i(465217),ey=e.i(599059),ew=e.i(459),ej=e.i(719367),eS=e.i(687821);let ek={active:{labelKey:"historyStatusActive",className:"bg-cyan-500/20 text-cyan-400"},open:{labelKey:"historyStatusOpen",className:"bg-blue-500/20 text-blue-400"},triggered:{labelKey:"historyStatusTriggered",className:"bg-amber-500/20 text-amber-400"},partially_filled:{labelKey:"historyStatusPartiallyFilled",className:"bg-blue-300/20 text-blue-300"},filled:{labelKey:"historyStatusFilled",className:"bg-emerald-500/20 text-emerald-400"},completed:{labelKey:"historyStatusCompleted",className:"bg-emerald-500/20 text-emerald-400"},paused:{labelKey:"historyStatusPaused",className:"bg-yellow-500/20 text-yellow-400"},canceled:{labelKey:"historyStatusCanceled",className:"bg-surface-interactive/20 text-muted-foreground"},rejected:{labelKey:"historyStatusRejected",className:"bg-red-500/20 text-red-400"},expired:{labelKey:"historyStatusExpired",className:"bg-surface-interactive/20 text-muted-foreground"},failed:{labelKey:"historyStatusFailed",className:"bg-red-500/20 text-red-400"},skipped:{labelKey:"historyStatusSkipped",className:"bg-surface-interactive/20 text-muted-foreground"}},eN=["active","open","triggered","partially_filled","filled","completed","paused","canceled","rejected","failed"],eP=new Set(["filled","completed","canceled","rejected","expired","failed","
2skipped"]);function eT(e){let t=ek["cancelled"===e?"canceled":e];return t||((0,eS.warnUnmapped)("order status",e),{labelKey:"historyUnknownLabel",rawValue:e,className:eS.UNMAPPED_BADGE_CLASS})}function eC(e){return eP.has("cancelled"===e?"canceled":e)}let eM={dca:{label:"DCA",legsLabelKey:"historyOrderBadgeDcaLegs"},dca_close:{labelKey:"historyOrderTypeDcaClose",legsLabelKey:"historyOrderBadgeDcaCloseLegs"},dca_time:{labelKey:"historyOrderTypeDcaTime",legsLabelKey:"historyOrderBadgeDcaTimeLegs"},dca_time_close:{labelKey:"historyOrderTypeDcaTime",legsLabelKey:"historyOrderBadgeDcaTimeLegs"},dca_ratchet:{labelKey:"historyOrderTypeDcaTrailing",legsLabelKey:"historyOrderBadgeDcaTrailingLegs"},dca_ratchet_close:{labelKey:"historyOrderTypeDcaTrailing",legsLabelKey:"historyOrderBadgeDcaTrailingLegs"}},e_={market:{labelKey:"historyOrderTypeMarket",className:"bg-green-500/20 text-green-400"},limit:{labelKey:"historyOrderTypeLimit",className:"bg-blue-500/20 text-blue-400"},stop_limit:{labelKey:"historyOrderTypeStop",className:"bg-red-500/20 text-red-400"},landmine:{labelKey:"historyOrderTypeLandmine",className:"bg-purple-500/20 text-purple-400"},private_tpsl:{label:"TP/SL",className:"bg-emerald-500/20 text-emerald-400"},ratchet:{labelKey:"historyOrderTypeTrailingSl",className:"bg-blue-500/20 text-blue-400"},fib_ratchet:{labelKey:"historyOrderTypeTrailingSl",className:"bg-blue-500/20 text-blue-400"},ratchet_entry:{labelKey:"historyOrderTypeTrailingEntry",className:"bg-blue-500/20 text-blue-400"},fib_ratchet_entry:{labelKey:"historyOrderTypeTrailingEntry",className:"bg-blue-500/20 text-blue-400"},indicator:{label:"RSI",className:"bg-amber-500/20 text-amber-400"},indicator_ratchet:{labelKey:"historyOrderTypeRsiTrailing",className:"bg-amber-500/20 text-amber-400"}};function eA(e,t){let r=eM[e];if(r){let i=e.startsWith("dca_ratchet")?"bg-teal-500/20 text-teal-400":"bg-cyan-500/20 text-cyan-400";return t?{legsLabel:{key:r.legsLabelKey,executed:String(t.legsExecuted),total:String(t.numLegs)},className:i}:{label:r.label,labelKey:r.labelKey,className:i}}let i=e_[e];return i||((0,eS.warnUnmapped)("order type",e),{labelKey:"historyUnknownLabel",rawValue:e,className:eS.UNMAPPED_BADGE_CLASS})}let eE=new Set(["dca","dca_close","dca_time_close","dca_ratchet_close","dca_time","dca_ratchet"]),eL=new Set(["ratchet","ratchet_entry","fib_ratchet","fib_ratchet_entry"]),eF=new Set(["indicator","indicator_ratchet"]);function eR(e){return eE.has(e)?"dca":eL.has(e)?"trailing":eF.has(e)?"rsi":"standard"}function eD(e,t){return`$${e.toLocaleString((0,ej.intlTag)(t),{minimumFractionDigits:2,maximumFractionDigits:2})}`}function eI(e,t,r){if(null==t)return"—";let i=parseFloat(t);if(isNaN(i))return"—";let s=null!=e?parseFloat(e):NaN;if(isNaN(s)||s<=0)return eD(i,r);let n=Math.round(i/s*100);return`${eD(i,r)} (${n}%)`}let eU={order_created:"historyEventOrderCreated",order_cancelled:"historyEventOrderCanceled",order_executed:"historyEventOrderExecuted",order_filled:"historyEventOrderFilled",order_partially_filled:"historyEventOrderPartiallyFilled",dca_leg_executed:"historyEventDcaLegExecuted",dca_leg_skipped:"historyEventDcaLegSkipped",dca_leg_failed:"historyEventDcaLegFailed",strategy_completed:"historyEventStrategyCompleted",ratchet_activated:"historyEventTrailingActivated",ratchet_engaged:"historyEventTrailingEngaged",ratchet_stop_armed:"historyEventTrailingStopArmed",ratchet_trigger_updated:"historyEventTriggerUpdated",circuit_breaker_tripped:"historyEventCircuitBreakerTripped",order_unfunded:"historyEventOrderUnfunded",indicator_monitoring_started:"historyEventIndicatorMonitoringStarted",indicator_condition_met:"historyEventIndicatorConditionMet",order_untracked:"historyEventOrderUntracked"};function eO(e){let t=eU[e];return t?{key:t}:((0,eS.warnUnmapped)("order event type",e),{key:"historyUnknownLabel",rawValue:e})}function eB(e){return e in eU}function ez(e,t){let r=parseFloat(e);return isNaN(r)?e:`$${r.toLocaleString((0,ej.intlTag)(t),{maximumFractionDigits:8})}`}function e$(e,t){let r=parseFloat(e);return isNaN(r)?null:(r/1e6).toLocaleString((0,ej.intlTag)(t),{maximumFractionDigits:1})}function eV(e,t,r){let i=null!=e.price?ez(e.price,t):null,s=null!=e.legIndex?r.leg(e.legIndex+1):null;switch(e.eventType){case"ratchet_activated":case"ratchet_engaged":case"ratchet_stop_armed":case"ratchet_trigger_updated":{var n;let s,a=null!=e.value?(n=e.value,isNaN(s=parseFloat(n))?null:ez(String(s/1e9),t)):null,l="ratchet_trigger_updated"===e.eventType?r.triggerUpdated:r.reference;if(a)return l(a);return i?l(i):e.reason??null}case"indicator_condition_met":{let r=null!=e.value?e$(e.value,t):null;if(r&&i)return`RSI ${r} @ ${i}`;if(r)return`RSI ${r}`;return e.reason??null}case"dca_leg_executed":case"dca_leg_skipped":case"dca_leg_failed":{let t=[s,e.reason,i?`@ ${i}
2`:null].filter(Boolean);return t.length>0?t.join(" · "):null}default:{let t=[e.reason,i?`@ ${i}`:null].filter(Boolean);return t.length>0?t.join(" "):null}}}e.s(["ORDER_STATUS_BADGES",0,ek,"ORDER_STATUS_FILTER_OPTIONS",0,eN,"eventTypeLabel",0,eO,"formatFilled",0,eI,"getOrderTypeBadge",0,eA,"getStatusBadge",0,eT,"isKnownEventType",0,eB,"isTerminalStatus",0,eC,"microRsiString",0,e$,"orderCategoryOf",0,eR,"summarizeEvent",0,eV],828533);var eH=e.i(457395),eW=e.i(202647);function eq(e,t=6){return e.length<=2*t+1?e:`${e.slice(0,t)}…${e.slice(-t)}`}function eK(){let e=(0,m.useTranslations)("positions");return{badge:t=>t.legsLabel?e(t.legsLabel.key,{executed:t.legsLabel.executed,total:t.legsLabel.total}):t.labelKey?e(t.labelKey):t.label??"",label:t=>e(t.key),rawTitle:t=>null==t.rawValue?void 0:e("historyUnknownRawTooltip",{value:t.rawValue}),priceCondition:{trail:t=>e("historyTrail",{distance:t}),market:e("historyOrderTypeMarket")},eventSummary:{leg:t=>e("historyEventSummaryLeg",{index:String(t)}),triggerUpdated:t=>e("historyEventSummaryTriggerUpdated",{value:t}),reference:t=>e("historyEventSummaryReference",{value:t})}}}function eG(){let e=(0,m.useTranslations)("positions");return{payment:t=>"text"in t.label?t.label.text:e(t.label.key,t.label.values),rate:t=>"text"in t?t.text:e(t.key,t.values),venue:t=>e(t.key,t.values),calculation:t=>t?e(t.key,t.values):null}}function eY({value:e}){let r=(0,m.useTranslations)("positions"),[i,s]=(0,d.useState)(!1);return(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"font-mono",children:eq(e)}),(0,t.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1500)}).catch(()=>{})},className:"text-muted-foreground hover:text-foreground transition-colors","aria-label":r("historyCopyToClipboard"),children:i?(0,t.jsx)(eW.Check,{className:"w-3 h-3 text-emerald-400"}):(0,t.jsx)(eH.Copy,{className:"w-3 h-3"})})]})}function eX({label:e,children:r}){return(0,t.jsxs)("div",{className:"flex items-center justify-between py-1.5 gap-4",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted shrink-0",children:e}),(0,t.jsx)("span",{className:"text-xs text-foreground font-mono tabular-nums text-right min-w-0 break-all",children:r})]})}function eQ({title:e,children:r}){return(0,t.jsxs)("div",{className:"border-t border-border pt-3",children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:e}),r]})}var eJ=e.i(299959),eZ=e.i(712963);function e0(e){let t=null!=e.period?`RSI(${e.period})`:"RSI",r=e.condition,i=(0,ew.conditionLabelKey)(r),s=i?(0,j.message)("trading",i):null==r?"":String(r).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),n=e.threshold??"",a=e.timeframe,l=null==a?null:/^\d+$/.test(String(a))?ew.TIMEFRAME_LABELS[Number(a)]??String(a):String(a),o=[t,s,n].filter(Boolean).join(" ");return l?`${o} \xb7 ${l}`:o}function e1(e,t,r){if(e.indicator)return e0(e.indicator);if("trailing"===eR(e.orderType)||e.ratchet){let i=e.ratchet?.trailDistance;return null!=i&&parseFloat(i)>0?r.trail((0,eb.formatRawPrice)(i,t)):null!=e.triggerPrice?(0,eb.formatRawPrice)(e.triggerPrice,t):"—"}if("market"===e.orderType)return r.market;if(null!=e.triggerPrice){let r="above"===e.triggerCondition?"≥ ":"below"===e.triggerCondition?"≤ ":"";return`${r}${(0,eb.formatRawPrice)(e.triggerPrice,t)}`}return"—"}function e2({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=eK(),n=(0,eJ.useFormatters)(),a=(0,L.getTokenInfo)(e.marketMint),l="long"===e.side,o=eA(e.orderType,e.dca),d=eT(e.displayStatus),c=e.underwriter?(0,ey.getVenueIcon)(e.underwriter,e.hedgeVenue):null;return(0,t.jsxs)("tr",{className:"border-b border-border cursor-pointer hover:bg-surface-interactive/30 transition-colors",onClick:()=>r(e),children:[(0,t.jsx)("td",{className:"py-3 px-3 w-[130px]",children:(0,t.jsxs)("div",{className:eZ.default.identity,children:[(0,t.jsxs)("div",{className:eZ.default.identityPrimary,children:[a.image&&(0,t.jsx)(ef.default,{src:a.image,alt:a.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:a.symbol}),(0,t.jsx)("span",{className:`${eZ.default.side} ${l?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i(l?"historyLongUpper":"historyShortUpper")})]}),(0,t.jsxs)("div",{className:eZ.default.metadata,children:[(0,t.jsx)("span",{title:s.rawTitle(o),className:`text-[10px] font-medium px-1.5 py-0.5 rounded whitespace-nowrap ${o.className}`,children:s.badge(o)}),c&&(0,t.jsx)(ef.default,{src:c.src,alt:c.alt,title:c.alt,width:14,height:14,className:"rounded-full",unoptimized:!0})]})]})}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground whitespace-nowrap",children:n.dateTime(e.createdAt)}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-foreground font-mono tabular-nums whitespace-nowrap",children:e1(e,n.intlTag,s.priceCondition)}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums`,children:n.rawUsd(e.sizeUsd)}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums whitespace-nowrap`,children:eI(e.sizeUsd,e.filledSizeUsd,n.intlTag)}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums`,children:n.rawPrice(e.avgFillPrice??e.dca?.avgFillPrice)}),(0,t.jsx)("td",{className:"py-3 px-3",children:e.statusReason?(0,t.jsx)(eg.TooltipProvider,{children:(0,t.jsxs)(eg.Tooltip,{children:[(0,t.jsx)(eg.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{title:s.rawTitle(d),className:`text-[10px] font-medium px-1.5 py-0.5 rounded cursor-help whitespace-nowrap ${d.className}`,children:s.badge(d)})}),(0,t.jsx)(eg.TooltipContent,{side:"top",className:"max-w-xs text-xs",children:e.statusReason})]})}):(0,t.jsx)("span",{title:s.rawTitle(d),className:`text-[10px] font-medium px-1.5 py-0.5 rounded whitespace-nowrap ${d.className}`,children:s.badge(d)})}),(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsx)("button",{onClick:t=>{t.stopPropagation(),r(e)},className:eZ.default.detailButton,"aria-label":i("historyOrderDetailsAria"),children:(0,t.jsx)(ex.ChevronRight,{className:"w-3.5 h-3.5"})})})]})}function e5({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=(0,m.useTranslations)("terms"),n=eK(),a=(0,eJ.useFormatters)(),l=(0,L.getTokenInfo)(e.marketMint),o="long"===e.side,d=eA(e.orderType,e.dca),c=eT(e.displayStatus),u=e.underwriter?(0,ey.getVenueIcon)(e.underwriter,e.hedgeVenue):null;return(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg px-3 py-3 cursor-pointer active:bg-surface-interactive/50",onClick:()=>r(e),children:[(0,t.jsx)("div",{className:"flex items-center justify-between mb-2",children:(0,t.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${o?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i(o?"historyLongUpper":"historyShortUpper")}
2),l.image&&(0,t.jsx)(ef.default,{src:l.image,alt:l.symbol,width:14,height:14,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:l.symbol}),(0,t.jsx)("span",{title:n.rawTitle(d),className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${d.className}`,children:n.badge(d)}),(0,t.jsx)("span",{title:n.rawTitle(c),className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${c.className}`,children:n.badge(c)})]})}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:s("size.full")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:a.rawUsd(e.sizeUsd)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:i("historyColFilled")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:eI(e.sizeUsd,e.filledSizeUsd,a.intlTag)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:i("historyColAvgFill")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:a.rawPrice(e.avgFillPrice??e.dca?.avgFillPrice)})]})]}),(0,t.jsx)("div",{className:"mt-1.5 text-[10px] text-label-muted font-mono tabular-nums",children:e1(e,a.intlTag,n.priceCondition)}),(0,t.jsxs)("div",{className:"mt-2 flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:a.dateTime(e.createdAt)}),u&&(0,t.jsx)(ef.default,{src:u.src,alt:u.alt,width:14,height:14,className:"rounded-full",unoptimized:!0})]})]})}var e3=e.i(845165),e4=e.i(756880),e6=e.i(637226),e8=e.i(685576),e9=e.i(986759),e7=e.i(905843);function te(e,...t){if(!e)return null;for(let r of t){let t=e[r];if("number"==typeof t&&!isNaN(t))return t;if("string"==typeof t&&""!==t&&!isNaN(parseFloat(t)))return parseFloat(t)}return null}function tt({detail:e}){let r=(0,m.useTranslations)("positions"),i=(0,m.useTranslations)("trading"),s=eK(),n=(0,eJ.useFormatters)(),a=e.dca,l=e.config,o=a?.numLegs??te(l,"numLegs","num_legs"),c=a?.legsExecuted??null,u=null!=e.sizeUsd?parseFloat(e.sizeUsd):NaN,h=!isNaN(u)&&null!=o&&o>0?u/o:null,p=te(l,"intervalSeconds","interval_seconds"),f=te(l,"weightingType","weighting_type"),x=te(l,"startPrice","start_price"),g=te(l,"endPrice","end_price","priceLimit","price_limit"),b=null!=x?x/1e9:null,v=null!=g?g/1e9:null,y=(0,d.useMemo)(()=>(function(e,t){let r=e.map(e=>({legIndex:e.legIndex??null,time:e.time,sizeUsd:e.sizeUsd,price:e.price,status:e.status??"filled",statusReason:e.statusReason}));for(let e of t)("dca_leg_skipped"===e.eventType||"dca_leg_failed"===e.eventType)&&r.push({legIndex:e.legIndex??null,time:e.timestamp,price:e.price,status:"dca_leg_skipped"===e.eventType?"skipped":"failed",statusReason:e.reason});return r.sort((e,t)=>e.time-t.time)})(e.fills??[],e.events??[]),[e.fills,e.events]);return(0,t.jsxs)(eQ,{title:r("historyDcaStrategy"),children:[(0,t.jsx)(eX,{label:r("historyDcaTotalSize"),children:n.rawUsd(e.sizeUsd)}),(0,t.jsx)(eX,{label:r("historyDcaPerLegSize"),children:null!=h?`≈ ${n.rawUsd(h.toFixed(2))}`:"—"}),(0,t.jsx)(eX,{label:r("historyDcaLegsExecuted"),children:null!=c&&null!=o?`${c} / ${o}`:"—"}),(0,t.jsx)(eX,{label:r("historyDcaLegsRemaining"),children:null!=c&&null!=o?Math.max(o-c,0):"—"}),(0,t.jsx)(eX,{label:r("historyDcaInterval"),children:null!=p?(0,e7.formatInterval)(p):"—"}),(0,t.jsx)(eX,{label:r("historyDcaWeighting"),children:null!=f?i(ew.WEIGHTING_LABEL_KEYS[f]):"—"}),(0,t.jsx)(eX,{label:r("historyDcaStartPrice"),children:null!=b?n.rawPrice(String(b)):"—"}),(0,t.jsx)(eX,{label:r("historyDcaEndPrice"),children:null!=v?n.rawPrice(String(v)):"—"}),(0,t.jsx)(eX,{label:r("historyAvgFillPrice"),children:n.rawPrice(a?.avgFillPrice)}),y.length>0&&(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:r("historyDcaLegExecutionLog")}),(0,t.jsx)("div",{className:"space-y-1",children:y.map((e,i)=>{let a=eT(e.status);return(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 py-1 border-b border-border/50 last:border-b-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground shrink-0",children:null!=e.legIndex?s.eventSummary.leg(e.legIndex+1):r("historyLeg")}),(0,t.jsx)("span",{title:s.rawTitle(a),className:`text-[10px] font-medium px-1.5 py-0.5 rounded shrink-0 ${a.className}`,children:s.badge(a)}),e.statusReason&&(0,t.jsx)("span",{className:"text-[10px] text-label-muted truncate",children:e.statusReason})]}),(0,t.jsxs)("div",{className:"text-right shrink-0",children:[(0,t.jsxs)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:[null!=e.sizeUsd?n.rawUsd(e.sizeUsd):""," ",null!=e.price?`@ ${n.rawPrice(e.price)}`:""]}),(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:n.dateTime(e.time)})]})]},i)})})]})]})}
2function tr({detail:e}){let r=(0,m.useTranslations)("positions"),i=(0,eJ.useFormatters)(),s=(e.events??[]).find(e=>"order_executed"===e.eventType),n=s?.timestamp??e.executedAt??null;return(0,t.jsxs)(eQ,{title:r("historyTrailingStrategy"),children:[(0,t.jsx)(eX,{label:r("historyRowTrailDistance"),children:i.rawPrice(e.ratchet?.trailDistance)}),(0,t.jsx)(eX,{label:r("historyRowStartingReference"),children:i.rawPrice(e.ratchet?.referencePrice)}),(0,t.jsx)(eX,{label:r("historyRowBestPriceSeen"),children:i.rawPrice(e.bestPriceSeen)}),(0,t.jsx)(eX,{label:r("historyRowFinalTrigger"),children:i.rawPrice(e.executionTriggerPrice)}),(0,t.jsx)(eX,{label:r("historyRowTimeTriggered"),children:null!=n?i.dateTime(n):"—"})]})}function ti({detail:e}){let r=(0,m.useTranslations)("positions"),i=(0,eJ.useFormatters)(),s=e.indicator,n=(e.events??[]).find(e=>"indicator_condition_met"===e.eventType),a="cancelled"===e.displayStatus?"canceled":e.displayStatus;return(0,t.jsxs)(eQ,{title:r("historyRsiIndicator"),children:[(0,t.jsx)(eX,{label:r("historyRowCondition"),children:s?e0(s):"—"}),(0,t.jsx)(eX,{label:r("historyRowConfirmation"),children:r("historyRsiConfirmationNote")}),n?(0,t.jsxs)("div",{className:"mt-2 rounded bg-amber-500/10 border border-amber-500/20 px-2.5 py-2",children:[(0,t.jsx)("div",{className:"text-[10px] text-amber-400 mb-1",children:r("historyConditionMet")}),(0,t.jsxs)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:[null!=n.value?`RSI ${e$(n.value,i.intlTag)??n.value}`:r("historyRsiConditionMet"),null!=n.price?` @ ${i.rawPrice(n.price)}`:""]}),(0,t.jsx)("div",{className:"text-[10px] text-label-muted mt-0.5",children:i.dateTime(n.timestamp)})]}):("expired"===a||"canceled"===a)&&(0,t.jsx)("div",{className:"mt-2 text-[10px] text-label-muted",children:r("expired"===a?"historyRsiExpiredBeforeMet":"historyRsiCanceledBeforeMet")})]})}let ts=new Set(["stop_limit","land_mine","private_tp_sl","ratchet","ratchet_entry","fib_ratchet","fib_ratchet_entry","indicator","indicator_ratchet"]);function tn({child:e}){let r=eK(),i=(0,eJ.useFormatters)(),s=eA(e.orderType,e.dca),n=eT(e.displayStatus);return(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 py-1.5 border-b border-border/50 last:border-b-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 min-w-0",children:[(0,t.jsx)("span",{title:r.rawTitle(s),className:`text-[10px] font-medium px-1.5 py-0.5 rounded shrink-0 ${s.className}`,children:r.badge(s)}),(0,t.jsx)("span",{title:r.rawTitle(n),className:`text-[10px] font-medium px-1.5 py-0.5 rounded shrink-0 ${n.className}`,children:r.badge(n)})]}),(0,t.jsxs)("div",{className:"text-xs text-foreground font-mono tabular-nums text-right shrink-0",children:[i.rawUsd(e.sizeUsd),null!=e.avgFillPrice?` @ ${i.rawPrice(e.avgFillPrice)}`:""]})]})}function ta({row:e,onOpenChange:r}){var i;let s=(i=e?.orderPda??null,(0,z.useQuery)({queryKey:["order-history-detail",i],queryFn:()=>Q(i),enabled:!!i,staleTime:3e4})),n=e?{...e,...s.data??{}}:null;return(0,t.jsx)(tl,{row:n,onOpenChange:r,isLoading:s.isLoading,isError:s.isError})}function tl({row:e,onOpenChange:r,isLoading:i=!1,isError:s=!1}){var n;let a,l=(0,m.useTranslations)("positions"),o=(0,m.useTranslations)("terms"),d=eK(),c=(0,eJ.useFormatters)(),u=!1===(0,el.useIsDesktop)();if(!e)return(0,t.jsx)(e8.Sheet,{open:!1,onOpenChange:r,children:(0,t.jsx)(e8.SheetContent,{side:u?"bottom":"right"})});let h=(0,L.getTokenInfo)(e.marketMint),f="long"===e.side,x=eA(e.orderType,e.dca),g=eT(e.displayStatus),b=e.underwriter?(0,ey.getVenueIcon)(e.underwriter):null,v=eR(e.orderType),y=e.events??[],w=e.fills??[],j=e.children??[],S=!i&&eC(e.displayStatus)&&null==e.statusReason&&0===y.length,k=null!=e.sizeUsd?parseFloat(e.sizeUsd):NaN,N=null!=e.filledSizeUsd?parseFloat(e.filledSizeUsd):NaN,P=isNaN(k)||isNaN(N)?null:Math.max(k-N,0),T=ts.has(e.orderType),C=null!=e.triggerPrice?parseFloat(e.triggerPrice):NaN,M=null!=e.avgFillPrice?parseFloat(e.avgFillPrice):NaN,_=!T||isNaN(C)||isNaN(M)?null:M-C,A=y.find(e=>"order_executed"===e.eventType),E=A?.timestamp??e.executedAt??null,F=isNaN(M)?parseFloat(e.executionTriggerPrice??e.triggerPrice??""):M,R=E??e.executedAt,D=null!=R&&isFinite(F);return(0,t.jsx)(e8.Sheet,{open:!!e,onOpenChange:r,children:(0,t.jsxs)(e8.SheetContent,{side:u?"bottom":"right",className:u?"bg-canvas border-border max-h-[85vh] overflow-y-auto":"bg-canvas border-border w-full sm:max-w-md overflow-y-auto",children:[(0,t.jsxs)(e8.SheetHeader,{className:"pb-0",children:[(0,t.jsx)(e8.SheetTitle,{className:"text-foreground",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 flex-wrap",children:[(0,t.jsx)("span",{title:d.rawTitle(x),className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${x.className}`,children:d.badge(x)}),h.image&&(0,t.jsx)(ef.default,{src:h.image,alt:h.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-sm",children:h.symbol}),(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${f?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:f?l("historyLongUpper"):l("historyShortUpper")}),(0,t.jsx)("span",{title:d.rawTitle(g),className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${g.className}`,children:d.badge(g)})]})}),e.statusReason&&(0,t.jsx)("div",{className:"text-xs text-muted-foreground mt-1",children:e.statusReason}),D&&(0,t.jsxs)("button",{onClick:()=>
2{if(!D||null==R)return;let t=e.executionTriggerPrice??e.triggerPrice;(0,e6.showFillOnChart)({marketMint:e.marketMint,symbol:h.symbol,venue:e.underwriter,hedgeVenue:e.hedgeVenue,timestampSec:R,price:F,locale:c.intlTag,triggerPrice:T&&null!=t?parseFloat(t):null}),r(!1)},className:"mt-1.5 inline-flex items-center gap-1.5 self-start text-xs text-blue-400 hover:text-blue-300",children:[(0,t.jsx)(e4.ChartCandlestick,{className:"w-3.5 h-3.5"}),l("historyShowFillOnChart")]}),S&&(0,t.jsx)("div",{className:"text-[10px] text-label-muted mt-1",children:l("historyNoHistoryNote")})]}),(0,t.jsxs)("div",{className:"px-4 pb-6 space-y-3",children:[i&&(0,t.jsx)("div",{className:"flex items-center justify-center py-2",children:(0,t.jsx)(p.Loader2,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),s&&(0,t.jsx)("div",{className:"text-[10px] text-red-400/80",children:l("historyDetailLoadError")}),(0,t.jsxs)(eQ,{title:l("historySectionIdentifiers"),children:[(0,t.jsx)(eX,{label:l("historyRowOrder"),children:(0,t.jsx)(eY,{value:e.orderPda})}),e.venueOrderId&&(0,t.jsx)(eX,{label:l("historyRowVenueOrderId"),children:(0,t.jsx)("span",{className:"font-mono",children:eq(e.venueOrderId)})}),(0,t.jsx)(eX,{label:l("historyRowVenue"),children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[b&&(0,t.jsx)(ef.default,{src:b.src,alt:b.alt,width:14,height:14,className:"rounded-full",unoptimized:!0}),b?.alt??e.underwriter??"—"]})})]}),(0,t.jsxs)(eQ,{title:l("historySectionTiming"),children:[(0,t.jsx)(eX,{label:l("historyRowSubmitted"),children:c.dateTime(e.createdAt)}),(0,t.jsx)(eX,{label:l("historyRowExecuted"),children:null!=e.executedAt?c.dateTime(e.executedAt):"—"}),(0,t.jsx)(eX,{label:l("historyRowCanceled"),children:null!=e.cancelledAt?c.dateTime(e.cancelledAt):"—"})]}),(0,t.jsxs)(eQ,{title:l("historySectionSizing"),children:[(0,t.jsx)(eX,{label:l("historyRowOriginalSize"),children:c.rawUsd(e.sizeUsd)}),(0,t.jsx)(eX,{label:l("historyColFilled"),children:c.rawUsd(e.filledSizeUsd)}),(0,t.jsx)(eX,{label:l("historyRowRemaining"),children:null!=P?c.rawUsd(P.toFixed(2)):"—"}),(0,t.jsx)(eX,{label:l("historyAvgFillPrice"),children:c.rawPrice(e.avgFillPrice)}),(0,t.jsx)(eX,{label:l("historyRowFees"),children:c.rawUsd(e.feesUsd)})]}),(0,t.jsxs)(eQ,{title:l("historySectionPrices"),children:[T?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eX,{label:l("historyRowTriggerPrice"),children:c.rawPrice(e.triggerPrice)}),(0,t.jsx)(eX,{label:l("historyAvgFillPrice"),children:c.rawPrice(e.avgFillPrice)}),(0,t.jsx)(eX,{label:l("historyRowSlippage"),children:null!=_?(0,t.jsx)("span",{className:0===_?void 0:_>0?"text-side-long":"text-side-short",children:(n=c.intlTag,a=Math.abs(_).toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:6}),`${_>=0?"+":"-"}$${a}`)}):"—"}),(0,t.jsx)(eX,{label:l("historyRowTimeTriggered"),children:null!=E?c.dateTime(E):"—"})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eX,{label:l("historyRowLimitPrice"),children:c.rawPrice(e.triggerPrice)}),(0,t.jsx)(eX,{label:l("historyAvgFillPrice"),children:c.rawPrice(e.avgFillPrice)})]}),null!=e.executionTriggerPrice&&(0,t.jsx)(eX,{label:l("historyRowExecutionTrigger"),children:c.rawPrice(e.executionTriggerPrice)})]}),"dca"===v&&(0,t.jsx)(tt,{detail:e}),"trailing"===v&&(0,t.jsx)(tr,{detail:e}),"rsi"===v&&(0,t.jsx)(ti,{detail:e}),w.length>0&&(0,t.jsx)(eQ,{title:l("historySectionFills"),children:(0,t.jsxs)("table",{className:"w-full text-xs",children:[(0,t.jsx)("thead",{className:"text-[10px] text-label-muted",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{className:"py-1 text-left font-normal",children:l("historyColTime")}),(0,t.jsx)("th",{className:"py-1 text-right font-normal",children:o("size.full")}),(0,t.jsx)("th",{className:"py-1 text-right font-normal",children:l("historyColPrice")}),(0,t.jsx)("th",{className:"py-1 text-right font-normal",children:l("historyRowFees")}),(0,t.jsx)("th",{className:"py-1 text-right font-normal",children:"Tx"})]})}),(0,t.jsx)("tbody",{children:w.map((e,r)=>(0,t.jsxs)("tr",{className:"border-t border-border/50",children:[(0,t.jsx)("td",{className:"py-1.5 text-muted-foreground whitespace-nowrap",children:c.dateTime(e.time)}),(0,t.jsx)("td",{className:"py-1.5 text-right text-foreground font-mono tabular-nums",children:c.rawUsd(e.sizeUsd)}),(0,t.jsx)("td",{className:"py-1.5 text-right text-foreground font-mono tabular-nums",children:c.rawPrice(e.price)}),(0,t.jsx)("td",{className:"py-1.5 text-right text-foreground font-mono tabular-nums",children:c.rawUsd(e.feesUsd)}),(0,t.jsx)("td",{className:"py-1.5 text-right",children:e.txSignature?(0,t.jsx)("a",{href:`${e9.EXPLORER_BASE}${e.txSignature}`,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-blue-400 hover:text-blue-300",children:(0,t.jsx)(e3.ExternalLink,{className:"w-3 h-3"})}):(0,t.jsx)("span",{className:"text-label-muted",children:"—"})})]},r))})]})}),y.length>0&&(0,t.jsx)(eQ,{title:l("historySectionEventLog"),children:(0,t.jsx)("div",{className:"space-y-0",children:y.map((e,r)=>{let i=eV(e,c.intlTag,d.eventSummary),s=eO(e.eventType),n=!eB(e.eventType);return(0,t.jsxs)("div",{className:"relative pl-4 pb-3 border-l border-border last:pb-0",children:[(0,t.jsx)("span",{className:"absolute -left-[3.5px] top-1 h-1.5 w-1.5 rounded-full bg-surface-interactive"}),(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-foreground",title:d.rawTitle(s),children:d.label(s)}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted whitespace-nowrap",children:c.dateTime(e.timestamp)})]}),i&&(0,t.jsx)("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:i}),e.signature&&(0,t.jsxs)("a",{href:`${e9.EXPLORER_BASE}${e.signature}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[10px] text-blue-400 hover:text-blue-300 mt-0.5",children:[l("historyViewTx")," ",(0,t.jsx)(e3.ExternalLink,{className:"w-2.5 h-2.5"})]}),n&&null!=e.payload&&(0,t.jsx)("pre",{className:"mt-1 text-[10px] font-mono text-label-muted bg-surface rounded p-1.5 overflow-x-auto",children:JSON.stringify(e.payload,null,2)})]},r)})})}),j.length>0&&(0,t.jsx)(eQ,{title:l("historyChildOrders",{count:String(j.length)}),children:j.map(e=>(0,t.jsx)(tn,{child:e},e.orderPda))})]})]})})}var to=e.i(884629),td=e.i(575146),tc=e.i(153517),tu=e.i(190459);let th=tu.ALL_ROW_VENUES.filter(e=>"armada"!==e).map(e=>
2({value:e,label:ey.VENUE_LABELS[e]})),tp=[{value:"all",labelKey:"historyAll"},{value:"standard",labelKey:"historyCategoryStandard"},{value:"dca",label:"DCA"},{value:"trailing",labelKey:"historyOrderTypeTrailing"},{value:"rsi",label:"RSI"}],tm=[["ALL","historyAll"],["WTD","historyPeriodWtd"],["MTD","historyPeriodMtd"],["YTD","historyPeriodYtd"],["CUSTOM","historyPeriodCustom"]];function tf(e){return"all"!==e.market||"all"!==e.underwriter||"all"!==e.side||"all"!==e.status||"all"!==e.category||"ALL"!==e.period}function tx({filters:e,onFiltersChange:r,onReset:i,availableMarkets:s}){let n=(0,m.useTranslations)("positions"),a=tf(e),l=(e,t="bg-surface-interactive text-foreground")=>(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e?t:"bg-surface-raised text-muted-foreground hover:text-foreground");return(0,t.jsxs)(td.Popover,{children:[(0,t.jsx)(td.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{className:"relative p-1.5 rounded hover:bg-surface-interactive transition-colors text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(to.SlidersHorizontal,{className:"h-3.5 w-3.5"}),a&&(0,t.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-orange-500"})]})}),(0,t.jsx)(td.PopoverContent,{side:"bottom",align:"start",sideOffset:8,updatePositionStrategy:"always",className:"w-72 max-h-[70vh] overflow-y-auto p-3 !animate-none !duration-0",children:(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionMarket")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({market:"all"}),className:l("all"===e.market),children:n("historyAll")}),s.map(i=>{let s=(0,L.getTokenInfo)(i);return(0,t.jsx)("button",{onClick:()=>r({market:i}),className:l(e.market===i),children:s.symbol},i)})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionVenue")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({underwriter:"all"}),className:l("all"===e.underwriter),children:n("historyAll")}),th.map(({value:i,label:s})=>{let n=(0,ey.getVenueIcon)(i);return(0,t.jsxs)("button",{onClick:()=>r({underwriter:i}),className:(0,tc.cn)(l(e.underwriter===i),"flex items-center gap-1"),children:[n&&(0,t.jsx)(ef.default,{src:n.src,alt:n.alt,width:12,height:12,className:"rounded-full",unoptimized:!0}),s]},i)})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionSide")}),(0,t.jsx)("div",{className:"flex gap-1",children:["all","long","short"].map(i=>(0,t.jsx)("button",{onClick:()=>r({side:i}),className:(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e.side===i?"long"===i?"bg-side-long/20 text-side-long":"short"===i?"bg-side-short/20 text-side-short":"bg-surface-interactive text-foreground":"long"===i?"bg-surface-raised text-side-long/85 hover:text-side-long":"short"===i?"bg-surface-raised text-side-short/85 hover:text-side-short":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:"all"===i?n("historyAll"):"long"===i?n("historyLong"):n("historyShort")},i))})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionStatus")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({status:"all"}),className:l("all"===e.status),children:n("historyAll")}),eN.map(i=>{let s=ek[i];return(0,t.jsx)("button",{onClick:()=>r({status:i}),className:l(e.status===i,s.className),children:s.labelKey?n(s.labelKey):s.label},i)})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionType")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:tp.map(i=>(0,t.jsx)("button",{onClick:()=>r({category:i.value}
2),className:l(e.category===i.value),children:"labelKey"in i?n(i.labelKey):i.label},i.value))})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionDate")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:tm.map(([i,s])=>(0,t.jsx)("button",{onClick:()=>r({period:i}),className:l(e.period===i),children:n(s)},i))}),"CUSTOM"===e.period&&(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-1.5",children:[(0,t.jsx)("input",{type:"date",value:e.customDateFrom??"",onChange:e=>r({customDateFrom:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"}),(0,t.jsx)("span",{className:"text-xs text-label-muted",children:n("historyDateRangeTo")}),(0,t.jsx)("input",{type:"date",value:e.customDateTo??"",onChange:e=>r({customDateTo:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsx)("button",{onClick:i,className:"w-full py-1.5 text-xs rounded bg-surface-raised text-muted-foreground hover:text-foreground hover:bg-surface-interactive transition-colors",children:n("historyResetFilters")})]})})]})}function tg({controls:e,totalCount:r=0}){let i=(0,m.useTranslations)("positions"),s=(0,m.useTranslations)("terms");return(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsxs)("th",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[i("historyRowOrder"),e]}),r>0&&(0,t.jsx)("div",{className:"text-[10px] text-muted-foreground font-normal font-mono tabular-nums",children:i("historyOrderCount",{count:r,amount:String(r)})})]}),(0,t.jsx)("th",{children:i("historySectionDate")}),(0,t.jsx)("th",{children:i("historyColPriceCondition")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:s("size.full")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:i("historyColFilled")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:i("historyColAvgFill")}),(0,t.jsx)("th",{children:i("historyColStatus")}),(0,t.jsx)("th",{children:(0,t.jsx)("span",{className:"sr-only",children:i("columnActions")})})]})})}function tb(){let e=(0,m.useTranslations)("positions"),r=(0,m.useTranslations)("terms");return(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{children:e("historyColMarket")}),(0,t.jsx)("th",{children:e("historyColTime")}),(0,t.jsx)("th",{children:e("historySectionSide")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:r("size.full")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:e("historyColRate")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:e("historyColPayment")}),(0,t.jsx)("th",{children:e("historySectionVenue")}),(0,t.jsx)("th",{children:(0,t.jsx)("span",{className:"sr-only",children:e("columnActions")})})]})})}function tv(){let e=(0,m.useTranslations)("positions");return(0,t.jsx)("thead",{className:"border-b border-border text-xs text-label-muted sticky top-0 bg-canvas z-10",children:(0,t.jsxs)("tr",{children:[(0,t.jsx)("th",{children:e("historyColToken")}),(0,t.jsx)("th",{children:e("historyColTime")}),(0,t.jsx)("th",{children:e("historySectionType")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:e("historyColAmount")}),(0,t.jsx)("th",{className:eZ.default.numeric,children:e("historyColValue")}),(0,t.jsx)("th",{children:e("historySectionProfile")}),(0,t.jsx)("th",{children:(0,t.jsx)("span",{className:"sr-only",children:e("columnActions")})})]})})}e.s(["DepositHistoryTableHead",0,tv,"FundingHistoryTableHead",0,tb,"OrderHistoryTableHead",0,tg],146911);let ty={market:"order-history-market",underwriter:"order-history-venue",side:"order-history-side",status:"order-history-status",category:"order-history-category",period:"order-history-period",customDateFrom:"order-history-date-from",customDateTo:"order-history-date-to"};function tw(){let e=(0,m.useTranslations)("positions"),{publicKey:r}=(0,y.useUnifiedWallet)(),i=(0,d.useMemo)(()=>r?.toBase58()??null,[r]),{status:s,isLoading:n}=(0,M.useApiHealth)(),a=!n&&s?.db!=="healthy",l=(0,el.useIsDesktop)(),{filters:o,setFilters:c,resetFilters:u}=ea(ty,V),h=tf(o),{orders:p,totalCount:f,hasMore:x,isFetchingNextPage:g,fetchNextPage:b,isLoading:v,error:w,refetch:j}=function({walletAddress:e,filters:t}){let r=(0,d.useMemo)(()=>W(t),[t]),{items:i,firstPage:s,...n}=et({queryKey:["order-history",e,r],enabled:!!e,fetchPage:async(t,i)=>e?X(e,{limit:i,offset:t,params:r}
2):er,pageItems:ei,pageTotalCount:es,itemId:en});return{orders:i,totalCount:s?.totalCount??0,...n}}({walletAddress:i,filters:o}),S=(0,d.useMemo)(()=>{let e=new Set(p.map(e=>e.marketMint));return"all"!==o.market&&e.add(o.market),Array.from(e)},[p,o.market]),[k,N]=(0,d.useState)(null);if(a)return(0,t.jsx)(ed,{label:e("historyLabelOrderHistory")});let P=(0,t.jsx)(tx,{filters:o,onFiltersChange:c,onReset:u,availableMarkets:S}),T=eu({isLoading:v,error:w,isEmpty:0===p.length,filtersActive:h,onRetry:()=>j(),onReset:u,errorText:e("historyOrderLoadError"),emptyFilteredText:e("historyOrderEmptyFiltered"),emptyText:e("historyOrderEmpty")});return(0,t.jsxs)("div",{className:"h-full overflow-y-auto",children:[!1===l&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[P,(0,t.jsx)("span",{className:"text-xs text-label-muted font-mono tabular-nums",children:f>0?e("historyOrderCount",{count:f,amount:String(f)}):""})]}),T??(0,t.jsxs)("div",{className:"space-y-3 p-3",children:[p.map(e=>(0,t.jsx)(e5,{row:e,onOpenDetail:N},e.orderPda)),x&&(0,t.jsx)(ec,{onClick:()=>b(),isFetching:g,fullWidth:!0})]})]}),l&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:eZ.default.scroller,children:(0,t.jsxs)("table",{className:eZ.default.table,children:[(0,t.jsx)(tg,{controls:P,totalCount:f}),(0,t.jsx)("tbody",{children:T?(0,t.jsx)("tr",{children:(0,t.jsx)("td",{colSpan:8,children:T})}):p.map(e=>(0,t.jsx)(e2,{row:e,onOpenDetail:N},e.orderPda))})]})}),!T&&x&&(0,t.jsx)("div",{className:"flex justify-center py-3 border-t border-border",children:(0,t.jsx)(ec,{onClick:()=>b(),isFetching:g})})]}),(0,t.jsx)(ta,{row:k,onOpenChange:e=>{e||N(null)}})]})}var tj=e.i(873029);let tS={market:"all",underwriter:"all",side:"all",direction:"all",period:"ALL",customDateFrom:null,customDateTo:null};function tk(e,t=new Date){let r={},i=(e,t)=>{t&&"all"!==t&&(r[e]=t)};i("market",e.market),i("underwriter",e.underwriter),i("side",e.side),i("direction",e.direction);let{from:s,to:n}=H(e.period,e.customDateFrom,e.customDateTo,t);return null!=s&&(r.from=String(s)),null!=n&&(r.to=String(n)),r}function tN(e){let t=null!=e.rate&&null!=e.rateScale?Number(e.rate)/10**e.rateScale:NaN;return{id:e.id,lifecycleId:e.lifecycleId,actionId:e.actionId??null,underwriter:e.underwriter,marketMint:e.marketMint,symbol:e.symbol,side:e.side,eventType:e.eventType,amountUsd:q(e.amount,1e6)??"0",positionSizeUsd:q(e.positionSizeUsd,1e6),positionSizeAfterUsd:q(e.positionSizeAfterUsd,1e6),effectiveRatePerSec:Number.isFinite(t)?t:null,spanStart:e.spanStart??null,spanEnd:e.spanEnd??null,signature:e.signature??null,eventAt:e.eventAt,payload:e.payload??null}}async function tP(e,t={}){let r=new URLSearchParams({walletAddress:e,limit:String(t.limit??50),offset:String(t.offset??0)});for(let[e,i]of Object.entries(t.params??{}))r.set(e,i);let i=await fetch(`https://api.imperial.space/api/v1/funding-history?${r}`,{cache:"no-store"});if(!i.ok)throw Error(`Failed to fetch funding history: ${i.status}`);let s=await i.json();return{events:(s.events??[]).map(tN),totalCount:s.totalCount??0,aggregates:{totalPaid:q(s.aggregates?.totalPaid,1e6)??"0",totalReceived:q(s.aggregates?.totalReceived,1e6)??"0",net:q(s.aggregates?.net,1e6)??"0"}}}e.s(["DEFAULT_FUNDING_HISTORY_FILTERS",0,tS,"buildFundingHistoryParams",0,tk,"fetchFundingHistory",0,tP],115887);let tT={events:[],totalCount:0,aggregates:{totalPaid:"0",totalReceived:"0",net:"0"}},tC=e=>e.events,tM=e=>e.totalCount,t_=e=>e.id,tA={jupiter:{venue:"Jupiter",labelKey:"historyFundingKindBorrow",kind:"borrow",hourlyQuote:!0,canReceive:!1},flash_trade:{venue:"Flash",labelKey:"historyFundingKindBorrow",kind:"borrow",hourlyQuote:!0,canReceive:!1},flash_v2:{venue:"Flash",labelKey:"historyFundingKindBorrow",kind:"borrow",hourlyQuote:!0,canReceive:!1},gmtrade:{venue:"GMTrade",labelKey:"historyFundingKindFunding",kind:"funding",hourlyQuote:!0,canReceive:!0},phoenix:{venue:"Phoenix",labelKey:"historyFundingKindFunding",kind:"funding",hourlyQuote:!0,canReceive:!0},pairs:{venue:"Pairs",labelKey:"historyFundingKindSkewFunding",kind:"funding",hourlyQuote:!1,canReceive:!0},sunrise:{venue:"Imperial",labelKey:"historyFundingKindFunding",kind:"funding",hourlyQuote:!0,canReceive:!0}};function tE(e){let t=tA[e.underwriter];if(t)return{key:"gmtrade"===e.underwriter&&"borrow_settled"===e.eventType?"historyFundingKindBorrow":t.labelKey,values:{venue:t.venue}};let r=e.underwriter.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");return{key:"funding_settled"===e.eventType?"historyFundingKindFunding":"historyFundingKindBorrow",values:{venue:r}}}
2function tL(e,t){return`$${e.toLocaleString((0,ej.intlTag)(t),{minimumFractionDigits:2,maximumFractionDigits:6})}`}function tF(e,t){let r=parseFloat(e);if(!Number.isFinite(r)||0===r)return{label:{text:ej.UNKNOWN_VALUE},className:"text-label-muted"};let i=tL(Math.abs(r),t);return r>0?{label:{key:"historyFundingPaidAmount",values:{amount:i}},className:"text-side-short"}:{label:{key:"historyFundingReceivedAmount",values:{amount:i}},className:"text-side-long"}}function tR(e){if(!Number.isFinite(e)||e<=0)return ej.UNKNOWN_VALUE;if(e<60)return"<1m";let t=Math.floor(e/86400),r=Math.floor(e%86400/3600),i=Math.floor(e%3600/60);return t>0?`${t}d ${r}h`:r>0?`${r}h ${i}m`:`${i}m`}function tD(e,t){let r=Number(e>=1?e.toFixed(2):e.toPrecision(2)),i=(String(r).split(".")[1]??"").length;return r.toLocaleString((0,ej.intlTag)(t),{useGrouping:!1,minimumFractionDigits:i,maximumFractionDigits:i})}function tI(e,t){let r=e.effectiveRatePerSec;if(null==r)return{text:ej.UNKNOWN_VALUE};let i=null!=e.spanStart&&null!=e.spanEnd&&e.spanEnd>e.spanStart?e.spanEnd-e.spanStart:null;if(tA[e.underwriter]?.hourlyQuote??!0){let e=`${tD(3600*Math.abs(r)*100,t)}%/hr`;return null!=i?{key:"historyFundingRateOverSpan",values:{rate:e,span:tR(i)}}:{text:e}}return null==i?{text:ej.UNKNOWN_VALUE}:{key:"historyFundingRateOverSpan",values:{rate:`${tD(Math.abs(r)*i*100,t)}%`,span:tR(i)}}}function tU({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=eG(),n=(0,eJ.useFormatters)(),a=(0,L.getTokenInfo)(e.marketMint),l=e.symbol||a.symbol,o="long"===e.side,d=tF(e.amountUsd,n.intlTag),c=(0,ey.getVenueIcon)(e.underwriter,e.hedgeVenue);return(0,t.jsxs)("tr",{className:"border-b border-border cursor-pointer hover:bg-surface-interactive/30 transition-colors",onClick:()=>r(e),children:[(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsxs)("div",{className:eZ.default.identityPrimary,children:[a.image&&(0,t.jsx)(ef.default,{src:a.image,alt:l,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:l})]})}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground whitespace-nowrap",children:n.dateTime(e.eventAt)}),(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsx)("span",{className:`text-xs font-medium px-2 py-0.5 rounded whitespace-nowrap ${o?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i(o?"historyLongUpper":"historyShortUpper")})}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums`,children:n.rawUsd(e.positionSizeUsd)}),(0,t.jsx)("td",{className:eZ.default.numeric,children:(0,t.jsxs)("div",{className:eZ.default.stack,children:[(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:s.rate(tI(e,n.intlTag))}),(0,t.jsx)("div",{className:"text-label-muted",children:s.venue(tE(e))})]})}),(0,t.jsx)("td",{className:`${eZ.default.numeric} font-mono tabular-nums whitespace-nowrap ${d.className}`,children:s.payment(d)}),(0,t.jsx)("td",{className:"py-3 px-3",children:c&&(0,t.jsx)(ef.default,{src:c.src,alt:c.alt,title:c.alt,width:14,height:14,className:"rounded-full",unoptimized:!0})}),(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsx)("button",{onClick:t=>{t.stopPropagation(),r(e)},className:eZ.default.detailButton,"aria-label":i("historyFundingDetailsAria"),children:(0,t.jsx)(ex.ChevronRight,{className:"w-3.5 h-3.5"})})})]})}function tO({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=(0,m.useTranslations)("terms"),n=eG(),a=(0,eJ.useFormatters)(),l=(0,L.getTokenInfo)(e.marketMint),o=e.symbol||l.symbol,d="long"===e.side,c=tF(e.amountUsd,a.intlTag),u=n.payment(c),h=(0,ey.getVenueIcon)(e.underwriter,e.hedgeVenue);return(0,t.jsxs)("div",{role:"button",tabIndex:0,"aria-label":"text"in c.label?i("historyFundingCardAria",{symbol:o,side:e.side}):i("historyFundingCardAriaWithPayment",{symbol:o,side:e.side,payment:u}),className:"bg-surface border border-border rounded-lg px-3 py-3 cursor-pointer active:bg-surface-interactive/50",onClick:()=>r(e),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),r(e))},children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,t.jsx)("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${d?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i(d?"historyLongUpper":"historyShortUpper")}
2),l.image&&(0,t.jsx)(ef.default,{src:l.image,alt:o,width:14,height:14,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:o})]}),(0,t.jsx)("span",{className:`text-xs font-mono tabular-nums ${c.className}`,children:u})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1.5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:s("size.full")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:a.rawUsd(e.positionSizeUsd)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:i("historyColRate")}),(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:n.rate(tI(e,a.intlTag))})]})]}),(0,t.jsxs)("div",{className:"mt-2 flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:a.dateTime(e.eventAt)}),h&&(0,t.jsx)(ef.default,{src:h.src,alt:h.alt,width:14,height:14,className:"rounded-full",unoptimized:!0})]})]})}function tB({row:e,onOpenChange:r}){let i=(0,m.useTranslations)("positions"),s=(0,m.useTranslations)("terms"),n=eG(),a=(0,eJ.useFormatters)(),l=!1===(0,el.useIsDesktop)();if(!e)return(0,t.jsx)(e8.Sheet,{open:!1,onOpenChange:r,children:(0,t.jsx)(e8.SheetContent,{side:l?"bottom":"right"})});let o=(0,L.getTokenInfo)(e.marketMint),d=e.symbol||o.symbol,c="long"===e.side,u=tF(e.amountUsd,a.intlTag),h=n.payment(u),p=(0,ey.getVenueIcon)(e.underwriter,e.hedgeVenue),f=n.calculation(function(e,t){let r=null!=e.positionSizeUsd?parseFloat(e.positionSizeUsd):NaN,i=parseFloat(e.amountUsd);if(!Number.isFinite(r)||r<=0||!Number.isFinite(i)||0===i)return null;let s=(Math.abs(i)/r*100).toLocaleString((0,ej.intlTag)(t),{useGrouping:!1,minimumFractionDigits:4,maximumFractionDigits:4});return{key:i>0?"historyFundingCalculationPaid":"historyFundingCalculationReceived",values:{notional:`$${r.toLocaleString((0,ej.intlTag)(t),{minimumFractionDigits:2,maximumFractionDigits:2})}`,pct:s,amount:tL(Math.abs(i),t)}}}(e,a.intlTag)),x=null!=e.spanStart&&null!=e.spanEnd&&e.spanEnd>e.spanStart?e.spanEnd-e.spanStart:null,g=e.payload?.spanApprox===!0,b=Object.entries(e.payload??{}).filter(([e])=>"spanApprox"!==e);return(0,t.jsx)(e8.Sheet,{open:!!e,onOpenChange:r,children:(0,t.jsxs)(e8.SheetContent,{side:l?"bottom":"right",className:l?"bg-canvas border-border max-h-[85vh] overflow-y-auto":"bg-canvas border-border w-full sm:max-w-md overflow-y-auto",children:[(0,t.jsx)(e8.SheetHeader,{className:"pb-0",children:(0,t.jsx)(e8.SheetTitle,{className:"text-foreground",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 flex-wrap",children:[o.image&&(0,t.jsx)(ef.default,{src:o.image,alt:d,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-sm",children:d}),(0,t.jsx)("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${c?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:i(c?"historyLongUpper":"historyShortUpper")}),(0,t.jsx)("span",{className:`text-xs font-mono tabular-nums ${u.className}`,children:h})]})})}),(0,t.jsxs)("div",{className:"px-4 pb-6 space-y-3",children:[(0,t.jsxs)(eQ,{title:i("historySectionPosition"),children:[(0,t.jsx)(eX,{label:i("historyColMarket"),children:d}),(0,t.jsx)(eX,{label:i("historySectionSide"),children:i(c?"historyLong":"historyShort")}),(0,t.jsx)(eX,{label:s("size.full"),children:a.rawUsd(e.positionSizeUsd)}),null!=e.positionSizeAfterUsd&&(0,t.jsx)(eX,{label:i("historyRowSizeAfter"),children:a.rawUsd(e.positionSizeAfterUsd)}),(0,t.jsx)(eX,{label:i("historyRowPositionId"),children:(0,t.jsx)(eY,{value:e.lifecycleId})})]}),(0,t.jsxs)(eQ,{title:i("historySectionFunding"),children:[(0,t.jsx)(eX,{label:i("historySectionType"),children:n.venue(tE(e))}),(0,t.jsx)(eX,{label:i("historyColRate"),children:n.rate(tI(e,a.intlTag))}),(0,t.jsx)(eX,{label:i("historyRowInterval"),children:null!=e.spanStart&&null!=e.spanEnd?(0,t.jsxs)("span",{children:[a.dateTime(e.spanStart)," → ",a.dateTime(e.spanEnd),null!=x?` (${tR(x)})`:""]}):"—"}),g&&(0,t.jsx)("div",{className:"text-[10px] text-label-muted py-0.5",children:i("historyIntervalApproxNote")}),f&&(0,t.jsx)("div",{className:"text-[10px] text-muted-foreground font-mono tabular-nums py-0.5",children:f}),(0,t.jsx)(eX,{label:i("historyColPayment"),children:(0,t.jsx)("span",{className:u.className,children:h})})]}),(0,t.jsxs)(eQ,{title:i("historySectionSettlement"),children:[(0,t.jsx)(eX,{label:i("historyRowSettled"),children:a.dateTime(e.eventAt)}),(0,t.jsx)(eX,{label:i("historySectionVenue"),children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[p&&(0,t.jsx)(ef.default,{src:p.src,alt:p.alt,width:14,height:14,className:"rounded-full",unoptimized:!0}),p?.alt??e.underwriter]})}),(0,t.jsx)(eX,{label:i("historyRowTransaction"),children:e.signature?(0,t.jsxs)("a",{href:`${e9.EXPLORER_BASE}${e.signature}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-blue-400 hover:text-blue-300",children:[eq(e.signature)," ",(0,t.jsx)(e3.ExternalLink,{className:"w-3 h-3"})]}):"—"})]}),b.length>0&&(0,t.jsx)(eQ,{title:i("historySectionVenueDetail"),children:b.map(([e,r])=>(0,t.jsx)(eX,{label:e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s]+/).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),children:(0,t.jsx)("span",{className:"font-mono text-[11px]",children:null==r?"—":"object"==typeof r?JSON.stringify(r):String(r)})},e))})]})]})})}let tz=tu.ALL_ROW_VENUES.filter(e=>"armada"!==e).map(e=>
2({value:e,label:ey.VENUE_LABELS[e]})),t$=[["ALL","historyAll"],["WTD","historyPeriodWtd"],["MTD","historyPeriodMtd"],["YTD","historyPeriodYtd"],["CUSTOM","historyPeriodCustom"]];function tV(e){return"all"!==e.market||"all"!==e.underwriter||"all"!==e.side||"all"!==e.direction||"ALL"!==e.period}function tH({filters:e,onFiltersChange:r,onReset:i,availableMarkets:s}){let n=(0,m.useTranslations)("positions"),a=tV(e),l=(e,t="bg-surface-interactive text-foreground")=>(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e?t:"bg-surface-raised text-muted-foreground hover:text-foreground");return(0,t.jsxs)(td.Popover,{children:[(0,t.jsx)(td.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{"aria-label":n("historyFundingFiltersAriaLabel"),className:"relative p-1.5 rounded hover:bg-surface-interactive transition-colors text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(to.SlidersHorizontal,{className:"h-3.5 w-3.5"}),a&&(0,t.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-orange-500"})]})}),(0,t.jsx)(td.PopoverContent,{side:"bottom",align:"start",sideOffset:8,updatePositionStrategy:"always",className:"w-72 max-h-[70vh] overflow-y-auto p-3 !animate-none !duration-0",children:(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historyColMarket")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({market:"all"}),className:l("all"===e.market),children:n("historyAll")}),s.map(i=>{let s=(0,L.getTokenInfo)(i);return(0,t.jsx)("button",{onClick:()=>r({market:i}),className:l(e.market===i),children:s.symbol},i)})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionVenue")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({underwriter:"all"}),className:l("all"===e.underwriter),children:n("historyAll")}),tz.map(({value:i,label:s})=>{let n=(0,ey.getVenueIcon)(i);return(0,t.jsxs)("button",{onClick:()=>r({underwriter:i}),className:(0,tc.cn)(l(e.underwriter===i),"flex items-center gap-1"),children:[n&&(0,t.jsx)(ef.default,{src:n.src,alt:n.alt,width:12,height:12,className:"rounded-full",unoptimized:!0}),s]},i)})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionSide")}),(0,t.jsx)("div",{className:"flex gap-1",children:["all","long","short"].map(i=>(0,t.jsx)("button",{onClick:()=>r({side:i}),className:(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e.side===i?"long"===i?"bg-side-long/20 text-side-long":"short"===i?"bg-side-short/20 text-side-short":"bg-surface-interactive text-foreground":"long"===i?"bg-surface-raised text-side-long/85 hover:text-side-long":"short"===i?"bg-surface-raised text-side-short/85 hover:text-side-short":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:"all"===i?n("historyAll"):"long"===i?n("historyLong"):n("historyShort")},i))})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionDirection")}),(0,t.jsx)("div",{className:"flex gap-1",children:["all","paid","received"].map(i=>(0,t.jsx)("button",{onClick:()=>r({direction:i}),className:(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e.direction===i?"paid"===i?"bg-side-short/20 text-side-short":"received"===i?"bg-side-long/20 text-side-long":"bg-surface-interactive text-foreground":"paid"===i?"bg-surface-raised text-side-short/85 hover:text-side-short":"received"===i?"bg-surface-raised text-side-long/85 hover:text-side-long":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:"all"===i?n("historyAll"):"paid"===i?n("historyDirectionPaid"):n("historyDirectionReceived")},i))})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionDate")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:t$.map(([i,s])=>(0,t.jsx)("button",{onClick:()=>r({period:i}),className:l(e.period===i),children:n(s)},i))}),"CUSTOM"===e.period&&(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-1.5",children:[(0,t.jsx)("input",{type:"date",value:e.customDateFrom??"",onChange:e=>r({customDateFrom:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"}),(0,t.jsx)("span",{className:"text-xs text-label-muted",children:n("historyDateRangeTo")}),(0,t.jsx)("input",{type:"date",value:e.customDateTo??"",onChange:e=>r({customDateTo:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsx)("button",{onClick:i,className:"w-full py-1.5 text-xs rounded bg-surface-raised text-muted-foreground hover:text-foreground hover:bg-surface-interactive transition-colors",children:n("historyResetFilters")})]})})]})}function tW(e,t,r){let{position:i}=e,s=i.fundingRateHourlyPercent;if(null!=s){let e=parseFloat(s);if(Number.isFinite(e))return r.perHourNow((0,eb.formatFixed)(Math.abs(e),Math.abs(e)>=1?2:4,t))}let n=function(e){let t=e.accruedFundingFrom??e.lastActionAt;if(null==t)return null;let r=Math.floor(Date.now()/1e3)-t;return r>0?r:null}(i);return null!=n?r.overSpan(tR(n)):null}function tq(){let e=(0,m.useTranslations)("positions");return{perHourNow:t=>e("historyRatePerHourNow",{pct:t}),overSpan:t=>e("historyRateOverSpan",{span:t})}}function tK({accrual:e}){let r=(0,m.useTranslations)("positions"),i=eG(),s=tq(),n=(0,eJ.useFormatters)(),{position:a,value:l}=e,o=(0,L.getTokenInfo)(a.asset),d=a.asset||o.symbol,c="long"===a.side,u=tF(String(l),n.intlTag),h=a.underwriter?(0,ey.getVenueIcon)(a.underwriter,a.hedgeVenue):null,p=a.underwriter?tA[a.underwriter]:void 0,f=p?r(p.labelKey,{venue:p.venue}):r("historyFundingFallbackLabel"),x=tW(e,n.intlTag,s);return(0,t.jsxs)("tr",{"data-funding-pending":!0,className:"border-b border-border/60 bg-surface-interactive/10",children:[(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsxs)("div",{className:eZ.default.identityPrimary,children:[o.image&&(0,t.jsx)(ef.default,{src:o.image,alt:d,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:d})]})}),(0,t.jsx)("td",{className:"py-3 px-3 whitespace-nowrap",children:(0,t.jsx)("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30",children:r("historyAccruing")})}),(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsx)("span",{className:`text-xs font-medium px-2 py-0.5 rounded whitespace-nowrap ${c?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:r(c?"historyLongUpper":"historyShortUpper")})}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums`,children:null!=a.sizeUsd?n.rawUsd(a.sizeUsd):"—"}),(0,t.jsx)("td",{className:eZ.default.numeric,children:(0,t.jsxs)("div",{className:eZ.default.stack,children:[(0,t.jsx)("div",{className:"text-xs text-foreground font-mono tabular-nums",children:x??"—"}),(0,t.jsx)("div",{className:"text-label-muted",children:f})]})}),(0,t.jsx)("td",{className:`${eZ.default.numeric} font-mono tabular-nums whitespace-nowrap ${u.className}`,children:(0,t.jsxs)("div",{className:eZ.default.stack,children:[(0,t.jsx)("div",{children:i.payment(u)}),(0,t.jsx)("div",{className:"text-label-muted",children:r("historyAccrualSoFarShort")})]})}),(0,t.jsx)("td",{className:"py-3 px-3",children:h&&(0,t.jsx)(ef.default,{src:h.src,alt:h.alt,title:h.alt,width:14,height:14,className:"rounded-full",unoptimized:!0})}),(0,t.jsx)("td",{className:"py-3 px-3"})]})}function tG({accrual:e}){let r=(0,m.useTranslations)("positions"),i=eG(),s=tq(),n=(0,eJ.useFormatters)(),{position:a,value:l}=e,o=(0,L.getTokenInfo)(a.asset),d=a.asset||o.symbol,c="long"===a.side,u=tF(String(l),n.intlTag),h=tW(e,n.intlTag,s);return(0,t.jsxs)("div",{className:"rounded-lg border border-amber-500/25 bg-surface-interactive/10 p-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[o.image&&(0,t.jsx)(ef.default,{src:o.image,alt:d,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:d}),(0,t.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${c?"bg-side-long/20 text-side-long":"bg-side-short/20 text-side-short"}`,children:r(c?"historyLongUpper":"historyShortUpper")})]}),(0,t.jsx)("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30",children:r("historyAccruing")})]}),(0,t.jsxs)("div",{className:"mt-2 flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:`text-xs font-mono tabular-nums ${u.className}`,children:i.payment(u)}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:h??""})]}),(0,t.jsx)("div",{className:"mt-1 text-[10px] text-label-muted",children:r("historyAccrualSoFarLong")})]})}let tY={market:"funding-history-market",underwriter:"funding-history-venue",side:"funding-history-side",direction:"funding-history-direction",period:"funding-history-period",customDateFrom:"funding-history-date-from",customDateTo:"funding-history-date-to"};function tX({positions:e}){let r=(0,m.useTranslations)("positions"),i=(0,eJ.useFormatters)(),{publicKey:s}=(0,y.useUnifiedWallet)(),n=(0,d.useMemo)(()=>s?.toBase58()??null,[s]),{status:a,isLoading:l}=(0,M.useApiHealth)(),o=!l&&a?.db!=="healthy",c=(0,el.useIsDesktop)(),{filters:u,setFilters:h,resetFilters:p}=ea(tY,tS),f=tV(u),{events:x,totalCount:g,aggregates:b,hasMore:v,isFetchingNextPage:w,fetchNextPage:j,isLoading:S,error:k,refetch:N}=function({walletAddress:e,filters:t}){let r=(0,d.useMemo)(()=>tk(t),[t]),{items:i,firstPage:s,...n}=et({queryKey:["funding-history",e,r],enabled:!!e,fetchPage:async(t,i)=>e?tP(e,{limit:i,offset:t,params:r}):tT,pageItems:tC,pageTotalCount:tM,itemId:t_});return{events:i,totalCount:s?.totalCount??0,aggregates:s?.aggregates??null,...n}}({walletAddress:n,filters:u}),P=(0,d.useMemo)(()=>{let e=new Set(x.map(e=>e.marketMint));return"all"!==u.market&&e.add(u.market),Array.from(e)},[x,u.market]),T=(0,d.useMemo)(()=>(e??[]).filter(e=>"open"===e.status),[e]),C=(0,d.useMemo)(()=>T.map(e=>{let t=e.accruedFundingUsd??e.borrowFeeOwed,r=null==t?NaN:parseFloat(t);return Number.isFinite(r)?{position:e,value:r}:null}).filter(e=>null!==e),[T]),_=(0,d.useMemo)(()=>C.length>0?C.reduce((e,t)=>
2e+t.value,0):null,[C]),A=(0,d.useMemo)(()=>f?[]:C.filter(e=>0!==e.value),[f,C]),[E,L]=(0,d.useState)(null);if(o)return(0,t.jsx)(ed,{label:r("historyLabelFundingHistory")});let F=null!=b?parseFloat(b.net):NaN,R=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-3 lg:px-4 py-2 border-b border-border",children:[(0,t.jsx)(tH,{filters:u,onFiltersChange:h,onReset:p,availableMarkets:P}),(0,t.jsx)("span",{className:"text-xs text-label-muted font-mono tabular-nums",children:g>0?r("historyEventCount",{count:g,amount:String(g)}):""}),null!=b&&g>0&&(0,t.jsxs)("div",{className:"flex items-center gap-3 text-xs font-mono tabular-nums",children:[(0,t.jsxs)("span",{className:"text-side-short",children:[r("historyDirectionPaid")," ",i.rawUsd(b.totalPaid)]}),(0,t.jsxs)("span",{className:"text-side-long",children:[r("historyDirectionReceived")," ",i.rawUsd(b.totalReceived)]}),Number.isFinite(F)&&(0,t.jsxs)("span",{className:F>0?"text-side-short":F<0?"text-side-long":"text-muted-foreground",children:[r(F>0?"historyNetPaid":F<0?"historyNetReceived":"historyAggregateNet")," ",i.rawUsd(String(Math.abs(F)))]}),(0,t.jsx)(eg.TooltipProvider,{children:(0,t.jsxs)(eg.Tooltip,{children:[(0,t.jsx)(eg.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("button",{className:"text-muted-foreground hover:text-foreground transition-colors","aria-label":r("historyPaymentConventionAria"),children:(0,t.jsx)(tj.Info,{className:"h-3 w-3"})})}),(0,t.jsx)(eg.TooltipContent,{side:"bottom",className:"max-w-xs text-xs",children:r("historyPaymentConvention")})]})})]})]}),D=null!=_&&0!==_&&(0,t.jsxs)("div",{className:"px-3 lg:px-4 py-2 border-b border-border",children:[(0,t.jsxs)("div",{className:"text-xs",children:[(0,t.jsxs)("span",{className:"text-label-muted",children:[r("historyAccruedFundingLabel")," "]}),(0,t.jsxs)("span",{className:`font-mono tabular-nums ${_>0?"text-side-short":_<0?"text-side-long":"text-muted-foreground"}`,children:[r(_>0?"historyAccruingPaying":"historyAccruingReceiving")," ",i.rawUsd(String(Math.abs(_)))]})]}),(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:r("historyAccrualNote")})]}),I=eu({isLoading:S,error:k,isEmpty:0===x.length&&0===A.length,filtersActive:f,onRetry:()=>N(),onReset:p,errorText:r("historyFundingLoadError"),emptyFilteredText:r("historyFundingEmptyFiltered"),emptyText:r("historyFundingEmpty")});return(0,t.jsxs)("div",{className:"h-full overflow-y-auto",children:[R,D,!1===c&&(I??(0,t.jsxs)("div",{className:"space-y-3 p-3",children:[A.map(e=>(0,t.jsx)(tG,{accrual:e},`pending-${e.position.id}`)),x.map(e=>(0,t.jsx)(tO,{row:e,onOpenDetail:L},e.id)),v&&(0,t.jsx)(ec,{onClick:()=>j(),isFetching:w,fullWidth:!0})]})),c&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:eZ.default.scroller,children:(0,t.jsxs)("table",{className:eZ.default.table,children:[(0,t.jsx)(tb,{}),(0,t.jsx)("tbody",{children:I?(0,t.jsx)("tr",{children:(0,t.jsx)("td",{colSpan:8,children:I})}):(0,t.jsxs)(t.Fragment,{children:[A.map(e=>(0,t.jsx)(tK,{accrual:e},`pending-${e.position.id}`)),x.map(e=>(0,t.jsx)(tU,{row:e,onOpenDetail:L},e.id))]})})]})}),!I&&v&&(0,t.jsx)("div",{className:"flex justify-center py-3 border-t border-border",children:(0,t.jsx)(ec,{onClick:()=>j(),isFetching:w})})]}),(0,t.jsx)(tB,{row:E,onOpenChange:e=>{e||L(null)}})]})}let tQ={market:"all",eventType:"all",period:"ALL",customDateFrom:null,customDateTo:null};function tJ(e,t=new Date){let r={},i=(e,t)=>{t&&"all"!==t&&(r[e]=t)};i("market",e.market),i("eventType",e.eventType);let{from:s,to:n}=H(e.period,e.customDateFrom,e.customDateTo,t);return null!=s&&(r.from=String(s)),null!=n&&(r.to=String(n)),r}function tZ(e){return{annotation:e.annotation??null,id:e.id,eventType:e.eventType,marketMint:e.marketMint,profileIndex:e.profileIndex,amountRaw:e.amount,amountUsd:q(e.amountUsd,1e6),counterparty:e.counterparty??null,counterpartyProfileIndex:e.counterpartyProfileIndex??null,signature:e.signature,eventAt:e.eventAt}}async function t0(e,t={}){let r=new URLSearchParams({walletAddress:e,limit:String(t.limit??50),offset:String(t.offset??0)});for(let[e,i]of Object.entries(t.params??{}))r.set(e,i);let i=await fetch(`https://api.imperial.space/api/v1/deposit-history?${r}`,{cache:"no-store"});if(!i.ok)throw Error(`Failed to fetch deposit history: ${i.status}`);let s=await i.json();return{events:(s.events??[]).map(tZ),totalCount:s.totalCount??0,aggregates:{totalIn:q(s.aggregates?.totalIn,1e6)??"0",totalOut:q(s.aggregates?.totalOut,1e6)??"0",net:q(s.aggregates?.net,1e6)??"0"}}}e.s(["DEFAULT_DEPOSIT_HISTORY_FILTERS",0,tQ,"buildDepositHistoryParams",0,tJ,"fetchDepositHistory",0,t0],775062);let t1={events:[],totalCount:0,aggregates:{totalIn:"0",totalOut:"0",net:"0"}},t2=e=>e.events,t5=e=>e.totalCount,t3=e=>e.id;var t4=e.i(124431);let t6={deposit:{labelKey:"historyDepositTypeDeposit",className:"bg-side-long/20 text-side-long"},external_deposit:{labelKey:"historyDepositTypeExternalDeposit",className:"bg-side-long/20 text-side-long"},withdrawal:{labelKey:"historyDepositTypeWithdrawal",className:"bg-side-short/20 text-side-short"},transfer_in:{labelKey:"historyDepositTypeTransferIn",className:"bg-surface-interactive text-foreground"},transfer_out:{labelKey:"historyDepositTypeTransferOut",className:"bg-surface-interactive text-foreground"}};function t8(e){let t=t6[e];return t||((0,eS.warnUnmapped)("deposit event type",e),{labelKey:"historyUnknownLabel",rawValue:e,className:eS.UNMAPPED_BADGE_CLASS})}function t9(e){let t=t4.PROFILE_TOKEN_MINTS.find(t=>t.mint.toBase58()===e);return t?{symbol:t.symbol,decimals:t.decimals,image:(0,ev.getFlashTokenImage)(t.symbol)}
2:{symbol:`${e.slice(0,4)}…`,decimals:6,image:null}}function t7(e){let t=`P${e.profileIndex}`;return null==e.counterpartyProfileIndex?t:"transfer_out"===e.eventType?`${t} → P${e.counterpartyProfileIndex}`:`P${e.counterpartyProfileIndex} → ${t}`}function re(e,t){let r=t9(e.marketMint),i=Number(e.amountRaw);if(!Number.isFinite(i)||0===i)return{text:"—",className:"text-label-muted"};let s=(Math.abs(i)/10**r.decimals).toLocaleString((0,ej.intlTag)(t),{minimumFractionDigits:2,maximumFractionDigits:6});return i>0?{text:`+${s} ${r.symbol}`,className:"text-side-long"}:{text:`-${s} ${r.symbol}`,className:"text-side-short"}}function rt({annotation:e}){return e?(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground whitespace-normal",children:e.relatedSignature?(0,t.jsxs)("a",{href:`${e9.EXPLORER_BASE}${encodeURIComponent(e.relatedSignature)}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[e.note," ",(0,t.jsx)(e3.ExternalLink,{className:"inline h-3 w-3"})]}):e.note}):null}function rr({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=(0,eJ.useFormatters)(),n=t9(e.marketMint),a=t8(e.eventType),l=i(a.labelKey),o=null==a.rawValue?void 0:i("historyUnknownRawTooltip",{value:a.rawValue}),d=re(e,s.intlTag);return(0,t.jsxs)("tr",{className:"border-b border-border cursor-pointer hover:bg-surface-interactive/30 transition-colors",onClick:()=>r(e),children:[(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsxs)("div",{className:eZ.default.identityPrimary,children:[n.image&&(0,t.jsx)(ef.default,{src:n.image,alt:n.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:n.symbol})]})}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-muted-foreground whitespace-nowrap",children:s.dateTime(e.eventAt)}),(0,t.jsxs)("td",{className:"py-3 px-3",children:[(0,t.jsx)("span",{title:o,className:`text-xs font-medium px-2 py-0.5 rounded whitespace-nowrap ${a.className}`,children:l}),(0,t.jsx)("div",{className:eZ.default.annotation,children:(0,t.jsx)(rt,{annotation:e.annotation})})]}),(0,t.jsx)("td",{className:`${eZ.default.numeric} font-mono tabular-nums whitespace-nowrap ${d.className}`,children:d.text}),(0,t.jsx)("td",{className:`${eZ.default.numeric} text-foreground font-mono tabular-nums whitespace-nowrap`,children:null!=e.amountUsd?s.rawUsd(String(Math.abs(parseFloat(e.amountUsd)))):"—"}),(0,t.jsx)("td",{className:"py-3 px-3 text-xs text-foreground font-mono tabular-nums whitespace-nowrap",children:t7(e)}),(0,t.jsx)("td",{className:"py-3 px-3",children:(0,t.jsx)("button",{onClick:t=>{t.stopPropagation(),r(e)},className:eZ.default.detailButton,"aria-label":i("historyTransferDetailsAria"),children:(0,t.jsx)(ex.ChevronRight,{className:"w-3.5 h-3.5"})})})]})}function ri({row:e,onOpenDetail:r}){let i=(0,m.useTranslations)("positions"),s=(0,eJ.useFormatters)(),n=t9(e.marketMint),a=t8(e.eventType),l=i(a.labelKey),o=null==a.rawValue?void 0:i("historyUnknownRawTooltip",{value:a.rawValue}),d=re(e,s.intlTag);return(0,t.jsxs)("div",{role:"button",tabIndex:0,"aria-label":`${l} ${"—"===d.text?"":d.text}`,className:"bg-surface border border-border rounded-lg px-3 py-3 cursor-pointer active:bg-surface-interactive/50",onClick:()=>r(e),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),r(e))},children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,t.jsx)("span",{title:o,className:`text-xs font-medium px-1.5 py-0.5 rounded ${a.className}`,children:l}),n.image&&(0,t.jsx)(ef.default,{src:n.image,alt:n.symbol,width:14,height:14,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-xs text-foreground",children:n.symbol})]}),(0,t.jsx)("span",{className:`text-xs font-mono tabular-nums ${d.className}`,children:d.text})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:s.dateTime(e.eventAt)}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted font-mono tabular-nums",children:t7(e)})]}),(0,t.jsx)(rt,{annotation:e.annotation})]})}function rs({row:e,onOpenChange:r}){let i=(0,m.useTranslations)("positions"),s=(0,eJ.useFormatters)(),n=!1===(0,el.useIsDesktop)();if(!e)return(0,t.jsx)(e8.Sheet,{open:!1,onOpenChange:r,children:(0,t.jsx)(e8.SheetContent,{side:n?"bottom":"right"})});let a=t9(e.marketMint),l=t8(e.eventType),o=i(l.labelKey),d=null==l.rawValue?void 0:i("historyUnknownRawTooltip",{value:l.rawValue}),c=re(e,s.intlTag),u="transfer_in"===e.eventType||"transfer_out"===e.eventType,h=i("withdrawal"===e.eventType?"historyDepositToWallet":"external_deposit"===e.eventType?"historyDepositFrom":u?"transfer_out"===e.eventType?"historyDepositToProfile":"historyDepositFromProfile":"historyDepositFromWallet");return(0,t.jsx)(e8.Sheet,{open:!!e,onOpenChange:r,children:(0,t.jsxs)(e8.SheetContent,{side:n?"bottom":"right",className:n?"bg-canvas border-border max-h-[85vh] overflow-y-auto":"bg-canvas border-border w-full sm:max-w-md overflow-y-auto",children:[(0,t.jsx)(e8.SheetHeader,{className:"pb-0",children:(0,t.jsx)(e8.SheetTitle,{className:"text-foreground",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 flex-wrap",children:[a.image&&(0,t.jsx)(ef.default,{src:a.image,alt:a.symbol,width:16,height:16,className:"rounded-full",unoptimized:!0,onError:ev.handleTokenImageError}),(0,t.jsx)("span",{className:"text-sm",children:a.symbol}),(0,t.jsx)("span",{title:d,className:`text-xs font-medium px-1.5 py-0.5 rounded ${l.className}`,children:o}),(0,t.jsx)("span",{className:`text-xs font-mono tabular-nums ${c.className}`,children:c.text})]})})}),(0,t.jsxs)("div",{className:"px-4 pb-6 space-y-3",children:[(0,t.jsx)(rt,{annotation:e.annotation}),(0,t.jsxs)(eQ,{title:i("historySectionTransfer"),children:[(0,t.jsx)(eX,{label:i("historySectionType"),children:(0,t.jsx)("span",{title:d,children:o})}),(0,t.jsx)(eX,{label:i("historyColToken"),children:a.symbol}),(0,t.jsx)(eX,{label:i("historyColAmount"),children:(0,t.jsx)("span",{className:c.className,children:c.text})}),null!=e.amountUsd&&(0,t.jsx)(eX,{label:i("historyColValue"),children:s.rawUsd(String(Math.abs(parseFloat(e.amountUsd))))}),(0,t.jsx)(eX,{label:i("historySectionProfile"),children:t7(e)}),e.counterparty&&(0,t.jsx)(eX,{label:h,children:(0,t.jsx)(eY,{value:e.counterparty})})]}),(0,t.jsxs)(eQ,{title:i("historySectionSettlement"),children:[(0,t.jsx)(eX,{label:i("historyColTime"),children:s.dateTime(e.eventAt)}),(0,t.jsx)(eX,{label:i("historyRowTransaction"),children:(0,t.jsxs)("a",{href:`${e9.EXPLORER_BASE}${e.signature}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-blue-400 hover:text-blue-300",children:[eq(e.signature)," ",(0,t.jsx)(e3.ExternalLink,{className:"w-3 h-3"})]})})]})]})]})})}let rn=[{value:"all",labelKey:"historyAll"},{value:"deposit",labelKey:"historyDepositFilterDeposits"},{value:"withdrawal",labelKey:"historyDepositFilterWithdrawals"},{value:"transfer",labelKey:"historyDepositFilterTransfers"},{value:"external_deposit",labelKey:"historyDepositFilterExternal"}],ra=[["ALL","historyAll"],["WTD","historyPeriodWtd"],["MTD","historyPeriodMtd"],["YTD","historyPeriodYtd"],["CUSTOM","historyPeriodCustom"]];function rl(e){return"all"!==e.market||"all"!==e.eventType||"ALL"!==e.period}function ro({filters:e,onFiltersChange:r,onReset:i,availableMarkets:s}){let n=(0,m.useTranslations)("positions"),a=rl(e),l=e=>(0,tc.cn)("px-2.5 py-1 text-xs rounded transition-colors",e?"bg-surface-interactive text-foreground":"bg-surface-raised text-muted-foreground hover:text-foreground");return(0,t.jsxs)(td.Popover,{children:[(0,t.jsx)(td.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{"aria-label":n("historyDepositFiltersAri
2aLabel"),className:"relative p-1.5 rounded hover:bg-surface-interactive transition-colors text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(to.SlidersHorizontal,{className:"h-3.5 w-3.5"}),a&&(0,t.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-orange-500"})]})}),(0,t.jsx)(td.PopoverContent,{side:"bottom",align:"start",sideOffset:8,updatePositionStrategy:"always",className:"w-72 max-h-[70vh] overflow-y-auto p-3 !animate-none !duration-0",children:(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionType")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:rn.map(({value:i,labelKey:s})=>(0,t.jsx)("button",{onClick:()=>r({eventType:i}),className:l(e.eventType===i),children:n(s)},i))})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historyColToken")}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,t.jsx)("button",{onClick:()=>r({market:"all"}),className:l("all"===e.market),children:n("historyAll")}),s.map(i=>(0,t.jsx)("button",{onClick:()=>r({market:i}),className:l(e.market===i),children:t9(i).symbol},i))]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:n("historySectionDate")}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:ra.map(([i,s])=>(0,t.jsx)("button",{onClick:()=>r({period:i}),className:l(e.period===i),children:n(s)},i))}),"CUSTOM"===e.period&&(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-1.5",children:[(0,t.jsx)("input",{type:"date",value:e.customDateFrom??"",onChange:e=>r({customDateFrom:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"}),(0,t.jsx)("span",{className:"text-xs text-label-muted",children:n("historyDateRangeTo")}),(0,t.jsx)("input",{type:"date",value:e.customDateTo??"",onChange:e=>r({customDateTo:e.target.value||null}),className:"bg-surface-raised text-foreground text-xs px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"})]})]}),(0,t.jsx)("div",{className:"h-px bg-surface-raised"}),(0,t.jsx)("button",{onClick:i,className:"w-full py-1.5 text-xs rounded bg-surface-raised text-muted-foreground hover:text-foreground hover:bg-surface-interactive transition-colors",children:n("historyResetFilters")})]})})]})}let rd={market:"deposit-history-market",eventType:"deposit-history-type",period:"deposit-history-period",customDateFrom:"deposit-history-date-from",customDateTo:"deposit-history-date-to"};function rc(){let e=(0,m.useTranslations)("positions"),r=(0,eJ.useFormatters)(),{publicKey:i}=(0,y.useUnifiedWallet)(),s=(0,d.useMemo)(()=>i?.toBase58()??null,[i]),{status:n,isLoading:a}=(0,M.useApiHealth)(),l=!a&&n?.db!=="healthy",o=(0,el.useIsDesktop)(),{filters:c,setFilters:u,resetFilters:h}=ea(rd,tQ),p=rl(c),{events:f,totalCount:x,aggregates:g,hasMore:b,isFetchingNextPage:v,fetchNextPage:w,isLoading:j,error:S,refetch:k}=function({walletAddress:e,filters:t}){let r=(0,d.useMemo)(()=>tJ(t),[t]),{items:i,firstPage:s,...n}=et({queryKey:["deposit-history",e,r],enabled:!!e,fetchPage:async(t,i)=>e?t0(e,{limit:i,offset:t,params:r}):t1,pageItems:t2,pageTotalCount:t5,itemId:t3});return{events:i,totalCount:s?.totalCount??0,aggregates:s?.aggregates??null,...n}}({walletAddress:s,filters:c}),N=(0,d.useMemo)(()=>{let e=new Set(f.map(e=>e.marketMint));return"all"!==c.market&&e.add(c.market),Array.from(e)},[f,c.market]),[P,T]=(0,d.useState)(null);if(l)return(0,t.jsx)(ed,{label:e("historyLabelDepositHistory")});let C=null!=g?parseFloat(g.net):NaN,_=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-3 lg:px-4 py-2 border-b border-border",children:[(0,t.jsx)(ro,{filters:c,onFiltersChange:u,onReset:h,availableMarkets:N}),(0,t.jsx)("span",{className:"text-xs text-label-muted font-mono tabular-nums",children:x>0?e("historyEventCount",{count:x,amount:String(x)}):""}),null!=g&&x>0&&(0,t.jsxs)("div",{className:"flex items-center gap-3 text-xs font-mono tabular-nums",children:[(0,t.jsxs)("span",{className:"text-side-long",children:[e("historyAggregateIn")," ",r.rawUsd(g.totalIn)]}),(0,t.jsxs)("span",{className:"text-side-short",children:[e("historyAggregateOut")," ",r.rawUsd(g.totalOut)]}),Number.isFinite(C)&&(0,t.jsxs)("span",{className:C>0?"text-side-long":C<0?"text-side-short":"text-muted-foreground",children:[e("historyAggregateNet")," ",C<0?"-":"",r.rawUsd(String(Math.abs(C)))]})]})]}),A=eu({isLoading:j,error:S,isEmpty:0===f.length,filtersActive:p,onRetry:()=>k(),onReset:h,errorText:e("historyDepositLoadError"),emptyFilteredText:e("historyDepositEmptyFiltered"),emptyText:e("historyDepositEmpty")});return(0,t.jsxs)("div",{className:"h-full overflow-y-auto",children:[_,!1===o&&(A??(0,t.jsxs)("div",{className:"space-y-3 p-3",children:[f.map(e=>(0,t.jsx)(ri,{row:e,onOpenDetail:T},e.id)),b&&(0,t.jsx)(ec,{onClick:()=>w(),isFetching:v,fullWidth:!0})]})),o&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:eZ.default.scroller,children:(0,t.jsxs)("table",{className:eZ.default.table,children:[(0,t.jsx)(tv,{}),(0,t.jsx)("tbody",{children:A?(0,t.jsx)("tr",{children:(0,t.jsx)("td",{colSpan:7,children:A})}):f.map(e=>(0,t.jsx)(rr,{row:e,onOpenDetail:T},e.id))})]})}),!A&&b&&(0,t.jsx)("div",{className:"flex justify-center py-3 border-t border-border",children:(0,t.jsx)(ec,{onClick:()=>w(),isFetching:v})})]}),(0,t.jsx)(rs,{row:P,onOpenChange:e=>{e||T(null)}})]})}var ru=e.i(626074),rh=e.i(111468);function rp(e){let t=Number.parseFloat(e??"");return Number.isFinite(t)?t:0}function rm(e){return Number.isFinite(e)&&e.toFixed(12).replace(/\.?0+$/,"")||"0"}function rf(e){let t=Date.parse(e);if(Number.isFinite(t))return Math.floor(t/1e3);let r=Number(e);return Number.isFinite(r)?r>1e11?Math.floor(r/1e3):Math.floor(r):0}function rx(e,t){if(e.slot!==t.slot)return e.slot-t.slot;if(e.slotIndex!==t.slotIndex)return e.slotIndex-t.slotIndex;if(e.eventIndex!==t.eventIndex)return e.eventIndex-t.eventIndex;let r=(e.instructionIndex??-1)-(t.instructionIndex??-1);return 0!==r?r:rf(e.timestamp)-rf(t.timestamp)}function rg(e,t){let r=0,i=0;for(let s of e){if(!t(Math.abs(rp(s.baseLotsBefore)),Math.abs(rp(s.baseLotsAfter))))continue;let e=rp(s.baseQty),n=rp(s.price);e<=0||n<=0||(r+=e,i+=e*n)}return r>0?rm(i/r):null}async function rb(e,t,r){let i=new URLSearchParams({limit:"50",offset:t.toString()}),s=await fetch(`https://api.imperial.space/api/v1/profile/${e}/rewards/payouts?${i}`,{signal:r});if(!s.ok)throw Error("Failed to fetch reward payouts");return s.json()}var rv=e.i(305916);let ry=[["ALL","historyAll"],["WTD","historyPeriodWtd"],["MTD","historyPeriodMtd"],["YTD","historyPeriodYtd"],["CUSTOM","historyPeriodCustom"]],rw=[["all","historyAll"],["long","historyLong"],["short","historyShort"]],rj="bg-surface-interactive text-foreground ring-border-strong",rS={all:rj,long:"bg-side-long/20 text-side-long ring-side-long/40",short:"bg-side-short/20 text-side-short ring-side-short/40"};function rk({label:e,children:r}){return(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-[10px] text-label-muted mb-1.5",children:e}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:r})]})}
2function rN(e){return!e.sourceFilter.has("all")||"all"!==e.sideFilter||"all"!==e.assetFilter||"ALL"!==e.period}let rP="flex items-center gap-1.5 px-2 py-1 text-xs rounded transition-colors bg-surface-raised text-muted-foreground hover:text-foreground";function rT({filters:e,onSourceFilterChange:r,onSideFilterChange:i,onAssetFilterChange:s,onPeriodChange:n,onCustomDateFromChange:a,onCustomDateToChange:l,onReset:o,createdProfiles:d,availableAssets:c}){let u=(0,m.useTranslations)("positions"),{sourceFilter:h,sideFilter:p,assetFilter:f,period:x,customDateFrom:g,customDateTo:b}=e,v=rN(e),y=(e,t=rj)=>(0,tc.cn)(rv.CHIP,e?(0,tc.cn)("ring-1 ring-inset",t):rv.CHIP_IDLE),w=e=>{let t=new Set(h);t.delete("all"),t.has(e)?t.delete(e):t.add(e),r(0===t.size?new Set(["all"]):t)};return(0,t.jsxs)(td.Popover,{children:[(0,t.jsx)(td.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{"aria-label":u("historyFiltersAriaLabel"),className:(0,tc.cn)("relative flex items-center gap-1.5 px-2 py-1 text-xs rounded transition-colors",v?"bg-orange-500/20 text-orange-300 hover:bg-orange-500/30":"bg-surface-raised text-muted-foreground hover:text-foreground"),children:[(0,t.jsx)(to.SlidersHorizontal,{className:"h-3 w-3"}),u("historyFilters")]})}),(0,t.jsxs)(td.PopoverContent,{side:"top",align:"end",sideOffset:8,updatePositionStrategy:"always",className:"w-72 max-h-[70vh] overflow-y-auto p-3 !animate-none !duration-0",children:[(0,t.jsxs)("div",{className:"flex items-baseline justify-between mb-3",children:[(0,t.jsx)("div",{className:"text-xs font-medium text-foreground",children:u("historyFilters")}),v&&(0,t.jsx)("button",{onClick:o,className:"text-[11px] text-muted-foreground hover:text-foreground transition-colors",children:u("historyClearAll")})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)(rk,{label:u("historySectionProfile"),children:[(0,t.jsx)("button",{onClick:()=>r(new Set(["all"])),className:y(h.has("all")),children:u("historyAll")}),d.map(e=>{let r=`profile_${e.index}`;return(0,t.jsx)("button",{onClick:()=>w(r),className:y(h.has(r)),children:e.name},r)}),(0,t.jsx)("button",{onClick:()=>w("phoenix_direct"),className:y(h.has("phoenix_direct"),"bg-orange-500/20 text-orange-300 ring-orange-500/40"),children:"Phoenix Direct"})]}),(0,t.jsx)(rk,{label:u("historySectionSide"),children:rw.map(([e,r])=>(0,t.jsx)("button",{onClick:()=>i(e),className:y(p===e,rS[e]),children:u(r)},e))}),(0,t.jsxs)(rk,{label:u("historySectionAsset"),children:[(0,t.jsx)("button",{onClick:()=>s("all"),className:y("all"===f),children:u("historyAll")}),c.map(e=>(0,t.jsx)("button",{onClick:()=>s(e),className:y(f===e),children:e},e))]}),(0,t.jsx)(rk,{label:u("historySectionDate"),children:ry.map(([e,r])=>(0,t.jsx)("button",{onClick:()=>n(e),className:y(x===e),children:u(r)},e))}),"CUSTOM"===x&&(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{type:"date",value:g??"",onChange:e=>a(e.target.value||null),className:"bg-surface-raised text-foreground text-[11px] px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"}),(0,t.jsx)("span",{className:"text-[11px] text-label-muted",children:u("historyDateRangeTo")}),(0,t.jsx)("input",{type:"date",value:b??"",onChange:e=>l(e.target.value||null),className:"bg-surface-raised text-foreground text-[11px] px-2 py-1 rounded border border-border-strong outline-none [color-scheme:dark]"})]})]})]})]})}let rC=(0,r.default)(()=>e.A(443425).then(e=>({default:e.PnlTab})),{loadableGenerated:{modules:[531605]},ssr:!1,loading:()=>(0,t.jsx)("div",{className:"flex items-center justify-center h-32 text-label-muted text-sm",children:"Loading PnL chart..."})}),rM=[{value:"order_history",labelKey:"tabOrderHistory"},{value:"funding_history",labelKey:"tabFundingHistory"},{value:"deposits",labelKey:"tabDepositHistory"},{value:"pnl",labelKey:"tabPnl"}],r_="px-0 py-2 max-lg:h-full max-lg:py-0 text-xs max-lg:text-sm max-[360px]:text-[12px] max-lg:font-medium lg:text-sm shrink-0 whitespace-nowrap data-[state=active]:text-foreground data-[state=active]:bg-transparent data-[state=active]:!shadow-none data-[state=inactive]:text-muted-foreground max-lg:data-[state=inactive]:text-foreground
2/50 hover:text-foreground !border-transparent !rounded-none !outline-none !ring-0 focus:!outline-none focus:!ring-0 focus-visible:!outline-none focus-visible:!ring-0",rA="lg:h-[37px] lg:py-0 lg:pt-[2px] lg:text-[14.313px] lg:leading-normal lg:font-medium lg:data-[state=active]:font-semibold lg:data-[state=active]:text-[#f5f5f7] lg:data-[state=inactive]:text-[#80858c]";function rE({value:e,active:r,label:i,shortLabel:s,count:n,desktopPerps:a}){return(0,t.jsxs)(g.TabsTrigger,{value:e,"data-tab":!0,"data-active":r,className:(0,tc.cn)("inline-flex",r_,a&&rA),children:[(0,t.jsx)("span",{className:"lg:hidden",children:s}),void 0!==n&&n>0&&(0,t.jsx)("span",{className:"lg:hidden ml-1 rounded-[7px] bg-[rgba(253,143,0,0.5)] px-[4px] py-[3px] text-[12px] max-[360px]:text-[10px] font-semibold leading-none text-white",children:String(n).padStart(2,"0")}),(0,t.jsx)("span",{className:"hidden lg:inline",children:i})]})}function rL({activeTab:e,onValueChange:r,t:i}){let[s,n]=(0,d.useState)(!1),a=rM.find(t=>t.value===e)?.labelKey,l=!!a;return(0,d.useEffect)(()=>{if(!s)return;let e=()=>n(!1);return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[s]),(0,t.jsxs)(ru.DropdownMenu,{children:[(0,t.jsx)(ru.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-tab":!0,"data-active":l,"aria-label":a?`${i(a)} \xb7 ${i("tabMore")}`:i("tabMore"),onPointerDownCapture:()=>n(!0),onKeyDownCapture:()=>n(!1),className:`lg:hidden ml-auto flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-[8px] bg-surface-raised px-2 text-xs transition-colors ${s?"outline-none":"focus-ring-inset"} ${l?"text-foreground":"text-secondary-foreground hover:text-foreground"}`,children:[a&&(0,t.jsx)("span",{children:i(a)}),(0,t.jsx)("span",{"aria-hidden":!0,className:"text-[15px] leading-none tracking-[1px]",children:"···"})]})}),(0,t.jsx)(ru.DropdownMenuContent,{align:"start",className:"lg:hidden",onPointerDownCapture:()=>n(!0),onKeyDownCapture:()=>n(!1),children:rM.map(({value:s,labelKey:n})=>(0,t.jsx)(ru.DropdownMenuItem,{onSelect:()=>r(s),className:e===s?"text-foreground bg-surface-interactive":"",children:i(n)},s))})]})}function rF({marketMint:e,positions:r,lifecycles:i,lifetimeStats:n,historyRead:z,totalCount:$,hasMore:V,isFetchingNextPage:H,onLoadMore:W,isLoading:q,onPositionChange:K,liveMarkPrice:G,livePrices:Y,orderbookMidPrice:X,orderbookSymbol:Q,hotkeys:J=!1,landOnTab:et,mobileScroll:er=!1}){(0,o.useTokenIconsVersion)();let ei=(0,m.useTranslations)("positions"),es=(0,s.useDesktopWorkspaceActivity)(),en=es?.collapsed??!1,[ea,el]=(0,d.useState)(()=>{let e=localStorage.getItem("bottom-panel-tab");return e&&"liq_map"!==e?e:"positions"}),[eo,ed]=(0,d.useState)(new Set),{publicKey:ec}=(0,v.useUnifiedWalletContext)(),eu=ec?.toBase58()??null,eh=!eu||0===r.length||r.some(e=>e.wallet!==eu)?null:JSON.stringify([eu,r.map(e=>JSON.stringify([e.id,e.lifecycleId,e.positionPda,e.wallet,e.profileIndex,e.asset,e.side,e.underwriter,e.ownership,e.openedAt,e.sunriseMarginSeat,e.directVenue?.traderAccount,e.directVenue?.pdaIndex,e.directVenue?.subaccountIndex])).sort()]),[ep,em]=function(e,t){let[r,i]=(0,d.useState)(null);null!==r&&(e||r!==t)&&i(null);let s=(0,d.useCallback)(r=>{i(r&&!e?t:null)},[e,t]);return[!e&&null!==t&&r===t,s]}(en,eh),[ef,ex]=(0,d.useState)(!1),[eg,eb]=(0,d.useState)(null),ev=(0,d.useRef)(et?.nonce??0),ey=et?.tab,ew=et?.nonce??0;(0,d.useEffect)(()=>{ew&&ew!==ev.current&&(ev.current=ew,ey&&el(ey),em(!1))},[ew,ey,em]);let{pendingPositions:ej,hasPendingCloseForPda:eS}=(0,x.usePendingPositions)(),[ek,eN]=(0,d.useState)(()=>{try{let e=localStorage.getItem("history-source-filter");if(e)return new Set(JSON.parse(e))}catch{}return new Set(["all"])}),[eP,eT]=(0,d.useState)(()=>localStorage.getItem("history-period-filter")||"ALL"),[eC,eM]=(0,d.useState)(()=>localStorage.getItem("history-side-filter")||"all"),[e_,eA]=(0,d.useState)(()=>localStorage.getItem("history-asset-filter")||"all"),[eE,eL]=(0,d.useState)(()=>localStorage.getItem("history-custom-date-from")||null),[eF,eR]=(0,d.useState)(()=>localStorage.getItem("history-custom-date-to")||null);(0,d.useEffect)(()=>{localStorage.setItem("history-source-filter",JSON.stringify([...ek]))},[ek]),(0,d.useEffect)(()=>{localStorage.setItem("history-period-filter",eP)},[eP]),(0,d.useEffect)(()=>{localStorage.setItem("history-side-filter",eC)},[eC]),(0,d.useEffect)(()=>{localStorage.setItem("history-asset-filter",e_)},[e_]),(0,d.useEffect)(()=>{eE?localStorage.setItem("history-custom-date-from",eE):localStorage.removeItem("history-custom-date-from")},[eE]),(0,d.useEffect)(()=>{eF?localStorage.setItem("history-custom-date-to",eF):localStorage.removeItem("history-custom-date-to")},[eF]);let{connection:eD}=(0,u.useConnection)(),{cancelPassthroughOrder:eI,cancelTriggerOrder:eU,executeOrderAtMarket:eO,updatePassthroughOrder:eB,batchUpdatePassthroughPriorities:ez}=(0,k.useTradeActions)(),{slippageBps:e$}=(0,N.useSlippageBps)(),{orders:eV,limitCloseOrders:eH,allCloseOrders:eW,refreshPositions:eq,isLoading:eK,walletState:eG}=(0,S.useUnifiedPositions)(),{status:eY,isError:eX}=(0,M.useApiHealth)(),eQ=eY?.db==="down"||eX,{createdProfiles:eJ}=(0,E.useProfile)(),eZ=(0,T.useHistoryPaneDemand)("history"===ea),e0=(0,C.usePhoenixDirectHistory)(eu,eZ),e1=function(e,t=!0){let r=(0,ee.useQueryClient)(),i=!!e&&t,s=(0,Z.useInfiniteQuery)({queryKey:["reward-payouts",e],queryFn:({pageParam:t=0,signal:r})=>rb(e,t,r),initialPageParam:0,getNextPageParam:e=>{let t=e.offset+e.entries.length;return t<e.totalCount?t:void 0},enabled:i,staleTime:6e4});return(0,d.useEffect)(()=>{let t=r.getQueryCache(),i=["reward-payouts",e],s=t.find({queryKey:i,exact:!0});if(!s)return;let n=()=>
2{if("idle"===s.state.fetchStatus||s.isActive())return;let e=s.promise;queueMicrotask(()=>{t.find({queryKey:i,exact:!0})!==s||s.promise!==e||"idle"===s.state.fetchStatus||s.isActive()||s.cancel({revert:!0})})},a=t.subscribe(e=>{e.query===s&&("observerRemoved"===e.type||"observerOptionsUpdated"===e.type)&&n()});return n(),()=>{a(),n()}},[r,i,e]),s}(eu??void 0,eZ),e2=(0,d.useMemo)(()=>e1.data?.pages.flatMap(e=>e.entries)??[],[e1.data]),e5=(0,d.useCallback)(e=>{el(e),localStorage.setItem("bottom-panel-tab",e),em(!1),ec&&eq()},[ec,eq,em]),e3=(0,d.useMemo)(()=>i.filter(e=>"open"!==e.status),[i]),e4=(0,d.useMemo)(()=>{let e=new Set(e3.map(e=>e.asset));for(let t of e0.actions)e.add(t.asset);return Array.from(e).sort()},[e3,e0.actions]),e6=(0,d.useMemo)(()=>({sourceFilter:ek,sideFilter:eC,assetFilter:e_,period:eP,customDateFrom:eE,customDateTo:eF}),[ek,eC,e_,eP,eE,eF]),e8=rN(e6),e9=(0,d.useCallback)(()=>{eN(new Set(["all"])),eM("all"),eA("all"),eT("ALL"),eL(null),eR(null)},[]),e7=(0,t.jsx)(rT,{filters:e6,onSourceFilterChange:eN,onSideFilterChange:eM,onAssetFilterChange:eA,onPeriodChange:eT,onCustomDateFromChange:eL,onCustomDateToChange:eR,onReset:e9,createdProfiles:eJ,availableAssets:e4}),te=(0,d.useMemo)(()=>e8?e3.filter(e=>{if("ALL"!==eP){let t=e.closedAt??e.openedAt;if("CUSTOM"===eP){if(eE&&t<new Date(eE).getTime()/1e3||eF&&t>=new Date(eF).getTime()/1e3+86400)return!1}else{let e,r=new Date;if("WTD"===eP){let t=r.getDay();e=new Date(r.getFullYear(),r.getMonth(),r.getDate()-(0===t?6:t-1)).getTime()/1e3}else e="MTD"===eP?new Date(r.getFullYear(),r.getMonth(),1).getTime()/1e3:new Date(r.getFullYear(),0,1).getTime()/1e3;if(t<e)return!1}}if(!ek.has("all")){if(null==e.profileIndex)return!1;let t=`profile_${e.profileIndex}`;if(!ek.has(t))return!1}return("all"===eC||e.side===eC)&&("all"===e_||e.asset===e_)}):e3,[e3,ek,eP,eC,e_,e8,eE,eF]),tt=(0,d.useMemo)(()=>e0.actions.filter(e=>{let t;if(!ek.has("all")&&!ek.has("phoenix_direct")||"all"!==eC&&e.side!==eC||"all"!==e_&&e.asset!==e_)return!1;if("ALL"===eP)return!0;let r=Date.parse(e.timestamp)/1e3;if(!Number.isFinite(r))return!1;if("CUSTOM"===eP)return!(eE&&r<new Date(eE).getTime()/1e3||eF&&r>=new Date(eF).getTime()/1e3+86400);let i=new Date;if("WTD"===eP){let e=i.getDay();t=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(0===e?6:e-1)).getTime()/1e3}else t="MTD"===eP?new Date(i.getFullYear(),i.getMonth(),1).getTime()/1e3:new Date(i.getFullYear(),0,1).getTime()/1e3;return r>=t}),[e0.actions,ek,eC,e_,eP,eE,eF]),tr=(0,d.useMemo)(()=>eu?(function(e,t,r=[]){let i=e.slice().sort((e,t)=>rx(e,t)||e.id.localeCompare(t.id)),s=r.slice().sort((e,t)=>rx(e,t)||e.id.localeCompare(t.id)),n=new Map,a=new Map,l=[],o=0;for(let e of i){for(;o<s.length&&0>=rx(s[o],e);){let e=s[o],t=rp(e.collateralAfter);for(let r of(a.set(e.subaccountIndex,t),n.values()))r.subaccountIndex===e.subaccountIndex&&(r.maxCollateralUsd=Math.max(r.maxCollateralUsd??0,t));o+=1}let r=rp(e.baseLotsBefore),i=rp(e.baseLotsAfter),d=Math.sign(r),c=Math.sign(i),u=d||c;if(0===u)continue;let h=`${e.subaccountIndex}:${e.asset}`,p=n.get(h);if(!p||0===d||Math.sign(r)!==("long"===p.side?1:-1)){let t=rp(e.price);p={asset:e.asset,subaccountIndex:e.subaccountIndex,side:u>0?"long":"short",fills:[],openNotionalUsd:Math.abs(r)*t,maxSizeUsd:Math.abs(r)*t,maxBaseUnits:0,maxCollateralUsd:0===e.subaccountIndex?null:a.get(e.subaccountIndex)??null},n.set(h,p)}p.fills.push(e);let m=Math.abs(r),f=Math.abs(i);f>m?p.openNotionalUsd+=rp(e.quoteQty):m>0&&(p.openNotionalUsd*=f/m),p.maxBaseUnits=Math.max(p.maxBaseUnits,Math.abs(r),Math.abs(i)),p.maxSizeUsd=Math.max(p.maxSizeUsd,p.openNotionalUsd,rp(e.quoteQty));let x=0!==d&&0!==c&&d!==c;(0===c||x)&&(l.push(function(e,t){let r=e.fills[0],i=e.fills[e.fills.length-1],s=e.fills.map((e,t)=>{var r;let i,s,n,a,l,o,d;return r=t+1,i=Math.abs(rp(e.baseLotsBefore)),n=(s=Math.abs(rp(e.baseLotsAfter)))>i,a=rp(e.quoteQty),l=rp(e.realizedPnl),o=e.transactionSignature??"",d=rf(e.timestamp),{id:e.id,actionType:"liquidation"===e.actionType?"liquidation":n?"increase":"decrease",status:"completed",sequenceNumber:r,failureReason:null,tx1Signature:o,tx1Timestamp:d,collateralDeposited:null,platformFee:null,hadSwap:!1,swapSlippage:null,tx2Signature:o||null,tx2Timestamp:d,sizeDelta:rm(n?a:-a),sizeDeltaTokens:rm(n?rp(e.baseQty):-rp(e.baseQty)),collateralDelta:null,jupiterFee:e.fees,interest:null,entryPrice:e.price,tx3Signature:n?null:o||null,tx3Timestamp:n?
2null:d,pnlRealized:n?null:e.realizedPnl,hasProfit:n?null:l>=0,userReceived:null,tx3PlatformFee:null,tx3SwapFee:null,tx3SweepSlippage:null,proOrderFee:null,collateralAfter:null,positionSizeAfter:rm(s*rp(e.price)),postLiquidationPriceUsd:null,orderType:"limit"===e.tradeType?"limit":"market",triggerPrice:null,triggerCondition:null,orderSizeUsd:rm(a),orderSlippageBps:null,orderCreatedAt:d,orderWaitPrice:null,orderWaitDurationSecs:null,orderWorstPrice:null,orderRatchetSize:null,orderExecutionTriggerPrice:null,orderIndicatorConfig:null,orderThresholdValue:null,orderTriggerDelaySecs:null,orderDcaNumLegs:null,orderDcaLegNumber:null,orderDcaLegTrigger:null,orderDcaStartPrice:null,orderDcaEndPrice:null,orderDcaPriceLimit:null,orderDcaIntervalSeconds:null}}),n=e.fills.reduce((e,t)=>e+rp(t.realizedPnl),0),a=e.fills.reduce((e,t)=>e+rp(t.fees),0),l=rg(e.fills,(e,t)=>t>e),o=rg(e.fills,(e,t)=>t<e),d=e.fills.some(e=>"liquidation"===e.actionType||"adl"===e.tradeType);return{id:`phoenix-direct-lifecycle:${r.id}:${i.id}`,positionPda:`phoenix-direct-history:${e.subaccountIndex}:${e.asset}:${r.id}`,wallet:t,source:"phoenix_direct",ownership:"venue_direct",directVenue:{marginMode:0===e.subaccountIndex?"cross":"isolated",traderAccount:"",pdaIndex:0,subaccountIndex:e.subaccountIndex,baseLots:"0",accountCollateralUsd:"",effectiveCollateralUsd:"",positionInitialMarginUsd:"",maintenanceMarginUsd:""},side:e.side,asset:e.asset,leverageX:null,sizeUsd:"0",sizeTokenAmount:rm(e.maxBaseUnits),collateralUsd:null,maxSizeUsd:rm(e.maxSizeUsd),maxCollateralUsd:null==e.maxCollateralUsd?null:rm(e.maxCollateralUsd),maxLeverageX:null,entryPrice:l,markPrice:o,liquidationPrice:null,partialLiquidationPriceUsd:null,breakevenPriceUsd:null,pnlUsd:rm(n),pnlPercent:null,netCashPnlUsd:null,totalFeesUsd:rm(a),feesOwed:null,borrowFeeOwed:null,closeFeeOwed:null,swapFeeOwed:null,fees:{platformFee:"0",swapFee:"0",slippage:"0",jupiterFee:rm(a),interest:"0",proOrderFee:"0"},status:d?"liquidated":"closed",openedAt:rf(r.timestamp),closedAt:rf(i.timestamp),lastActionAt:rf(i.timestamp),underwriter:"phoenix",tpslOrders:[],actions:s}}(p,t)),n.delete(h))}return l.sort((e,t)=>(t.closedAt??0)-(e.closedAt??0))})(e0.actions,eu,e0.collateralEvents).filter(e=>{let t;if(!ek.has("all")&&!ek.has("phoenix_direct")||"all"!==eC&&e.side!==eC||"all"!==e_&&e.asset!==e_)return!1;if("ALL"===eP)return!0;let r=e.closedAt??e.openedAt;if("CUSTOM"===eP)return!(eE&&r<new Date(eE).getTime()/1e3||eF&&r>=new Date(eF).getTime()/1e3+86400);let i=new Date;if("WTD"===eP){let e=i.getDay();t=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(0===e?6:e-1)).getTime()/1e3}else t="MTD"===eP?new Date(i.getFullYear(),i.getMonth(),1).getTime()/1e3:new Date(i.getFullYear(),0,1).getTime()/1e3;return r>=t}):[],[e0.actions,e0.collateralEvents,eu,ek,eC,e_,eP,eE,eF]),ti=(0,d.useMemo)(()=>[...te,...tr].sort((e,t)=>(t.closedAt??t.openedAt)-(e.closedAt??e.openedAt)),[te,tr]),ts=(0,d.useCallback)(()=>{let e=new Map(eJ.map(e=>[e.index,e.name??ei("profileFallbackName",{index:e.index+1})]));(0,L.exportLifecyclesToCsv)(ti,e)},[ti,eJ]),tn=(0,d.useMemo)(()=>{if(null===n)return null;let e=0,t=0,r=0,i=0,s=0,a=0,l=0,o=0,d=null,c=0;for(let n of e8?te:e3)e+=(0,I.parseRawValue)(n.maxCollateralUsd),("closed"===n.status||"liquidated"===n.status)&&(t+=(0,I.closedDisplayPnl)(n)),c+=(0,I.parseRawValue)(n.maxSizeUsd),n.fees&&(r+=(0,I.parseRawValue)(n.fees.platformFee),i+=(0,I.parseRawValue)(n.fees.proOrderFee),s+=(0,I.parseRawValue)(n.fees.swapFee),a+=(0,I.parseRawValue)(n.fees.slippage),l+=(0,I.parseRawValue)(n.fees.interest),o+=(0,I.parseRawValue)(n.fees.jupiterFee),null!=n.fees.pairsImpactFee&&(d=(d??0)+(0,I.parseRawValue)(n.fees.pairsImpactFee)));let u=r+i+a+l+o;return{collateralUsd:e.toFixed(2),pnlUsd:e8?t.toFixed(2):n.pnlUsd,feesUsd:e8?u.toFixed(2):n.feesUsd,cumulativeSizeUsd:c.toFixed(2),feeBreakdown:e8?{platformFee:r.toFixed(2),proOrderFee:i.toFixed(2),swapFee:s.toFixed(2),slippage:a.toFixed(2),interest:l.toFixed(2),jupiterFee:o.toFixed(2),pairsImpactFee:d?.toFixed(2)??null}:n.feeBreakdown}},[te,e3,e8,n]),{actions:ta,isLoading:tl,unverified:to}=(0,P.useChainPositionHistory)(ec,eZ&&eQ),td=eQ&&ta.length>0?"chain":"api",tu=eV.length,[th,tp]=(0,d.useState)(null),tm=async(e,t,r,i,s)=>{tp(e);try{let i=eW.filter(t=>t.orderPda&&t.parentOrderPda===e),n=await eI({orderPda:e,collateralMint:t,profileIndex:r,underwriter:s});return n&&(f.toast.success(i.length>0?ei("toastCanceledOrdersCount",{count:i.length+1}):ei("toastOrderCanceled")),K?.()),!!n}catch(e){return e instanceof y.WalletUnresponsiveError?f.toast.error(ei("toastWallet
2NotResponding"),{description:e.lnaHint?(0,j.errorText)("walletUnresponsiveLnaHint"):ei("toastWalletNotRespondingHint")}):(0,w.isUserRejection)(e)||(console.error("Failed to cancel passthrough order:",e),f.toast.error(ei("toastCancelOrderFailed"))),!1}finally{tp(null)}},[tf,tx]=(0,d.useState)(null),tg=(0,d.useCallback)(async e=>{if(void 0!==e.loanMultiplierMicro)return e.loanMultiplierMicro;if(!eD)return null;try{let t=await eD.getAccountInfo(new c.PublicKey(e.orderPda),"processed");if(!t)return null;return(0,O.orderDecoder)(t)?.loanMultiplierMicro??null}catch{return null}},[eD]),tb=(0,d.useCallback)(async e=>{if(!e.marketMint||!e.side)return void f.toast.error(ei("errorMissingOrderData"));let t=e.collateralAmount??0;if(t<=0)return void f.toast.error(ei("errorInvalidCollateralAmount"));let r=Y?.[e.marketMint];if(!r)return void f.toast.error(ei("errorNoLivePriceForMarket"));let i=parseFloat(e.sizeUsd),s=e.profileIndex??0,n=e.dca??e.dcaTime??e.dcaRatchet??e.dcaClose??e.dcaTimeClose??e.dcaRatchetClose,a=t,l=i;if(n&&n.legsExecuted>0&&n.legsExecuted<n.numLegs){let{numLegs:e,weightingType:r,legsExecuted:s}=n,o=Math.floor(1e6*t),d=Math.floor(1e6*i),c=n.leverageWeightingType??0,u=n.startLeverageScaled??0,h=n.endLeverageScaled??0,p=0,m=0;for(let t=0;t<s;t++)p+=U.PassthroughClient.calculateDcaLegCollateral(o,e,r,t),m+=U.PassthroughClient.calculateDcaLegSizeUsd(d,o,e,r,t,c,u,h);a=(o-p)/1e6,l=(d-m)/1e6}let o=await tg(e);if(null===o)return void f.toast.error(ei("errorLoanTermsUnreadable"),{description:ei("errorLoanTermsUnreadableHint")});let d=o>1e6?{loanAmountUsd:a*(o/1e6-1)}:void 0;tx(e.orderPda);try{await eO({orderPda:e.orderPda,marketMint:e.marketMint,side:e.side,sizeUsd:l,collateralAmount:a,currentPrice:r,profileIndex:s,slippageBps:e$,underwriter:e.underwriter,loanLeg:d})&&K?.()}catch(e){console.error("Execute at market failed:",e),f.toast.error(ei("toastExecuteAtMarketFailed"))}finally{tx(null)}},[eO,Y,K,tg,e$]),tv=(0,d.useCallback)(async e=>{await ez(e)||f.toast.error(ei("toastUpdatePrioritiesFailed"))},[ez]),ty=(0,A.useClosePosition)({marketMint:e,livePrices:Y,liveMarkPrice:G,onPositionChange:K}),tj=(0,d.useCallback)(async(e,t)=>{ed(t=>new Set(t).add(e.id));try{await ty(e,t)}finally{ed(t=>{if(!t.has(e.id))return t;let r=new Set(t);return r.delete(e.id),r})}},[ty]),tS=(0,d.useCallback)(e=>eo.has(e.id)||eS(e.positionPda,e.asset),[eo,eS]),tk=(0,d.useCallback)(async()=>{if(!en&&eh&&!ef){if(!ep)return void em(!0);em(!1),ex(!0);try{for(let e of r)await tj(e,100)}finally{ex(!1)}}},[en,eh,ef,ep,r,tj,em]);return(0,d.useEffect)(()=>{if(!ep)return;let e=setTimeout(()=>em(!1),5e3),t=e=>{"Escape"===e.key&&em(!1)};return window.addEventListener("keydown",t),()=>{clearTimeout(e),window.removeEventListener("keydown",t)}},[ep,em]),(0,rh.useHotkey)("tab-positions",()=>e5("positions"),J),(0,rh.useHotkey)("tab-orders",()=>e5("orders"),J),(0,rh.useHotkey)("tab-history",()=>e5("history"),J),(0,rh.useHotkey)("close-all-positions",()=>{"positions"!==ea?e5("positions"):0===r.length||ef||tk()},J),(0,t.jsx)("div",{className:`${er?"":"trading-panel-surface"} lg:h-full flex flex-col min-w-0 lg:overflow-hidden lg:font-[family-name:var(--font-inter)]`,children:(0,t.jsxs)(g.Tabs,{value:ea,onValueChange:e5,className:(0,tc.cn)("flex flex-col lg:h-full min-w-0 lg:overflow-hidden","lg:gap-0"),children:[(0,t.jsxs)("div",{className:`border-b border-border shrink-0 ${er?"max-lg:sticky max-lg:top-0 max-lg:z-10 max-lg:bg-canvas":""}`,children:[(0,t.jsxs)("div",{className:(0,tc.cn)("flex items-center justify-between min-w-0 max-lg:h-11 max-lg:px-2.5","lg:h-[37px] lg:px-[13.31px]"),children:[(0,t.jsxs)("div",{className:"contents lg:flex lg:min-w-0 lg:items-center lg:gap-2",children:[(0,t.jsx)(s.DesktopWorkspacePanelTools,{}),(0,t.jsx)(g.TabsList,{onClick:()=>es?.reveal(),onFocusCapture:e=>{e.target instanceof HTMLElement&&"tab"===e.target.getAttribute("role")&&es?.reveal()},className:(0,tc.cn)("bg-transparent border-0 rounded-none p-0 max-w-full min-w-0 max-lg:h-full","lg:h-full"),children:(0,t.jsxs)(b.SlidingUnderline,{activeKey:ea,className:(0,tc.cn)("flex items-center gap-5 max-lg:gap-2 overflow-x-auto justify-start max-w-full min-w-0 max-lg:flex-1 max-lg:h-full","lg:gap-[13.29px] lg:h-full"),barClassName:(0,tc.cn)("bg-primary max-lg:h-px","lg:bg-[#f79929] lg:h-[2.556
2px] lg:rounded-[1.533px]"),children:[(0,t.jsx)(rE,{desktopPerps:!0,value:"positions",active:"positions"===ea,shortLabel:ei("tabPositionsBare"),count:r.length,label:ei("tabPositions",{count:r.length})}),(0,t.jsx)(rE,{desktopPerps:!0,value:"orders",active:"orders"===ea,shortLabel:ei("tabOrdersBare"),count:tu,label:ei("tabOrders",{count:tu})}),(0,t.jsx)(rE,{desktopPerps:!0,value:"history",active:"history"===ea,shortLabel:ei("tabHistoryShort"),label:ei("tabTradeHistory")}),(0,t.jsx)(g.TabsTrigger,{value:"order_history","data-tab":!0,"data-active":"order_history"===ea,className:(0,tc.cn)("hidden lg:inline-flex",r_,rA),children:ei("tabOrderHistory")}),(0,t.jsx)(g.TabsTrigger,{value:"funding_history","data-tab":!0,"data-active":"funding_history"===ea,className:(0,tc.cn)("hidden lg:inline-flex",r_,rA),children:ei("tabFundingHistory")}),(0,t.jsx)(g.TabsTrigger,{value:"deposits","data-tab":!0,"data-active":"deposits"===ea,className:(0,tc.cn)("hidden lg:inline-flex",r_,rA),children:ei("tabDepositHistory")}),(0,t.jsx)(g.TabsTrigger,{value:"pnl","data-tab":!0,"data-active":"pnl"===ea,className:(0,tc.cn)("hidden lg:inline-flex",r_,rA),children:ei("tabPnl")}),(0,t.jsx)(rL,{activeTab:ea,onValueChange:e5,t:ei})]})})]}),!en&&"positions"===ea&&r.length>0&&(0,t.jsx)("button",{onClick:tk,disabled:ef,type:"button","aria-label":ep?ei("confirmCloseAll"):ei("closeAll"),"aria-busy":ef,className:`shrink-0 max-lg:min-h-11 max-lg:ml-1 max-lg:px-1 max-lg:text-[10px] px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${ef?"bg-red-500/20 text-red-400 cursor-not-allowed":ep?"bg-red-500/30 text-red-400 hover:bg-red-500/40":"text-muted-foreground hover:text-foreground bg-surface-raised"}`,onBlur:()=>em(!1),children:ef?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(p.Loader2,{className:"h-3 w-3 animate-spin"}),ei("closingAll")]}):ep?ei("confirmCloseAll"):ei("closeAll")}),!en&&"history"===ea&&"disconnected"!==eG&&(0,t.jsxs)("div",{className:"hidden shrink-0 lg:flex items-center gap-2",children:[(0,t.jsx)("div",{ref:eb,className:"flex shrink-0 items-center"}),"chain"!==td&&e7,ti.length>0&&(0,t.jsxs)("button",{onClick:ts,className:rP,children:[(0,t.jsx)(h.Download,{className:"h-3 w-3"}),ei("exportCsv")]})]})]}),!en&&"history"===ea&&"disconnected"!==eG&&(0,t.jsxs)("div",{className:"lg:hidden flex items-center gap-2 px-4 pb-2",children:["chain"!==td&&e7,ti.length>0&&(0,t.jsxs)("button",{onClick:ts,className:(0,tc.cn)(rP,"ml-auto"),children:[(0,t.jsx)(h.Download,{className:"h-3 w-3"}),ei("exportCsv")]})]})]}),(0,t.jsx)(_.SunrisePayoutSync,{}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"positions",className:(0,tc.cn)("m-0 lg:flex-1 lg:min-h-0 min-w-0 lg:overflow-hidden","lg:data-[state=active]:flex lg:flex-col lg:overflow-y-auto"),children:(0,t.jsx)(F.PositionsTab,{desktopEmptyState:!0,positions:r,isLoading:eK,isPositionClosing:tS,livePrices:Y,orderbookMidPrice:X,orderbookSymbol:Q,onClosePosition:tj,createPassthroughCancelHandler:(e,t)=>async(r,i)=>{try{let s="long"===e?L.WSOL_MINT.toBase58():L.USDC_MINT.toBase58(),n=await eI({orderPda:r,collateralMint:s,profileIndex:i,underwriter:t});return n&&(f.toast.success(ei("toastOrderCanceled")),K?.()),!!n}catch(e){return e instanceof y.WalletUnresponsiveError?f.toast.error(ei("toastWalletNotResponding"),{description:e.lnaHint?(0,j.errorText)("walletUnresponsiveLnaHint"):ei("toastWalletNotRespondingHint")}):(0,w.isUserRejection)(e)||(console.error("Failed to cancel passthrough order:",e),f.toast.error(ei("toastCancelOrderFailed"))),!1}},createJupiterCancelHandler:(e,t,r,i)=>async t=>{try{let s=await eU({positionPubkey:e,positionRequestPubkey:t,positionSource:"imperial",profileIndex:r,underwriter:i});return s&&(f.toast.success(ei("toastOrderCanceled")),K?.()),!!s}catch(e){return console.error("Failed to cancel Jupiter order:",e),f.toast.error(ei("toastCancelOrderFailed")),!1}},onPositionChange:K})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"orders",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:(0,t.jsx)(R.OrdersTab,{passthroughOrders:eV,cancelingOrderId:th,onCancelPassthroughOrder:tm,livePrice
2s:Y,executingOrderId:tf,onExecuteNow:tb,limitCloseOrders:eH,onPositionChange:K,onUpdatePriority:(e,t,r)=>{eB({orderPda:e,profileIndex:t,priority:r})},onBatchUpdatePriorities:tv})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"history",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:"disconnected"===eG?(0,t.jsx)(B.TabConnectEmptyState,{title:ei("connectToViewHistory"),hint:ei("connectToViewHistoryHint")}):(0,t.jsxs)(t.Fragment,{children:[z&&(0,t.jsx)(l.HistoryReadControls,{view:z}),(0,t.jsx)(D.HistoryTab,{reportToolbarTarget:eg,lifecycles:ti,rewardPayouts:e2,lifetimeStats:tn,unverifiedRead:!!z&&(0,a.hasUnverifiedAccountUpdate)(z.availability)||e0.isError||eQ&&to,chainActions:ta,chainLoading:tl,phoenixDirectActions:tt,dataSource:td,dbDown:eQ,isLoading:(z?z.loading&&0===e3.length:q)||!!eu&&"history"===ea&&e0.isPending,filtersActive:e8,onResetFilters:e9,sideFilter:eC,assetFilter:e_,period:eP,customDateFrom:eE,customDateTo:eF,hasMore:V&&!e8,isFetchingNextPage:H,onLoadMore:W,phoenixDirectHasMore:e0.hasNextPage,phoenixDirectLoadingMore:e0.isFetchingNextPage,phoenixDirectReadBlocked:e0.requestBlocked,onLoadMorePhoenixDirect:e0.loadMore})]})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"order_history",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:(0,t.jsx)(tw,{})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"funding_history",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:(0,t.jsx)(tX,{positions:r})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"deposits",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:(0,t.jsx)(rc,{})}),(0,t.jsx)(g.TabsContent,{inert:en||void 0,"aria-hidden":en||void 0,value:"pnl",className:"m-0 flex-1 min-h-0 min-w-0 overflow-x-auto",children:eu?(0,t.jsxs)(t.Fragment,{children:[z&&(0,t.jsx)(l.HistoryReadControls,{view:z}),(0,t.jsx)(rC,{lifecycles:i,createdProfiles:eJ,hasMore:V,isFetchingNextPage:H,onLoadMore:W,historyScopeKey:`${eu??"disconnected"}:${z?.availability.metadata?.visibility??"unknown"}`,historyReady:!!eu&&!q&&!eQ&&!!z&&"available"===z.availability.status&&!z.stale&&!z.olderStale&&!z.availability.exits.length&&(!z.hasOlderPages||z.olderAvailability?.status==="available"),historyError:eQ||z?.availability.status==="unavailable"||z?.olderAvailability?.status==="unavailable",dataUpdatedAt:Math.min(z?.availability.lastSuccessAt??0,z?.hasOlderPages?z.olderAvailability?.lastSuccessAt??0:1/0)})]}):"disconnected"===eG?(0,t.jsx)(B.TabConnectEmptyState,{desktop:!0,title:ei("connectToViewPnl"),hint:ei("connectToViewPnlHint")}):(0,t.jsxs)("div",{className:"flex items-center justify-center py-12",role:"status",children:[(0,t.jsx)(p.Loader2,{className:"size-6 animate-spin text-muted-foreground"}),(0,t.jsx)("span",{className:"sr-only",children:ei("loadingEllipsis")})]})})]})})}function rR(){let e=(0,m.useTranslations)("settings");return(0,t.jsx)("div",{role:"status",className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:e("multiChartLoading")})}e.s(["MultiChartLoadError",0,function(){let e=(0,m.useTranslations)("settings"),r=(0,m.useTranslations)("common");return(0,t.jsxs)("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2 px-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:e("multiChartLoadFailed")}),(0,t.jsx)("button",{type:"button",onClick:()=>window.location.reload(),className:"focus-ring rounded text-foreground underline",children:r("refresh")})]})},"MultiChartLoading",0,rR],933657);let rD=(0,r.default)(()=>e.A(382630).then(e=>e.MultiChartWorkspaceTicket),{loadableGenerated:{modules:[29363]},ssr:!1,loading:()=>(0,t.jsx)(rR,{})});function rI(e){let r=(0,s.useDesktopWorkspacePanelVisible)(),a=(0,s.useDesktopWorkspacePanelActive)(),{desktopCharts:l}=(0,i.useMarketContext)();return l.enabled?(0,t.jsx)(rD,{...e}):(0,t.jsx)(n.JupiterPerpsTradingPanel,{...e,active:r,hotkeys:a})}function rU(e){let r=(0,s.useDesktopWorkspacePanelActive)();return(0,t.jsx)(rF,{...e,hotkeys:r})}},765960,367884,992616,128144,635753,583568,526370,458924,308871,454358,378650,75764,557723,87942,282080,519063,796049,197944,901715,665709,376326,e=>{"use strict";e.s(["QuickTradeModal",()=>ry],665709),e.s(["SunriseOrderbookPanel",()=>t4],282080),e.s(["PoolOrderbook",()=>t2],87942),e.s(["PhoenixOrderbook",()=>tI],557723),e.s(["TerminalStatusBar",()=>
2to],378650),e.s(["JupiterPerpsHeader",()=>eR],765960),e.s(["AccountBalancePill",()=>O],367884);var t=e.i(394390),r=e.i(183023),i=e.i(457058),s=e.i(465217),n=e.i(1169),a=e.i(58596),l=e.i(942553),o=e.i(575146),d=e.i(406470),c=e.i(299959);e.i(965155);var u=e.i(250672),h=e.i(875574),p=e.i(142298),m=e.i(894771),f=e.i(599059),x=e.i(430232),g=e.i(942289);e.i(654249);var b=e.i(71917),v=e.i(759550),y=e.i(76990),w=e.i(678872),j=e.i(585457),S=e.i(859394),k=e.i(741697),N=e.i(225806),P=e.i(508972),T=e.i(921575),C=e.i(931387),M=e.i(88783),_=e.i(441253),A=e.i(202647),E=e.i(528277),L=e.i(282027),F=e.i(623984),R=e.i(462503),D=e.i(347554),I=e.i(153517),U=e.i(466134);function O({className:e,fundMode:i,onFundModeChange:s,accounts:a=!1,desktopPerps:u=!1,compactHeader:h=!1}){let f=(0,l.useTranslations)("trading"),x=(0,l.useTranslations)("wallet"),g=(0,l.useTranslations)("common"),b=(0,c.useFormatters)(),{activeProfileIndex:v,createdProfiles:y,setActiveProfileIndex:w}=(0,m.useProfile)(),j=(0,D.usePortfolioValues)(),{profiles:S,isLoading:k,isStale:N}=j,{publicKey:P}=(0,p.useUnifiedWallet)(),T=(0,F.useOnramp)(),[$,V]=(0,r.useState)(!1),[H,W]=(0,r.useState)(null),q=void 0!==i?i:H,K=s??W,G=null!==v,Y=G?S.get(v):null,X=Y?.unrealizedValue??0,Q=Y?.investedValue??0,J=Y?.cashBalance??0,Z=Y?.lockedInOrders??0,ee=!k&&!!Y?.cashUnknown,et=y.find(e=>e.index===v)??null,er=e=>{var t;return u&&k?"$…":`$${t=b.intlTag,e>=1e6?(0,d.formatFixed)(e/1e6,2,t)+"M":e>=1e3?(0,d.formatFixed)(e/1e3,2,t)+"K":(0,d.formatFixed)(e,2,t)}`},ei=u&&!k&&(!G||!Y),es=ei||u&&ee?"—":er(X),en=e=>{V(!1),K(e)};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(o.Popover,{open:$,onOpenChange:V,children:[(0,t.jsx)(o.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":u?x("accountAndPortfolio"):void 0,title:h?`${x("activeAccount")}${et?` \xb7 ${et.name}`:""}: ${es}`:void 0,className:(0,I.cn)("focus-ring flex items-center gap-2 px-3 transition-colors hover:bg-surface-interactive",u?"h-[34px] min-w-[115px] max-w-[200px] shrink-0 rounded-[5.112px] bg-[#161719]":"h-9 rounded-lg bg-surface-raised",h&&C.default.accountControl,e),children:[(0,t.jsx)("span",{className:(0,I.cn)("shrink-0 font-medium tabular-nums text-foreground",u?"text-[14.313px]":"text-sm"),children:es}),et&&(0,t.jsx)("span",{className:(0,I.cn)("hidden max-w-[9ch] truncate text-muted-foreground md:inline",u?"text-[13.29px]":"text-sm",h&&C.default.accountName),children:et.name}),u&&N&&(0,t.jsx)(L.TriangleAlert,{"aria-hidden":!0,className:"size-3 shrink-0 text-amber-400"}),u?(0,t.jsx)("img",{src:"/desktop-dashboard/balance-chevron.svg",alt:"",className:$?"shrink-0 rotate-180":"shrink-0"}):(0,t.jsx)(n.ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),(0,t.jsxs)(o.PopoverContent,{align:"end",className:(0,I.cn)("max-h-[min(640px,calc(100dvh-80px))] overflow-y-auto p-0",u?"w-[330px] rounded-[7px]":"w-72"),children:[(0,t.jsxs)("div",{className:"space-y-2 p-3",children:[(0,t.jsxs)("span",{className:"text-[10px] font-medium tracking-tight text-label-muted",children:[u?x("activeAccount"):g("total"),u&&et?` \xb7 ${et.name}`:""]}),(0,t.jsx)("div",{className:"font-mono text-2xl tabular-nums text-foreground",children:es}),(0,t.jsxs)("div",{className:"space-y-1 pt-1 text-xs",children:[(0,t.jsx)(z,{label:g("positions"),value:ei?"—":er(Q)}),Z>0&&(0,t.jsx)(z,{label:g("orders"),value:er(Z)}),(0,t.jsx)(z,{label:f("cash"),value:ei||ee?"—":er(J)})]})]}),a&&y.length>0&&(0,t.jsxs)("div",{className:"border-t border-border p-2",children:[(0,t.jsx)("span",{className:"px-1 text-[10px] font-medium tracking-tight text-label-muted",children:x("navAccount")}),(0,t.jsx)("div",{className:"mt-1 flex flex-col",children:y.map(e=>{let r=e.index===v,i=S.get(e.index);return(0,t.jsxs)("button",{type:"button",onClick:()=>{r||w(e.index),V(!1)},className:(0,I.cn)("focus-ring flex items-center justify-between gap-3 rounded-md px-2 py-1.5 text-left","transition-colors hover:bg-surface-interactive",r&&"bg-surface-interactive"),children:[(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(A.Check,{className:(0,I.cn)("size-3.5 shrink-0",r?"text-primary":"opacity-0")}),(0,t.jsx)("span",{className:"truncate text-[13px] text-foreground",children:e.name})]}),(0,t.jsx)("span",{className:"shrink-0 font-mono text-[12px] tabular-nums text-muted-foreground",children:u&&!k&&(!i||i.cashUnknown)?"—":er(i?.unrealizedValue??0)})]},e.index)})})]}),u&&(0,t.jsx)("div",{className:"border-t border-border p-3",children:(0,t.jsx)(R.PortfolioValueBreakdown,{values:j,walletAddress:P?.toBase58(),inline:!0})}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-1 border-t border-border p-2",children:[T.available&&(0,t.jsx)(B,{icon:(0,t.jsx)(E.CreditCard,{className:"h-4 w-4"}),label:x("buyWithCard"),disabled:T.isOpening,onClick:()=>{V(!1),T.buy()}}),(0,t.jsx)(B,{icon:(0,t.jsx)(M.ArrowDownToLine,{className:"h-4 w-4"}),label:x("deposit"),onClick:()=>en("deposit")}),(0,t.jsx)(B,{icon:(0,t.jsx)(_.ArrowUpFromLine,{className:"h-4 w-4"}),label:x("withdraw"),onClick:()=>en("withdraw")})]})]})]}),void 0===i&&null!==q&&(0,t.jsx)(U.DepositWithdrawDialog,{open:!0,onOpenChange:e=>{e||K(null)},initialMode:q},q)]})}function B({icon:e,label:r,onClick:i,disabled:s}){return(0,t.jsxs)("button",{type:"button",onClick:i,disabled:s,className:(0,I.cn)("focus-ring flex flex-col items-center gap-1.5 rounded-lg px-2 py-2.5","text-[11px] text-secondary-foreground transition-colors","hover:bg-surface-interactive hover:text-foreground","disabled:opacity-40 disabled:hover:bg-transparent"),children:[e,(0,t.jsx)("span",{className:"text-center leading-tight",children:r})]})}function z({label:e,value:r}){return(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:e}),(0,t.jsx)("span",{className:"tabular-nums text-foreground",children:r})]})}var $=e.i(319136),V=e.i(889563);function H(e){let t=(0,r.useRef)(void 0),i=(0,r.useRef)(null),[s,n]=(0,r.useState)("");return(0,r.useEffect)(()=>
2{if(void 0===e||void 0===t.current){t.current=e;return}if(e!==t.current)return n(e>t.current?"price-tick-up":"price-tick-down"),t.current=e,i.current&&clearTimeout(i.current),i.current=setTimeout(()=>n(""),300),()=>{i.current&&clearTimeout(i.current)}},[e]),s}var W=e.i(744427),q=e.i(157157),K=e.i(259048),G=e.i(873029);function Y({label:e,className:r,valueClassName:i,children:s,...n}){return(0,t.jsxs)("div",{"data-slot":"market-stat",className:(0,I.cn)("flex flex-col justify-center gap-0.5 border-l border-border px-4 first:border-l-0 first:pl-0 whitespace-nowrap",r),...n,children:[(0,t.jsx)("span",{"data-slot":"market-stat-label",className:"text-3xs font-medium uppercase tracking-wider text-label-muted",children:e}),(0,t.jsx)("div",{"data-slot":"market-stat-value",className:(0,I.cn)("text-xs font-semibold font-mono tabular-nums text-foreground",i),children:s})]})}function X(...e){let t=e.map(Math.abs).filter(e=>e>0);return 0===t.length||Math.min(...t)>=1e-4?4:6}function Q(e,t,r){return 0!==e&&1e-6>Math.abs(e)?`${e<0?"-":""}<${(0,d.formatFixed)(1e-6,6,r)}%`:`${(0,d.formatFixed)(e,t,r)}%`}function J(e,t,r){return`${e>=0?"+":""}${Q(e,t,r)}`}function Z(e,t){if("borrow"===e.kind){let r=X(e.longPerHourPct,e.shortPerHourPct);return{labelKey:"borrow1h",long:Q(e.longPerHourPct,r,t),short:Q(e.shortPerHourPct,r,t)}}return{labelKey:"funding1h",text:J(e.longPerHourPct,X(e.longPerHourPct),t),value:e.longPerHourPct}}var ee=e.i(810661),et=e.i(989714);function er({venue:e,stats:r}){let i=(0,l.useTranslations)("trading"),s=(0,c.useFormatters)(),n="armada"===e?f.HEDGE_VENUE_LABELS[e]:f.VENUE_LABELS[e],a=r.fundingRate1hPct,o=r.imperialFundingRate1hPct,d=(0,et.useTickingNowSecs)(null!=r.nextFundingAtMs),u=null!=r.nextFundingAtMs?r.nextFundingAtMs/1e3-d:0,h=X(...[o,a].filter(e=>null!=e)),p=null==a?null:(0,t.jsx)("div",{className:"text-muted-foreground text-[11px] leading-[14px] font-normal font-mono tabular-nums",children:i("hedgeFundingInline",{venue:n,rate:J(a,h,s.intlTag)})});return(0,t.jsxs)(es,{label:i("funding1h"),help:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("p",{children:null==o?i("sunriseFundingNone"):i("sunriseFundingTooltip",{rate:Q(24*o,X(24*o),s.intlTag),side:o>=0?"long":"short"})}),null!=a&&(0,t.jsx)("p",{className:"text-muted-foreground",children:i("hedgeFundingTooltip",{venue:n})}),u>0&&(0,t.jsxs)("p",{className:"text-muted-foreground",children:[i("nextFundingHedge",{venue:n})," ",(0,ee.fmtCountdown)(u)]})]}),children:[null==o?(0,t.jsx)("div",{className:"text-foreground",children:"—"}):(0,t.jsx)("div",{className:`font-mono tabular-nums ${o>=0?"text-emerald-400":"text-red-400"}`,children:J(o,h,s.intlTag)}),p]})}function ei({venue:e,rate:r}){let i=(0,l.useTranslations)("trading"),s=(0,c.useFormatters)(),n=f.VENUE_LABELS[e];if(!r)return(0,t.jsx)(Y,{label:i("funding1h"),children:"—"});let a=Z(r,s.intlTag);if("borrow1h"===a.labelKey){let e=X(24*r.longPerHourPct,24*r.shortPerHourPct);return(0,t.jsx)(es,{label:i("borrow1h"),help:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("p",{children:i("borrowFeeTooltip",{venue:n})}),(0,t.jsx)("p",{className:"text-muted-foreground",children:i("perDayLongShort",{long:Q(24*r.longPerHourPct,e,s.intlTag),short:Q(24*r.shortPerHourPct,e,s.intlTag)})})]}),children:i("borrowSides",{long:a.long,short:a.short})})}let o=a.value;return(0,t.jsx)(es,{label:i("funding1h"),help:i("fundingTooltip",{venue:n,rate:Q(24*o,X(24*o),s.intlTag),side:o>=0?"long":"short"}),children:(0,t.jsx)("span",{className:(0,K.pnlColor)(o),children:a.text})})}function es({label:e,help:r,children:i}){let s=(0,l.useTranslations)("trading");return(0,t.jsx)(Y,{label:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1",children:[e,(0,t.jsxs)(o.Popover,{children:[(0,t.jsx)(o.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":s("rateInfoLabel",{label:e}),className:"focus-ring relative inline-flex size-4 shrink-0 items-center justify-center rounded text-label-muted hover:text-foreground after:absolute after:-inset-3 [@media(pointer:fine)]:after:hidden",children:(0,t.jsx)(G.Info,{className:"size-3","aria-hidden":"true"})})}),(0,t.jsx)(o.PopoverContent,{side:"bottom",align:"start","aria-label":s("rateInfoLabel",{label:e}),className:"w-64 max-w-[calc(100vw-2rem)] space-y-1 bg-surface px-3 py-2 text-xs font-normal normal-case tracking-normal leading-relaxed",children:r})]})]}),children:i})}var en=e.i(679555);let ea="imperial_market_stats_open",el=!1,eo=!1,ed=new Set;function ec(){for(let e of ed)e()}
2function eu(e){if(ed.add(e),!eo){try{el="1"===sessionStorage.getItem(ea)}catch{}eo=!0,ec()}return()=>{ed.delete(e)}}function eh({id:e,open:i,animate:s,cells:n}){let a=53*!!i,[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(i);return d!==i&&(c(i),s&&o(!0)),(0,r.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>o(!1),200);return()=>window.clearTimeout(e)},[l,i]),(0,t.jsx)("div",{id:e,"data-market-stats-disclosure":!0,inert:!i,"aria-hidden":!i,style:{height:a},onTransitionEnd:e=>{"height"===e.propertyName&&o(!1)},className:`overflow-hidden ${l?"absolute left-0 right-0 top-full z-20 bg-[var(--phone-band)]":""} ${s?"transition-[height] duration-[160ms] ease-out motion-reduce:transition-none":""}`,children:(0,t.jsx)("div",{style:{gridTemplateColumns:`repeat(${n.length}, minmax(0, 1fr))`,height:52},className:"grid items-center gap-2 border-b border-border px-3.5",children:n.map(e=>(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-3xs font-medium uppercase tracking-wider text-label-muted",children:e.label}),"loading"===e.state?(0,t.jsx)(en.Skeleton,{className:"h-3 w-4/5 rounded-[3px]"}):(0,t.jsx)("span",{className:`overflow-hidden text-ellipsis font-mono text-2xs font-semibold tabular-nums ${"value"===e.state&&e.valueClass||"text-foreground"}`,children:"unknown"===e.state?"—":e.value})]},e.id))})})}var ep=e.i(907169),em=e.i(631797);let ef="https://imperial.space";function ex({pulse:e}){return(0,t.jsxs)("a",{href:ef,className:"focus-ring flex min-h-11 min-w-11 shrink-0 items-center rounded-md",children:[(0,t.jsx)(em.ImperialMark,{variant:"brand",pulse:e,className:"h-4 w-auto shrink-0"}),(0,t.jsx)("span",{className:"sr-only",children:"Imperial"})]})}e.s(["BrandLink",0,function({compactHeader:e=!1}){return(0,t.jsxs)("a",{href:ef,"aria-label":"Imperial",className:"focus-ring flex h-[34px] min-w-[34px] shrink-0 items-center rounded-md",children:[(0,t.jsx)(i.default,{src:"/[email protected]",alt:"Imperial",width:120,height:32,className:e?`h-auto w-[138.014px] ${C.default.brandWordmark}`:"h-8 w-auto",priority:!0}),e&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(em.ImperialMark,{variant:"brand",className:C.default.brandMark}),(0,t.jsx)("span",{className:"sr-only",children:"Imperial"})]})]})},"PhoneBrandLink",0,ex],992616);var eg=e.i(967678),eb=e.i(470981),ev=e.i(42013),ey=e.i(369018),ew=e.i(148292);function ej({address:e,onOpen:s,compact:a=!1}){let o=(0,l.useTranslations)("wallet"),{wallet:d}=(0,ev.useWallet)(),{walletName:c}=(0,h.useUnifiedWalletContext)(),{username:u}=(0,m.useProfile)(),p=(0,ew.usePrimaryDomain)(e),f=u||p||(0,I.shortAddress)(e),[x,g]=(0,r.useState)(null),b=d?.adapter.icon??null,v=function({isMwa:e,adapterIcon:t,failedSrc:r}){return e||!t||t===r?"/icons/app/icon-192.png":t}({isMwa:c===ey.MWA_WALLET_NAME,adapterIcon:b,failedSrc:x});return(0,t.jsxs)("button",{type:"button",onClick:s,"aria-label":`${o("navAccount")}: ${f} (${e})`,title:e,className:`focus-ring hit-target flex h-[34px] shrink-0 items-center gap-[5px] rounded-[5px] border-[0.875px] border-[var(--phone-chip-border)] bg-[var(--phone-chip)] px-[9px] [--hit:44px] ${a?"max-[380px]:gap-1 max-[380px]:px-1.5":""}`,children:[(0,t.jsx)(i.default,{src:v,alt:"",width:14,height:14,unoptimized:!0,onError:()=>g(b),className:"h-3.5 w-3.5 shrink-0 rounded-[3px] object-contain"}),(0,t.jsx)("span",{className:`max-w-[90px] truncate text-2xs font-medium text-foreground ${u||p?"":"font-mono tabular-nums"}`,children:f}),(0,t.jsx)(n.ChevronDown,{"aria-hidden":!0,className:`h-3 w-3 shrink-0 text-muted-foreground ${a?"max-[380px]:hidden":""}`})]})}let eS="hit-target focus-ring flex shrink-0 items-center justify-center bg-[image:var(--gradient-cta)] text-[11.6px] font-semibold text-[color:var(--on-cta)] transition-transform active:scale-95 motion-reduce:transition-none [--hit:44px]",ek=(0,r.memo)(function({insetClassName:e,onOpenAccount:i,onDeposit:s}){let n=(0,l.useTranslations)("trading"),a=(0,l.useTranslations)("wallet"),{publicKey:o,isLoading:d}=(0,h.useUnifiedWalletContext)(),c=d?"settling":o?"connected":"disconnected",[u,p]=(0,r.useState)(!1);(0,r.useEffect)(()=>
2{if("settling"!==c)return;let e=setTimeout(()=>p(!0),3e3);return()=>{clearTimeout(e),p(!1)}},[c]);let m="settling"===c&&!u,f="disconnected"===c||"settling"===c&&u,g=(0,r.useSyncExternalStore)(eb.pulseMark.subscribe,eb.pulseMark.getSnapshot,eb.pulseMark.getServerSnapshot),[b,v]=(0,r.useState)(g);(0,r.useEffect)(()=>{if(g===b)return;let e=setTimeout(()=>v(g),600);return()=>clearTimeout(e)},[g,b]);let y=g!==b;return(0,t.jsxs)("div",{"data-slot":"home-identity",style:{height:eg.IDENTITY_ROW_PX},className:`flex items-center gap-2 ${e}`,children:[(0,t.jsx)(ex,{pulse:y}),(0,t.jsx)(ep.ArmadaAccessEntry,{phone:!0}),f?(0,t.jsx)("button",{type:"button",onClick:x.promptConnectWallet,className:`${eS} ml-auto h-[31px] w-[113px] rounded-[5px]`,children:a("getStarted")}):(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-2",inert:m,children:[(0,t.jsx)("button",{type:"button",onClick:s,className:`${eS} h-[34px] rounded-[5px] px-[15px] max-[380px]:px-[10px]`,children:n("deposit")}),i&&(m||!o?(0,t.jsx)(en.Skeleton,{className:"h-[34px] w-[72px] rounded-[5px]"}):(0,t.jsx)(ej,{compact:!0,address:o.toBase58(),onOpen:i}))]})]})});e.s(["PhoneIdentityRow",0,ek],128144);var eN=e.i(268680);let eP="imperial:desktop-market-search",eT="desktop-market-search-trigger",eC="imperial:desktop-market-search-target",eM=!1,e_=new Set;function eA(e){eM!==e&&(eM=e,e_.forEach(e=>e()))}e.s(["DESKTOP_MARKET_SEARCH_EVENT",0,eP,"DESKTOP_MARKET_SEARCH_REQUEST_EVENT",0,eC,"DESKTOP_MARKET_SEARCH_TRIGGER_ID",0,eT,"getDesktopMarketSearchOpen",0,function(){return eM},"openDesktopMarketSearch",0,function(e,t){window.dispatchEvent(new CustomEvent(eC,{detail:{target:e,anchor:t}}))},"setDesktopMarketSearchOpen",0,eA,"subscribeDesktopMarketSearch",0,function(e){return e_.add(e),()=>{e_.delete(e)}},"toggleDesktopMarketSearch",0,function(){window.dispatchEvent(new Event(eP))}],635753);var eE=e.i(111468),eL=e.i(710729);function eF(e,t){return e>=1e9?`$${(0,d.formatNumber)(e/1e9,{},t)}B`:e>=1e6?`$${(0,d.formatNumber)(e/1e6,{},t)}M`:e>=1e3?`$${(0,d.formatNumber)(e/1e3,{},t)}K`:`$${(0,d.formatNumber)(e,{},t)}`}function eR({desktopChartTools:e,layout:d,marketMint:h,marketInfo:C,allMarkets:M,phoenixStats:_,resolvedUnderwriter:A,gmTradePrice:E,onOpenProfile:L,onDeposit:F,onMarketDrawerChange:R,marketDrawerOpen:D,onMarketPick:I}){let B,z,G,X="phoenix"===A?_:null,Q=(0,l.useTranslations)("trading"),J=(0,c.useFormatters)(),{setMarketMint:ee,desktopCharts:et}=(0,j.useMarketContext)(),es="desktop"===d,[en,eo]=(0,r.useState)(null),[ed,ep]=(0,r.useState)(!1),[em,ef]=(0,r.useState)(!1),[ex,eg]=(0,r.useState)(null),[eb,ev]=(0,r.useState)(null),ey=(0,r.useRef)(null),ew=null!==ex&&null===eb,ej=(0,r.useCallback)(()=>{ey.current=null,ef(!1),ep(!1)},[]);(0,r.useEffect)(()=>{if(es)return eA(ed),()=>eA(!1)},[es,ed]);let eS=(0,r.useCallback)(()=>{ey.current=null,ev(null),eg(es?document.getElementById(eT):null),ef(!1),ep(!0)},[es]);(0,r.useEffect)(()=>{if(!es)return;let e=()=>{ed?ej():eS()};return window.addEventListener(eP,e),()=>window.removeEventListener(eP,e)},[es,eS,ed,ej]),(0,r.useEffect)(()=>{if("desktop"===d&&ed)return window.addEventListener(k.CHART_POINTER_DOWN_EVENT,ej),()=>window.removeEventListener(k.CHART_POINTER_DOWN_EVENT,ej)},[d,ed,ej]),(0,r.useEffect)(()=>{if(!es)return;let e=e=>{let t=e.detail;if(t?.anchor?.isConnected&&et.isTargetCurrent(t.target)){if(ed&&ey.current?.anchor===t.anchor)return void ej();ey.current=t,ev(t),eg(t.anchor),ef(!1),ep(!0)}};return window.addEventListener(eC,e),()=>window.removeEventListener(eC,e)},[es,et,ed,ej]),(0,r.useEffect)(()=>{!ed||!eb||eb.anchor.isConnected&&et.isTargetCurrent(eb.target)||queueMicrotask(()=>{ey.current===eb&&ej()})},[ed,eb,et,ej]),(0,r.useEffect)(()=>()=>{ey.current=null},[]);let eM=eb&&"add"!==eb.target.kind?et.cells.findIndex(e=>"fill"===eb.target.kind?e.position===eb.target.position&&!e.slot:"replace"===eb.target.kind&&e.slot?.id===eb.target.chartId):-1,e_=eb?et.cells[eM]?.slot?.marketMint??"":h,eD=eb?"add"===eb.target.kind?Q("chartDeskAdd"):"fill"===eb.target.kind?Q("chartDeskChoose"):Q("chartDeskChange",{symbol:M.find(e=>e.mint===e_)?.symbol??e_}):void 0,eI=(0,S.useRouter)(),eU=(0,r.useRef)(null),{publicKey:eO}=(0,p.useUnifiedWallet)(),{activeProfileUnderwriter:eB,activeProfileExcludedVenues:ez}=(0,m.useProfile)(),{price:e$}=(0,u.usePythPriceContext)(),{book:eV,isPending:eH}=(0,W.useSunriseOrderbook)(C.symbol,A),eW=eV?.stats.markPrice??E??e$,eq=H(eW),eK=H(X?.markPx),{rate:eG,isPending:eY}=(0,q.useVenueFundingRate)(C.symbol,A),{stats:eX,isPending:eQ}=(0,$.useVenueMarketStats)(!0,ez),eJ=eX.get(C.symbol),eZ=function(e){let[t,i]=(0,r.useState)(null);return(0,r.useEffect)(()=>{let t=!1;i(null);let r=async()=>{try{let r=Math.floor(Date.now()/1e3),s=await (0,V.getChartData)(e,"regular","1H",{timeFrom:r-86400,timeTo:r});if(t||0===s.length)return;let n=-1/0,a=1/0;for(let e of s)e.high>n&&(n=e.high),e.low<a&&(a=e.low);let l=s[0].open,o=s[s.length-1].close;i({high24h:n,low24h:a,priceChange24h:l>0?(o-l)/l*100:0})}catch(e){console.error("Failed to fetch 24h stats:",e)}};r();let s=setInterval(r,6e4);return()=>{t=!0,clearInterval(s)}},[e]),t}(h),e0=M.find(e=>e.mint===h),e1=e0?.maxLeverage,{data:e2,isPlaceholderData:e5}=(0,y.usePhoenixMarkets)(),{data:e3}=(0,w.useLendingPoolState)(),e4=(0,r.useMemo)(()=>e2?.find(e=>e.symbol===C.symbol)??null,[e2,C.symbol]),e6=e4&&e4.maxLeverage>0&&isFinite(e4.maxLeverage)?e4.maxLeverage:void 0,e8=(0,r.useMemo)(()=>!e3||null==e6||ez.includes("phoenix")?null:(0,b.loanAwareMaxLeverage)(e6,(0,v.toRouterPoolState)(e3),C.symbol),[e3,e6,ez,C.symbol]),e9=(0,r.useMemo)(()=>{let e=e1||void 0;return null!=e8?Math.round(null!=e?Math.max(e,e8):e8):null!=e?Math.round(e):void 0},[e1,e8]),e7=(0,r.useMemo)(()=>{let e=e0?.leverageByUnderwriter;if(!e)return[];let t=Object.entries(e).filter(([,e])=>"number"==typeof e&&e>0).map(([e,t])=>({venue:e,cap:(0,g.floorTo2)(t)}));return t.sort((e,t)=>
2t.cap-e.cap),t},[e0]),te=(0,r.useId)(),tt=(0,r.useSyncExternalStore)(eu,()=>el,()=>!1),[tr,ti]=(0,r.useState)(!1),ts=null!==e4,tn="phoenix"===A&&(e5||ts&&!X),ta=(0,r.useMemo)(()=>{if("phone"!==d||!tt)return[];let e=(e,t,r,i)=>null!==r?{id:e,label:t,state:"value",value:r}:i?{id:e,label:t,state:"loading"}:null,t="armada"===A,r=t?eV?.stats.indexPrice:X?.oraclePx,i=e("index",Q("index"),null!=r?`$${J.number(r)}`:null,t?eH:tn),s=eJ?.volume24hUsd??null,n=e("volume",Q("volume24h"),null!==s?`$${J.numberShort(s)}`:null,eQ),a=eJ?.totalOiUsd??null,l=e("oi",Q("openInterest"),null!==a?`$${J.numberShort(a)}`:null,eQ),o=eV?.stats.imperialFundingRate1hPct,c=t?null!=o?{kind:"funding",longPerHourPct:o,shortPerHourPct:-o}:null:eG,u=c?Z(c,J.intlTag):null,h=Q(u?.labelKey??"funding1h");return[i,n,l,u?"borrow1h"===u.labelKey?{id:"funding",label:h,state:"value",value:Q("borrowSides",{long:u.long,short:u.short})}:{id:"funding",label:h,state:"value",value:u.text,valueClass:(0,K.pnlColor)(u.value)}:{id:"funding",label:h,state:(t?eH:eY)?"loading":"unknown"}].filter(e=>null!==e)},[d,tt,X,tn,eJ,eQ,eG,eY,A,eV,eH,J,Q]),tl=(0,r.useCallback)(e=>{if(eb){if(ey.current!==eb)return;M.some(t=>t.mint===e)&&et.selectTarget(eb.target,e),ej();return}ej(),R?.(!1),e!==h&&(I?I(e):ee(e))},[h,R,I,ee,eb,M,et,ej]),to="phone"===d&&(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,t.jsxs)("button",{type:"button",onClick:e=>{eU.current=e.currentTarget,R(!0)},"aria-label":`${Q("exploreMarket")}: ${C.symbol}`,"aria-haspopup":"dialog","aria-expanded":D,className:"focus-ring flex h-[35px] min-w-0 items-center gap-1 text-left",children:[(0,t.jsx)(i.default,{src:C.image,alt:"",width:22,height:22,className:"shrink-0 rounded-full",unoptimized:!0,onError:s.handleTokenImageError}),(0,t.jsx)("span",{className:"truncate text-[17.07px] font-semibold text-foreground",children:C.symbol}),e1&&(0,t.jsxs)("span",{className:"shrink-0 text-[11px] font-medium tracking-[0.17px] text-[#8C9199]",children:[e9,"x"]}),(0,t.jsx)(n.ChevronDown,{"aria-hidden":!0,className:"h-3 w-3 shrink-0 text-muted-foreground"})]}),(0,t.jsxs)("button",{type:"button",onClick:()=>{ti(!0),el=!el;try{sessionStorage.setItem(ea,el?"1":"0")}catch{}ec()},"aria-expanded":tt,"aria-controls":te,className:"focus-ring ml-1 flex h-[35px] shrink-0 items-center gap-2 text-left",children:[X?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:`text-[18.2px] font-bold tabular-nums ${eK}`,children:["$",J.number(X.markPx)]}),X.prevDayPx>0&&(B=(X.markPx-X.prevDayPx)/X.prevDayPx*100,(0,t.jsx)("span",{className:`text-[14.8px] font-medium tabular-nums ${(0,K.pnlColor)(B)}`,children:J.signedPercent(B,2)}))]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:`text-[18.2px] font-bold tabular-nums ${eq}`,children:void 0!==eW?`$${J.number(eW)}`:"—"}),eZ&&(0,t.jsxs)("span",{className:`text-[14.8px] font-medium tabular-nums ${(0,K.pnlColor)(eZ.priceChange24h)}`,children:[eZ.priceChange24h>=0?"+":"",J.percent(eZ.priceChange24h,2)]})]}),(0,t.jsx)(n.ChevronDown,{"aria-hidden":!0,strokeWidth:2.5,className:`h-5 w-5 shrink-0 text-primary transition-transform duration-[160ms] motion-reduce:transition-none ${tt?"rotate-180":""}`})]})]}),td="desktop"===d;return(0,eE.useHotkey)("open-market-search",eS,td),(0,eE.useHotkey)("open-deposit",()=>eO?eo("deposit"):(0,x.promptConnectWallet)(),td),(0,eE.useHotkey)("open-withdraw",()=>eO?eo("withdraw"):(0,x.promptConnectWallet)(),td),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:es?"h-[48px] border-b border-border font-[family-name:var(--font-bai-jamjuree)]":"lg:border-b border-border lg:px-4 lg:py-2",children:["phone"===d&&(0,t.jsxs)("div",{className:"lg:hidden bg-[var(--phone-band)] pb-[5px]",children:[(0,t.jsx)(ek,{insetClassName:"pl-[18px] pr-[7px]",onOpenAccount:L,onDeposit:F}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsxs)("div",{"data-slot":"home-market",className:"flex h-[35px] items-center gap-1.5 pl-3.5 pr-[7px]",children:[(0,t.jsx)("div",{className:"flex h-full min-w-0 flex-1 items-center",children:to}),(0,t.jsx)("button",{ref:eU,type:"button",onClick:e=>{eU.current=e.currentTarget,R(!0)},"aria-label":Q("exploreMarket"),className:"focus-ring hit-target flex h-[34px] w-10 shrink-0 items-center justify-center rounded-[5px] border-[0.875px] border-[var(--phone-chip-border)] bg-[var(--phone-chip)] text-foreground [--hit:44px] ml-auto",children:(0,t.jsx)(a.Search,{className:"h-[11px] w-[11px]",strokeWidth:2.2})})]}),(0,t.jsx)(eh,{id:te,open:tt,animate:tr,cells:ta})]}),(0,t.jsx)(N.MobileMarketSelector,{returnFocusRef:eU,open:D,ownsHistory:!1,onOpenChange:R,carryOpen:em,onCarryOpenChange:ef,allMarkets:M,marketMint:h,onSelect:tl,activeProfileUnderwriter:eB,activeProfileExcludedVenues:ez})]}),"desktop"===d&&(0,t.jsxs)("div",{className:es?"hidden h-full items-center justify-between lg:flex":"hidden lg:flex items-center justify-between",children:[(0,t.jsxs)("div",{className:es?"flex h-full min-w-0 flex-1 items-center gap-[18px]":"flex items-center gap-2 md:gap-6 min-w-0 flex-1",children:[(0,t.jsxs)(o.Popover,{open:ed,onOpenChange:e=>{e?(ey.current=null,ev(null),eg(null),ep(!0)):ej()},children:[ex&&(0,t.jsx)(o.PopoverAnchor,{virtualRef:{current:ex}}),(0,t.jsx)(o.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:es?"focus-ring hidden h-full w-[236px] shrink-0 items-center justify-center gap-[9.201px] bg-[#161719] px-2 transition-colors hover:bg-surface-interactive lg:flex":"hidden lg:flex items-center gap-3 hover:bg-surface-interactive rounded-control px-2 py-1 transition-colors",children:(0,t.jsxs)("div",{className:es?"flex min-w-0 items-center gap-[9.201px]":"flex items-center gap-2",children:[(0,t.jsx)(i.default,{src:C.image,onError:s.handleTokenImageError,alt:C.symbol,width:es?27:32,height:es?27:32,className:es?"size-[29.857px] shrink-0 rounded-full":"rounded-full",unoptimized:!0}),(0,t.jsx)("span",{className:es?"min-w-0 truncate text-[18.194px] font-bold leading-normal text-[#f2f3f6]":"text-xl font-semibold text-foreground",children:`${C.symbol}-PERP`}),e1&&(e7.length>0?(0,t.jsxs)(eN.Tooltip,{children:[(0,t.jsx)(eN.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("span",{className:es?"flex h-[18.661px] min-w-[45.719px] shrink-0 items-center justify-center rounded-[2.545px] border border-[#2b2e33] bg-[#101112] px-1 text-[10.263px] font-normal leading-none tabular-nums text-white cursor-help":"text-xs font-medium font-mono tabular-nums text-muted-foreground bg-surface-raised rounded px-1.5 py-0.5 cursor-help",children:[e9,"x"]})}),(0,t.jsxs)(eN.TooltipContent,{side:"bottom",sideOffset:4,showArrow:!1,className:"text-xs px-3 py-2",children:[(0,t.jsx)("div",{className:"text-[11px] text-muted-foreground mb-1.5",children:Q("routingByLeverage")}),(0,t.jsxs)("div",{className:"space-y-1",children:[e7.map(({venue:e,cap:r})=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4 text-xs",children:[(0,t.jsx)("span",{className:"text-secondary-foreground",children:f.VENUE_LABELS[e]}),(0,t.jsx)("span",{className:"text-foreground tabular-nums",children:Q("upToLeverage",{leverage:`${r}x`})})]},e)),null!=e8&&(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4 text-xs border-t border-border pt-1 mt-1",children:[(0,t.jsx)("span",{className:"text-sky-400",children:Q("imperialLoanLower")}),(0,t.jsx)("span",{className:"text-sky-400 tabular-nums",children:Q("upToLeverage",{leverage:`${(0,g.floorTo2)(e8)}x`})})]})]})]})]}):(0,t.jsxs)("span",{className:es?"flex h-[18.661px] min-w-[45.719px] shrink-0 items-center justify-center rounded-[2.545px] border border-[#2b2e33] bg-[#101112] px-1 text-[10.263px] font-normal leading-none tabular-nums text-white":"text-xs font-medium font-mono tabular-nums text-muted-foreground bg-surface-raised rounded px-1.5 py-0.5",children:[e9,"x"]})),es&&(0,t.jsx)("svg",{"aria-hidden":"true",viewBox:"0 0 15.675 9.14373",fill:"none",className:"h-[9.143px] w-[15.674px] shrink-0 text-[#9ca3ae]",children:(0,t.jsx)("path",{d:"M1.30625 1.30625L7.83748 7.83748L14.3687 1.30625",stroke:"currentColor",strokeWidth:"2.61249",strokeLinecap:"round",strokeLinejoin:"round"})})]})})}),(0,t.jsx)(o.PopoverContent,{"aria-label":eD??Q("workspaceMarkets"),onInteractOutside:e=>{es&&(document.getElementById(eT)?.contains(e.target)||eb?.anchor.contains(e.target))&&e.preventDefault()},onCloseAutoFocus:e=>{!e.defaultPrevented&&ex?.isConnected&&(e.preventDefault(),ex.focus())},className:`w-[820px] max-w-[calc(100vw-24px)] p-0 shadow-2xl ${es?"rounded-[6px] overflow-hidden [&_input]:rounded-[5px]":""}`,align:ew?"end":"start",sideOffset:8,collisionPadding:12,children:em?(0,t.jsx)(P.PairCarryPanel,{onBack:()=>ef(!1),onOpened:()=>{ef(!1),ep(!1)},onBrowseAll:e=>{ef(!1),ep(!1),eI.push(e?`/pair-finder?long=${e.longSymbol}&short=${e.shortSymbol}`:"/pair-finder")}}):(0,t.jsx)(T.MarketSelectorTable,{allMarkets:M,marketMint:e_,onSelect:tl,enabled:ed,activeProfileUnderwriter:eB,activeProfileExcludedVenues:ez,onOpenCarry:es?void 0:()=>ef(!0),onDismiss:ej,searchLabel:eD,showQuickCards:!eb,refinedDesktop:es,showCarry:!es},eb?"add"===eb.target.kind?"add":"fill"===eb.target.kind?`fill:${eb.target.position}`:`replace:${eb.target.chartId}`:"global")})]}),(0,t.jsxs)("div",{tabIndex:0,className:es?"hidden h-full min-w-0 items-center gap-[20.4px] overflow-x-auto pt-0 lg:flex focus-ring [&_[data-slot=market-stat]]:shrink-0 [&_[data-slot=market-stat]]:border-0 [&_[data-slot=market-stat]]:px-0 [&_[data-slot=market-stat]]:gap-[3px] [&_[data-slot=market-stat-label]]:text-[12px] [&_[data-slot=market-stat-label]]:leading-[16
2px] [&_[data-slot=market-stat-label]]:font-normal [&_[data-slot=market-stat-label]]:normal-case [&_[data-slot=market-stat-label]]:tracking-normal [&_[data-slot=market-stat-label]]:text-[#9ca3ae] [&_[data-slot=market-stat-value]]:font-[family-name:var(--font-bai-jamjuree)] [&_[data-slot=market-stat-value]]:text-[13px] [&_[data-slot=market-stat-value]]:leading-[16px] [&_[data-slot=market-stat-value]]:font-bold [&_[data-slot=market-stat-value]_*]:font-[family-name:var(--font-bai-jamjuree)]":"hidden lg:flex items-stretch min-w-0 overflow-x-auto py-0.5 [mask-image:linear-gradient(to_right,black_calc(100%-20px),transparent)] focus-ring rounded-sm",children:[X?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Y,{label:Q("mark"),valueClassName:"text-sm",children:(0,t.jsxs)("span",{className:eK,children:["$",J.number(X.markPx)]})}),(0,t.jsxs)(Y,{label:Q("index"),children:["$",J.number(X.oraclePx)]}),X.prevDayPx>0&&(G=(z=X.markPx-X.prevDayPx)/X.prevDayPx*100,(0,t.jsx)(Y,{label:Q("change24h"),children:(0,t.jsxs)("span",{className:(0,K.pnlColor)(z),children:[z>=0?"▲":"▼"," $",J.fixed(Math.abs(z),2)," (",J.percent(Math.abs(G),2),")"]})}))]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Y,{label:eV?Q("mark"):Q("markPrice"),valueClassName:"text-sm",children:(0,t.jsx)("span",{className:eq,children:void 0!==eW?`$${J.number(eW)}`:"—"})}),eV?.stats.indexPrice!=null&&(0,t.jsxs)(Y,{label:Q("index"),valueClassName:"text-sm",children:["$",J.number(eV.stats.indexPrice)]}),eZ&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Y,{label:Q("change24hUpper"),children:(0,t.jsxs)("span",{className:(0,K.pnlColor)(eZ.priceChange24h),children:[eZ.priceChange24h>=0?"+":"",J.percent(eZ.priceChange24h,2)]})}),(0,t.jsxs)(Y,{label:Q("high24h"),children:["$",J.number(eZ.high24h)]}),(0,t.jsxs)(Y,{label:Q("low24h"),children:["$",J.number(eZ.low24h)]})]})]}),eV?(0,t.jsx)(er,{venue:A,stats:eV.stats}):(0,t.jsx)(ei,{venue:A,rate:eG}),eJ?.volume24hUsd!=null&&(0,t.jsx)(Y,{label:Q("volume24h"),children:eF(eJ.volume24hUsd,J.intlTag)}),eJ?.totalOiUsd!=null&&(0,t.jsx)(Y,{label:Q("openInterest"),children:eF(eJ.totalOiUsd,J.intlTag)})]})]}),es&&(0,t.jsxs)("div",{className:"flex shrink-0 items-center px-1","data-chart-workspace-tools":"",children:[e,(0,t.jsx)(eL.DesktopWorkspacePanelTools,{})]}),eO&&!es&&(0,t.jsx)("div",{className:"hidden lg:flex items-center gap-3 shrink-0 pl-3",children:(0,t.jsx)(O,{fundMode:en,onFundModeChange:eo})})]})]}),null!==en&&(0,t.jsx)(U.DepositWithdrawDialog,{open:!0,onOpenChange:e=>{e||eo(null)},initialMode:en},en)]})}e.s(["useDesktopFooterLabels",0,function(){let e=(0,l.useTranslations)("trading"),t=(0,l.useTranslations)("nav");return(0,r.useMemo)(()=>({utilities:e("desktopUtilities"),terms:e("desktopTerms"),privacy:e("privacyPolicy"),docs:t("docs"),x:t("xTwitter"),discord:t("discord"),ticker:{title:e("desktopTicker"),pause:e("desktopTickerPause"),resume:e("desktopTickerResume"),manualScroll:e("desktopTickerManual"),noMarkets:e("desktopTickerEmpty"),selectMarket:t=>e("desktopTickerSelect",{symbol:t})}}),[e,t])}],583568);var eD=e.i(504458);let eI=(0,eD.default)("book-open",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);e.s(["BookOpen",0,eI],526370);var eU=e.i(735006),eO=e.i(457395),eB=e.i(409686),ez=e.i(967090),e$=e.i(943494),eV=e.i(43690),eH=e.i(514049);let eW="https://api.imperial.space";async function eq(e){let t=await fetch(`${eW}/api/v1/telegram/link-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wallet:e})});if(!t.ok)throw Error((await t.json().catch(()=>({error:t.statusText}))).error||"Failed to create link request");return t.json()}async function eK(e){try{let t=await fetch(`${eW}/api/v1/telegram/status/${e}`);if(!t.ok)return null;let r=await t.json();return{linked:r.linked,chatUrl:r.chatUrl,eligibleForTelegramBonus:r.eligibleForTelegramBonus,telegramBonusExpiresAt:r.telegramBonusExpiresAt,telegramBonusBps:r.telegramBonusBps}}catch{return null}}async function eG(e){try{let t=await fetch(`${eW}/api/v1/telegram/preferences/${e}`);if(!t.ok)return null;return await t.json()}catch{return null}}async function eY(t,r,i,s){let n=`imperial-telegram-prefs:${Math.floor(Date.now()/1e3)}:${r}:${i}`,a=await s(new TextEncoder().encode(n)),l=(await e.A(730276)).default.encode(a),o=await fetch(`${eW}/api/v1/telegram/preferences`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wallet:t,message:n,signature:l,category:r,enabled:i})});if(!o.ok)throw Error((await o.json().catch(()=>({error:o.statusText}))).error||"Failed to update preferences");return await o.json()}function eX(e){let t=(0,eH.useQueryClient)(),i=(0,r.useRef)(null),{data:s}=(0,eV.useQuery)({queryKey:["telegram-status",e],queryFn:()=>eK(e),enabled:!!e,refetchInterval:6e4}),n=s?.linked??!1,{data:a}=(0,eV.useQuery)({queryKey:["telegram-deeplink",e],queryFn:async()=>(await eq(e)).deepLink,enabled:!!e&&!!s&&!n,refetchInterval:24e4,staleTime:24e4,gcTime:24e4});(0,r.useEffect)(()=>()=>{i.current&&clearInterval(i.current)},[]);let l=(0,r.useCallback)(()=>{i.current&&clearInterval(i.current);let r=0;i.current=setInterval(async()=>{r+=1;let s=await eK(e);s&&t.setQueryData(["telegram-status",e],s),(s?.linked||r>=6)&&(i.current&&clearInterval(i.current),i.current=null,s?.linked&&(t.invali
2dateQueries({queryKey:["season-points","me",e]}),t.invalidateQueries({queryKey:["scout-status",e]})))},5e3)},[e,t]);return{status:s??null,linked:n,deepLink:a,preparing:!!e&&!n&&!a,onConnect:l}}e.s(["createTelegramLinkRequest",0,eq,"getTelegramLinkStatus",0,eK,"getTelegramPreferences",0,eG,"updateTelegramPreferences",0,eY],458924),e.s(["useTelegramLink",0,eX],308871);var eQ=e.i(213076),eJ=e.i(328771);let eZ=()=>(0,t.jsx)(eJ.TelegramIcon,{className:"size-4"});function e0({size:e="default"}={}){let r=(0,l.useTranslations)("common"),{publicKey:i}=(0,p.useUnifiedWallet)(),{status:s,linked:n,deepLink:a,preparing:o,onConnect:d}=eX(i?.toBase58()??""),c=s?.chatUrl,u=null!==s&&!n,h="sm"===e?"size-7 relative":"size-9 rounded-control bg-surface border border-border hover:bg-surface-interactive/80 md:bg-transparent relative",m=r(n?"telegramViewBot":"telegramLink"),f=n?c:a,x=(0,t.jsxs)(t.Fragment,{children:[i&&o?(0,t.jsx)(e$.Loader2,{className:"size-4 animate-spin"}):(0,t.jsx)(eZ,{}),u&&(0,t.jsxs)("span",{className:"absolute top-0 right-0 flex size-2",children:[(0,t.jsx)("span",{className:"absolute inline-flex size-full animate-ping rounded-full bg-primary opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex size-2 rounded-full bg-primary"})]})]}),g=f?(0,t.jsx)(eQ.Button,{asChild:!0,variant:"ghost",size:"icon",className:h,"aria-label":m,children:(0,t.jsx)("a",{href:f,target:"_blank",rel:"noopener noreferrer",onClick:n?void 0:d,children:x})}):(0,t.jsx)(eQ.Button,{variant:"ghost",size:"icon",className:h,disabled:!i||o,"aria-label":m,children:x});return(0,t.jsxs)(eN.Tooltip,{children:[(0,t.jsx)(eN.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{className:"inline-flex",children:g})}),(0,t.jsx)(eN.TooltipContent,{side:"bottom",sideOffset:4,showArrow:!1,className:"text-xs px-3 py-1.5",children:m})]})}e.s(["TelegramHeaderButton",0,e0],454358);var e1=e.i(208665),e2=e.i(7658),e5=e.i(124593),e3=e.i(725102),e4=e.i(831979),e6=e.i(807702),e8=e.i(619966),e9=e.i(884722),e7=e.i(721680);let te=(0,r.memo)(function({mint:e,symbol:r,image:n,price:a,change:l,current:o,repeat:d=!1,label:c,descriptionId:u,fmt:h,onSelectMarket:p,onFocusMarket:m}){return(0,t.jsxs)("button",{type:"button",tabIndex:d?-1:void 0,className:e7.default.market,"aria-label":d?void 0:c,"aria-describedby":d?void 0:`${u}-price ${u}-change`,title:c,"aria-current":o?"true":void 0,onClick:()=>{o||p(e)},onMouseDown:e=>e.preventDefault(),onFocus:d?void 0:e=>m(e.currentTarget),children:[(0,t.jsx)(i.default,{unoptimized:!0,src:n,alt:"",width:16,height:16,className:e7.default.marketIcon,onError:s.handleTokenImageError}),(0,t.jsx)("span",{className:e7.default.symbol,children:r}),(0,t.jsx)("span",{id:d?void 0:`${u}-price`,className:e7.default.price,children:null===a?"—":`$${h.number(a)}`}),(0,t.jsx)("span",{id:d?void 0:`${u}-change`,className:null===l?e7.default.unknown:l>=0?e7.default.positive:e7.default.negative,children:null===l?"—":h.signedPercent(l,2)})]})}),tt=(0,r.memo)(function({rows:e,repeat:r=!1,marketMint:i,tickerId:s,fmt:n,selectMarketLabel:a,noMarketsLabel:l,onSelectMarket:o,onFocusMarket:d}){return(0,t.jsxs)(t.Fragment,{children:[e.map((e,l)=>(0,t.jsx)(te,{...e,repeat:r,current:e.mint===i,label:a(e.symbol),descriptionId:`${s}-${l}`,fmt:n,onSelectMarket:o,onFocusMarket:d},e.mint)),0===e.length&&(0,t.jsx)("span",{className:e7.default.empty,children:l})]})},(e,t)=>{var r,i;return e.repeat===t.repeat&&e.marketMint===t.marketMint&&e.tickerId===t.tickerId&&e.fmt===t.fmt&&e.selectMarketLabel===t.selectMarketLabel&&e.noMarketsLabel===t.noMarketsLabel&&e.onSelectMarket===t.onSelectMarket&&e.onFocusMarket===t.onFocusMarket&&((r=e.rows)===(i=t.rows)||r.length===i.length&&r.every((e,t)=>{let r=i[t];return e.mint===r.mint&&e.symbol===r.symbol&&e.image===r.image&&Object.is(e.price,r.price)&&Object.is(e.change,r.change)}))}),tr=(0,r.memo)(function({allMarkets:e,marketMint:i,onSelectMarket:n,labels:a,isMarketEligible:l}){let{activeProfileExcludedVenues:o}=(0,m.useProfile)(),{stats:d}=(0,$.useVenueMarketStats)(!0,o),{favorites:u}=(0,e6.useFavoriteMarkets)(),{isMarketSelectable:h}=(0,e9.useMarketSelectionEligibility)(),p=(0,c.useFormatters)(),f=(0,r.useId)(),x=(0,e8.useMediaQuery)("(prefers-reduced-motion: reduce)",!0),[g,b]=(0,r.useState)(!1),[v,y]=(0,r.useState)(!1),[w,j]=(0,r.useState)(!1),[S,k]=(0,r.useState)({width:0,viewport:0,repeatCount:0}),N=(0,r.useRef)(null),P=(0,r.useRef)(null),T=(0,r.useRef)(null),C=(0,r.useRef)(null),M=(0,r.useRef)(null),_=(0,r.useRef)(null),A=g||v||x,E=(0,r.useRef)(A),L=S.width>S.viewport+1,F=(0,r.useMemo)(()=>(function(e,t,r,i){let s=[],n=[],a=new Set;for(let l of e)!a.has(l.mint)&&(a.add(l.mint),(l.mint===t||!1!==l.allowOpenPosition&&i(l))&&(r.has(l.mint)?s:n).push(l));return[...s,...n]})(e,i,u,e=>h(e)&&(l?.(e)??!0)),[e,i,u,l,h]),R=(0,r.useMemo)(()=>
2F.map(({mint:e,symbol:t,image:r})=>{let i=d.get(t.toUpperCase()),n=i?.price,a=i?.change24h;return{mint:e,symbol:t,image:(0,s.getFlashTokenImage)(t,r),price:null!=n&&Number.isFinite(n)&&n>0?n:null,change:null!=a&&Number.isFinite(a)?a:null}}),[F,d]),D=(0,r.useCallback)(e=>{_.current=e,E.current&&e.scrollIntoView({block:"nearest",inline:"nearest"})},[]);(0,r.useEffect)(()=>{let e=N.current,t=T.current;if(!e||!t)return;let r=()=>{let r=t.scrollWidth,i=0,s=0;if(r>e.clientWidth+1){for(let r of t.children)if(s+=r.getBoundingClientRect().width,i++,s>=e.clientWidth)break}let n={width:r,viewport:e.clientWidth,repeatCount:i};k(e=>e.width===n.width&&e.viewport===n.viewport&&e.repeatCount===n.repeatCount?e:n)},i=new ResizeObserver(r);return i.observe(e),i.observe(t),C.current&&i.observe(C.current),r(),()=>i.disconnect()},[F.length,S.repeatCount]),(0,r.useLayoutEffect)(()=>{let e=N.current,t=P.current;if(e&&t)return M.current=function(e,t,r=24){let i=null,s=0;return{sync(n,a,l,o){let d,c=n>a+1;if(i&&!l&&c&&s===n)return void(o?i.pause():i.play());let u=i?(d=Number(i?.currentTime??0),((s>0&&Number.isFinite(d)?(d*r/1e3%s+s)%s:0)+e.scrollLeft)%s):e.scrollLeft;if(i?.cancel(),i=null,s=n,l||!c||"function"!=typeof t.animate){e.scrollLeft=c?Math.max(0,Math.min(u,n)):0;return}e.scrollLeft=0,(i=t.animate([{transform:"translateX(0px)"},{transform:`translateX(-${n}px)`}],{duration:n/r*1e3,iterations:1/0,easing:"linear"})).pause(),i.currentTime=(u%n+n)%n/r*1e3,o||i.play()},destroy(){i?.cancel(),i=null}}}(e,t),()=>{M.current?.destroy(),M.current=null}},[]),(0,r.useLayoutEffect)(()=>{E.current=A,M.current?.sync(S.width,S.viewport,A,w),A&&_.current?.scrollIntoView({block:"nearest",inline:"nearest"})},[S,A,w]);let I={marketMint:i,tickerId:f,fmt:p,selectMarketLabel:a.selectMarket,noMarketsLabel:a.noMarkets,onSelectMarket:n,onFocusMarket:D};return(0,t.jsxs)("div",{className:e7.default.ticker,role:"region","aria-label":a.title,children:[(0,t.jsx)("button",{type:"button",className:e7.default.motionButton,onClick:()=>b(e=>!e),disabled:x||!L,"aria-pressed":g,"aria-label":x?a.manualScroll:g?a.resume:a.pause,title:x?a.manualScroll:g?a.resume:a.pause,children:(0,t.jsx)("svg",{viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor","aria-hidden":"true",children:g||x?(0,t.jsx)("path",{d:"M5 3.5 12 8l-7 4.5z"}):(0,t.jsx)("path",{d:"M4 3h3v10H4zm5 0h3v10H9z"})})}),(0,t.jsx)("div",{ref:N,className:e7.default.viewport,onMouseEnter:()=>j(!0),onMouseLeave:()=>j(!1),onWheel:()=>b(!0),onMouseDownCapture:()=>{let e=_.current;e&&N.current?.contains(e)&&e.blur(),_.current=null,y(!1)},onFocusCapture:()=>y(!0),onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||(_.current=null,y(!1))},children:(0,t.jsxs)("div",{ref:P,className:`${e7.default.track} ${A?e7.default.manual:""}`,children:[(0,t.jsx)("div",{ref:T,className:e7.default.cycle,children:(0,t.jsx)(tt,{rows:R,...I})}),S.repeatCount>0&&(0,t.jsx)("div",{ref:C,className:e7.default.repeat,"aria-hidden":"true",children:(0,t.jsx)(tt,{rows:R.slice(0,S.repeatCount),repeat:!0,...I})})]})})]})});var ti=e.i(257355),ts=e.i(319522),tn=e.i(993628);let ta=[{href:e3.DISCORD_URL,labelKey:"discord",Icon:eJ.DiscordIcon},{href:e3.DOCS_URL,labelKey:"documentation",Icon:eI}],tl=new Map,to=(0,r.memo)(function({desktopDashboard:e=!1,allMarkets:i,marketMint:s,onSelectMarket:n,isMarketEligible:a,labels:d}){let u=(0,l.useTranslations)("trading"),p=(0,l.useTranslations)("wallet"),f=(0,l.useTranslations)("nav"),g=(0,l.useTranslations)("common"),b=(0,c.useFormatters)(),{publicKey:v}=(0,h.useUnifiedWalletContext)(),{createdProfiles:y,activeProfileIndex:w,setActiveProfileIndex:j,canCreateMore:S,hasLoadedProfiles:k,isLoading:N}=(0,m.useProfile)(),{isPro:P}=(0,e5.useProWhitelist)(),{profiles:T,isLoading:C,isStale:M}=(0,D.usePortfolioValues)(),{status:_,overallHealth:A}=(0,e2.useApiHealth)(),[E,L]=(0,r.useState)(!1),[F,R]=(0,r.useState)(!1),U=(0,r.useRef)(null),O=(0,r.useRef)(null),B=v?.toBase58()??null,{unpinned:z,explainerDismissed:$}=(0,ts.useAccountPins)(B);(0,r.useLayoutEffect)(()=>{O.current&&(O.current.scrollLeft=0)},[w,B]);let V=(0,r.useMemo)(()=>new Map(y.map(e=>[e.index,e.pda.toBase58()])),[y]),H=(0,r.useMemo)(()=>new Set(y.map(e=>e.index)),[y]);(0,r.useEffect)(()=>
2{if(!B||!k||N||0===H.size)return;let e=(0,tn.readUnpinnedStored)(B);e.some(e=>!H.has(e))&&(0,tn.writeUnpinned)(B,new Set(e),H)},[B,k,N,H]);let[W,q]=(0,r.useState)(null),K=(0,r.useRef)(null),G=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{K.current&&clearTimeout(K.current),G.current&&clearTimeout(G.current)},[]);let Y=(e,t,r=!1)=>{G.current&&(clearTimeout(G.current),G.current=null),K.current&&clearTimeout(K.current);let i=U.current;if(!i)return;let s=i.getBoundingClientRect(),n=Math.max(8,Math.min(t.getBoundingClientRect().left-s.left,s.width-300-8));r?q({index:e,left:n}):K.current=setTimeout(()=>q({index:e,left:n}),250)};(0,r.useEffect)(()=>{if(!W)return;let e=e=>{"Escape"===e.key&&q(null)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[W]);let X=()=>{K.current&&(clearTimeout(K.current),K.current=null),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>q(null),200)},Q=(0,r.useMemo)(()=>y.filter(e=>e.index===w||!z.has(e.index)),[y,w,z]),{healthLabel:J,healthTitle:Z,healthDotClass:ee}=(0,r.useMemo)(()=>{let e=e=>"healthy"===e?u("statusBarHealthy"):"degraded"===e?u("statusBarDegradedState"):"down"===e?u("statusBarDown"):u("statusBarUnknown");return{healthTitle:u("statusBarHealthDetail",{api:e(_?"healthy"===_.db?"healthy":"down":void 0),indexer:e(_?.indexer?.status),orderBot:e(_?.orderBot?.status)}),healthLabel:"healthy"===A?u("statusBarOnline"):"degraded"===A?u("statusBarDegraded"):u("statusBarOffline"),healthDotClass:"healthy"===A?"bg-side-long":"degraded"===A?"bg-imperial-gold":"bg-side-short"}},[u,_,A]),et=e&&i&&s&&n&&d?{allMarkets:i,marketMint:s,onSelectMarket:n,isMarketEligible:a,labels:d.ticker}:null,er=et&&C?tl:T,ei=e=>er.get(e)?.unrealizedValue,es=W?Q.find(e=>e.index===W.index):void 0,en=(0,t.jsxs)("span",{role:"status","aria-label":`${J} — ${Z}`,title:Z,className:"flex shrink-0 cursor-default items-center gap-[5px] text-muted-foreground",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:`h-[7px] w-[7px] rounded-full ${ee}`}),J]}),ea=(0,t.jsxs)(o.Popover,{open:F,onOpenChange:R,children:[(0,t.jsx)(o.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":et?p("accounts"):p("addAccount"),title:et?p("accounts"):p("addAccount"),"aria-busy":et&&!!v&&!k||void 0,className:et?e7.default.accountsTrigger:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[7px] border border-dashed border-border-strong text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:et?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:p("accounts")}),!v&&(0,t.jsx)("span",{className:e7.default.accountsHint,children:p("connectWallet")}),!!v&&!k&&(0,t.jsx)("span",{"aria-hidden":!0,children:"…"}),(0,t.jsx)(eU.ChevronUp,{size:12,"aria-hidden":!0})]}):(0,t.jsx)(eB.Plus,{className:"h-3.5 w-3.5"})})}),(0,t.jsx)(o.PopoverContent,{side:"top",align:"start",sideOffset:8,"aria-label":p("accounts"),className:"w-[320px] max-w-[calc(100vw-24px)] max-h-[min(480px,70dvh)] overflow-y-auto p-2.5 shadow-[0_14px_36px_rgba(0,0,0,0.55)]",children:v?et&&!k?(0,t.jsx)("p",{role:"status",className:"px-2 py-3 text-xs text-muted-foreground",children:g("loadingEllipsis")}):(0,t.jsxs)(t.Fragment,{children:[0===y.length&&(0,t.jsx)("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:u("desktopAccountsEmpty")}),(0,t.jsx)(ts.AccountsPopoverBody,{profiles:y,activeIndex:w,unpinned:z,addr58:V,values:er,valuesStale:M,explainerDismissed:0===y.length||$,canCreate:S&&P,onPick:e=>{e!==w&&j(e),B&&(0,tn.pinStored)(B,e),R(!1)},onDismissExplainer:()=>B&&(0,tn.writeExplainerDismissed)(B),onCreate:()=>{R(!1),L(!0)}})]}):(0,t.jsxs)("div",{className:"space-y-3 px-2 py-2",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:p("connectWalletFirst")}),(0,t.jsx)("button",{type:"button",className:e7.default.connectAccounts,onClick:()=>{R(!1),(0,x.promptConnectWallet)()},children:p("connectWallet")})]})})]}),el=et?[...Q].sort((e,t)=>Number(t.index===w)-Number(e.index===w)):Q,eo=(0,t.jsxs)("div",{ref:U,role:et?"group":void 0,"aria-label":et?p("accounts"):void 0,className:et?e7.default.accountRow:`relative hidden h-8 shrink-0 items-center gap-2.5 border-t border-border bg-surface px-2.5 text-2xs lg:flex ${e?ti.default.footer:""}`,children:[!et&&en,et&&ea,v&&es&&W&&(!et||k)&&(0,t.jsx)("div",{onMouseEnter:()=>{G.current&&(clearTimeout(G.current),G.current=null)},onMouseLeave:X,style:{left:W.left,width:300},className:"absolute bottom-full z-50 mb-2 rounded-float border border-border-strong bg-popover px-3.5 py-3 shadow-[0_14px_36px_rgba(0,0,0,0.55)]",children:(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,t.jsx)("span",{className:"flex h-[34px] w-[34px] shrink-0 items-center justify-center rounded-[9px] bg-surface-interactive font-sans text-[13px] font-semibold text-secondary-foreground",children:es.index+1}),(0,t.jsxs)("span",{className:"min-w-0",children:[(0,t.jsx)("span",{className:"block truncate text-[13px] font-semibold text-foreground",children:es.name??p("profileFallback",{index:String(es.index+1)})}),(0,t.jsxs)("button",{type:"button",onClick:()=>(0,ts.copyAddress)(V.get(es.index)??"",p("addressCopied")),className:`gap-[5px] text-2xs ${ts.COPY_ADDRESS_CLASS}`,children:[(0,I.shortAddress)(V.get(es.index)??""),(0,t.jsx)(eO.Copy,{className:"h-[11px] w-[11px]","aria-hidden":!0})]})]}),(0,t.jsx)("span",{className:"ml-auto text-right",children:(0,t.jsx)("span",{title:M?u("statusBarUnknown"):void 0,className:`block font-mono text-sm font-semibold tabular-nums text-foreground ${M?"opacity-60":""}`,children:void 0===ei(es.index)?"—":`$${b.number(ei(es.index))}`})})]})}),v&&y.length>0&&(!et||k)&&(0,t.jsxs)(t.Fragment,{children:[!et&&(0,t.jsx)("span",{"aria-hidden":!0,
2className:"h-4 w-px shrink-0 bg-border"}),(0,t.jsxs)("div",{ref:et?O:void 0,className:et?e7.default.accountTabs:"flex min-w-0 flex-1 items-center gap-2.5 overflow-x-auto",children:[el.map(e=>{let r=e.index===w,i=ei(e.index),s=e.name??p("profileFallback",{index:String(e.index+1)});return(0,t.jsxs)("span",{className:"group relative shrink-0",onMouseEnter:t=>Y(e.index,t.currentTarget),onMouseLeave:X,onFocus:t=>Y(e.index,t.currentTarget,!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||X()},children:[(0,t.jsxs)("button",{type:"button","aria-current":r?"true":void 0,onClick:()=>{r||j(e.index)},onFocus:e=>e.currentTarget.scrollIntoView({block:"nearest",inline:"nearest"}),className:`${et?e7.default.accountTab:"flex h-6 shrink-0 items-center gap-1.5 rounded-[7px] border px-2.5 font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60"} ${r?"border-border-strong bg-surface-interactive text-foreground":`border-border text-secondary-foreground hover:bg-surface-interactive/60 hover:text-foreground ${et?e7.default.inactiveAccountTab:"group-hover:pr-7 group-focus-within:pr-7"}`}`,children:[(0,t.jsx)("span",{className:et?e7.default.accountName:"max-w-28 truncate",children:s}),(0,t.jsxs)("span",{"aria-busy":et&&C||void 0,title:et&&M?u("statusBarUnknown"):void 0,className:`shrink-0 font-mono text-3xs tabular-nums text-muted-foreground${et&&M?" opacity-60":""}`,children:[void 0===i?"—":`$${b.numberShort(i)}`,et&&M&&(0,t.jsxs)("span",{className:"sr-only",children:[" ",u("statusBarUnknown")]})]})]}),!r&&(0,t.jsx)("button",{type:"button",onClick:()=>{B&&(q(null),(0,ts.unpinStored)(B,e.index,H,u("tabClosed"),g("undo")))},"aria-label":u("closeTab"),title:u("closeTab"),className:"absolute right-0.5 top-1/2 hidden h-6 w-6 -translate-y-1/2 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 group-hover:flex group-focus-within:flex",children:(0,t.jsx)(ez.X,{className:"h-3.5 w-3.5"})})]},e.index)}),!et&&ea]})]}),!et&&(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-1",children:[(0,t.jsx)(e0,{size:"sm"}),ta.map(({href:e,labelKey:r,Icon:i})=>(0,t.jsx)(eQ.Button,{asChild:!0,variant:"ghost",size:"icon",className:"size-7",children:(0,t.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer","aria-label":f(r),title:f(r),children:(0,t.jsx)(i,{className:"size-4"})})},e))]}),(0,t.jsx)(e1.CreateProfileDialog,{open:E,onOpenChange:L})]});return et&&d?(0,t.jsx)("div",{className:e7.default.footer,children:(0,t.jsxs)("div",{className:e7.default.utilityRow,children:[en,eo,(0,t.jsx)(tr,{...et}),(0,t.jsxs)("nav",{className:e7.default.utilities,"aria-label":d.utilities,children:[[{href:e3.TERMS_OF_SERVICE_URL,label:d.terms},{href:e3.PRIVACY_POLICY_URL,label:d.privacy},{href:e3.DOCS_URL,label:d.docs}].map(({href:e,label:r})=>(0,t.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:e7.default.utilityLink,children:r},e)),(0,t.jsx)(e0,{size:"sm"}),(0,t.jsx)("a",{href:e3.X_URL,target:"_blank",rel:"noopener noreferrer","aria-label":d.x,title:d.x,className:e7.default.iconLink,children:(0,t.jsx)(e4.XIcon,{})}),(0,t.jsx)("a",{href:e3.DISCORD_URL,target:"_blank",rel:"noopener noreferrer","aria-label":d.discord,title:d.discord,className:e7.default.iconLink,children:(0,t.jsx)(eJ.DiscordIcon,{})})]})]})}):eo}),td=[1e-8,1e-7,1e-6,1e-5,1e-4,.001,.01,.1,1,10,100,1e3],tc={precision:.01,denom:"usdc",sideFilter:"both"};function tu(e){return Math.max(0,-Math.round(Math.log10(e)))}function th(e){return Number.isFinite(e)&&0!==e?Math.max(2,Math.min(8,1-Math.floor(Math.log10(Math.abs(e))))):2}function tp(e,t,r){let i=e/t,s=Math.round(i),n=Math.abs(i-s)<=Number.EPSILON*Math.abs(i)*4?s:i;return"ask"===r?Math.ceil(n):Math.floor(n)}function tm(e,t,r,i,s,n){return s&&Number.isFinite(s)&&!(s<=0)&&n&&Number.isFinite(n)&&!(n<=0)?function(e,t,{precision:r,denom:i},s,n=0){if(!e.length)return s.map(()=>null);let a=new Map;for(let s of e){let e=tp(s.price+n,r,t),l="usdc"===i?s.quoteSize??s.price*s.size:s.size;a.set(e,(a.get(e)??0)+l)}let l=0,o=[...a.keys()].sort((e,r)=>"ask"===t?e-r:r-e).map(e=>({tick:e,total:l+=a.get(e)})),d=o[o.length-1].tick;return s.map(({price:e})=>{let i=tp(e,r,t);if("ask"===t?i>d:i<d)return null;let s=0,n=o.length;for(;s<n;){let e=s+n>>>1;("ask"===t?o[e].tick<=i:o[e].tick>=i)?s=e+1:n=e}return s>0?o[s-1].total:0})}(e,t,r,i,s-n):i.map(()=>null)}function tf(e,t,{precision:r,denom:i},s){let n=new Map;for(let s of e){let e=tp(s.price,r,t),a="usdc"===i?s.quoteSize??s.size*s.price:s.size;n.set(e,(n.get(e)??0)+a)}let a=0,l=[...n.keys()].sort((e,r)=>"ask"===t?e-r:r-e);if(!l.length)return[];let o=Array.from({length:Math.min(s,Math.abs(l[l.length-1]-l[0])+1)},(e,i)=>
2{let s=l[0]+i*("ask"===t?1:-1),o=n.get(s)??0;return a+=o,{price:Number((s*r).toFixed(tu(r))),size:o,total:a}});return"ask"===t?o.reverse():o}function tx(e,t,r){let i=0;for(let s of e)if(s&&("bid"!==t.sideFilter&&(i=Math.max(i,tf(s.asks,"ask",t,r)[0]?.total??0)),"ask"!==t.sideFilter)){let e=tf(s.bids,"bid",t,r);i=Math.max(i,e[e.length-1]?.total??0)}return i}function tg(e,t,r,i){if(!e.asks.length||!e.bids.length||!r.length||!i.length||!Number.isFinite(t)||t<=0)return null;let s=(e,r,i)=>{if(i.some(({price:e})=>!Number.isFinite(e)||e<=0))return NaN;let s=tp(i[0].price,t,r),n=tp(i[i.length-1].price,t,r);if(!Number.isFinite(s)||!Number.isFinite(n))return NaN;let a=Math.min(s,n),l=Math.max(s,n),o=0;for(let i of e){if(!Number.isFinite(i.price)||i.price<=0||!Number.isFinite(i.size)||i.size<0)return NaN;let e=tp(i.price,t,r);e>=a&&e<=l&&(o+=i.size)}return o},n=s(e.asks,"ask",r),a=s(e.bids,"bid",i);if(!Number.isFinite(n)||!Number.isFinite(a)||n+a<=0)return null;let l=Math.max(n,a),o=a/l/(n/l+a/l)*100;return{bidPercent:o,askPercent:100-o}}e.s(["BOOK_PRECISIONS",0,td,"DEFAULT_BOOK_SETTINGS",0,tc,"bookDepthScale",0,tx,"comparisonDepthAtMarkOffsets",0,tm,"defaultBookPrecision",0,function(e){if(!e||!Number.isFinite(e)||e<=0)return tc.precision;let t=Math.round(Math.log10(e/1e4));return td.reduce((e,r)=>Math.abs(Math.log10(r)-t)<Math.abs(Math.log10(e)-t)?r:e)},"displayedBaseDepthShare",0,tg,"groupBookSide",0,tf,"precisionDecimals",0,tu,"spreadDisplayDecimals",0,th],75764);var tb=e.i(296234),tv=e.i(101034),ty=e.i(438495),tw=e.i(98788);function tj(e,t){return e>=1e6?(0,d.formatFixed)(e/1e6,2,t)+"M":e>=1e3?(0,d.formatFixed)(e/1e3,0,t)+"K":e>=1?(0,d.formatFixed)(e,0,t):(0,d.formatFixed)(e,2,t)}function tS({value:e,options:i,labels:s,onChange:a}){let[l,o]=(0,r.useState)(!1),d=(0,r.useRef)(null);return(0,r.useEffect)(()=>{if(!l)return;let e=e=>{d.current&&!d.current.contains(e.target)&&o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[l]),(0,t.jsxs)("div",{ref:d,className:"relative",children:[(0,t.jsxs)("button",{onClick:()=>o(!l),className:"focus-ring flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-muted-foreground hover:text-secondary-foreground hover:bg-surface-interactive transition-colors",children:[s[e],(0,t.jsx)(n.ChevronDown,{className:"w-3 h-3"})]}),l&&(0,t.jsx)("div",{className:"absolute top-full left-0 mt-1 z-50 bg-popover border border-border-strong rounded-float shadow-lg min-w-[70px] max-h-60 overflow-y-auto",children:i.map(r=>(0,t.jsxs)("button",{onClick:()=>{a(r),o(!1)},className:(0,I.cn)("focus-ring flex items-center gap-2 w-full px-3 py-1.5 text-[10px] hover:bg-surface-interactive transition-colors",e===r?"text-foreground":"text-muted-foreground"),children:[s[r],e===r&&(0,t.jsx)("span",{className:"text-label-muted ml-auto",children:"✓"})]},r))})]})}let tk=(0,t.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",children:[(0,t.jsx)("rect",{x:"0",y:"0",width:"12",height:"5",rx:"1",fill:"var(--side-short)"}),(0,t.jsx)("rect",{x:"0",y:"7",width:"12",height:"5",rx:"1",fill:"var(--side-long)"})]}),tN=(0,t.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",children:(0,t.jsx)("rect",{x:"0",y:"0",width:"12",height:"12",rx:"1",fill:"var(--side-short)"})}),tP=(0,t.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",children:(0,t.jsx)("rect",{x:"0",y:"0",width:"12",height:"12",rx:"1",fill:"var(--side-long)"})}),tT=[{value:"both",labelKey:"sideBoth",icon:tk},{value:"ask",labelKey:"sideAsk",icon:tN},{value:"bid",labelKey:"sideBid",icon:tP}],tC=[{value:"all",labelKey:"sideBoth",icon:tk},{value:"buy",labelKey:"sideLong",icon:tP},{value:"sell",labelKey:"sideShort",icon:tN}];function tM({value:e,onChange:i,mode:s="book"}){let a=(0,l.useTranslations)("trading"),[o,d]=(0,r.useState)(!1),c=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!o)return;let e=e=>{c.current&&!c.current.contains(e.target)&&d(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[o]);let u="book"===s?tT:tC,h=u.find(t=>t.value===e)??u[0];return(0,t.jsxs)("div",{ref:c,className:"relative",children:[(0,t.jsxs)("button",{type:"button",onClick:()=>d(!o),"aria-label":a(h.labelKey),className:"focus-ring flex items-center gap-1 p-1 rounded hover:bg-surface-interactive transition-colors",children:[h.icon,(0,t.jsx)(n.ChevronDown,{className:"w-2.5 h-2.5 text-label-muted"})]}),o&&(0,t.jsx)("div",{className:"absolute top-full right-0 mt-1 z-50 bg-surface border border-border rounded shadow-lg min-w-[80px]",children:u.map(r=>(0,t.jsxs)("button",{type:"button",onClick:()=>{i(r.value),d(!1)},className:(0,I.cn)("focus-ring flex items-center gap-2 w-full px-3 py-1.5 text-[10px] hover:bg-surface-interactive transition-colors",e===r.value?"text-foreground":"text-muted-foreground"),children:[r.icon,a(r.labelKey),e===r.value&&(0,t.jsx)("span",{className:"text-label-muted ml-auto",children:"✓"})]},r.value))})]})}function t_({price:e,size:r,total:i,maxTotal:s,side:n,onSelect:a,onInspect:o,selected:d}){let u=(0,l.useTranslations)("trading"),h=(0,c.useFormatters)(),p=s>0?Math.min(100,i/s*100):0,m="bid"===n,f=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"absolute inset-y-0 right-0 opacity-15",style:{width:`${p}%`,backgroundColor:m?"var(--side-long)":"var(--side-short)"}}),(0,t.jsx)("span",{className:(0,I.cn)("relative z-10 w-[35%] text-left",m?"text-side-long":"text-side-short"),children:e}),(0,t.jsx)("span",{className:"relative z-10 w-[30%] text-right text-secondary-foreground",children:tj(r,h.intlTag)}),(0,t.jsx)("span",{className:"relative z-10 w-[35%] text-right text-muted-foreground",children:tj(i,h.intlTag)})]}),x=(0,I.cn)("relative flex shrink-0 items-center w-full h-[22px] px-2 text-[11px] tabular-nums font-mono",d&&"bg-surface-interactive");return a||o?(0,t.jsx)("button",{type:"button",onClick:a??o,onMouseEnter:o,onFocus:o,"aria-label":u(a?"setLimitPriceTo":"compareDepthAtPrice",{price:`${e} USDC`}
2),className:(0,I.cn)(x,"cursor-pointer transition-colors duration-150 motion-reduce:transition-none","hover:bg-surface-interactive focus-visible:bg-surface-interactive focus-visible:outline-none"),children:f}):(0,t.jsx)("div",{className:x,children:f})}function tA({asks:e,bids:i,maxTotal:s,formatPrice:n,formatPriceMachine:a,middle:o,sideFilter:d="both",onPriceSelect:u,headers:h,comparison:p,depthShare:m}){let f=(0,l.useTranslations)("trading"),x=(0,c.useFormatters)(),[g,b]=(0,r.useState)(null),v=g&&("both"===d||d===g.side)?g.side:"ask"===d?"ask":"bid",y="ask"===v?e:i,w=g?y.findIndex(e=>e.price===g.price):-1,j=w>=0?w:"ask"===v?0:y.length-1,S=y[j],k=p?.["ask"===v?"asks":"bids"][j],N=p&&S?S.price-p.markPrice:0,P=`${N<0?"−":"+"}$${x.fixed(Math.abs(N),th(N))}`,T=e=>u?()=>u(a(e)):void 0;return(0,t.jsxs)("div",{className:"flex flex-col flex-1 min-h-0",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center h-6 px-2 text-[10px] text-label-muted font-medium border-b border-border/50",children:[(0,t.jsx)("span",{className:"w-[35%] text-left",children:h.price}),(0,t.jsx)("span",{className:"w-[30%] text-right",children:h.size}),(0,t.jsx)("span",{className:"w-[35%] text-right",children:h.total})]}),("both"===d||"ask"===d)&&(0,t.jsx)("div",{className:"flex flex-col justify-end overflow-hidden flex-1",children:e.map((e,r)=>(0,t.jsx)(t_,{price:n(e.price),size:e.size,total:e.total,maxTotal:s,side:"ask",onSelect:T(e.price),onInspect:p?()=>b({price:e.price,side:"ask"}):void 0,selected:!!p&&g?.side==="ask"&&g.price===e.price},`ask-${r}`))}),"both"===d&&o,("both"===d||"bid"===d)&&(0,t.jsx)("div",{className:"flex-1 flex flex-col overflow-hidden",children:i.map((e,r)=>(0,t.jsx)(t_,{price:n(e.price),size:e.size,total:e.total,maxTotal:s,side:"bid",onSelect:T(e.price),onInspect:p?()=>b({price:e.price,side:"bid"}):void 0,selected:!!p&&g?.side==="bid"&&g.price===e.price},`bid-${r}`))}),p&&(0,t.jsxs)("div",{"data-depth-detail":!0,className:"flex h-14 shrink-0 flex-col justify-center gap-1 border-t border-border/50 px-2 text-[10px]",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1 text-label-muted",children:[(0,t.jsx)("span",{children:S?f("depthFromMark",{side:f("ask"===v?"sideAsk":"sideBid"),distance:P}):f("depthSharedScale")}),(0,t.jsx)("span",{children:p.unit})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 tabular-nums",children:[(0,t.jsxs)("span",{className:"text-secondary-foreground",children:["Armada ",(0,t.jsx)("strong",{className:"font-mono font-medium",children:S?tj(S.total,x.intlTag):"—"})]}),(0,t.jsxs)("span",{className:"bid"===v?"text-depth-comparison-bid":"text-depth-comparison-ask",title:null==k?f("depthOutsideFeed"):void 0,children:["Phoenix ",(0,t.jsx)("strong",{className:"font-mono font-medium",children:null!=k?tj(k,x.intlTag):"—"})]})]})]}),"both"===d&&m&&(0,t.jsx)(tE,{...m})]})}function tE({bidPercent:e,venue:i,symbol:s}){let n=(0,l.useTranslations)("trading"),a=(0,c.useFormatters)(),o=(0,r.useId)(),d=Math.round(e),u=a.percent(d,0),h=a.percent(100-d,0);return(0,t.jsxs)(eN.Tooltip,{children:[(0,t.jsx)(eN.TooltipTrigger,{asChild:!0,onClick:e=>e.preventDefault(),children:(0,t.jsx)("button",{type:"button","data-book-depth-share":!0,"aria-label":n("bookDepthShareLabel",{venue:i,bid:u,ask:h}),"aria-describedby":o,className:"focus-ring relative flex h-10 w-full shrink-0 cursor-help items-center border-t border-border/50 px-2 focus-visible:-outline-offset-2",children:(0,t.jsxs)("span",{"aria-hidden":"true",className:"relative flex h-6 w-full items-center overflow-hidden rounded border border-border/50 px-1.5 text-[10px] tabular-nums",children:[(0,t.jsx)("span",{className:"absolute inset-y-0 left-0 bg-side-long/15",style:{width:`${e}%`}}),(0,t.jsx)("span",{className:"absolute inset-y-0 right-0 bg-side-short/15",style:{width:`${100-e}%`}}),(0,t.jsxs)("span",{className:"relative flex w-full items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"text-side-long",children:[n("sideBid")," ",(0,t.jsx)("strong",{className:"font-mono font-medium",children:u})]}),(0,t.jsxs)("span",{className:"text-side-short",children:[n("sideAsk")," ",(0,t.jsx)("strong",{className:"font-mono font-medium",children:h})]})]})]})})}),(0,t.jsx)("span",{id:o,className:"sr-only",children:n("bookDepthShareHelp",{venue:i,symbol:s})}),(0,t.jsx)(eN.TooltipContent,{side:"top",sideOffset:4,showArrow:!1,className:"max-w-[260px] text-xs leading-relaxed",children:n("bookDepthShareHelp",{venue:i,symbol:s})})]})}let tL=td.map(String),tF=Object.fromEntries(tL.map(e=>[e,e]));
2function tR({value:e,onChange:r}){return(0,t.jsx)(tS,{value:String(e),options:tL,labels:tF,onChange:e=>r(Number(e))})}function tD(e,t,r){return(0,d.formatFixed)(e,tu(t),r)}function tI({orderbook:e,orderbookStatus:i,orderbookReceivedAt:s,orderbookGeneration:n,trades:a,symbol:o,active:d=!0,armadaComparisonAvailable:u=!1,onPriceSelect:h,settings:p,onSettingsChange:m,comparisonBook:f}){let x=(0,l.useTranslations)("trading"),g=("live"===i||"empty"===i)&&((0,tw.isPhoenixBookRevoked)(n)||!(0,tw.isPhoenixBookFresh)(s))?"stale":i,b="live"===g,v="empty"===g?x("bookEmpty"):"disconnected"===g?x("bookReconnecting"):b?null:x("bookWaitingForUpdate"),y=b&&h?e=>{!(0,tw.isPhoenixBookRevoked)(n)&&(0,tw.isPhoenixBookFresh)(s)&&h(e)}:void 0,w=(0,l.useTranslations)("terms"),j=(0,c.useFormatters)(),[S,k]=(0,r.useState)("book"),{precision:N,denom:P,sideFilter:T}=p,{book:C}=(0,W.useDisplayedSunriseOrderbook)(o,u?"armada":null,N,d&&"book"===S),M=f??C,[_,A]=(0,r.useState)("all"),E=(0,r.useRef)(null),[L,F]=(0,r.useState)(12),R=(0,r.useCallback)(()=>{E.current&&F(Math.max(1,Math.floor((E.current.clientHeight-(85+88*("both"===T)))/("both"===T?2:1)/22)))},[T]);(0,r.useEffect)(()=>{R();let e=new ResizeObserver(R);return E.current&&e.observe(E.current),()=>e.disconnect()},[R]);let{askRows:D,bidRows:U,maxTotal:O,spread:B,spreadPct:z,mid:$,depthShare:V}=(0,r.useMemo)(()=>{let t={asks:e.asks.map(([e,t])=>({price:e,size:t})),bids:e.bids.map(([e,t])=>({price:e,size:t}))},r=tf(t.asks,"ask",p,L),i=tf(t.bids,"bid",p,L),s=tx([t,M],p,L),n=e.asks.length?Math.min(...e.asks.map(([e])=>e)):0,a=e.bids.length?Math.max(...e.bids.map(([e])=>e)):0,l=n>0&&a>0?n-a:0;return{askRows:r,bidRows:i,maxTotal:s,spread:l,spreadPct:a>0?l/a*100:0,mid:n>0&&a>0?(n+a)/2:0,depthShare:"both"===T?tg(t,N,r,i):null}},[e,L,p,M,T,N]),H="usdc"===P?"USDC":o;return(0,t.jsxs)("div",{ref:E,className:"trading-panel-surface flex flex-col h-full overflow-hidden border-l border-border",children:[(0,t.jsxs)(ty.SlidingUnderline,{activeKey:S,className:"flex items-center border-b border-border",barClassName:"bg-foreground",children:[(0,t.jsx)(eL.DesktopWorkspacePanelTools,{}),(0,t.jsx)(tb.DesktopChartLinkBadge,{}),(0,t.jsx)("button",{"data-tab":!0,"data-active":"book"===S,onClick:()=>k("book"),className:(0,I.cn)("focus-ring flex-1 py-2 text-xs font-medium transition-colors","book"===S?"text-foreground":"text-label-muted hover:text-secondary-foreground"),children:x("orderBook")}),(0,t.jsx)("button",{"data-tab":!0,"data-active":"trades"===S,onClick:()=>k("trades"),className:(0,I.cn)("focus-ring flex-1 py-2 text-xs font-medium transition-colors","trades"===S?"text-foreground":"text-label-muted hover:text-secondary-foreground"),children:x("trades")})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-7 px-2 border-b border-border/50",children:[(0,t.jsx)(tR,{value:N,onChange:e=>m({...p,precision:e})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsxs)("button",{onClick:()=>m({...p,denom:"usdc"===P?"asset":"usdc"}),className:"focus-ring flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-muted-foreground hover:text-secondary-foreground hover:bg-surface-interactive transition-colors",children:["usdc"===P?"USDC":o,(0,t.jsx)(tv.ArrowLeftRight,{className:"w-3 h-3"})]}
2),(0,t.jsx)(tM,{value:"book"===S?T:_,onChange:e=>"book"===S?m({...p,sideFilter:e}):A(e),mode:S})]})]}),"book"===S?(0,t.jsxs)("div",{className:"relative flex flex-col flex-1 min-h-0","data-book-status":g,children:[(0,t.jsx)("div",{className:(0,I.cn)("flex flex-col flex-1 min-h-0",!b&&"opacity-40"),children:(0,t.jsx)(tA,{asks:D,bids:U,maxTotal:O,sideFilter:T,depthShare:b&&V?{...V,venue:"Phoenix",symbol:o}:null,formatPrice:e=>tD(e,N,j.intlTag),formatPriceMachine:e=>e.toFixed(tu(N)),onPriceSelect:y,headers:{price:(0,t.jsxs)(t.Fragment,{children:[x("price")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"USDC"})]}),size:(0,t.jsxs)(t.Fragment,{children:[w("size.full")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:H})]}),total:(0,t.jsxs)(t.Fragment,{children:[x("total")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:H})]})},middle:(0,t.jsxs)("div",{className:"flex flex-col bg-canvas border-y border-border/50 tabular-nums font-mono",children:[(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2 h-7 px-2 text-[12px]",children:[(0,t.jsx)("span",{className:"text-foreground",children:b&&$>0?tD($,N,j.intlTag):"—"}),(0,t.jsx)("span",{className:"text-label-muted text-[10px]",children:x("mid")})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-5 px-2 text-[10px] border-t border-border/50",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:b&&$>0?tD(B,N,j.intlTag):"—"}),(0,t.jsx)("span",{className:"text-label-muted",children:x("spread")}),(0,t.jsx)("span",{className:"text-muted-foreground",children:b&&$>0?j.percent(z,3):"—"})]})]})})}),v&&(0,t.jsx)("div",{role:"status",className:"pointer-events-none absolute inset-0 flex items-center justify-center px-3",children:(0,t.jsx)("span",{className:"rounded bg-canvas/95 px-3 py-2 text-center text-xs text-muted-foreground",children:v})})]}):(0,t.jsxs)("div",{className:"flex flex-col flex-1 min-h-0",children:[(0,t.jsxs)("div",{className:"flex items-center h-6 px-2 text-[10px] text-label-muted font-medium border-b border-border/50",children:[(0,t.jsx)("span",{className:"w-[34%]",children:x("time")}),(0,t.jsx)("span",{className:"w-[33%] text-right",children:x("price")}),(0,t.jsxs)("span",{className:"w-[33%] text-right",children:[w("size.full")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"usdc"===P?"USDC":o})]})]}),(0,t.jsx)("div",{className:"flex-1 overflow-y-auto",children:0===a.length?(0,t.jsx)("div",{className:"flex items-center justify-center h-20 text-xs text-label-muted",children:x("waitingForTrades")}):a.filter(e=>"all"===_||e.side===_).map((e,r)=>{var i,s;let n,a="buy"===e.side,l="usdc"===P?e.quoteAmount:e.baseAmount;return(0,t.jsxs)("div",{className:"flex items-center h-[22px] px-2 text-[11px] tabular-nums font-mono transition-colors duration-150 hover:bg-surface-interactive motion-reduce:transition-none",children:[(0,t.jsx)("span",{className:"w-[34%] text-label-muted",children:(i=e.timestamp,s=j.intlTag,new Date((n="string"==typeof i?parseInt(i,10):i)>1e12?n:1e3*n).toLocaleTimeString(s,{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}))}),(0,t.jsx)("span",{className:(0,I.cn)("w-[33%] text-right",a?"text-emerald-400":"text-red-400"),children:j.fixed(e.price,2)}),(0,t.jsx)("span",{className:"w-[33%] text-right text-secondary-foreground",children:tj(l,j.intlTag)})]},`trade-${r}`)})})]})]})}var tU=e.i(994754),tO=e.i(653982),tB=e.i(467577),tz=e.i(824088),t$=e.i(91262);function tV(e,t,r,i,s,n){let a;if(!(n>s)||i<1||!(t>0))return{levels:[],spanBps:0};let l=n/s,o=[],d=0,c=1/0,u=0;for(let n=0;n<i;n++){let h=s*Math.pow(l,n/(i-1||1)),p=e(h,r,"open");if(!isFinite(p)){a=d>0?d:void 0;break}let m="long"===r?t*(1+p/1e4):t*(1-p/1e4);o.push({price:m,size:h-d,total:h,bps:p}),d=h;let f=Math.abs(p);f<c&&(c=f),f>u&&(u=f)}return o.length>0&&void 0===a&&(a=n),{levels:o,capUsd:a,spanBps:o.length>0?u-c:0}}function tH(e){return e>=1e4?10:e>=1e3?1:e>=100?.1:e>=10?.01:e>=1?.001:e>=.01?1e-4:!Number.isFinite(e)||e<=0?1e-5:Math.pow(10,Math.floor(Math.log10(e))-2)}function tW(e,t){return Math.round(e/t)*t}class tq{levels=new Map;ticks=[];head=0;tickCount=0;precision;windowMs;
2currentPrice=0;prevPrice=0;prevTickTs=0;prevBinnedPrice=0;constructor(e,t=3e5){this.precision=e,this.windowMs=t}pushTick(e){let t=tW(e.price,this.precision),r=e.timestamp>1e12?e.timestamp:1e3*e.timestamp;if(this.prevTickTs>0&&0!==this.prevBinnedPrice){let e=Math.max(0,r-this.prevTickTs),t=this.levels.get(this.prevBinnedPrice);t&&(t.dwellTimeMs+=e)}let i=this.levels.get(t);i?(i.tickCount++,i.lastSeenTs=r,i.volume+=e.volume):this.levels.set(t,{price:t,tickCount:1,dwellTimeMs:0,lastSeenTs:r,volume:e.volume});let s={price:e.price,binnedPrice:t,ts:r,volume:e.volume};this.tickCount<2e3?(this.ticks.push(s),this.tickCount++):this.ticks[this.head]=s,this.head=(this.head+1)%2e3,this.prevPrice=this.currentPrice,this.currentPrice=e.price,this.prevTickTs=r,this.prevBinnedPrice=t}getSnapshot(e){if(0===this.currentPrice)return null;let t=Date.now();this.prune(t);let r=tW(this.currentPrice,this.precision),i=new Map;for(let e of this.levels.values())i.set(e.price,e);let s=tW(r+Math.floor(e/2)*this.precision,this.precision),n=[];for(let t=0;t<e;t++){let e=tW(s-t*this.precision,this.precision),r=i.get(e);r?n.push(r):n.push({price:e,tickCount:0,dwellTimeMs:0,lastSeenTs:0,volume:0})}let a=this.currentPrice>this.prevPrice?"up":this.currentPrice<this.prevPrice?"down":"neutral";return{asOfMs:t,levels:n,currentPrice:this.currentPrice,currentPriceLevel:r,direction:a,windowMs:this.windowMs}}setPrecision(e){e!==this.precision&&(this.precision=e,this.rebuildFromTicks())}setWindow(e){this.windowMs=e,this.prune()}getPrecision(){return this.precision}backfillFromBars(e){for(let t of e){let e=1e3*t.time;
2this.pushTick({symbol:"",price:t.open,timestamp:e,volume:0}),this.pushTick({symbol:"",price:t.high,timestamp:e+15e3,volume:0}),this.pushTick({symbol:"",price:t.low,timestamp:e+3e4,volume:0}),this.pushTick({symbol:"",price:t.close,timestamp:e+45e3,volume:t.volume??0})}}prune(e=Date.now()){let t=e-this.windowMs;for(let[e,r]of this.levels)r.lastSeenTs<t&&this.levels.delete(e);if(this.levels.size>200){let e=Array.from(this.levels.entries()).sort((e,t)=>e[1].lastSeenTs-t[1].lastSeenTs);for(let[t]of e.slice(0,e.length-200))this.levels.delete(t)}}rebuildFromTicks(){this.levels.clear(),this.prevTickTs=0,this.prevBinnedPrice=0;let e=Math.min(this.tickCount,2e3),t=this.tickCount<=2e3?0:this.head;for(let r=0;r<e;r++){let e=(t+r)%2e3,i=this.ticks[e],s=tW(i.price,this.precision),n=i.ts;if(this.prevTickTs>0&&0!==this.prevBinnedPrice){let e=Math.max(0,n-this.prevTickTs),t=this.levels.get(this.prevBinnedPrice);t&&(t.dwellTimeMs+=e)}let a=this.levels.get(s);a?(a.tickCount++,a.lastSeenTs=n,a.volume+=i.volume):this.levels.set(s,{price:s,tickCount:1,dwellTimeMs:0,lastSeenTs:n,volume:i.volume}),this.prevTickTs=n,this.prevBinnedPrice=s}}}var tK=e.i(798526);let tG=0,tY=[{value:3e5,label:"5m"},{value:9e5,label:"15m"},{value:36e5,label:"1h"},{value:144e5,label:"4h"},{value:864e5,label:"24h"}];function tX({value:e,options:i,labels:s,onChange:a}){let[l,o]=(0,r.useState)(!1),d=(0,r.useRef)(null);return(0,r.useEffect)(()=>{if(!l)return;let e=e=>{d.current&&!d.current.contains(e.target)&&o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[l]),(0,t.jsxs)("div",{ref:d,className:"relative",children:[(0,t.jsxs)("button",{onClick:()=>o(!l),className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-muted-foreground hover:text-secondary-foreground hover:bg-surface-interactive transition-colors",children:[s[e],(0,t.jsx)(n.ChevronDown,{className:"w-3 h-3"})]}),l&&(0,t.jsx)("div",{className:"absolute top-full left-0 mt-1 z-50 bg-popover border border-border-strong rounded-float shadow-lg min-w-[70px]",children:i.map(r=>(0,t.jsxs)("button",{onClick:()=>{a(r),o(!1)},className:(0,I.cn)("flex items-center gap-2 w-full px-3 py-1.5 text-[10px] hover:bg-surface-interactive transition-colors",e===r?"text-foreground":"text-muted-foreground"),children:[s[r],e===r&&(0,t.jsx)("span",{className:"text-label-muted ml-auto",children:"✓"})]},r))})]})}function tQ(e){return e>=1?0:Math.max(0,Math.ceil(-Math.log10(e)))}function tJ(e,t,r){return(0,d.formatFixed)(e,tQ(t),r)}function tZ(e,t){return e>=6e4?`${(0,d.formatFixed)(e/6e4,1,t)}m`:e>=1e3?`${(0,d.formatFixed)(e/1e3,1,t)}s`:`${Math.round(e)}ms`}function t0({level:e,asOfMs:r,precision:i,maxDwellMs:s,windowMs:n,isCurrentPrice:a,isAboveCurrent:l}){let o=(0,c.useFormatters)(),d=s>0?Math.min(100,e.dwellTimeMs/s*100):0,u=e.lastSeenTs>0?Math.max(0,1-(r-e.lastSeenTs)/n):0,h=a?"text-foreground font-medium":0===e.tickCount?"text-muted-foreground":l?"text-side-short":"text-side-long";return(0,t.jsxs)("div",{className:(0,I.cn)("relative flex items-center h-[22px] px-2 text-[11px] font-mono tabular-nums",a&&"bg-canvas"),children:[d>0&&(0,t.jsx)("div",{className:"absolute inset-y-0 left-0",style:{width:`${d}%`,backgroundColor:l?"var(--side-short)":"var(--side-long)",opacity:.1+.18*u}}),(0,t.jsx)("span",{className:(0,I.cn)("relative z-10 w-[40%] text-left",h),children:tJ(e.price,i,o.intlTag)}),(0,t.jsx)("span",{className:"relative z-10 w-[35%] text-right text-muted-foreground",children:e.dwellTimeMs>0?tZ(e.dwellTimeMs,o.intlTag):""}),(0,t.jsx)("span",{className:"relative z-10 w-[25%] text-right text-label-muted",children:e.tickCount>0?e.tickCount:""})]})}function t1({symbol:e,mintAddress:i,currentPrice:s}){let n=(0,l.useTranslations)("trading"),a=(0,c.useFormatters)(),o=(0,r.useRef)(null),[u,h]=(0,r.useState)(30),p=(0,r.useCallback)(()=>{o.current&&h(Math.max(10,Math.floor((o.current.clientHeight-113)/22)))},[]);(0,r.useEffect)(()=>{p();let e=new ResizeObserver(p);return o.current&&e.observe(o.current),()=>e.disconnect()},[p]);let{snapshot:m,precision:f,setPrecision:x,windowMs:g,setWindow:b,precisionOptions:v}
2=function(e,t,i,s=40){let[n,a]=(0,r.useState)(null),[l,o]=(0,r.useState)(null),[d,c]=(0,r.useState)(36e5),u=(0,r.useRef)(null),h=(0,r.useRef)(!1),p=(0,r.useRef)(0),m=(0,r.useRef)(()=>{}),f=(0,r.useRef)(s);f.current=s,(0,r.useEffect)(()=>{o(null)},[e]);let x=(0,r.useMemo)(()=>null!==l?l:void 0!==i?tH(i):null,[l,i]),g=(0,r.useMemo)(()=>{if(void 0!==i){let e;return[e=tH(i),10*e,100*e]}return[]},[i]);return(0,r.useEffect)(()=>{if(null===x)return;let r=new tq(x,d);u.current=r,a(null),h.current=!1;let i=`tick-ladder-${++tG}`,s=!1,n=Math.ceil(d/1e3),l=Math.floor(Date.now()/1e3);function o(){0===p.current&&(p.current=requestAnimationFrame(()=>{p.current=0,h.current&&u.current===r&&(h.current=!1,a(r.getSnapshot(f.current)))}))}return m.current=o,(0,V.getChartData)(t,"regular","1m",{timeFrom:l-n,timeTo:l}).then(e=>{!s&&u.current===r&&e.length>0&&(r.backfillFromBars(e),h.current=!0,o())}).catch(e=>{console.warn("[PriceLadder] backfill failed:",e)}),(0,tK.addListener)(i,e,e=>{r.pushTick(e),h.current=!0,o()}),()=>{s=!0,(0,tK.removeListener)(i,e),0!==p.current&&cancelAnimationFrame(p.current),p.current=0,m.current=()=>{},u.current=null}},[e,t,x]),(0,r.useEffect)(()=>{let e=u.current;if(!e)return;e.setWindow(d);let r=!1,i=Math.ceil(d/1e3),s=Math.floor(Date.now()/1e3);return(0,V.getChartData)(t,"regular","1m",{timeFrom:s-i,timeTo:s}).then(t=>{!r&&u.current===e&&t.length>0&&(e.backfillFromBars(t),h.current=!0,m.current())}).catch(e=>{console.warn("[PriceLadder] window re-backfill failed:",e)}),()=>{r=!0}},[d,t]),(0,r.useEffect)(()=>{let t=u.current;
2t&&void 0!==i&&(t.pushTick({symbol:e,price:i,timestamp:Date.now(),volume:0}),h.current=!0,m.current())},[i,e]),{snapshot:n,precision:x,setPrecision:(0,r.useCallback)(e=>{o(e),u.current?.setPrecision(e),h.current=!0,m.current()},[]),windowMs:d,setWindow:(0,r.useCallback)(e=>{c(e)},[]),precisionOptions:g}}(e,i,s,u),y=(0,r.useMemo)(()=>{let e={};for(let r of v){var t;e[r.toString()]=(t=a.intlTag,(0,d.formatFixed)(r,tQ(r),t))}return e},[v,a]),w=(0,r.useMemo)(()=>{let e={};for(let t of tY)e[t.value.toString()]=t.label;return e},[]),{aboveRows:j,belowRows:S,maxDwellMs:k}=(0,r.useMemo)(()=>{if(!m)return{aboveRows:[],belowRows:[],maxDwellMs:0};let e=[],t=[],r=0;for(let i of m.levels)i.dwellTimeMs>r&&(r=i.dwellTimeMs),i.price>m.currentPriceLevel?e.push(i):i.price<m.currentPriceLevel&&t.push(i);return{aboveRows:e,belowRows:t,maxDwellMs:r}},[m]),N=(0,r.useMemo)(()=>m?m.levels.find(e=>e.price===m.currentPriceLevel)??null:null,[m]);return(0,t.jsxs)("div",{ref:o,className:"trading-panel-surface flex flex-col h-full overflow-hidden",children:[(0,t.jsxs)("div",{className:"flex items-center border-b border-border",children:[(0,t.jsx)(eL.DesktopWorkspacePanelTools,{}),(0,t.jsx)("button",{className:"flex-1 py-2 text-xs font-medium text-foreground border-b border-white transition-colors",children:n("priceLadder")})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-7 px-2 border-b border-border/50",children:[null!==f&&v.length>0?(0,t.jsx)(tX,{value:f.toString(),options:v.map(String),labels:y,onChange:e=>x(parseFloat(e))}):(0,t.jsx)("div",{}),(0,t.jsx)(tX,{value:g.toString(),options:tY.map(e=>e.value.toString()),labels:w,onChange:e=>b(parseInt(e,10))})]}),(0,t.jsxs)("div",{className:"flex items-center h-6 px-2 text-[10px] text-label-muted font-medium border-b border-border/50",children:[(0,t.jsx)("span",{className:"w-[40%] text-left",children:n("price")}),(0,t.jsx)("span",{className:"w-[35%] text-right",children:n("dwell")}),(0,t.jsx)("span",{className:"w-[25%] text-right",children:n("ticks")})]}),m?(0,t.jsxs)("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden",children:[(0,t.jsx)("div",{className:"flex flex-col justify-end flex-1 min-h-0",children:j.map(e=>(0,t.jsx)(t0,{level:e,asOfMs:m.asOfMs,precision:f??.01,maxDwellMs:k,windowMs:g,isCurrentPrice:!1,isAboveCurrent:!0},e.price))}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-7 px-2 bg-canvas border-y border-border/50 text-[11px] font-mono tabular-nums flex-shrink-0",children:[(0,t.jsx)("span",{className:"text-foreground font-medium",children:null!==f?tJ(m.currentPrice,f,a.intlTag):a.fixed(m.currentPrice,2)}),(0,t.jsx)("span",{className:(0,I.cn)("text-sm","up"===m.direction?"text-side-long":"down"===m.direction?"text-side-short":"text-label-muted"),children:"up"===m.direction?"▲":"down"===m.direction?"▼":"◆"}),N&&N.dwellTimeMs>0&&(0,t.jsx)("span",{className:"text-label-muted text-[10px]",children:tZ(N.dwellTimeMs,a.intlTag)})]}),(0,t.jsx)("div",{className:"flex flex-col flex-1 min-h-0",children:S.map(e=>(0,t.jsx)(t0,{level:e,asOfMs:m.asOfMs,precision:f??.01,maxDwellMs:k,windowMs:g,isCurrentPrice:!1,isAboveCurrent:!1},e.price))})]}):(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center",children:(0,t.jsxs)("div",{className:"text-xs text-label-muted flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-3 h-3 border-2 border-border-strong border-t-transparent rounded-full animate-spin"}),n("waitingForOracleData")]})})]})}function t2({symbol:e,mintAddress:i,currentPrice:s,venue:n}){let a=(0,l.useTranslations)("trading"),o=(0,l.useTranslations)("terms"),u=(0,c.useFormatters)(),h=(0,r.useRef)(null),[p,m]=(0,r.useState)("both"),[x,g]=(0,r.useState)(12),b=(0,r.useCallback)(()=>{h.current&&g(Math.max(3,Math.floor((h.current.clientHeight-(85+48*("both"===p)))/("both"===p?2:1)/22)))},[p]);(0,r.useEffect)(()=>{b();let e=new ResizeObserver(b);return h.current&&e.observe(h.current),()=>e.disconnect()},[b]);let v=function({asset:e,venue:t,mark:i,rows:s}){let n=(0,tz.useGmTradeWs)(),{data:a}=function(e,t=!0){let{connection:r}=(0,tU.useConnection)(),i=tO.ASSET_TO_MINT[e],s=i?tO.CUSTODIES[i]:void 0;return(0,eV.useQuery)({queryKey:["jupiter-custody",s?.toBase58()??null],queryFn:async()=>
2{if(!s)return null;let e=await r.getAccountInfo(s);return e?(0,tB.decodeJupiterCustodyPricing)(new Uint8Array(e.data),Math.floor(Date.now()/1e3)):null},refetchInterval:1e4,enabled:t&&void 0!==s})}(e,"jupiter"===t),l=n.getMarketLiquidity(e);return(0,r.useMemo)(()=>{if(!t||!i||i<=0||s<1)return null;let r=(0,t$.buildLiquidityMap)({asset:e,gmtrade:"gmtrade"===t&&l?l:null,jupiter:"jupiter"===t?a??null:null})[t];if(!r)return null;let n=function(e,t){switch(e){case"jupiter":return t.jupiterPricing?{long:(0,tB.jupiterMaxNotional)(t.jupiterPricing,"long"),short:(0,tB.jupiterMaxNotional)(t.jupiterPricing,"short")}:{};case"gmtrade":return t.gmLiquidity?{long:t.gmLiquidity.longAvailableUsd,short:t.gmLiquidity.shortAvailableUsd}:{};default:return{}}}(t,{jupiterPricing:a??null,gmLiquidity:l}),o=function(e){let{effectiveBps:t,mark:r,rows:i,maxNotional:s}=e,n=e=>Math.max(e/1e3,Math.min(10,e/10)),a=e.minNotional??n(s.long),l=e.minNotional??n(s.short),o=tV(t,r,"long",i,a,s.long),d=tV(t,r,"short",i,l,s.short);return{asks:[...o.levels].reverse(),bids:d.levels,mark:r,askCapUsd:o.capUsd,bidCapUsd:d.capUsd,askSpanBps:o.spanBps,bidSpanBps:d.spanBps}}({effectiveBps:r.priceImpactBps,mark:i,rows:s,maxNotional:{long:n.long??1e6,short:n.short??1e6}});return 0===o.asks.length&&0===o.bids.length?null:{book:o,isFlat:o.askSpanBps<.05&&o.bidSpanBps<.05,capIsReal:void 0!==n.long||void 0!==n.short}},[t,i,s,e,l,a])}({asset:e,venue:n,mark:s,rows:x});if(!v)return(0,t.jsx)(t1,{symbol:e,mintAddress:i,currentPrice:s});let{book:y,isFlat:w,capIsReal:j}=v,S=function(e,t,r){if(t.length<2)return e;let i=Math.max(...t)-Math.min(...t);return i>0?Math.min(8,Math.max(e,Math.ceil(Math.log10(Math.max(2,r)/i)))):e}(Math.max(0,-Math.floor(Math.log10(tH(y.mark)))),[...y.asks,...y.bids].map(e=>e.price),x),k=e=>(0,d.formatFixed)(e,S,u.intlTag),N=Math.max(y.asks.length>0?y.asks[0].total:0,y.bids.length>0?y.bids[y.bids.length-1].total:0),P=Math.max(y.askCapUsd??0,y.bidCapUsd??0);return(0,t.jsxs)("div",{ref:h,className:"trading-panel-surface flex flex-col h-full overflow-hidden border-l border-border",children:[(0,t.jsxs)("div",{className:"flex items-center border-b border-border",children:[(0,t.jsx)(eL.DesktopWorkspacePanelTools,{}),(0,t.jsx)(tb.DesktopChartLinkBadge,{}),(0,t.jsxs)("h2",{className:"w-1/2 py-2 flex items-center justify-center gap-1 text-xs font-medium text-foreground border-b border-white",children:[a("poolDepth"),(0,t.jsxs)(eN.Tooltip,{children:[(0,t.jsx)(eN.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":a("poolDepthExplainer"),className:"focus-ring rounded cursor-help text-label-muted hover:text-secondary-foreground transition-colors",children:(0,t.jsx)(G.Info,{className:"w-3 h-3"})})}),(0,t.jsx)(eN.TooltipContent,{side:"bottom",sideOffset:4,showArrow:!1,className:"text-xs px-3 py-2 max-w-[260px] font-normal leading-relaxed",children:a("poolDepthExplainer")})]})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-7 px-2 border-b border-border/50",children:[(0,t.jsx)("span",{className:"px-1.5 py-0.5 text-[10px] text-muted-foreground",children:n?f.VENUE_LABELS[n]:""}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"px-1.5 py-0.5 text-[10px] text-label-muted",children:a("inclFees")}),(0,t.jsx)(tM,{value:p,onChange:e=>m(e)})]})]}),(0,t.jsx)(tA,{asks:y.asks.slice(-x),bids:y.bids.slice(0,x),maxTotal:N,sideFilter:p,formatPrice:k,formatPriceMachine:e=>e.toFixed(S),headers:{price:(0,t.jsxs)(t.Fragment,{children:[a("price")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"USDC"})]}),size:(0,t.jsxs)(t.Fragment,{children:[o("size.full")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"USDC"})]}),total:(0,t.jsxs)(t.Fragment,{children:[a("total")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"USDC"})]})},middle:(0,t.jsxs)("div",{className:"flex flex-col bg-canvas border-y border-border/50 tabular-nums font-mono",children:[(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2 h-7 px-2 text-[12px]",children:[(0,t.jsx)("span",{className:"text-foreground",children:k(y.mark)}),(0,t.jsx)("span",{className:"text-label-muted text-[10px]",children:a("mark")})]}),P>0&&j&&(0,t.jsxs)("div",{className:"flex items-center justify-between h-5 px-2 text-[10px] border-t border-border/50",children:[(0,t.jsx)("span",{className:"text-label-muted",children:w?a("noSizeImpactBelow",{size:tj(P,u.intlTag)}):a("maxOrderSize")}),!w&&(0,t.jsx)("span",{className:"text-muted-foreground",children:tj(P,u.intlTag)})]})]})})]})}var t5=e.i(48813);function t3({enabled:e,available:r,onChange:i}){let s=(0,l.useTranslations)("trading");return(0,t.jsxs)("div",{className:"flex h-8 shrink-0 items-center justify-between gap-2 border-b border-border/50 px-2 text-[10px]",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-secondary-foreground",children:[(0,t.jsxs)("span",{"aria-hidden":"true",className:"flex h-2.5 w-3 overflow-hidden rounded-[2px]",children:[(0,t.jsx)("span",{className:"w-1/2 bg-side-short/50"}),(0,t.jsx)("span",{className:"w-1/2 bg-side-long/50"})]}),"Armada"]}),(0,t.jsx)("span",{className:"text-label-muted",title:s("depthSharedScale"),children:s("depthMarkAlignment")}),(0,t.jsxs)("button",{type:"button",role:"switch","aria-checked":e&&r,"aria-label":s("comparePhoenixDepth"),title:s(r?"depthSharedScale":"phoenixDepthUnavailable"),disabled:!r,onClick:()=>i(!e),className:"focus-ring flex h-7 items-center gap-1.5 rounded text-muted-foreground disabled:opacity-40 enabled:hover:text-foreground",children:[(0,t.jsxs)("span",{"aria-hidden":"true",className:"flex h-2.5 w-3 overflow-hidden rounded-[2px]",children:[(0,t.jsx)("span",{className:"w-1/2 roun
2ded-l-[2px] border-y border-l border-depth-comparison-ask"}),(0,t.jsx)("span",{className:"w-1/2 rounded-r-[2px] border-y border-r border-depth-comparison-bid"})]}),"Phoenix",(0,t.jsx)("span",{"aria-hidden":"true",className:(0,I.cn)("relative ml-1 h-3.5 w-6 rounded-full transition-colors",e&&r?"bg-side-long/20":"bg-surface-interactive"),children:(0,t.jsx)("span",{className:(0,I.cn)("absolute left-0 top-0.5 h-2.5 w-2.5 rounded-full transition-transform",e&&r?"translate-x-3 bg-depth-comparison-bid":"translate-x-0.5 bg-muted-foreground")})})]})]})}function t4(e){return(0,t.jsx)(t6,{...e},e.symbol)}let t6=(0,r.memo)(function(e){let r=(0,t5.useThrottledValue)(e.comparisonBook,100),i=e.comparisonBook?.asks.length||e.comparisonBook?.bids.length?r:e.comparisonBook;return(0,t.jsx)(t8,{...e,comparisonBook:i})}),t8=(0,r.memo)(function({symbol:e,venue:i,settings:s,onSettingsChange:n,comparisonBook:a,active:o=!0}){let u=(0,l.useTranslations)("trading"),h=(0,l.useTranslations)("terms"),p=(0,c.useFormatters)(),m=(0,r.useRef)(null),{precision:x,denom:g,sideFilter:b}=s,[v,y]=(0,r.useState)(12),[w,j]=(0,r.useState)(!0),{book:S,isPending:k}=(0,W.useDisplayedSunriseOrderbook)(e,i,x,o),N=S?.depthMarkPrice!==void 0?S.depthMarkPrice:S?.stats.markPrice,P=a?.markPrice,T=!!S?.venueReachable&&!!(a?.asks.length||a?.bids.length)&&!!N&&Number.isFinite(N)&&N>0&&!!P&&Number.isFinite(P)&&P>0,C=w&&T,M=(0,r.useCallback)(()=>{m.current&&y(Math.max(1,Math.floor((m.current.clientHeight-(117+56*!!C+88*("both"===b)))/("both"===b?2:1)/22)))},[b,C]);(0,r.useEffect)(()=>{M();let e=new ResizeObserver(M);return m.current&&e.observe(m.current),()=>e.disconnect()},[M]);let{askRows:_,bidRows:A,maxTotal:E,comparison:L,depthShare:F}=(0,r.useMemo)(()=>{let t=tf(S?.asks??[],"ask",{precision:x,denom:g},v),r=tf(S?.bids??[],"bid",{precision:x,denom:g},v),i=C&&a&&N?{asks:tm(a.asks,"ask",s,t,N,P),bids:tm(a.bids,"bid",s,r,N,P),unit:"usdc"===g?"USDC":e,markPrice:N}:void 0,n=[..."bid"!==b?t.map(e=>e.total).concat(i?.asks.map(e=>e??0)??[]):[],..."ask"!==b?r.map(e=>e.total).concat(i?.bids.map(e=>e??0)??[]):[]];return{askRows:t,bidRows:r,maxTotal:i?Math.max(0,...n):tx([S,a],s,v),comparison:i,depthShare:"both"===b&&S?.venueReachable?tg(S,x,t,r):null}},[S,v,s,a,x,g,C,b,e,N,P]),R="usdc"===g?"USDC":e,D=tu(x),I=e=>(0,d.formatFixed)(e,D,p.intlTag),U=_.length>0||A.length>0;return(0,t.jsxs)("div",{ref:m,className:"trading-panel-surface flex flex-col h-full overflow-hidden border-l border-border",children:[(0,t.jsxs)("div",{className:"flex items-center shrink-0 border-b border-border",children:[(0,t.jsx)(eL.DesktopWorkspacePanelTools,{}),(0,t.jsx)(tb.DesktopChartLinkBadge,{}),(0,t.jsx)("h2",{className:"w-1/2 py-2 flex items-center justify-center text-xs font-medium text-foreground border-b border-white",children:u("orderBook")})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center justify-between h-7 px-2 border-b border-border/50",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)(tR,{value:x,onChange:e=>n({...s,precision:e})}),(0,t.jsx)("span",{className:"text-[10px] text-muted-foreground",children:f.VENUE_LABELS[i]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[S&&!S.venueReachable&&(0,t.jsx)("span",{className:"px-1.5 py-0.5 text-[10px] text-amber-400",children:u("bookReconnecting")}),(0,t.jsxs)("button",{type:"button",onClick:()=>n({...s,denom:"usdc"===g?"asset":"usdc"}),"aria-label":u("switchToUnit",{unit:"usdc"===g?e:"USDC"}),className:"focus-ring flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-muted-foreground hover:text-secondary-foreground hover:bg-surface-interactive transition-colors",children:[R,(0,t.jsx)(tv.ArrowLeftRight,{className:"w-3 h-3"})]}),(0,t.jsx)(tM,{value:b,onChange:e=>n({...s,sideFilter:e})})]})]}),(0,t.jsx)(t3,{enabled:w,available:T,onChange:j}),U?(0,t.jsx)(tA,{asks:_,bids:A,maxTotal:E,comparison:L,sideFilter:b,depthShare:F?{...F,venue:f.VENUE_LABELS[i],symbol:e}:null,formatPrice:I,formatPriceMachine:e=>e.toFixed(D),headers:{price:(0,t.jsxs)(t.Fragment,{children:[u("price")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:"USDC"})]}),size:(0,t.jsxs)(t.Fragment,{children:[h("size.full")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:R})]}),total:(0,t.jsxs)(t.Fragment,{children:[u("total")," ",(0,t.jsx)("span",{className:"text-muted-foreground",children:R})]})},middle:(0,t.jsxs)("div",{className:"flex shrink-0 flex-col bg-canvas border-y border-border/50 tabular-nums font-mono",children:[(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2 h-7 px-2 text-[12px]",children:[(0,t.jsx)("span",{className:"text-foreground",children:S?.mid!=null?I(S.mid):"—"}),(0,t.jsx)("span",{className:"text-label-muted text-[10px]",children:u("mid")})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between h-5 px-2 text-[10px] border-t border-border/50",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:S?.spread!=null?p.fixed(S.spread,th(S.spread)):"—"}),(0,t.jsx)("span",{className:"text-label-muted",children:u("spread")}),(0,t.jsx)("span",{className:"text-muted-foreground",children:S?.spreadBps!=null?p.percent(S.spreadBps/100,Math.max(3,th(S.spreadBps/100))):"—"})]})]})}):(0,t.jsx)("div",{className:"flex flex-1 items-center justify-center px-4 text-center text-xs text-label-muted",children:k?"":u("bookUnavailable",{venue:f.VENUE_LABELS[i]})})]})});e.s(["ParkedActivity",0,function({active:e,busy:i=!1,children:s}){let n=e||i,[a,l]=(0,r.useState)(n);return n&&!a&&l(!0),(0,r.useEffect)(()=>
2{if(n)return;let e=setTimeout(()=>l(!1),300);return()=>clearTimeout(e)},[n]),(0,t.jsx)(r.Activity,{mode:n||a?"visible":"hidden",children:s})}],519063);var t9=e.i(810638);e.s(["useStillFresh",0,function(e,t){let[i,s]=(0,r.useState)();return(0,r.useLayoutEffect)(()=>{if(void 0===e)return;let r=e+t-Date.now();if(r<=0)return void s(e);let i=window.setTimeout(()=>s(e),r);return()=>window.clearTimeout(i)},[e,t]),(0,t9.useResumeSignal)(()=>{void 0!==e&&Date.now()>=e+t&&s(e)}),void 0!==e&&i!==e}],796049);var t7=e.i(845165),re=e.i(623075),rt=e.i(568299),rr=e.i(22156),ri=e.i(541043),rs=e.i(389896),rn=e.i(157265),ra=e.i(650883),rl=e.i(581285);let ro=(0,eD.default)("moon",[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]),rd=(0,eD.default)("circle-pause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);var rc=e.i(142910),ru=e.i(142981),rh=e.i(403628),rp=e.i(722732),rm=e.i(622463),rf=e.i(555641);function rx({marketMint:e,symbol:i}){let s=(0,l.useTranslations)("markets"),n=(0,c.useIntlTag)(),[a,o]=(0,r.useState)(0),d=(0,r.useSyncExternalStore)(rc.subscribeFeedRegistry,rc.getFeedRegistryVersion,()=>0),u=(0,r.useMemo)(()=>(0,rc.getSchedule)(e)??(0,rc.getScheduleBySymbol)(i),[e,i,d]),h=(0,r.useMemo)(()=>u&&!(0,ru.is24x7)(u)?(0,ru.parseSchedule)(u):null,[u]),{data:p}=(0,rh.useGmTradeMarkets)(),m=(0,r.useMemo)(()=>{if(!p||!i)return!1;let e=!1;for(let t of p)if(t.symbol===i&&(e=!0,!t.closed))return!1;return e},[p,i]),x=(0,r.useSyncExternalStore)(rp.subscribeGmTradeRegistry,rp.getGmTradeRegistryVersion,()=>0),g=(0,r.useSyncExternalStore)(rm.subscribePhoenixRegistry,rm.getPhoenixRegistryVersion,()=>0),b=(0,r.useMemo)(()=>(0,rf.pausedVenueForMarket)(e),[e,x,g]);(0,r.useEffect)(()=>{if(!h)return;let e=setInterval(()=>o(e=>e+1),6e4);return()=>clearInterval(e)},[h]);let v=(0,r.useMemo)(()=>!h||(0,ru.isMarketOpenAt)(h,new Date),[h,a]),y=v&&!m,w=(0,r.useMemo)(()=>v||!h?null:(0,ru.nextOpenTime)(h),[v,h]);return b?(0,t.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-amber-200 text-xs",children:[(0,t.jsx)(rd,{className:"h-3.5 w-3.5 text-amber-400 flex-shrink-0"}),(0,t.jsx)("span",{className:"min-w-0",children:s("venueOpensPausedNotice",{venue:f.VENUE_LABELS[b]})})]}):!y&&(h||m)?(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3 px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-amber-200 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,t.jsx)(ro,{className:"h-3.5 w-3.5 text-amber-400 flex-shrink-0"}),(0,t.jsxs)("span",{className:"truncate",children:[s("marketClosedNotice")," ",(0,t.jsx)("a",{href:"https://docs.phoenix.trade/phoenix/real-world-assets/index-price",target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 hover:text-amber-100",children:s("learnMore")})]})]}),w&&(0,t.jsx)("span",{className:"flex-shrink-0 text-amber-300 whitespace-nowrap",children:s("marketOpensAt",{time:(0,ru.formatReopenTime)(w,n)})})]}):null}e.s(["MarketClosedBanner",0,rx],197944);let rg={CRUDEOIL:{asset:"Crude oil",contract:"NYMEX WTI"},NATGAS:{asset:"Natural gas",contract:"NYMEX Henry Hub"}};function rb(e){return`futures-contract-banner-dismissed:${e}`}function rv({symbol:e}){let i=(0,l.useTranslations)("trading"),s=rg[e],[n,a]=(0,r.useState)(!0);return((0,r.useEffect)(()=>{s&&a("1"===window.localStorage.getItem(rb(e)))},[e,s]),!s||n)?null:(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-amber-200 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(G.Info,{className:"h-3.5 w-3.5 text-amber-400 flex-shrink-0"}),(0,t.jsx)("span",{children:i("futuresContractNotice",{asset:s.asset,contract:s.contract})})]}),(0,t.jsx)("button",{onClick:()=>{window.localStorage.setItem(rb(e),"1"),a(!0)},className:"ml-2 p-0.5 hover:bg-amber-500/20 rounded transition-colors flex-shrink-0","aria-label":i("dismiss"),children:(0,t.jsx)(ez.X,{className:"h-3.5 w-3.5"})})]})}function ry({mint:e,allMarkets:n,positions:a,onClose:o,onPositionChange:d}){let u=(0,l.useTranslations)("trading"),h=(0,c.useFormatters)(),{activeProfileIndex:p}=(0,m.useProfile)(),{setMarketMint:f}=(0,j.useMarketContext)(),x=n.find(t=>t.mint===e),g=x?.symbol,b=ri.MINT_TO_PYTH_SYMBOL[e]??g,v=(0,rr.usePriceForSymbol)(b),{getPrice
2:y}=(0,tz.useGmTradeWs)(),w=v??(g?y(g):void 0),S=(0,r.useMemo)(()=>a.filter(e=>e.asset===x?.symbol&&(null==e.profileIndex||e.profileIndex===p)),[a,x,p]);return x?(0,t.jsx)(re.Dialog,{open:!0,onOpenChange:e=>{e||o()},children:(0,t.jsxs)(re.DialogContent,{className:"p-0 gap-0 sm:max-w-[420px] max-h-[85vh] flex flex-col",children:[(0,t.jsx)(re.DialogHeader,{className:"px-4 py-3 border-b flex-shrink-0",children:(0,t.jsx)(re.DialogTitle,{asChild:!0,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 mr-8",children:[(0,t.jsx)(i.default,{src:x.image,alt:x.symbol,width:22,height:22,className:"rounded-full flex-shrink-0",unoptimized:!0,onError:s.handleTokenImageError}),(0,t.jsx)("span",{className:"font-semibold text-foreground text-sm",children:(0,T.displayName)(x.symbol)}),(0,t.jsx)("span",{className:"text-sm text-secondary-foreground font-mono tabular-nums",children:void 0!==w?`$${h.number(w)}`:""}),(0,t.jsxs)("button",{type:"button",onClick:()=>{f(e),o()},className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[u("goToMarket"),(0,t.jsx)(t7.ExternalLink,{className:"w-3 h-3"})]})]})})}),(0,t.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[(0,t.jsx)(rx,{marketMint:e,symbol:x.symbol}),(0,t.jsx)(rv,{symbol:x.symbol}),(0,t.jsx)(ra.ErrorBoundary,{children:(0,t.jsx)(rt.RoutingProvider,{children:(0,t.jsx)(rw,{mint:e,symbol:x.symbol,n
2ame:x.name,image:x.image,price:w,onPositionChange:d,existingPositions:S})})})]})]})}):null}function rw({mint:e,symbol:i,name:s,image:n,price:a,existingPositions:l,onPositionChange:o}){let{activeProfilePda:d}=(0,m.useProfile)(),c=d?.toBase58(),{data:u}=(0,y.usePhoenixMarkets)(),h=(u??[]).some(e=>e.symbol===i),p=(0,rs.usePhoenixWs)(h?i:null,h?c:null,100),f=(0,rn.usePhoenixExecutionBook)(i,h,p),[x,g]=(0,r.useState)(null),b=(0,r.useCallback)(t=>{g(r=>r?.mint===e&&r.profilePda===c&&r.venue===t?r:{mint:e,profilePda:c,venue:t})},[e,c]),v=x?.mint===e&&x.profilePda===c&&"phoenix"===x.venue;return(0,t.jsx)(rl.JupiterPerpsTradingPanel,{marketMint:e,marketInfo:{symbol:i,name:s,image:n},marketPrice:v&&p.marketStats?.markPx||a,oraclePrice:v&&p.marketStats?.oraclePx||a,...f,onResolvedVenueChange:b,onPositionChange:o,existingPositions:l,compact:!0,active:!0})}e.s(["FuturesContractBanner",0,rv],901715),e.i(889723);var rj=e.i(985433),rS=e.i(373447),rk=e.i(578152);let rN=BigInt(1e6);function rP(e){return`usdt-banner-dismissed:${e}`}e.s(["UsdtDepositBanner",0,function(){let e=(0,l.useTranslations)("trading"),i=(0,c.useFormatters)(),{publicKey:s,isJWTMode:n}=(0,p.useUnifiedWallet)(),{rawBalance:a,uiBalance:o}=(0,rS.useUsdtWalletBalance)(n?null:s),[d,u]=(0,r.useState)(!0),h=s?.toBase58()??null;(0,r.useEffect)(()=>{h?u("1"===window.localStorage.getItem(rP(h))):u(!0)},[h]);let m=!d&&a>=rN&&!n,{quote:f,swap:x,pending:g}=(0,rk.useSwapUsdtToUsdc)({rawUsdtBalance:a,enabled:m});return m?(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 bg-sky-500/10 border-b border-sky-500/20 text-sky-200 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 min-w-0",children:[(0,t.jsx)("span",{className:"truncate",children:e.rich("usdtSwapPrompt",{amount:`${i.fixed(o,2)} USDT`,strong:e=>(0,t.jsx)("span",{className:"font-semibold font-mono tabular-nums text-foreground",children:e})})}),(0,t.jsxs)("button",{onClick:()=>void x(),disabled:g||!f,className:"inline-flex items-center gap-1 px-2.5 py-1 rounded bg-sky-500/20 hover:bg-sky-500/30 border border-sky-500/40 text-sky-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0",children:[g?e("swapping"):e("swapTo",{token:"USDC"}),!g&&(0,t.jsx)(rj.ArrowRight,{className:"h-3 w-3"})]})]}),(0,t.jsx)("button",{onClick:()=>{h&&window.localStorage.setItem(rP(h),"1"),u(!0)},className:"ml-2 p-0.5 hover:bg-sky-500/20 rounded transition-colors flex-shrink-0","aria-label":e("dismiss"),children:(0,t.jsx)(ez.X,{className:"h-3.5 w-3.5"})})]}):null}],376326)},889723,849361,e=>{"use strict";e.s(["JupiterPerpsMarketView",()=>eQ],889723);var t=e.i(394390),r=e.i(257355),i=e.i(157285),s=e.i(918401),n=e.i(632588),a=e.i(183023),l=e.i(859394),o=e.i(942553),d=e.i(875574),c=e.i(142298),u=e.i(894771),h=e.i(568299),p=e.i(777180),m=e.i(299959),f=e.i(687229),x=e.i(585457),g=e.i(637226),b=e.i(547371),v=e.i(594651),y=e.i(945592),w=e.i(846140),j=e.i(459),S=e.i(116082);e.i(965155);var k=e.i(250672),N=e.i(22156);e.i(486212);var P=e.i(670374),T=e.i(727322),C=e.i(76990),M=e.i(403628),_=e.i(578866),A=e.i(555641),E=e.i(855600),L=e.i(389896),F=e.i(157265),R=e.i(824088),D=e.i(275927),I=e.i(519052),U=e.i(708853),O=e.i(967678),B=e.i(772604),z=e.i(240001),$=e.i(723181),V=e.i(765960),H=e.i(581285),W=e.i(583568),q=e.i(378650),K=e.i(168537),G=e.i(623075),Y=e.i(61162),X=e.i(75764),Q=e.i(557723),J=e.i(87942),Z=e.i(282080),ee=e.i(744427),et=e.i(308759),er=e.i(106128),ei=e.i(519063),es=e.i(807956),en=e.i(179730),ea=e.i(933657),el=e.i(619966),eo=e.i(106476),ed=e.i(796049),ec=e.i(650883),eu=e.i(25158),eh=e.i(937626),ep=e.i(406513),em=e.i(665709),ef=e.i(197944),ex=e.i(901715),eg=e.i(376326),eb=e.i(33623),ev=e.i(897406),ey=e.i(967090),ew=e.i(626074);let ej=e=>`imperial_subacct_banner_session_${e}`,eS=e=>`imperial_subacct_banner_hidden_${e}`,ek=e=>`imperial_subacct_banner_all_${e}`;function eN(e){try{let t=JSON.parse(localStorage.getItem(eS(e))??"[]");return Array.isArray(t)?t.filter(e=>Number.isInteger(e)):[]}catch{return[]}}let eP=null,eT=new Set;function eC(){for(let e of eT)e()}function eM(e,t){try{return"1"===sessionStorage.getItem(ej(e))||"1"===localStorage.getItem(ek(e))||eN(e).includes(t)}catch{return!1}}function e_(e){eP&&e.key&&(e.key===eS(eP.pk)||e.key===ek(eP.pk))&&(eP={...eP,hidden:eM(eP.pk,eP.index)},eC())}function eA(e,t,r){try{r()}catch{}eP={pk:e,index:t,hidden:!0},eC()}function eE(){let e=(0,o.useTranslations)("trading"),r=(0,o.useTranslations)("wallet"),{publicKey:i}=(0,d.useUnifiedWalletContext)(),{activeProfileIndex:s,createdProfiles:n}=(0,u.useProfile)(),l=i?.toBase58()??null,c=(0,a.useCallback)(e=>(0===eT.size&&window.addEventListener("storage",e_),eT.add(e),l&&null!=s&&(eP?.pk!==l||eP.index!==s)&&(eP={pk:l,index:s,hidden:eM(l,s)},eC()),()=>{eT.delete(e),0===eT.size&&window.removeEventListener("storage",e_)}),[l,s]),h=(0,a.useSyncExternalStore)(c,()=>!l||null==s||eP?.pk!==l||eP.index!==s||eP.hidden,()=>!0);if(!l||null==s||0===s||h)return null;let p=n.find(e=>e.index===s);if(!p)return null;let m=()=>eA(l,s,()=>sessionStorage.setItem(ej(l),"1"));return(0,t.jsxs)("div",{className:"hidden lg:flex h-[34px] shrink-0 items-center gap-2.5 border-b border-border-strong bg-surface-raised px-3 text-xs text-secondary-foreground",children:[(0,t.jsx)(ev.Users,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:e.rich("tradingOnSubaccount",{name:p.name??r("profileFallback",{index:String(p.index+1)}),strong:e=>(0,t.jsx)("span",{className:"font-semibold text-foreground",children:e})})}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-1",children:[(0,t.jsxs)(ew.DropdownMenu,{children:[(0,t.jsx)(ew.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":e("bannerHideOptions"),className:"flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-surface-interactive hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:(0,t.jsx)(eb.MoreHorizontal,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(ew.DropdownMenuContent,{align:"end",children:[(0,t.jsx)(ew.DropdownMenuItem,{onSelect:m,children:e("bannerHideSession")}),(0,t.jsx)(ew.DropdownMenuItem,{onSelect:()=>eA(l,s,()=>
2{let e=Array.from(new Set([...eN(l),s]));localStorage.setItem(eS(l),JSON.stringify(e))}),children:e("bannerHideSubaccount")}),(0,t.jsx)(ew.DropdownMenuItem,{onSelect:()=>eA(l,s,()=>localStorage.setItem(ek(l),"1")),children:e("bannerHideAll")})]})]}),(0,t.jsx)("button",{type:"button",onClick:m,"aria-label":e("bannerHideSession"),className:"flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-surface-interactive hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:(0,t.jsx)(ey.X,{className:"h-3.5 w-3.5"})})]})]})}var eL=e.i(275683),eF=e.i(797699),eR=e.i(685576),eD=e.i(341575),eI=e.i(379452),eU=e.i(928993),eO=e.i(615923);let eB=[{ua:/Phantom\/ios/i,insetPx:88}],ez=null;function e$(){var e,t,r;let i;return null===ez&&(e=navigator.userAgent,t=window.screen.height,r=window.innerHeight,ez=(i=eB.find(t=>t.ua.test(e)))&&t-r<=100?i.insetPx:0),ez}let eV=()=>()=>{};function eH(){return(0,a.useSyncExternalStore)(eV,e$,()=>0)}e.s(["useInAppToolbarInset",0,eH],849361);var eW=e.i(441399);let eq="imperial.rip.packoverlays";function eK(e,t,r){return(0,eL.unifiedPositionRowId)(e,t,r)}function eG(){try{let e=localStorage.getItem(eq);if(!e)return null;let t=JSON.parse(e);if(!t||"string"!=typeof t.wallet||!t.entries)return null;return t}catch{return null}}function eY(e){try{localStorage.setItem(eq,JSON.stringify(e))}catch{}}function eX(e){let t=Date.now(),r=Object.entries(e).filter(([,e])=>t-e.atMs<=2592e6);return r.sort((e,t)=>t[1].atMs-e[1].atMs),Object.fromEntries(r.slice(0,64))}function eQ(){let e=(0,o.useTranslations)("markets"),{marketMint:r,marketInfo:i}=(0,x.useMarketContext)();return i?(0,t.jsx)(h.RoutingProvider,{children:(0,t.jsx)(k.PythPriceProvider,{marketMint:r,children:(0,t.jsx)(e1,{marketMint:r,marketInfo:i})})}):(0,t.jsx)("div",{className:"h-full bg-canvas flex items-center justify-center",children:(0,t.jsx)("span",{className:"text-muted-foreground",children:e("marketNotFound")})})}let eJ=new Set(["INPUT","TEXTAREA"]),eZ=e=>e?`${e}px`:"env(safe-area-inset-bottom)",e0=(0,es.default)(()=>e.A(20110).then(e=>e.DesktopChartGrid),{loadableGenerated:{modules:[2911]},ssr:!1,loading:()=>(0,t.jsx)(ea.MultiChartLoading,{})});function e1({marketMint:e,marketInfo:d}){let es=(0,o.useTranslations)("markets"),eb=(0,o.useTranslations)("trading"),ev=(0,o.useTranslations)("settings"),ey=(0,s.useDesktopWorkspaceLabels)(),{setMarketMint:ew,desktopCharts:ej}=(0,x.useMarketContext)(),{preferenceRevision:eS}=(0,eo.useMultiChartPreference)(),ek=(0,W.useDesktopFooterLabels)(),eN=(0,o.useTranslations)("common"),eP=(0,m.useFormatters)(),eT=(0,l.useSearchParams)(),eC=(0,el.useIsDesktop)(),[eM,e_]=(0,a.useReducer)(eD.phoneShellReducer,void 0,()=>{let e=eT.get("tab");return"account"===e||"leaderboard"===e?(0,eD.initialPhoneShellState)({page:"more"}):"trade"===e?(0,eD.initialPhoneShellState)({terminal:"full"}):"positions"===e?(0,eD.initialPhoneShellState)({page:"positions"}):"book"===e?(0,eD.initialPhoneShellState)({bandView:"book"}):(0,eD.initialPhoneShellState)({})}),eA=(0,eD.mobileTabOf)(eM),eB=eM.overlays.includes(eD.MENU_OVERLAY),ez=(0,a.useCallback)(e=>{for(let t of(0,eD.actionsForMobileTab)(e))e_(t)},[]),[e$,eV]=(0,a.useState)({}),[eq,eQ]=(0,a.useState)("60"),e5=(0,a.useRef)(null),e3=(0,a.useRef)(0),[e4,e6]=(0,a.useState)(null),e8=e4?.workspaceRevision===eS?e4:null,e9=(0,a.useCallback)(t=>{e3.current+=1,(!ej.enabled||ej.isCurrentFocus(ej.focusRevision))&&e6({price:t,requestId:e3.current,marketMint:e,workspaceRevision:(0,eo.getMultiChartPreferenceRevision)(),focusRevision:ej.enabled?ej.focusRevision:void 0})},[e,ej]),e7=(0,a.useRef)(0),[te,tt]=(0,a.useState)(null),tr=(0,a.useRef)(0),[ti,ts]=(0,a.useState)(void 0),[tn,ta]=(0,a.useState)(!1),tl=(0,a.useRef)(null),to=(0,a.useRef)(null),td=(0,a.useRef)(null),[tc,tu]=(0,a.useState)(null),th=(0,a.useCallback)((e,t)=>{to.current=t,tu(e),e_({type:"openOverlay",id:eD.ACCOUNT_OVERLAY})},[]),tp=(0,a.useCallback)(()=>th(null,document.activeElement),[th]),tm=(0,a.useCallback)(()=>th("deposit",document.activeElement),[th]),tf=(0,a.useCallback)(()=>{e_({type:"closeOverlay",id:eD.MENU_OVERLAY}),th(null,td.current)},[th]),tx=(0,a.useCallback)(()=>{td.current=document.activeElement,e_({type:"openOverlay",id:eD.MENU_OVERLAY})},[]),tg=(0,a.useRef)(null),tb=(0,a.useRef)(eM.terminal);(0,a.useLayoutEffect)(()=>{tb.current=eM.terminal},[eM.terminal]);let tv=(0,a.useRef)(0),[ty,tw]=(0,a.useState)(!0),tj=(0,a.useRef)(!1),tS=(0,a.useCallback)(e=>{tj.current=e,e&&tw(!0)},[]),tk=(0,a.useCallback)(()=>{tw(!0),e_({type:"closeTerminal"});let e=tl.current;tl.current=null,requestAnimationFrame(()=>{if(document.activeElement!==document.body)return;let t=e?.isConnected?e:tg.current?.querySelector("button");t?.focus()})},[]),tN=(0,eU.useSheetDrag)({onDismiss:tk,extended:!1,onExpand:()=>tw(!0),onCollapse:()=>tw(!0)}),{resetForOpen:tP,contentRef:tT}=tN,[tC,tM]=(0,a.useState)(null),t_=(0,a.useCallback)(e=>{tT.current=e,tM(e)},[tT]),tA=(0,a.useCallback)((e,t)=>{let r=t?.kind==="order"?"orders":"positions",i=Date.now()-tv.current<600;"full"!==tb.current||i||(tk(),tr.current+=1,ts({tab:r,nonce:tr.current}),requestAnimationFrame(()=>document.querySelector('[data-slot="home-shelf"]')?.scrollIntoView({block:"start"}))),S.toast.success(eb("orders"===r?"orderRestingLive":"orderOpenedLive",{side:"long"===e?eb("sideLong"):eb("sideShort"),symbol:d.symbol}),{description:t?.streakMessage??void 0})},[tk,d.symbol,eb]),tE=(0,a.useCallback)(e=>{"full"!==tb.current&&(tv.current=Date.now()),tj.current&&tw(!0),tl.current=document.activeElement instanceof HTMLElement?document.activeElement:null,e&&(e7.current+=1,tt({side:e,nonce:e7.current}),(0,eF.gtagEvent)("mobile_trade_bar_tap",{side:e})),tP(),e_({type:"openTerminal"})},[tP]),tL=(0,a.useCallback)(e=>{e9(e),tE()},[e9,tE]),tF=(0,a.useCallback)(e=>ew(e,(0,eI.handOffPhoneShellEntry)("marketDrawer")?"replace":"push"),[ew]),tR=(0,g.useChartFocus)(),tD=(0,a.useRef)(0);(0,a.useEffect)(()=>{tR&&tR.id!==tD.current&&(tD.current=tR.id,tR.marketMint!==e&&ew(tR.marketMint),ez("chart"))},[tR,e,ew,ez]);let[tI,tU]=(0,a.useState)(()=>{try{let e=localStorage.getItem("imperial_hidden_order_lines");return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}),{publicKey:tO}=(0,c.useUnifiedWallet)(),{activeProfileIndex:tB,activeProfileUnderwriter:tz,activeProfileExcludedVenues:t$,activeProfilePda:tV}=(0,u.useProfile)(),{price:tH,lastUpdate:tW}=(0,k.usePythPriceContext)(100),tq=(0,ed.useStillFresh)(tW,3e4),{prices:tK}=(0,N.useAllMarketsPricesThrottled)(),tG=eH(),tY=(0,eD.terminalIsOpen)(eM),[tX,tQ]=(0,a.useState)(!1),tJ="market"===eM.page,tZ=`calc(${O.NAV_ROW_PX+1}px + ${eZ(tG)})`,t0=eZ(tG),[t1,t2]=(0,a.useState)(null);(0,a.useEffect)(()=>{tY&&t1&&0!==t1.scrollTop&&t1.scrollTo({top:0})},[tY,t1]);let t5=(0,a.useRef)(!1);(0,a.useEffect)(()=>
2{if(void 0===eC||t5.current)return;let e=new URLSearchParams(window.location.search);if("more"!==e.get("tab"))return;t5.current=!0,eC||e_({type:"openOverlay",id:eD.MENU_OVERLAY}),e.delete("tab");let t=e.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${t?`?${t}`:""}${window.location.hash}`)},[eC]),(0,a.useEffect)(()=>{tO||e_({type:"closeOverlay",id:eD.ACCOUNT_OVERLAY})},[tO]),(0,a.useEffect)(()=>{},[]);let t3=(0,a.useMemo)(()=>tY?[eD.TERMINAL_TOKEN,...eM.overlays]:eM.overlays,[tY,eM.overlays]),t4=t3.length>0;(0,a.useEffect)(()=>{(0,eI.forgetPhoneShellEntry)()},[]);let t6=(0,a.useRef)(()=>{});(0,a.useLayoutEffect)(()=>{t6.current=e=>{e===eD.TERMINAL_TOKEN?tk():e_({type:"closeOverlay",id:e})}},[tk]);let t8=(0,a.useRef)(t3);(0,a.useLayoutEffect)(()=>{t8.current=t3},[t3]),(0,a.useEffect)(()=>{if(t4)return(0,eI.syncPhoneShellHistory)({tokens:t8.current,onPopTop:e=>t6.current(e)})},[t4]),(0,a.useEffect)(()=>{t4&&(0,eI.updatePhoneShellHistory)(t3)},[t4,t3]),(0,a.useEffect)(()=>{let e=window.visualViewport;if(!e||!tC||!tY)return;let t=0,r=-1,i=window.innerHeight,s=0,n=0,a=()=>{let e=document.activeElement;return e instanceof HTMLElement&&tC.contains(e)&&eJ.has(e.tagName)},l=()=>{let t=document.activeElement;!(t instanceof HTMLElement&&tC.contains(t)&&t!==tC)||window.innerHeight-e.height*e.scale>=100||window.innerHeight<=i-100?tC.removeAttribute("data-keyboardless"):tC.setAttribute("data-keyboardless",""),n||a()||tC.removeAttribute("data-field-focus")},o=()=>{t||(t=requestAnimationFrame(()=>{t=0;let i=window.innerHeight-e.height-Math.max(0,e.offsetTop),n=i>=100?Math.round(i):0;n!==r&&(r=n,tC.style.setProperty("--kb-inset",`${n}px`)),s||l()}))},d=e=>{e.target instanceof HTMLElement&&eJ.has(e.target.tagName)&&(window.clearTimeout(n),n=0,tC.setAttribute("data-field-focus","")),i=Math.max(i,window.innerHeight),e.target instanceof HTMLElement&&"none"===e.target.inputMode?tC.setAttribute("data-keyboardless",""):tC.removeAttribute("data-keyboardless"),window.clearTimeout(s),s=window.setTimeout(()=>{s=0,l()},800)},c=()=>{window.clearTimeout(s),s=0,tC.removeAttribute("data-keyboardless"),window.clearTimeout(n),n=window.setTimeout(()=>{n=0,a()||tC.removeAttribute("data-field-focus")},150)},u=()=>{i=window.innerHeight},h=()=>{a()||u(),o()};return o(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("resize",h),window.addEventListener("orientationchange",u),tC.addEventListener("focusin",d),tC.addEventListener("focusout",c),()=>{cancelAnimationFrame(t),window.clearTimeout(s),window.clearTimeout(n),e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("resize",h),window.removeEventListener("orientationchange",u),tC.removeEventListener("focusin",d),tC.removeEventListener("focusout",c),tC.style.removeProperty("--kb-inset"),tC.removeAttribute("data-keyboardless"),tC.removeAttribute("data-field-focus")}},[tY,tC]);let{data:t9}=(0,C.usePhoenixMarkets)(),{data:t7}=(0,M.useGmTradeMarkets)(),{data:re}=(0,_.useSunriseMarkets)(),{tickers:rt}=(0,R.useGmTradeWs)(),rr=(0,h.useRoutingContext)(),ri=(0,p.useRoutedVenue)({asset:d.symbol,side:rr?.inputs.side??"long",desiredLeverage:rr?.inputs.desiredLeverage,notional:rr?.inputs.notional}),rs=ri?ri.venue:(0,A.resolveConcreteUnderwriter)(tz,e,t$),rn="phoenix"===rs,ra="gmtrade"===rs,rl="armada"===rs,ro=(0,a.useMemo)(()=>(t9??[]).some(e=>e.symbol===d.symbol),[t9,d.symbol]),rd=(0,L.usePhoenixWs)(ro?d.symbol:null,ro?tV?.toBase58():null,100),rc=ra?rt.get(d.symbol)?.price:void 0,{book:ru}=(0,ee.useSunriseOrderbook)(d.symbol,rs),rh=rn&&rd.marketStats?.markPx?rd.marketStats.markPx:ru?.stats.markPrice??rc??tH,rp=e$[d.symbol],rm=(0,X.defaultBookPrecision)(rh),rf=(0,a.useMemo)(()=>rp??{...X.DEFAULT_BOOK_SETTINGS,precision:rm},[rp,rm]),rx=(0,a.useCallback)(e=>{eV(t=>({...t,[d.symbol]:e}))},[d.symbol]),rg=(re??[]).some(e=>e.symbol===d.symbol),rb=(0,a.useMemo)(()=>({asks:rd.orderbook.asks.map(([e,t])=>({price:e,size:t})),bids:rd.orderbook.bids.map(([e,t])=>({price:e,size:t}))}),[rd.orderbook]),rv=(0,a.useMemo)(()=>({...rb,markPrice:rd.marketStats?.markPx}),[rb,rd.marketStats?.markPx]),ry=rn&&rd.marketStats?.oraclePx?rd.marketStats.oraclePx:ru?.stats.indexPrice??rc??tH,rw=(0,a.useRef)(void 0),rj=(0,a.useRef)(d.symbol);(0,a.useEffect)(()=>
2{if("u"<typeof document)return;let e=d.symbol;if(rj.current!==e){rj.current=e,rw.current=void 0,document.title=`${e} | Imperial`;return}let t=rw.current?.symbol===e?rw.current.price:void 0,r=rh??t;void 0!==rh&&(rw.current={symbol:e,price:rh}),document.title=void 0!==r?`$${eP.number(r)} ${e} | Imperial`:`${e} | Imperial`},[rh,d.symbol,eP]),(0,a.useEffect)(()=>()=>{"u">typeof document&&(document.title="Imperial")},[]),(0,a.useEffect)(()=>{e5.current?.scrollTo({top:0})},[eM.page,eM.bandView]);let rS=(0,a.useRef)(null),rk=(0,a.useRef)(null);(0,a.useEffect)(()=>{if(!1!==eC)return;let e=rk.current;if(!e)return;let t=document.documentElement,r=0,i=()=>{r||(r=requestAnimationFrame(()=>{r=0;let i=`${Math.round(e.getBoundingClientRect().height)}px`;t.style.getPropertyValue("--phone-header-h")!==i&&t.style.setProperty("--phone-header-h",i)}))};i();let s=new ResizeObserver(i);return s.observe(e),()=>{cancelAnimationFrame(r),s.disconnect(),t.style.removeProperty("--phone-header-h")}},[eC]),(0,a.useEffect)(()=>{if(!1!==eC)return;let e=document.documentElement;e.classList.add("phone-shell-lock");let t=0,r=()=>{t||(t=requestAnimationFrame(()=>{t=0;let r=rS.current?.getBoundingClientRect(),i=r?r.top+window.scrollY:0,s=Math.max(0,window.innerHeight-Math.max(0,i)),n=`${Math.round(s)}px`;e.style.getPropertyValue("--app-vh")!==n&&e.style.setProperty("--app-vh",n);let a=`${Math.round(Math.max(0,i))}px`;e.style.getPropertyValue("--shell-top")!==a&&e.style.setProperty("--shell-top",a)}))};r(),window.addEventListener("resize",r),window.addEventListener("orientationchange",r);let i=new ResizeObserver(r);for(let e=rS.current?.parentElement;e&&e!==document.body;e=e.parentElement)i.observe(e);return()=>{cancelAnimationFrame(t),window.removeEventListener("resize",r),window.removeEventListener("orientationchange",r),i.disconnect(),e.style.removeProperty("--app-vh"),e.style.removeProperty("--shell-top"),e.classList.remove("phone-shell-lock")}},[eC]);let rN=(0,F.usePhoenixExecutionBook)(d.symbol,ro,rd),rP=(0,a.useMemo)(()=>{if(!rn)return;let{asks:e,bids:t}=rd.orderbook;if(0===e.length||0===t.length)return;let r=1/0;for(let[t]of e)t<r&&(r=t);let i=0;for(let[e]of t)e>i&&(i=e);if(isFinite(r)&&!(i<=0))return(r+i)/2},[rn,rd.orderbook]),{positions:rT,orders:rC,refreshPositions:rM}=(0,f.useUnifiedPositions)(),r_=(0,a.useMemo)(()=>{let t={};for(let[e,r]of Object.entries(tK)){if(void 0===r)continue;t[e]=r;let i=(0,P.getMarketMintFromAsset)(e);i&&(t[i]=r)}for(let e of t9??[]){let r=tK[e.symbol];void 0!==r&&(t[e.orderbook]=r)}for(let e of t7??[]){let r=rt.get(e.symbol)?.price,i=r??tK[e.symbol];void 0!==i&&void 0===t[e.indexTokenMint]&&(t[e.indexTokenMint]=i),void 0!==r&&void 0===t[e.symbol]&&(t[e.symbol]=r)}for(let e of re??[])null!==e.markPrice&&void 0===t[e.symbol]&&(t[e.symbol]=e.markPrice);let r=tq?tH:void 0,i=rn&&rd.marketStats?.markPx?rd.marketStats.markPx:ru?.stats.markPrice??rc??r;if(void 0!==i&&(t[e]=i,t[d.symbol]=i),ra)for(let[e,r]of rt)t[e]=r.price;for(let e of rT){if("phoenix"!==e.underwriter)continue;let r=parseFloat(e.markPrice);r>0&&(t[(0,eW.venueLivePriceKey)("phoenix",e.asset)]=r)}for(let e of re??[])null!==e.markPrice&&(t[(0,eW.venueLivePriceKey)("sunrise",e.symbol)]=e.markPrice);for(let[e,r]of rt)t[(0,eW.venueLivePriceKey)("gmtrade",e)]=r.price;return rn&&rd.marketStats?.markPx&&(t[(0,eW.venueLivePriceKey)("phoenix",d.symbol)]=rd.marketStats.markPx),ru?.stats.markPrice!=null&&(t[(0,eW.venueLivePriceKey)("sunrise",d.symbol)]=ru.stats.markPrice),t},[tK,t9,t7,re,rn,rd.marketStats?.markPx,ra,rt,e,rc,tH,tq,ru?.stats.markPrice,d.symbol,rT]),{mode:rA,setMode:rE}=(0,w.useChartLabelMode)(),rL=(0,v.useOrderLines)({positions:rT,orders:rC,marketMint:e,livePrice:rh,activeProfileIndex:tB,enabled:!0,labelMode:rA}),rF=(0,er.useEstLiqPreview)(),rR=(0,et.previewAllowedBeside)(rL),rD=(0,a.useMemo)(()=>rF&&rF.market===e&&rR?{id:et.EST_LIQ_PREVIEW_LINE_ID,price:rF.price,color:"rgba(245,158,11,0.55)",label:(0,et.estLiqLineLabel)(rF.price,eP.intlTag),lineStyle:"dashed",draggable:!1}:null,[rF,e,eP.intlTag,rR]),rI=(0,a.useMemo)(()=>rD?[...rL,rD]:rL,[rL,rD]),rU=(0,a.useCallback)(e=>{(0,et.hideIsPersistable)(e)&&tU(t=>{let r=new Set(t);r.add(e);try{localStorage.setItem("imperial_hidden_order_lines",JSON.stringify([...r]))}catch{}return r})},[]),{updateTriggerOrder:rO,updatePassthroughOrder:rB}=(0,T.useTradeActions)(),[rz,r$]=(0,a.useState)(new Map),rV=tO?.toBase58()??null;(0,a.useEffect)(()=>{r$(function(e){if(!e)return new Map;let t=eG();return t&&t.wallet===e?new Map(Object.entries(eX(t.entries))):new Map}(rV))},[rV]);let rH=(0,a.useRef)(new Map);(0,a.useEffect)(()=>{for(let e of rT){if(!e.apiData)continue;let t=eK(e.positionPda,e.asset,e.side),r=e.apiData.packPrize,i=r?`${e.entryPrice}|${JSON.stringify(r)}`:"none";rH.current.get(t)!==i&&(rH.current.set(t,i),r?function(e,t,r,i){if(!e)return;let s=eG(),n=s&&s.wallet===e?{...s.entries}:{};n[t]={overlay:r,entryPrice:i,atMs:Date.now()},eY({wallet:e,entries:eX(n)})}(rV,t,r,e.entryPrice):function(e,t){if(!e)return;let r=eG();if(!r||r.wallet!==e||!(t in r.entries))return;let i={...r.entries};delete i[t],eY({wallet:e,entries:i})}
2(rV,t))}},[rT,rV]),(0,a.useEffect)(()=>{rH.current.clear()},[rV]);let rW=(0,a.useMemo)(()=>{let e=rT.filter(e=>"open"===e.status||"pending"===e.status).map(e=>{var t,r,i;let s,n,a;if(e.apiData){let t=new Set(e.apiData.tpslOrders.map(e=>e.orderPda)),r=new Map(e.tpslOrders.map(e=>[e.orderPda,e])),i=[...e.apiData.tpslOrders.map(e=>{let t=e.orderPda?r.get(e.orderPda):void 0;if(!t)return e;let i=t.dcaTimeClose?.lastLegTimestamp??t.dcaRatchetClose?.lastLegTimestamp??t.dcaTime?.lastLegTimestamp??t.dcaRatchet?.lastLegTimestamp,s=t.dcaTimeClose?.legsExecuted??t.dcaRatchetClose?.legsExecuted??t.dcaTime?.legsExecuted??t.dcaRatchet?.legsExecuted,n=t.dcaRatchetClose?.priceLimit??t.dcaTimeClose?.priceLimit??t.dcaRatchet?.priceLimit??t.dcaTime?.priceLimit,a=t.dcaTimeClose?.startAt??t.dcaRatchetClose?.startAt??t.dcaTime?.startAt??t.dcaRatchet?.startAt;return{...e,creationSignature:t.creationSignature||e.creationSignature,closeBps:t.closeBps??e.closeBps,...void 0!==i&&{dcaLastLegTimestamp:i},...void 0!==s&&{dcaLegsExecuted:s},...void 0!==n&&n>0&&{dcaPriceLimitUsd:n.toString()},...void 0!==a&&{dcaStartAt:a}}}),...e.tpslOrders.filter(e=>!t.has(e.orderPda)).map(e=>({source:e.source,orderType:e.orderType,triggerPriceUsd:e.triggerPriceUsd,sizeUsd:e.sizeUsd,orderPda:e.orderPda,creationSignature:e.creationSignature,closeBps:e.closeBps,triggerCondition:e.triggerCondition,worstPriceUsd:e.ratchet?.worstPrice?.toString(),ratchetSizeUsd:(e.ratchet?.ratchetSize??e.dcaRatchetClose?.ratchetSize??e.dcaRatchet?.ratchetSize)?.toString(),stopTriggerPriceUsd:e.ratchet?.stopTriggerPrice?e.ratchet.stopTriggerPrice.toString():void 0,currentBestPriceUsd:e.ratchet&&e.ratchet.bestPriceSeen>0?e.ratchet.bestPriceSeen.toString():e.dcaRatchetClose&&e.dcaRatchetClose.bestPriceSeen>0?e.dcaRatchetClose.bestPriceSeen.toString():e.dcaRatchet&&e.dcaRatchet.bestPriceSeen>0?e.dcaRatchet.bestPriceSeen.toString():void 0,profileIndex:e.profileIndex,indicatorThreshold:e.indicator?.thresholdValue?.toString(),indicatorTimeframe:e.indicator?j.TIMEFRAME_LABELS[e.indicator.timeframeCode]:void 0,indicatorCondition:e.indicator?0===e.indicator.indicatorCondition?"below":"above":void 0,currentIndicatorValue:e.indicator?.currentValue,indicatorRatchetSize:"indicator_ratchet"===e.orderType&&e.ratchet?e.ratchet.ratchetSize.toString():void 0,dcaNumLegs:e.dcaClose?.numLegs??e.dcaTimeClose?.numLegs??e.dcaRatchetClose?.numLegs??e.dcaTime?.numLegs??e.dcaRatchet?.numLegs,dcaLegsExecuted:e.dcaClose?.legsExecuted??e.dcaTimeClose?.legsExecuted??e.dcaRatchetClose?.legsExecuted??e.dcaTime?.legsExecuted??e.dcaRatchet?.legsExecuted,dcaWeightingType:e.dcaClose?.weightingType??e.dcaTimeClose?.weightingType??e.dcaRatchetClose?.weightingType??e.dcaTime?.weightingType??e.dcaRatchet?.weightingType,dcaStartPriceUsd:e.dcaClose?e.dcaClose.startPrice.toString():void 0,dcaEndPriceUsd:e.dcaClose?e.dcaClose.endPrice.toString():void 0,dcaPriceLimitUsd:(e.dcaRatchetClose?.priceLimit??e.dcaTimeClose?.priceLimit??e.dcaRatchet?.priceLimit??e.dcaTime?.priceLimit)?.toString(),dcaIntervalSeconds:e.dcaTimeClose?.intervalSeconds??e.dcaRatchetClose?.intervalSeconds??e.dcaTime?.intervalSeconds??e.dcaRatchet?.intervalSeconds,dcaLastLegTimestamp:e.dcaTimeClose?.lastLegTimestamp??e.dcaRatchetClose?.lastLegTimestamp??e.dcaTime?.lastLegTimestamp??e.dcaRatchet?.lastLegTimestamp,dcaStartAt:e.dcaTimeClose?.startAt??e.dcaRatchetClose?.startAt??e.dcaTime?.startAt??e.dcaRatchet?.startAt}))];return{id:(0,eL.unifiedPositionRowId)(e.positionPda,e.asset,e.side),lifecycleId:e.apiData.id,positionPda:e.positionPda,wallet:e.apiData.wallet||"",source:e.apiData.source,ownership:e.ownership??e.apiData.ownership??"imperial",directVenue:e.directVenue??e.apiData.directVenue,isPhoenixCrossSeat:e.isPhoenixCrossSeat,sunriseMarginSeat:void 0!==e.sunriseMarginSeat?e.sunriseMarginSeat:e.apiData.sunriseMarginSeat,isSunriseCrossMargin:e.isSunriseCrossMargin,profileIndex:e.profileIndex,side:e.side,asset:e.asset,leverageX:e.leverageX,sizeUsd:e.sizeUsd,sizeTokenAmount:e.apiData.sizeTokenAmount,collateralUsd:e.collateralUsd,maxSizeUsd:e.sizeUsd,maxCollateralUsd:e.collateralUsd,maxLeverageX:e.leverageX,entryPrice:e.entryPrice,markPrice:e.markPrice,liquidationPrice:e.liquidationPrice,partialLiquidationPriceUsd:e.apiData.partialLiquidationPriceUsd,breakevenPriceUsd:e.apiData.breakevenPriceUsd,ownedCollateralUsd:e.apiData.ownedCollateralUsd,borrowedCollateralUsd:e.apiData.borrowedCollateralUsd,accruedInterestUsd:e.apiData.accruedInterestUsd,loanOriginationNotionalUsd:e.apiData.loanOriginationNotionalUsd,ourLiquidationPriceUsd:e.apiData.ourLiquidationPriceUsd,baseLeverageX:e.apiData.baseLeverageX,effectiveLeverageX:e.apiData.effectiveLeverageX,loanRateBps:e.apiData.loanRateBps,seatCollateralUsd:e.apiData.seat
2CollateralUsd,pnlUsd:e.unrealizedPnl,pnlPercent:e.unrealizedPnlPercent,netCashPnlUsd:null,packPrize:e.apiData.packPrize,totalFeesUsd:e.estimatedFees||e.apiData.totalFeesUsd||"0",feesOwed:e.apiData.feesOwed,borrowFeeOwed:e.apiData.borrowFeeOwed,closeFeeOwed:e.apiData.closeFeeOwed,swapFeeOwed:e.apiData.swapFeeOwed,accruedFundingUsd:e.apiData.accruedFundingUsd,accruedFundingFrom:e.apiData.accruedFundingFrom,fundingRateHourlyPercent:e.apiData.fundingRateHourlyPercent,fees:e.apiData.fees,status:(e.status,"open"),openedAt:e.openTime||e.apiData.openedAt,closedAt:e.apiData.closedAt,lastActionAt:e.apiData.lastActionAt,underwriter:e.apiData.underwriter,tpslOrders:i,actions:e.apiData.actions||[]}}let l=e.tpslOrders.map(e=>({source:e.source,orderType:e.orderType,triggerPriceUsd:e.triggerPriceUsd,sizeUsd:e.sizeUsd,orderPda:e.orderPda,creationSignature:e.creationSignature,closeBps:e.closeBps,triggerCondition:e.triggerCondition,worstPriceUsd:e.ratchet?.worstPrice?.toString(),ratchetSizeUsd:(e.ratchet?.ratchetSize??e.dcaRatchetClose?.ratchetSize??e.dcaRatchet?.ratchetSize)?.toString(),stopTriggerPriceUsd:e.ratchet?.stopTriggerPrice?e.ratchet.stopTriggerPrice.toString():void 0,currentBestPriceUsd:e.ratchet&&e.ratchet.bestPriceSeen>0?e.ratchet.bestPriceSeen.toString():e.dcaRatchetClose&&e.dcaRatchetClose.bestPriceSeen>0?e.dcaRatchetClose.bestPriceSeen.toString():e.dcaRatchet&&e.dcaRatchet.bestPriceSeen>0?e.dcaRatchet.bestPriceSeen.toString():void 0,profileIndex:e.profileIndex,indicatorThreshold:e.indicator?.thresholdValue?.toString(),indicatorTimeframe:e.indicator?j.TIMEFRAME_LABELS[e.indicator.timeframeCode]:void 0,indicatorCondition:e.indicator?0===e.indicator.indicatorCondition?"below":"above":void 0,currentIndicatorValue:e.indicator?.currentValue,indicatorRatchetSize:"indicator_ratchet"===e.orderType&&e.ratchet?e.ratchet.ratchetSize.toString():void 0,dcaNumLegs:e.dcaClose?.numLegs??e.dcaTimeClose?.numLegs??e.dcaRatchetClose?.numLegs??e.dcaTime?.numLegs??e.dcaRatchet?.numLegs,dcaLegsExecuted:e.dcaClose?.legsExecuted??e.dcaTimeClose?.legsExecuted??e.dcaRatchetClose?.legsExecuted??e.dcaTime?.legsExecuted??e.dcaRatchet?.legsExecuted,dcaWeightingType:e.dcaClose?.weightingType??e.dcaTimeClose?.weightingType??e.dcaRatchetClose?.weightingType??e.dcaTime?.weightingType??e.dcaRatchet?.weightingType,dcaStartPriceUsd:e.dcaClose?e.dcaClose.startPrice.toString():void 0,dcaEndPriceUsd:e.dcaClose?e.dcaClose.endPrice.toString():void 0,dcaPriceLimitUsd:(e.dcaRatchetClose?.priceLimit??e.dcaTimeClose?.priceLimit??e.dcaRatchet?.priceLimit??e.dcaTime?.priceLimit)?.toString(),dcaIntervalSeconds:e.dcaTimeClose?.intervalSeconds??e.dcaRatchetClose?.intervalSeconds??e.dcaTime?.intervalSeconds??e.dcaRatchet?.intervalSeconds,dcaLastLegTimestamp:e.dcaTimeClose?.lastLegTimestamp??e.dcaRatchetClose?.lastLegTimestamp??e.dcaTime?.lastLegTimestamp??e.dcaRatchet?.lastLegTimestamp,dcaStartAt:e.dcaTimeClose?.startAt??e.dcaRatchetClose?.startAt??e.dcaTime?.startAt??e.dcaRatchet?.startAt}));return{id:(0,eL.unifiedPositionRowId)(e.positionPda,e.asset,e.side),positionPda:e.positionPda,wallet:e.wallet??"",source:"imperial",ownership:e.ownership??"imperial",directVenue:e.directVenue,isPhoenixCrossSeat:e.isPhoenixCrossSeat,sunriseMarginSeat:e.sunriseMarginSeat,isSunriseCrossMargin:e.isSunriseCrossMargin,profileIndex:e.profileIndex,side:e.side,asset:e.asset,leverageX:e.leverageX,sizeUsd:e.sizeUsd,sizeTokenAmount:null,collateralUsd:e.collateralUsd,maxSizeUsd:e.sizeUsd,maxCollateralUsd:e.collateralUsd,maxLeverageX:e.leverageX,entryPrice:e.entryPrice,markPrice:e.markPrice,liquidationPrice:e.liquidationPrice,partialLiquidationPriceUsd:null,breakevenPriceUsd:null,packPrize:(t=eK(e.positionPda,e.asset,e.side),r=e.entryPrice,(s=rz.get(t))&&(i=s.entryPrice,n=Number(i),a=Number(r),Number.isFinite(n)&&Number.isFinite(a)&&n===a)?s.overlay:null),pnlUsd:e.unrealizedPnl,pnlPercent:e.unrealizedPnlPercent,netCashPnlUsd:null,totalFeesUsd:e.estimatedFees||"0",feesOwed:null,borrowFeeOwed:null,closeFeeOwed:null,swapFeeOwed:null,fees:{platformFee:"0",swapFee:"0",slippage:"0",jupiterFee:"0",interest:"0",proOrderFee:"0"},status:(e.status,"open"),openedAt:e.openTime,closedAt:null,underwriter:e.underwriter,tpslOrders:l,actions:[],lastActionAt:e.openTime}});return(0,eL.dedupePositionRows)(e)},[rT,rz]),{lifecycles:rq,lifetimeStats:rK,historyRead:rG,totalCount:rY,hasMore:rX,isFetchingNextPage:rQ,fetchNextPage:rJ,isLoading:rZ,invalidate:r0}=(0,b.useJupiterHistory)({walletAddress:tO?.toBase58(),refreshIntervalMs:3e4}),r1=(0,a.useMemo)(()=>({positions:rT,orders:rC,lifecycles:rq,activeProfileIndex:tB}),[rT,rC,rq,tB]),r2=(0,y.useTradeMarkers)({lifecycles:rq,marketMint:e,enabled:!0}),r5=(0,a.useCallback)(()=>{rM(),r0()},[rM,r0]),r3=JSON.stringify([rV,tB,tV?.toBase58(),tz,rs,e,ej.enabled?ej.focusRevision:null]),r4=(0,a.useRef)({key:r3,revision:0,walletAddress:rV,orderLines:rL,livePrice
2s:r_,oraclePrice:tq?tH:void 0});(0,a.useLayoutEffect)(()=>{let e=r4.current;r4.current={key:r3,revision:e.revision+ +(e.key!==r3),walletAddress:rV,orderLines:rL,livePrices:r_,oraclePrice:tq?tH:void 0}},[r3,rV,rL,r_,tq,tH]);let r6=(0,a.useCallback)((e,t,r,i)=>{let s=r4.current,n=ej.focusRevision,a=(0,eo.getMultiChartPreferenceRevision)(),l=s.orderLines.find(t=>t.id===e),o={...r},c=()=>{let c=r4.current,u=c.orderLines.find(t=>t.id===e),h=u?.dragMeta;if((0,eo.getMultiChartPreferenceRevision)()!==a||ej.enabled&&!ej.isCurrentFocus(n)||i.aborted||!s.walletAddress||!Number.isInteger(r.profileIndex)||c.revision!==s.revision||!l||!u||u.price!==l.price||!h||Object.keys(o).some(e=>h[e]!==o[e]))return S.toast.error(es("orderUpdateFailed")),!1;if(!Number.isFinite(t)||t<=0)return S.toast.error(es("invalidPrice")),!1;let p="armada"===r.underwriter?"sunrise":r.underwriter,m=(0,eW.venueLivePrice)(c.livePrices,p,d.symbol,c.oraclePrice);if(void 0===m||!Number.isFinite(m)||m<=0)return S.toast.error(es("invalidPrice")),!1;if("tp"===r.orderType){if("long"===r.side&&t<=m)return S.toast.error(es("takeProfitAboveMarkForLongs")),!1;if("short"===r.side&&t>=m)return S.toast.error(es("takeProfitBelowMarkForShorts")),!1}else if("sl"===r.orderType){if("long"===r.side&&t>=m)return S.toast.error(es("stopLossBelowMarkForLongs")),!1;if("short"===r.side&&t<=m)return S.toast.error(es("stopLossAboveMarkForShorts")),!1}return!0};if(!c())return Promise.resolve(!1);let u=`move-order-${r.orderPda}`;return new Promise(e=>{let s=r.orderType.toUpperCase(),n=!1,a=!1,l=()=>{n||(o(!1),S.toast.dismiss(u))},o=t=>{a||(a=!0,i.removeEventListener("abort",l),e(t))};i.addEventListener("abort",l),(0,S.toast)(es("moveOrderConfirm",{label:s,price:eP.priceDigits(t)}),{id:u,duration:1e4,action:{label:es("confirm"),onClick:async()=>{if(!a&&!n){if(!c())return void o(!1);n=!0;try{if("imperial_passthrough"===r.source&&void 0!==r.profileIndex?await rB({orderPda:r.orderPda,profileIndex:r.profileIndex,triggerPrice:t,sizeUsd:r.sizeUsd,underwriter:r.underwriter}):await rO({positionPubkey:r.positionPda,positionRequestPubkey:r.orderPda,profileIndex:r.profileIndex,underwriter:r.underwriter??"jupiter",marketMint:r.marketMint,sizeUsd:r.sizeUsd,triggerPrice:t}))S.toast.success(es("orderUpdated",{label:s,price:eP.priceDigits(t)})),r5(),o(!0);else S.toast.error(es("orderUpdateFailed")),o(!1)}catch(t){console.error("[order-line] order update failed",t);let e=(0,E.chainActionReason)(t,"imperial_passthrough"===r.source?"passthrough":"jupiter");S.toast.error(es("orderUpdateFailed"),e?{description:e}:void 0),o(!1)}}}},cancel:{label:es("cancel"),onClick:l},onDismiss:l,onAutoClose:()=>{n||o(!1)}})})},[d.symbol,rO,rB,r5,eP,es,ej]),r8=(0,ep.useAllMarkets)(),r9=(0,a.useMemo)(()=>r8.find(t=>t.mint===e)?.underwriters,[r8,e]),r7=rW?.filter(e=>e.asset===d.symbol&&(null==e.profileIndex||e.profileIndex===tB))??[],[ie,it]=(0,a.useState)(null),[ir,ii]=(0,a.useState)(null),is=eM.bandView,ia=(0,a.useCallback)(()=>e_({type:"setBandView",view:"book"===is?"chart":"book"}),[is]),il=(0,a.useCallback)(t=>{t===e?document.querySelector('button[data-side="long"]')?.focus():ii(t)},[e]),io=(0,a.useRef)(r7);(0,a.useLayoutEffect)(()=>{io.current=r7},[r7]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;if(!t?.side)return;let r=io.current.find(e=>e.side===t.side);if(!r)return;let i="number"==typeof t.amountUsd&&t.amountUsd>0?t.amountUsd:0;it({lifecycle:r,amount:i>0?i.toFixed(2):""})};return window.addEventListener("imperial:add-collateral",e),()=>window.removeEventListener("imperial:add-collateral",e)},[]);let id=(0,el.useMediaQuery)("(min-width: 1280px)",!1);return(0,t.jsx)(eu.QuickTradeProvider,{openQuickTrade:il,children:(0,t.jsx)(eh.PairTicketProvider,{children:(0,t.jsxs)("div",{className:`${r.default.viewport} trading-shell-surface flex flex-col w-full max-w-full overflow-hidden lg:overflow-x-hidden lg:h-[calc(100dvh-var(--site-header-h))] lg:overflow-y-hidden`,children:["1"===eT.get("vpdebug")&&(0,t.jsx)(e2,{sheet:tC}),(0,t.jsx)(eg.UsdtDepositBanner,{}),eC&&(0,t.jsx)(eE,{}),!0!==eC&&(0,t.jsxs)("div",{ref:rS,className:"phone-shell-surface lg:hidden relative flex flex-col w-full h-[var(--app-vh,100svh)] overflow-hidden",style:{paddingBottom:tZ},children:[(0,t.jsx)("div",{ref:rk,"data-mobile-trading-header":"",className:"flex-shrink-0",children:(0,t.jsx)(V.JupiterPerps
2Header,{layout:"phone",onMarketDrawerChange:e=>e_(e?{type:"openOverlay",id:"marketDrawer"}:{type:"closeOverlay",id:"marketDrawer"}),marketDrawerOpen:eM.overlays.includes("marketDrawer"),onMarketPick:tF,marketMint:e,marketInfo:d,allMarkets:r8,phoenixStats:rd.marketStats,resolvedUnderwriter:rs,gmTradePrice:rc,onOpenProfile:tp,onDeposit:tm})}),(0,t.jsxs)("div",{ref:e5,"data-slot":"mobile-market-scroll",className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",inert:tY,children:[!1===eC&&(0,t.jsxs)(I.MobileChartBand,{active:tJ,inert:!tJ||tY,resizable:!0,resizeEnabled:!tY&&"chart"===eM.bandView,resizeLabel:`${ey.resize}: ${ey.panels.chart}`,resizeActions:{shrink:ey.shrink,reset:eb("mobileChartResetHeight"),expand:ey.expand},children:[(0,t.jsx)(ex.FuturesContractBanner,{symbol:d.symbol}),(0,t.jsx)("div",{className:"book"===eM.bandView?"invisible absolute inset-0 flex flex-col":"flex flex-1 min-h-0 flex-col",children:(0,t.jsx)(D.MobileChartView,{symbol:d.symbol,mintAddress:e,underwriters:r9,resolution:eq,onResolutionChange:eQ,positionLines:rI,tradeMarkers:r2,hiddenLineIds:tI,onHideLine:rU,labelMode:rA,onLabelModeChange:rE,onLineDragged:r6})}),"book"===eM.bandView&&(0,t.jsx)("div",{className:"absolute inset-0 flex flex-col overscroll-contain bg-surface",children:(0,t.jsx)(ec.ErrorBoundary,{children:rn?(0,t.jsx)(Q.PhoenixOrderbook,{active:tJ,settings:rf,armadaComparisonAvailable:rg,onSettingsChange:rx,orderbook:rd.displayOrderbook,orderbookStatus:rd.orderbookStatus,orderbookReceivedAt:rd.orderbookReceivedAt,orderbookGeneration:rd.orderbookGeneration,trades:rd.trades,symbol:d.symbol,onPriceSelect:tL}):rl?(0,t.jsx)(Z.SunriseOrderbookPanel,{active:tJ,symbol:d.symbol,venue:rs,settings:rf,onSettingsChange:rx,comparisonBook:rv}):(0,t.jsx)(J.PoolOrderbook,{symbol:d.symbol,mintAddress:e,currentPrice:rh,venue:rs})})})]}),!1===eC&&tJ&&(0,t.jsx)("div",{"data-slot":"home-shelf",className:"min-w-0 pb-3",children:(0,t.jsx)(ec.ErrorBoundary,{children:(0,t.jsx)(K.JupiterPerpsBottomPanel,{mobileScroll:!0,marketMint:e,marketInfo:d,positions:rW,lifecycles:rq,lifetimeStats:rK,historyRead:rG,totalCount:rY,hasMore:rX,isFetchingNextPage:rQ,onLoadMore:rJ,isLoading:rZ,liveMarkPrice:rh,livePrices:r_,orderbookMidPrice:rP,orderbookSymbol:rn?d.symbol:void 0,onPositionChange:r5,landOnTab:ti})})}),"more"===eA&&(0,t.jsx)("div",{children:(0,t.jsx)(B.MobileMoreTab,{})}),"positions"===eA&&(0,t.jsx)("div",{className:"min-w-0 pb-3",children:(0,t.jsx)(ec.ErrorBoundary,{children:(0,t.jsx)(K.JupiterPerpsBottomPanel,{mobileScroll:!0,marketMint:e,marketInfo:d,positions:rW,lifecycles:rq,lifetimeStats:rK,historyRead:rG,totalCount:rY,hasMore:rX,isFetchingNextPage:rQ,onLoadMore:rJ,isLoading:rZ,liveMarkPrice:rh,livePrices:r_,orderbookMidPrice:rP,orderbookSymbol:rn?d.symbol:void 0,onPositionChange:r5})})})]}),!1===eC&&tJ&&(0,t.jsx)("div",{ref:tg,className:"contents",inert:tY,children:(0,t.jsx)(eO.MobileTradeBar,{activeSide:te?.side??"long",onSide:tE,bookActive:"book"===eM.bandView,onToggleBook:ia})}),!1===eC&&(0,t.jsx)(eR.Sheet,{open:tY,modal:!1,onOpenChange:e=>{e||tk()},children:(0,t.jsxs)(eR.SheetContent,{ref:t_,side:"bottom",forceMount:!0,hideClose:!0,hideHandle:!0,"aria-describedby":void 0,onInteractOutside:e=>e.preventDefault(),onPointerDownOutside:e=>e.preventDefault(),onFocusOutside:e=>e.preventDefault(),onPointerDownCapture:e=>{let t=e.target;if(!(t instanceof Element)||!e.currentTarget.contains(t)||t.closest('input, textarea, select, button, a[href], label, summary, [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="slider"], [role="switch"], [role="checkbox"], [role="radio"], [role="tab"], [role="combobox"], [role="option"], [role="menuitem"], [data-numeric-keypad]'))return;let r=document.activeElement;r instanceof HTMLElement&&e.currentTarget.contains(r)&&(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r.isContentEditable)&&r.blur()},onEscapeKeyDown:e=>{(!tY||tn)&&e.preventDefault()},tabIndex:-1,onOpenAutoFocus:e=>{e.preventDefault();let t=tN.contentRef.current;
2t&&!t.contains(document.activeElement)&&t.focus()},inert:!tY,"aria-hidden":!tY||void 0,className:"z-50 px-0 pt-0 pb-0 gap-0 overflow-visible rounded-t-[9px] border-x border-t border-border bg-[image:var(--gradient-phone-drawer)] shadow-none data-[state=closed]:fill-mode-forwards focus:outline-none focus-visible:outline-none motion-reduce:animate-none! motion-reduce:transition-none","data-phone-terminal":"","data-detent":ty?"extended":"rest",style:{"--terminal-inset":t0},children:[(0,t.jsx)(eR.SheetTitle,{className:"sr-only",children:eb("terminalTitle")}),(0,t.jsxs)("div",{className:"absolute -top-[36px] left-0 right-0 z-10 h-[44px]",children:[(0,t.jsx)("div",{...tN.grabProps,className:"absolute inset-0 cursor-grab touch-none active:cursor-grabbing"}),(0,t.jsx)(eR.SheetHandle,{className:"pointer-events-none absolute left-1/2 top-[16px] h-1 w-[55px] -translate-x-1/2 bg-[var(--phone-pill)]"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(ef.MarketClosedBanner,{marketMint:e,symbol:d.symbol}),(0,t.jsx)(ex.FuturesContractBanner,{symbol:d.symbol})]}),(0,t.jsx)("div",{ref:t2,className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:(0,t.jsx)(ei.ParkedActivity,{active:tY,busy:tX,children:(0,t.jsx)(ec.ErrorBoundary,{children:(0,t.jsx)(H.JupiterPerpsTradingPanel,{marketMint:e,marketInfo:d,marketPrice:rh,oraclePrice:ry,...rN,onPositionChange:r5,publishChartPreview:!0,existingPositions:r7,chartResolution:eq,compact:!0,active:tY,onBusyChange:tQ,limitPricePrefill:e8,sideIntent:te,onOrderPlaced:tA,onInnerSurfaceChange:ta,onTallTicketChange:tS})})})})]})}),(0,t.jsx)("div",{className:"contents",inert:tY,children:(0,t.jsx)(U.MobileBottomNav,{activeTab:eA,moreOpen:eB,onTabChange:e=>{"more"===e?tx():"trade"!==e?ez(e):e_({type:"setPage",page:"market"})},toolbarInset:tG})}),tY&&(0,t.jsx)("button",{type:"button","aria-label":eN("close"),onClick:tk,style:{top:`var(--phone-header-h, ${O.PHONE_HEADER_PX}px)`},className:"absolute inset-x-0 bottom-0 z-50 bg-black/50 lg:hidden animate-in fade-in-0 duration-200 transition-[top] duration-[240ms] ease-out motion-reduce:animate-none! motion-reduce:transition-none"})]}),eC&&(0,t.jsxs)("div",{"data-desktop-terminal":"",className:`${r.default.shell} hidden lg:flex flex-col flex-1 min-h-0 min-w-0`,children:[(0,t.jsx)(ef.MarketClosedBanner,{marketMint:e,symbol:d.symbol}),(0,t.jsx)(ex.FuturesContractBanner,{symbol:d.symbol}),(0,t.jsx)(i.DesktopWorkspace,{availableBook:id,labels:ey,slots:{chart:ej.enabled?(0,t.jsx)(ec.ErrorBoundary,{fallback:(0,t.jsx)(ea.MultiChartLoadError,{}),children:(0,t.jsx)(e0,{allMarkets:r8,overlayData:r1,livePrices:r_,oraclePrices:tK,renderHeader:r=>(0,t.jsx)(V.JupiterPerpsHeader,{layout:"desktop",desktopChartTools:r,marketMint:e,marketInfo:d,allMarkets:r8,phoenixStats:rd.marketStats,resolvedUnderwriter:rs,gmTradePrice:rc}),activeChartProps:{onResolutionChange:eQ,positionLines:rI,tradeMarkers:r2,hiddenLineIds:tI,onHideLine:rU,labelMode:rA,onLabelModeChange:rE,onLineDragged:r6}})}):(0,t.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,t.jsx)("div",{className:"shrink-0",children:(0,t.jsx)(V.JupiterPerpsHeader,{layout:"desktop",marketMint:e,marketInfo:d,allMarkets:r8,phoenixStats:rd.marketStats,resolvedUnderwriter:rs,gmTradePrice:rc})}),ej.loading&&(0,t.jsx)("div",{role:"status",className:"shrink-0 border-b border-border px-3 py-1 text-xs text-muted-foreground",children:ev("multiChartLoading")}),ej.error&&(0,t.jsxs)("div",{role:"status",className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-1 text-xs text-muted-foreground",children:[(0,t.jsx)("span",{children:ev("multiChartLoadFailed")}),(0,t.jsx)("button",{type:"button",onClick:ej.retry,className:"focus-ring rounded text-foreground underline",children:eN("retry")})]}),(0,t.jsx)("div",{className:"relative flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)(ec.ErrorBoundary,{children:(0,t.jsx)(en.default,{desktopLayout:!0,symbol:d.symbol,mintAddress:e,underwriters:r9,onResolutionChange:eQ,positionLines:rI,tradeMarkers:r2,hiddenLineIds:tI,onHideLine:rU,labelMode:rA,onLabelModeChange:rE,onLineDragged:r6})})})]}),book:(0,t.jsx)(ec.ErrorBoundary,{children:rn?(0,t.jsx)(Q.PhoenixOrderbook,{settings:rf,armadaComparisonAvailable:rg,onSettingsChange:rx,orderbook:rd.displayOrderbook,orderbookStatus:rd.orderbookStatus,orderbookReceivedAt:rd.orderbookReceivedAt,orderbookGeneration:rd.orderbookGeneration,trades:rd.trades,symbol:d.symbol,onPriceSelect:e9}):rl?(0,t.jsx)(Z.SunriseOrderbookPanel,{symbol:d.symbol,venue:rs,settings:rf,onSettingsChange:rx,comparisonBook:rv}):(0,t.jsx)(J.PoolOrderbook,{symbol:d.symbol,mintAddress:e,currentPrice:rh,venue:rs})}),ticket:(0,t.jsx)(ec.ErrorBoundary,{fallback:ej.enabled?(0,t.jsx)(ea.MultiChartLoadError,{}):void 0,children:(0,t.jsx)(n.DesktopWorkspaceTicket,{marketMint:e,marketInfo:d,marketPrice:rh,oraclePrice:ry,...rN,onPositionChange:r5,publishChartPreview:!0,existingPositions:r7,chartResolution:ej.enabled?ej.state.slots.find(e=>e.id===ej.state.activeId)?.resolution??eq:eq,limitPricePrefill:e8})},ej.enabled?"multi-chart-ticket":"single-chart-ticket"),activity:(0,t.jsx)(ec.ErrorBoundary,{children:(0,t.jsx)(n.DesktopWorkspaceActivity,{marketMint:e,marketInfo:d,positions:rW,lifecycles:rq,lifetimeStats:rK,historyRead:rG,totalCount:rY,hasMore:rX,isFetchingNextPage:rQ,onLoadMore:rJ,isLoading:rZ,onPositionChange:r5,liveMarkPrice:rh,livePrice
2s:r_,orderbookMidPrice:rP,orderbookSymbol:rn?d.symbol:void 0})})}})]}),eC&&(0,t.jsx)(q.TerminalStatusBar,{desktopDashboard:!0,allMarkets:r8,marketMint:e,labels:ek,onSelectMarket:ew}),ie&&(0,t.jsx)(G.Dialog,{open:!0,onOpenChange:e=>{e||it(null)},children:(0,t.jsxs)(G.DialogContent,{className:"gap-0 sm:max-w-md",children:[(0,t.jsx)(G.DialogHeader,{children:(0,t.jsx)(G.DialogTitle,{children:es("addCollateral")})}),(0,t.jsx)(Y.InlineEditCollateralForm,{lifecycle:ie.lifecycle,initialAmount:ie.amount,onClose:()=>it(null),onPositionChange:r5})]})}),ir&&(0,t.jsx)(em.QuickTradeModal,{mint:ir,allMarkets:r8,positions:rW,onClose:()=>ii(null),onPositionChange:r5}),!1===eC&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(z.AccountDrawer,{open:eM.overlays.includes(eD.ACCOUNT_OVERLAY),openWith:tc,onClose:()=>e_({type:"closeOverlay",id:eD.ACCOUNT_OVERLAY}),returnFocusRef:to}),(0,t.jsx)($.MoreMenuSheet,{open:eB,onClose:()=>e_({type:"closeOverlay",id:eD.MENU_OVERLAY}),onOpenAccount:tf,returnFocusRef:td})]})]})})})}function e2({sheet:e}){let[r,i]=(0,a.useState)({}),s=(0,a.useRef)(null),n=(0,a.useRef)(null),l=(0,a.useRef)(null),o=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>{let t=()=>{let t=window.visualViewport;i({innerH:window.innerHeight,outerH:window.outerHeight,"vv.height":t?Math.round(t.height):"n/a","vv.offsetTop":t?Math.round(t.offsetTop):"n/a","screen.h":window.screen.height,"screen.availH":window.screen.availHeight,"px 100svh":s.current?.clientHeight??"?","px 100dvh":n.current?.clientHeight??"?","px 100lvh":l.current?.clientHeight??"?","safe-top":o.current?.clientHeight??"?","safe-bottom":d.current?.clientHeight??"?","--app-vh":document.documentElement.style.getPropertyValue("--app-vh")||"unset","--shell-top":document.documentElement.style.getPropertyValue("--shell-top")||"unset","--kb-inset":e?.style.getPropertyValue("--kb-inset")||"unset",focused:document.activeElement?.tagName??"none",ua:navigator.userAgent})};t();let r=window.visualViewport;r?.addEventListener("resize",t),r?.addEventListener("scroll",t),window.addEventListener("resize",t);let a=window.setInterval(t,1e3);return()=>{r?.removeEventListener("resize",t),r?.removeEventListener("scroll",t),window.removeEventListener("resize",t),window.clearInterval(a)}},[e]);let c={position:"absolute",left:-9999,top:0,width:1};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{ref:s,"aria-hidden":!0,style:{...c,height:"100svh"}}),(0,t.jsx)("div",{ref:n,"aria-hidden":!0,style:{...c,height:"100dvh"}}),(0,t.jsx)("div",{ref:l,"aria-hidden":!0,style:{...c,height:"100lvh"}}),(0,t.jsx)("div",{ref:o,"aria-hidden":!0,style:{...c,height:"env(safe-area-inset-top)"}}),(0,t.jsx)("div",{ref:d,"aria-hidden":!0,style:{...c,height:"env(safe-area-inset-bottom)"}}),(0,t.jsx)("div",{className:"fixed top-0 left-0 right-0 z-[9999] bg-black/90 text-3xs leading-tight text-lime-300 font-mono p-2 break-all",children:Object.entries(r).map(([e,r])=>(0,t.jsxs)("div",{children:[(0,t.jsxs)("span",{className:"text-muted-foreground",children:[e,":"]})," ",String(r)]},e))})]})}},581285,615923,216136,882847,51559,718177,e=>{"use strict";e.s(["JupiterPerpsTradingPanel",()=>tI],581285);var t=e.i(394390),r=e.i(684446),i=e.i(296234),s=e.i(717997),n=e.i(475274),a=e.i(734195),l=e.i(756950),o=e.i(183023),d=e.i(807956),c=e.i(942553),u=e.i(831519),h=e.i(599059),p=e.i(271434),m=e.i(331037),f=e.i(710729),x=e.i(59392),g=e.i(784010),b=e.i(937626),v=e.i(213076),y=e.i(153517),w=e.i(406470),j=e.i(532906),S=e.i(277589),k=e.i(308759),N=e.i(106128),P=e.i(689384),T=e.i(161708);e.i(889723);var C=e.i(49332),M=e.i(727322),_=e.i(875574),A=e.i(142298),E=e.i(894771),L=e.i(190459),F=e.i(777180),R=e.i(988408),D=e.i(678872);e.i(654249);var I=e.i(364589),U=e.i(71917),O=e.i(759550),B=e.i(942289),z=e.i(465027),$=e.i(815),V=e.i(806082),H=e.i(568299),W=e.i(687229),q=e.i(124431),K=e.i(193568),G=e.i(722732),Y=e.i(670374),X=e.i(116082),Q=e.i(739835),J=e.i(936548),Z=e.i(855600),ee=e.i(567978),et=e.i(473344),er=e.i(394802),ei=e.i(1169),es=e.i(202647),en=e.i(670258),ea=e.i(641971),el=e.i(373641),eo=e.i(285620),ed=e.i(409686),ec=e.i(744900),eu=e.i(912881),eh=e.i(464992),ep=e.i(926643),em=e.i(596331),ef=e.i(685576),ex=e.i(575146),eg=e.i(657645),eb=e.i(482317),ev=e.i(268680),ey=e.i(35e4),ew=e.i(767041),ej=e.i(85161),eS=e.i(103887),ek=e.i(637740),eN=e.i(631193),eP=e.i(797699),eT=e.i(872541),eC=e.i(430232),eM=e.i(470981),e_=e.i(984457),eA=e.i(765918),eE=e.i(346731),eL=e.i(616730),eF=e.i(821043),eR=e.i(308146),eD=e.i(702193),eI=e.i(491681),eU=e.i(836758),eO=e.i(299959),eB=e.i(76990),ez=e.i(208329),e$=e.i(148974),eV=e.i(565183),eH=e.i(332608),eW=e.i(403652),eq=e.i(555641),eK=e.i(824088),eG=e.i(623075),eY=e.i(208665),eX=e.i(260431),eQ=e.i(546642),eJ=e.i(111468),eZ=e.i(725452),e0=e.i(134042),e1=e.i(494286),e2=e.i(744427),e5=e.i(727104),e3=e.i(828047),e4=e.i(634692),e6=e.i(578866),e8=e.i(47935),e9=e.i(967678);let e7=(0,t.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:"h-5 w-5","aria-hidden":!0,
2children:[(0,t.jsx)("path",{d:"M3 7h9M3 11h7M3 15h5M3 19h3"}),(0,t.jsx)("path",{d:"M21 7h-3M21 11h-5M21 15h-7M21 19h-9"})]}),te=(0,t.jsx)(e8.CandlestickChart,{className:"h-5 w-5",strokeWidth:2,"aria-hidden":!0}),tt="h-[45px] flex-1 rounded-[6px] text-[15px] font-medium transition-colors duration-150 motion-reduce:transition-none focus-ring",tr="bg-[var(--side-pad-long)] text-[var(--side-ink-long)]",ti="bg-[var(--side-pad-short)] text-side-short",ts="text-[var(--side-ink-idle)]";function tn({onSide:e,activeSide:r}){let i=(0,c.useTranslations)("trading");return(0,t.jsxs)("div",{role:"group","aria-label":i("orderTypeHeading"),className:"flex h-[53px] min-w-0 flex-1 items-center rounded-[9px] bg-black/40 p-1",children:[(0,t.jsx)("button",{type:"button","data-side":"long","aria-pressed":"long"===r,onClick:()=>e("long"),className:`${tt} ${"long"===r?tr:ts}`,children:i("sideLong")}),(0,t.jsx)("button",{type:"button","data-side":"short","aria-pressed":"short"===r,onClick:()=>e("short"),className:`${tt} ${"short"===r?ti:ts}`,children:i("sideShort")})]})}let ta=(0,o.memo)(function({onSide:e,activeSide:r,bookActive:i,onToggleBook:s}){let n=(0,c.useTranslations)("nav"),a=(0,c.useTranslations)("wallet"),{publicKey:l}=(0,_.useUnifiedWalletContext)(),o=n(i?"showChart":"showBook"),d=(0,t.jsx)("button",{type:"button",onClick:s,"aria-pressed":i,"aria-label":o,className:`flex h-[43px] w-[43px] shrink-0 items-center justify-center rounded-[6px] bg-[var(--confirm-pad)] text-primary transition-colors hover:brightness-110 focus-ring${l?" mt-[5px]":""}`,children:i?e7:te});return(0,t.jsx)("div",{className:`mt-[5px] flex shrink-0 rounded-t-[5px] border-t border-x border-border bg-[image:var(--gradient-phone-footer)] [touch-action:manipulation] ${l?"items-start gap-[9px] pl-1 pr-[9px] pt-1":"items-center gap-[9px] px-2.5"}`,style:{height:e9.TRADE_BAR_PX},children:l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(tn,{onSide:e,activeSide:r}),d]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button","data-side":"long",onClick:eC.promptConnectWallet,className:"h-[45px] flex-1 rounded-[6px] bg-[image:var(--gradient-cta-wide)] text-[14px] font-semibold text-[var(--on-cta-wide)] shadow-[0_-3px_10px_-6px_rgba(243,189,29,0.08),0_3px_7px_-6px_rgba(38,227,192,0.2)] [text-shadow:0_1px_0_rgba(0,0,0,0.1)] active:scale-[0.98] transition-[transform,filter] duration-100 motion-reduce:transition-none hover:brightness-105 focus-ring",children:a("connectWallet")}),d]})})});e.s(["MobileTradeBar",0,ta,"SEGMENT_LONG_ON",0,tr,"SEGMENT_OFF",0,ts,"SEGMENT_SHORT_ON",0,ti],615923);var tl=e.i(309264),to=e.i(985433),td=e.i(873029);let tc=(0,e.i(504458).default)("user-round",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);function tu({title:e,children:r}){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("h2",{children:e}),r&&(0,t.jsx)("p",{className:"ip-sub",children:r})]})}function th({children:e,error:r,neutral:i}){return(0,t.jsxs)("div",{className:`ip-note${r?" ip-error":i?" ip-neutral":""}`,role:r?"alert":"note",children:[(0,t.jsx)(td.Info,{size:16}),(0,t.jsx)("div",{children:e})]})}function tp({className:e="",...r}){return(0,t.jsx)("button",{type:"button",className:`ip-primary ${e}`,...r})}function tm({className:e="",...r}){return(0,t.jsx)("button",{type:"button",className:`ip-text-button ip-full-text ${e}`,...r})}function tf({eyebrow:e,onBack:r}){let i=(0,c.useTranslations)("onboarding.shell");return(0,t.jsxs)("div",{className:"ip-panel-top",children:[(0,t.jsx)("span",{className:"ip-eyebrow",children:e}),r&&(0,t.jsxs)("button",{type:"button",className:"ip-back",onClick:r,children:[(0,t.jsx)(tl.ArrowLeft,{size:14}),i("back")]})]})}function tx({rows:e}){return(0,t.jsx)("ul",{className:"ip-details",children:e.map(([e,r],i)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{children:e}),(0,t.jsx)("strong",{children:r})]},i))})}function tg({snapshot:e,matchesCurrent:r,quoteAvailable:i,onConfirm:s,onCancel:n}){let a=(0,c.useTranslations)("onboarding.trade"),[l,d]=(0,o.useState)(!1),u=l&&r&&i&&e.quoteAvailable;return(0,t.jsx)(eG.Dialog,{open:!0,onOpenChange:e=>{e||n()},children:(0,t.jsxs)(eG.DialogContent,{className:"imperial-onboarding-review sm:max-w-[420px] border-0 bg-transparent gap-0",onOpenAutoFocus:e=>{e.preventDefault(),document.getElementById("onboarding-first-trade-heading")?.focus({preventScroll:!0})},children:[(0,t.jsx)(eG.DialogTitle,{className:"sr-only",children:a("title")}),(0,t.jsx)(eG.DialogDescription,{className:"sr-only",children:a("description")}),(0,t.jsxs)("div",{className:"ip-panel",children:[(0,t.jsx)(tf,{eyebrow:a("eyebrow"),onBack:n}),(0,t.jsx)("div",{id:"onboarding-first-trade-heading",tabIndex:-1,
2children:(0,t.jsx)(tu,{title:a("title"),children:a("description")})}),(0,t.jsx)(tx,{rows:e.rows}),(0,t.jsx)(th,{children:a(e.unifiedMargin?"crossRisk":"risk")}),!r&&(0,t.jsx)(th,{error:!0,children:a("changed")}),r&&(!i||!e.quoteAvailable)&&(0,t.jsx)(th,{error:!0,children:a("quoteUnavailable")}),(0,t.jsxs)("label",{className:"ip-checkbox",children:[(0,t.jsx)("input",{type:"checkbox",checked:l,onChange:e=>d(e.target.checked),disabled:!r||!i}),(0,t.jsx)("span",{children:a("acknowledgement")})]}),(0,t.jsx)(tp,{disabled:!u,onClick:()=>{u&&s()},children:a("confirm",{side:a(e.side),collateral:e.collateralLabel})}),(0,t.jsx)(tm,{onClick:n,children:a("returnToTicket")}),(0,t.jsx)("p",{className:"ip-skip",children:a("estimateNote")})]})]})})}e.s(["Choice",0,function({title:e,description:r,icon:i,...s}){return(0,t.jsxs)("button",{type:"button",className:"ip-choice",...s,children:[(0,t.jsx)("span",{className:"ip-choice-icon",children:i}),(0,t.jsxs)("span",{className:"ip-choice-copy",children:[(0,t.jsx)("b",{children:e}),(0,t.jsx)("small",{children:r})]}),(0,t.jsx)(to.ArrowRight,{size:16})]})},"Details",0,tx,"Heading",0,tu,"Identity",0,function(){let e=(0,c.useTranslations)("onboarding.shell"),{publicKey:r}=(0,_.useUnifiedWalletContext)(),{createdProfiles:i,activeProfileIndex:s}=(0,E.useProfile)(),n=i.find(e=>e.index===s),a=r?.toBase58()??"";return(0,t.jsxs)("div",{className:"ip-identity",children:[(0,t.jsx)(tc,{size:18}),(0,t.jsx)("span",{title:a,children:a?`${a.slice(0,4)}…${a.slice(-4)}`:e("connected")}),(0,t.jsx)("small",{children:n?.name||e("main")})]})},"Note",0,th,"PanelTop",0,tf,"PrimaryButton",0,tp,"SecondaryButton",0,function({className:e="",...r}){return(0,t.jsx)("button",{type:"button",className:`ip-secondary-button ${e}`,...r})},"StatusSymbol",0,function({children:e,success:r}){return(0,t.jsx)("div",{className:`ip-status-symbol${r?" ip-success":""}`,children:e})},"TextButton",0,tm],216136);let tb=new Map;function tv(e,t){return`imperial:first-trade-review:${e}:${t}`}function ty(e){try{let t=localStorage.getItem(e);if("pending"===t||"done"===t)return t}catch{}return tb.get(e)??null}function tw(e,t){tb.set(e,t);try{localStorage.setItem(e,t)}catch{}}function tj(e,t){return null!==t&&!!e&&"pending"===ty(tv(e,t))}function tS(e,t){tw(tv(e,t),"done")}function tk(e){return JSON.stringify(e)}function tN(e,t){return e.length>0&&e===t}e.s(["completeFirstTradeReview",0,tS,"firstTradeIntentKey",0,tk,"matchesFirstTradeIntent",0,tN,"needsFirstTradeReview",0,tj,"requestFirstTradeReview",0,function(e,t){if(!e||!Number.isInteger(t)||t<0)return;let r=tv(e,t);"done"!==ty(r)&&tw(r,"pending")}],882847);let tP="margin-mode-picker",tT="flex-1 min-h-0 overflow-y-auto overscroll-contain [touch-action:manipulation] px-[7px]",tC=(0,d.default)(()=>e.A(256705).then(e=>({default:e.DepositWithdrawDialog})),{loadableGenerated:{modules:[172739]},ssr:!1}),tM=(0,d.default)(()=>e.A(297078).then(e=>({default:e.VenueSettingsDialog})),{loadableGenerated:{modules:[251512]},ssr:!1});function t_(e,t){return`${(0,w.formatFixed)(e,+!Number.isInteger(e),t)}x`}let tA=(0,t.jsxs)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[(0,t.jsx)("path",{d:"M3 16l4.2-6.2L11 14l4-6 3.5 4.6"}),(0,t.jsx)("path",{d:"M15.5 19.5H21",strokeDasharray:"2.6 2.6"}),(0,t.jsx)("circle",{cx:"18.5",cy:"12.6",r:"1.4"})]}),tE=(0,t.jsxs)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[(0,t.jsx)("path",{d:"M4.5 18.5v-3.5M9.5 18.5v-6.5M14.5 18.5v-9.5M19.5 18.5V6"}),(0,t.jsx)("path",{d:"M3 21h18",opacity:".35"})]}),tL=(0,t.jsxs)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[(0,t.jsx)("path",{d:"M3 12.5h3.5L9 6.5l4 11.5 2.3-5.5H21"}),(0,t.jsx)("circle",{cx:"15.6",cy:"12.4",r:"1.5",fill:"currentColor",stroke:"none"})]});function tF(e){return(0,eF.toDecimalInputValue)(Math.round(10*e)/10)}function tR(e,t,r){return!isFinite(e)||e<=0?"":"base"===t&&r>0?(e/r).toFixed(r>=1e3?5:r>=10?3:2):e.toFixed(2)}let tD="text-base";function tI({executionIdentity:e,executionFocusRevision:d,isExecutionCurrent:w,marketMint:_,marketInfo:e8,marketPrice:e9,oraclePrice:e7,phoenixOrderbook:te,phoenixOrderbookReceivedAt:tt,phoenixOrderbookGeneration:tn,onResolvedVenueChange:ta,onPositionChange:tl,existingPositions:to=[],chartResolution:td,compact:tc,active:tu=!0,onBusyChange:th,hotkeys:tp=!1,publishChartPreview:tm=!1,limitPricePrefill:tf,sideIntent:tx,onOrderPlaced:tb,onInnerSurfaceChange:tv,onTallTicketChange:ty}){let tw,tU,tO,tB,tz,t$,tV,tH,tW,tq,tK,tG,tY,tX,tQ,tJ,tZ,t0=(0,c.useTranslations)("trading"),t1=(0,c.useTranslations)("wallet"),t2=(0,c.useTranslations)("positions"),t5=(0,c.useTranslations)("terms"),t3=(0,c.useTranslations)("common"),t4=(0,c.useTranslations)("onboarding.trade"),t6=(0,eO.useFormatters)(),t8=(0,eO.useDecimalSeparator)(),[t9,t7]=(0,r.useDesktopTicketDraftState)("ticket.orderType","market"),[re,rt]=(0,r.useDesktopTicketDraftState)("ticket.side","long"),[rr,ri]=(0,o.useState)(null),rs=(0,o.useRef)(null),rn=(0,o.useRef)({intentKey:"",quoteAvailable:!1});(0,o.useEffect)(()=>()=>{rs.current?.(null),rs.current=null},[]),(0,o.useEffect)(()=>{tu||(rs.current?.(null),rs.current=null,ri(null))},[tu]);let[ra,rl]=(0,r.useDesktopTicketDraftState)("ticket.reduceOnly",!1),ro="long"===re,[rd,rc]=(0,r.useDesktopTicketDraftState)("ticket.size",""),[ru,rh]=(0,r.useDesktopTicketDraftState)("ticket.sizeDisplay",""),[rp,rm]=(0,r.useDesktopTicketDraftState)("ticket.sizeDisplayUnit",()=>"base"===localStorage.getItem("sizeDisplayUnit")?"base":"usd"),rf=(0,o.useRef)(!1),rx=(0,o.useRef)(null),[rg,rb]=(0,o.useState)(null);(0,o.useEffect)(()=>
2{if("failure"!==rg)return;let e=setTimeout(()=>rb(null),6e3);return()=>clearTimeout(e)},[rg]);let rv=()=>rb(e=>"failure"===e?null:e),[ry,rw]=(0,o.useState)(!1),[rj,rS]=(0,o.useState)(""),rk=(0,o.useRef)(null);function rN(e,t){rb(null),rS(t0("order"===t?"orderRestingLive":"orderOpenedLive",{side:"long"===e?t0("sideLong"):t0("sideShort"),symbol:e8.symbol})),tb?.(e,{streakMessage:"order"===t?null:sg?.message??null,kind:t})}function rP(e,t){eM.pulseMark.trigger("trade-open"),rb(null),rw(!0),rS(t0("order"===t?"orderRestingLive":"orderOpenedLive",{side:"long"===e?t0("sideLong"):t0("sideShort"),symbol:e8.symbol})),rk.current=setTimeout(()=>{rk.current=null,rw(!1),rN(e,t)},600)}function rT(){iY()?rb("partialTpSl"):!0!==iX()&&rb("failure")}(0,o.useEffect)(()=>()=>{rk.current&&clearTimeout(rk.current)},[]);let[rC,rM]=(0,r.useDesktopTicketDraftState)("ticket.collateral",""),[r_,rA]=(0,r.useDesktopTicketDraftState)("ticket.inputMode",()=>"size"===localStorage.getItem("tradeInputMode")?"size":"cost"),[rE,rL]=(0,o.useState)(null),[rF,rR]=(0,o.useState)(""),[rD,rI]=(0,o.useState)(!1),[rU,rO]=(0,r.useDesktopTicketDraftState)("ticket.limitPrice",""),[rB,rz]=(0,r.useDesktopTicketDraftState)("ticket.bboActive",!1),r$=`lastLeverage_${_}`,[rV,rH]=(0,r.useDesktopTicketDraftState)("ticket.leverage",()=>{{let e=parseFloat(localStorage.getItem(r$)||"");if(!isNaN(e)&&e>=eU.LEVERAGE_MIN)return e}return 3}),[rW,rq]=(0,o.useState)(!1),[rK,rG]=(0,r.useDesktopTicketDraftState)("ticket.leverageDraft",""),[rY,rX]=(0,o.useState)({text:"",n:0}),rQ=e=>rX(t=>({text:e,n:t.n+1})),rJ=(0,o.useRef)(null),{publish:rZ}=(0,b.usePairTicket)();(0,o.useEffect)(()=>{rZ({collateralUsd:parseFloat(rC)||0,leverage:rV})},[rC,rV,rZ]);let r0=(0,r.useDesktopTicketDraftHas)("ticket.leverage"),r1=(0,o.useRef)(r0),r2=(0,o.useRef)(null),{slippageBps:r5,setSlippageBps:r3}=(0,eN.useSlippageBps)(),[r4,r6]=(0,o.useState)(!1),r8=(0,o.useRef)(null),[r9,r7]=(0,o.useState)(()=>
2[50,100,200,500].includes(r5)?"":(r5/100).toString()),[ie,it]=(0,o.useState)(null),[ir,ii]=(0,o.useState)(null),[is,ia]=(0,o.useState)(null),[il,io]=(0,o.useState)(null),[id,ic]=(0,o.useState)(null),[iu,ih]=(0,o.useState)(null),[ip,im]=(0,o.useState)(null),[ix,ig]=(0,o.useState)(!1),ib=(0,o.useRef)(null);(0,V.useRevealOnOpen)(ix,ib);let[iv,iy]=(0,o.useState)(()=>{{let e=localStorage.getItem("showEntryPrice");return null===e||"true"===e}}),[iw,ij]=(0,o.useState)(()=>{{let e=localStorage.getItem("showLiqPrice");return null===e||"true"===e}}),[iS,ik]=(0,o.useState)(()=>{{let e=localStorage.getItem("showBorrowRate");return null===e||"true"===e}}),[iN,iP]=(0,o.useState)(()=>{{let e=localStorage.getItem("showPayFees");return null===e||"true"===e}}),[iT,iC]=(0,o.useState)(!1),[iM,i_]=(0,o.useState)(!1),iA=(0,o.useRef)(null),iE=(0,o.useRef)(null),iL=(0,o.useRef)(null),iF=(0,o.useRef)(null),iR=!0===tc&&iM;(0,o.useEffect)(()=>{tv?.(iR||null!==rr)},[iR,rr,tv]);let iD="trailing"===t9||"dca"===t9||"indicator"===t9;(0,o.useEffect)(()=>{ty?.(iD)},[iD,ty]);let iI=iM&&!iT;(0,$.useBackToClose)(iR,()=>i_(!1),"imperialMarginPicker");let iU=(0,o.useRef)(!1);(0,o.useEffect)(()=>{let e=iU.current;if(iU.current=iM,!e&&iM)return void iE.current?.focus();if(e===iM)return;let t=document.activeElement;t&&t!==document.body||iA.current?.focus()},[iM]);let{openPositionViaPassthrough:iO,openLimitOrderViaPassthrough:iB,createRatchetEntryOrder:iz,createIndicatorOrder:i$,createDcaOrder:iV,createDcaTimeOrder:iH,createDcaRatchetOrder:iW,depositCollateral:iq,withdrawCollateral:iK,submitting:iG,getLastCloseOrderFailures:iY,wasLastErrorRejection:iX}=(0,M.useTradeActions)(),{pullIntoProfile:iQ,pulling:iJ}=(0,eI.useArmadaAccountPull)(),iZ=iG||iJ;(0,o.useEffect)(()=>{th?.(iZ||ry||iT)},[th,iZ,ry,iT]);let{activeProfileIndex:i0,activeProfileUnderwriter:i1,activeProfileExcludedVenues:i2,activeProfileMarginMode:i5,activeProfileVenueLock:i3,setProfileMarginMode:i4,createdProfiles:i6,setActiveProfileIndex:i8,canCreateMore:i9}=(0,E.useProfile)(),i7="unified"===i5,se=to.find(e=>"long"===e.side&&(0,e0.positionMatchesMarginMode)(e,i5)),st=to.find(e=>"short"===e.side&&(0,e0.positionMatchesMarginMode)(e,i5)),sr=!!se,si=!!st;(0,o.useEffect)(()=>{i_(!1),r6(!1),nz(!1)},[tu,i0,e8.symbol]);let{registerForPhoenix:ss}=(0,z.usePhoenixRegistration)(),{positions:sn,watchSunriseMarket:sa,orders:sl}=(0,W.useUnifiedPositions)(),{balances:so,syncStatus:sd,triggerSync:sc,hasNonUsdcBalance:su}=(0,q.useProfileBalance)(),{publicKey:sh}=(0,A.useUnifiedWallet)(),{data:sp}=(0,R.useTradingStats)(sh?.toBase58()),sm=(0,R.resolveHoldHours)(sp,e8.symbol),sf=parseFloat(rC)||0,sx=i7?parseFloat(rd)||0:sf*rV,sg=function(e,t){let r,i=(0,c.useTranslations)("trading"),{data:s}=(0,ec.useSeasonPoints)(e),n=s?.currentWeek;if(!e||!n)return null;let a=n.dailyVolumeTodayUsdMicros/1e6;if(a>=100)return null;let l=n.dailyStreakPending,o=a+(t>0?t:0),d=o>=100,u=Math.max(0,100-o),h="$100";if(d)r=l>0?i("streakExtends",{count:l,next:l+1}):i("streakStarts");else if(t>0){let e={current:`$${Math.floor(o)}`,goal:h,remaining:`$${Math.ceil(u)}`,count:l};r=i(l>0?"streakProgressExtend":"streakProgress",e)}else{let e={current:`$${Math.floor(a)}`,goal:h,count:l};r=i(l>0?"streakTodayKeep":"streakTodayStart",e)}return{message:r,wouldExtend:d}}(sh?.toBase58(),sx),sb=(0,F.useRoutedVenue)({asset:e8.symbol,side:re,desiredLeverage:rV,notional:sx>0?sx:void 0,armadaPrimeMarketOpen:!i7&&"market"===t9}),{data:sv}=(0,D.useLendingPoolState)(),sy=(0,o.useMemo)(()=>(0,O.toRouterPoolState)(sv),[sv]),{data:sw}=(0,D.useBorrowPower)(sh?.toBase58()),sj=parseFloat(sw?.availableUsd??"0")||0,sS=sw?.premiumBps??0,sk=sw?.maxLoanBeforeUtilGateUsd!=null?parseFloat(sw.maxLoanBeforeUtilGateUsd):NaN,sN=Number.isFinite(sk)?sk:void 0,sP=(0,H.useRoutingContext)(),sT=sP?.setInputs,sC=sP?.setManualVenue;(0,o.useEffect)(()=>{sT?.({desiredLeverage:rV,notional:sx>0?sx:void 0,side:re})},[sT,rV,sx,re]);let sM=sb?sb.venue:(0,eq.resolveConcreteUnderwriter)(i1,_,i2);(0,o.useLayoutEffect)(()=>{ta?.(sM)},[sM,ta]);let s_="phoenix"===sM,sA="gmtrade"===sM,sE=B.OPENS_PAUSED_VENUES.has(sM),sL=t0("venueOpensPaused",{venue:h.VENUE_
2LABELS[sM]});(0,o.useEffect)(()=>"sunrise"!==(0,L.underwriterLiteralFrom)(sM)?void sa(null):(sa(e8.symbol),()=>sa(null)),[sM,e8.symbol,sa]);let sF=e=>(0,eT.trackOrderSubmitted)({...e,marketMint:_,venue:String(sM)}),sR=(0,o.useMemo)(()=>{let e=sy?.perMarket.find(e=>e.symbol===e8.symbol);return e?(0,U.premiumBpsFor)(e,sM):0},[sy,e8.symbol,sM]),{getMaxLeverage:sD,getMarketFees:sI,getMarketLiquidity:sU}=(0,eK.useGmTradeWs)(),{data:sO,isPlaceholderData:sB}=(0,eB.usePhoenixMarkets)(),sz=(0,o.useMemo)(()=>sO?.find(e=>e.symbol===e8.symbol)??null,[sO,e8.symbol]),s$=sz?sz.maxLeverage>0&&isFinite(sz.maxLeverage)?sz.maxLeverage:19:void 0,sV=(0,o.useMemo)(()=>{if("sunrise"===(0,L.underwriterLiteralFrom)(sM))return{open:0,close:0,hasCollateralSwap:!1,borrowRateHourlyPct:0}},[sM]),sH=sD(e8.symbol),{data:sW,isPending:sq,isPlaceholderData:sK}=(0,e6.useSunriseMarkets)(),sG=(0,e4.useSunriseOpensAllowed)(),sY=(0,o.useMemo)(()=>{let e=(sW??[]).find(e=>e.symbol===e8.symbol)?.maxLeverage;return"number"==typeof e&&isFinite(e)&&e>0?e:void 0},[sW,e8.symbol]),sX=sn.some(e=>e.profileIndex===i0&&e.asset===e8.symbol&&("open"===e.status||"pending"===e.status||"closing"===e.status)&&!(e.underwriter&&B.OPENS_PAUSED_VENUES.has(e.underwriter))),sQ=(0,C.isJupiterMarket)(_)?B.JUPITER_MAX_LEVERAGE_BY_ASSET[e8.symbol]??250:void 0,sJ=new Set(i2),sZ=[["phoenix",s$],["gmtrade",sH],["jupiter",sQ],["armada",sG?sY:void 0]],s0=e=>sZ.find(([t])=>t===e)?.[1],s1=sZ.filter(([,e])=>"number"==typeof e&&isFinite(e)&&e>0).map(([,e])=>e),s2=s0(sM)??(s1.length>0?Math.max(...s1):1),s5=(0,K.useTradingPreload)(_),s3=sz?.takerFeeMicro??0,s4="market"!==t9,s6=(0,o.useMemo)(()=>(0,T.flatCollateralFeeBps)((0,T.feePolicy)(sh?.toBase58())),[sh]),s8=(0,o.useMemo)(()=>{let e=parseFloat(rC)||0;if(e<=0||!s_)return s_?(0,B.phoenixEffectiveMaxLeverage)(s2,s3,s6/1e4):s2;let t=Math.floor(1e6*e),r=Math.floor(t*s6/1e4),i=1,s=s2;for(let n=0;n<30;n++){let n,a,l,o=(i+s)/2,d=Math.floor(e*o*1e6),c=(0,em.calculateProgressiveFee)(0,d,!0);{n=d;let e=d/1e6,r=te&&!s4?(0,eH.estimatePhoenixOpenFillLossFraction)(te.asks,te.bids,e,e9??0):null;a=t-(null!=r?Math.floor(d*r):0),l=Math.floor(d*s3/1e6)}let u=a-c-l-r;if(u<=0){s=o;continue}n/u<=s2?i=o:s=o}return(0,B.floorTo2)(i*B.PHOENIX_OPEN_LEVERAGE_BUFFER)},[rC,s2,s_,s3,te,e9,s4,s6]),s9=s6/1e4,s7=(e,t)=>"phoenix"===e?(0,B.phoenixEffectiveMaxLeverage)(t,s3,s9):t,ne=e=>!i7||(i3?.venues??[]).includes(e),nt=sX?[]:sZ.filter(([e,t])=>e!==sM&&!sJ.has(e)&&!B.OPENS_PAUSED_VENUES.has(e)&&ne(e)&&"number"==typeof t&&isFinite(t)&&t>0).map(([e,t])=>s7(e,t)),nr=!sJ.has(sM)||sX||0===nt.length?Math.max(s8,...nt):Math.max(...nt),ni=!i7&&!!sv&&!sJ.has("phoenix")&&void 0!==s$&&(!sX||"phoenix"===sM),ns=null!=s$?(0,B.phoenixEffectiveMaxLeverage)(s$,s3):void 0,nn=ni?(0,U.loanAwareMaxLeverage)(ns,sy,e8.symbol,sf,sN):null,na=sW?.find(e=>e.symbol===e8.symbol)?.armadaPrime,nl=i7||"market"!==t9||sX||!sG||sJ.has("armada")||B.OPENS_PAUSED_VENUES.has("armada")?null:(0,U.armadaPrimePool)(sy,e8.symbol,na),no=(()=>{if(!nl||!sY||!na)return null;let e=(0,U.loanAwareMaxLeverage)(sY,nl,e8.symbol,sf,sN);return null==e?null:Math.min(e,.999999/(na.gminBps/1e4+na.fee1e6/1e6))})(),nd=(no??0)>(nn??0),nc=nd?no:nn,nu=nd?sY:ns,nh=(()=>{if(null==nc)return null;if(!(sS>0)||!(sf>0)||!((sy?sy.maxMultiplierMicro/1e6:0)>1)||!(nu>0))return nc;let e=sS/1e4*Math.max(0,Math.max(0,nc/nu-1)-sj/sf);return nc*(1-Math.min(e,1))})(),np=null!=nh?Math.max(nr,(0,B.floorTo2)(nh)):nr,nm=Math.min(rV,np),nf=i7?nm:rV,nx=(0,o.useMemo)(()=>{let e=[["phoenix",s_,sO?.find(e=>e.symbol===e8.symbol)?.maxLeverage],["gmtrade",sA,sH]],t=null;for(let[r,i,s]of e)!(i||B.OPENS_PAUSED_VENUES.has(r))&&(null==s||s<=np||s<=(t?.maxLeverage??0)||(t={underwriter:r,maxLeverage:s}));return t},[s_,sA,sO,sH,e8.symbol,np]),ng=(0,o.useMemo)(()=>sz&&e9?sz.maxSizeBaseLots*Math.pow(10,-sz.baseLotsDecimals)*e9:null,[sz,e9]),nb=(e,t)=>{if(!s_||!sz||!e||!e9||e9<=0||i7)return null;let r=parseFloat(e.sizeUsd??""),i=parseFloat(e.entryPrice??""),s=parseFloat(e.collateralUsd??"");if(!isFinite(r)||!isFinite(i)||!isFinite(s)||r<=0||i<=0||s<=0)return null;let n=parseFloat(e.seatCollateralUsd??""),a=isFinite(n)&&n>s?n:s,l=parseFloat(e.borrowedCollateralUsd??""),o=isFinite(l)&&l>0?l:Math.max(0,a-s),d=parseFloat(e.accruedInterestUsd??""),c=isFinite(d)&&d>0?d:0,u=parseFloat(e.loanOriginationNotionalUsd??"");
2return{pos:{side:t,sizeUsd:r,entryPrice:i,collateralUsd:s,seatCollateralUsd:a,borrowedPrincipalUsd:o,accruedInterestUsd:c,loanOriginationNotionalUsd:isFinite(u)&&u>0?u:0},markPrice:e9}},nv="number"==typeof e9&&e9>0,ny=(0,o.useMemo)(()=>nb(se,"long"),[s_,i7,sz?.symbol,nv,se?.lastActionAt,se?.sizeUsd,se?.entryPrice,se?.collateralUsd,se?.seatCollateralUsd,se?.borrowedCollateralUsd,se?.accruedInterestUsd,se?.loanOriginationNotionalUsd]),nw=(0,o.useMemo)(()=>nb(st,"short"),[s_,i7,sz?.symbol,nv,st?.lastActionAt,st?.sizeUsd,st?.entryPrice,st?.collateralUsd,st?.seatCollateralUsd,st?.borrowedCollateralUsd,st?.accruedInterestUsd,st?.loanOriginationNotionalUsd]),nj=(0,o.useMemo)(()=>{if(!s_||!sz||"dca"!==t9||i7)return null;let e=(0,B.phoenixEffectiveMaxLeverage)(sz.maxLeverage,sz.takerFeeMicro);return!isFinite(e)||e<=0||!isFinite(rV)||rV<=0||rV<.9*e?null:{capX:e,impliedX:rV,symbol:e8.symbol}},[s_,sz,t9,rV,e8.symbol,i7]);(0,o.useMemo)(()=>sA&&"dca"===t9?{symbol:e8.symbol}:null,[sA,t9,e8.symbol]),(0,o.useEffect)(()=>{sA&&"dca"===t9&&t7("market")},[sA,t9]);let[nS,nk]=(0,o.useState)(!1),nN=()=>nk(!0),[nP,nT]=(0,o.useState)(!1),[nC,nM]=(0,o.useState)(!1),[n_,nA]=(0,o.useState)(!1),[nE,nL]=(0,r.useDesktopTicketDraftState)("ticket.closeOrderItems",[]),[nF,nR]=(0,o.useState)(0),nD=(0,r.useClearDesktopTicketDraftPrefix)(),nI=()=>{nD("tpsl."),nL([]),nR(e=>e+1)},[nU,nO]=(0,r.useDesktopTicketDraftState)("ticket.deferFunding",!1),[nB,nz]=(0,o.useState)(!1),n$=(0,o.useMemo)(()=>{if(i7||"armada"===sM&&("market"!==t9||sX||!nl))return null;let e=sb?.loanSplit;return!e||e.loanAmountUsd<=0||sb.venue!==sM?null:e},[sb,sM,i7,t9,sX,nl]),nV=(0,o.useCallback)(e=>{if(n$&&!sn.some(t=>{let r=t.underwriter??(0,E.normalizeUnderwriter)(t.apiData?.underwriter);return(0,Y.getMarketMintFromAsset)(t.asset)===_&&t.side===e&&(t.profileIndex??null)===(i0??null)&&r===sM&&"closed"!==t.status}))return{loanAmountUsd:n$.loanAmountUsd}},[n$,sn,_,i0,sM]),nH=(0,o.useCallback)((e,t,r,i)=>nV(e)&&t?(0,U.loanSlTriggerPriceUsd)({isLong:"long"===e,entryPrice:t,ownedCollateralUsd:i,notionalUsd:r,premiumBps:sR}):null,[nV,sR]),nW=e=>{let r=e.loanUsd<1e3?`$${t6.fixed(e.loanUsd,2)}`:`$${t6.numberShort(e.loanUsd)}`,i=`${t6.grouped(parseFloat(rV.toFixed(1)),{maximumFractionDigits:1})}x`,s=null!=e.venueLeverage?`${t6.grouped(parseFloat(e.venueLeverage.toFixed(1)),{maximumFractionDigits:1})}x`:null,n=t6.fixed(e.ourRateBps/100,1),a=e.loanUsd*(e.ourRateBps/1e4)/365,l=a>=.01?`$${t6.fixed(a,2)}/day`:`<$${t6.fixed(.01,2)}/day`,o=parseFloat(rC)||0,d=o>0?`$${t6.fixed(o,2)}`:"—",c=o>0?`$${t6.fixed(o+e.loanUsd,2)}`:null,u=null!=e.loanSlLiq&&e.loanSlLiq>0?`$${t6.number(e.loanSlLiq)}`:null;return(0,t.jsx)(ev.TooltipProvider,{children:(0,t.jsxs)(ev.Tooltip,{children:[(0,t.jsx)(ev.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("div",{className:"flex items-center justify-between cursor-help",children:[(0,t.jsx)("span",{className:"text-sky-400",children:t0("imperialLoan")}),(0,t.jsx)("span",{className:"text-secondary-foreground tabular-nums underline decoration-dotted underline-offset-2 decoration-sky-500/40",children:(0,t.jsx)("span",{className:"text-sky-400",children:t0("loanLentAmount",{amount:r})})})]})}),(0,t.jsx)(ev.TooltipContent,{side:"top",className:"font-mono text-xs",children:(0,t.jsxs)("div",{className:"space-y-1 whitespace-nowrap",children:[(0,t.jsx)("div",{className:"text-sky-400 border-b border-border pb-1",children:e.whyLine}),(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("youPost")}),(0,t.jsx)("span",{className:"tabular-nums",children:d})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-sky-400",children:t0("imperialAdds")}),(0,t.jsxs)("span",{className:"tabular-nums text-sky-400",children:["+",r]})]}),c&&(0,t.jsxs)("div",{className:"flex justify-between gap-6 border-t border-border pt-1",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("totalMargin")}),(0,t.jsx)("span",{className:"tabular-nums",children:c})]}),e.isReach&&s&&(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("opensAt")}),(0,t.jsx)("span",{className:"tabular-nums",children:t0("opensAtValue",{effective:i,venue:s})})]}),u&&(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("loanStop")}),(0,t.jsx)("span",{className:"tabular-nums text-sky-400",children:u})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("interest")}),(0,t.jsx)("span",{className:"tabular-nums",children:t0("aprAndDaily",{apr:n,daily:l})})]})]})})]})})},nq=(0,o.useRef)(_);(0,o.useEffect)(()=>
2{if(nq.current!==_){nq.current=_,r1.current=!1,r2.current=null,rc(""),rM(""),rO(""),rz(!1),it(null),ii(null),ia(null),io(null),ic(null),ih(null),im(null),nI(),rb(null),rw(!1),rk.current&&(clearTimeout(rk.current),rk.current=null);let e=parseFloat(localStorage.getItem(`lastLeverage_${_}`)||"");!isNaN(e)&&e>=eU.LEVERAGE_MIN&&rH(e)}},[_]),(0,o.useEffect)(()=>{"limit"!==t9&&rz(!1)},[t9]);let nK=(0,o.useRef)(void 0);(0,o.useEffect)(()=>{!tf||nK.current===tf.requestId||void 0!==tf.marketMint&&tf.marketMint!==_||void 0!==tf.focusRevision&&tf.focusRevision!==d||(!w||w())&&(nK.current=tf.requestId,t7("limit"),rz(!1),rO(tf.price))},[tf,_,d,w]);let nG=(0,o.useRef)(void 0);(0,o.useEffect)(()=>{tx&&nG.current!==tx.nonce&&(nG.current=tx.nonce,rt(tx.side))},[tx]);let{publicKey:nY,connection:nX,isJWTMode:nQ}=(0,A.useUnifiedWallet)(),{addPendingPosition:nJ}=(0,ee.usePendingPositions)(),{data:nZ,refetch:n0}=(0,ez.usePhoenixMarginAccount)(nY?.toBase58()??null,i0,i7&&s_),{data:n1,refetch:n2}=(0,e1.useSunriseMargin)(nY?.toBase58()??null,i0,null,i7&&"armada"===sM),n5=(0,e0.crossMarginFreeCollateralUsd)(sM,(0,ez.freeCollateralUsd)(nZ),n1?.freeCollateralUsd??null),n3=so.USDC,{data:n4,refetch:n6}=(0,e1.useSunriseMargin)(nY?.toBase58()??null,i0,null,!0),n8=(0,e0.armadaAccountDrawForTicket)(sM,i7,void 0!==nV(re),(0,e1.armadaAccountDrawableUsd)(n4)),n9="armada"===sM?null:(0,eD.armadaOrderPullableUsd)((0,e1.armadaAccountWithdrawableUsd)(n4),n4),n7=null===n3?null:n3+(n8??0)+(n9??0),ae=(0,o.useRef)(!0);(0,o.useLayoutEffect)(()=>(ae.current=!0,()=>{ae.current=!1}),[]);let at=(0,l.useExecutionGeneration)(sM),ar=()=>ae.current&&at()&&(!w||w()),[ai,as]=(0,o.useState)(!1);(0,o.useEffect)(()=>{as(!1)},[_,i0,sM,t9,re,rd,rC,rU]);let an=async(e,t,r)=>{if(!ar())return null;if(as(!1),"armada"===sM||t||null===i0||!(0,eD.spendMayNeedArmadaPull)(e,n3,n9))return e;let i=(0,eR.floorNumberToBaseUnits)(e,6);if(null===i)return e;let s=await iQ({profileIndex:i0,neededRaw:i,forOrder:!0,incompleteMessage:t1("armadaPullIncomplete"),failedMessage:t1("armadaPullFailed"),isAlive:ar});if(null===s||!ar())return null;let n=s.spendRaw<i?Number(s.spendRaw)/1e6:e;return r&&"confirm"===(0,eD.orderAfterArmadaPull)({pulled:s.pulled,elapsedMs:Date.now()-r.clickedAt,stillValid:r.stillValid(n)})?(as(!0),null):n},aa=(0,o.useRef)([]),al=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(null===n3)return;let e=aa.current,t=e[e.length-1];(!t||t.value!==n3)&&(e.push({value:n3,time:Date.now()}),e.length>20&&e.shift())},[n3]);let ao=parseFloat(rd)||0,ad=i7?ao>0&&isFinite(nm)&&nm>0?ao/nm:0:parseFloat(rC)||0,ac=i7?ad:0,{walletUsd:au,collateralAmountUsd:ah}=(0,e0.crossTicketFunding)(sM,ac,n5),ap=i7?au:ad,am=i7?ao>=1:ad>=1,af=i7?(n5??0)+ap:ad,ax=i7&&"armada"===sM,ag=ax?(0,e1.sunriseWithdrawableNowUsd)(n1):(0,ez.withdrawableUsd)(nZ),ab=ax?(0,e1.sunriseArrivingUsd)(n1):null,{submitWithArrivingWait:av}=(0,e$.useArrivingWithdrawal)(),ay=ax?n1?.initialMarginUsd??null:(0,ez.parseAccountUsd)(nZ?.initialMarginUsd),aw=ax?n1?.effectiveCollateralUsd??null:(0,ez.parseAccountUsd)(nZ?.effectiveCollateralUsd),aj=ax?n1?.maintenanceMarginUsd??null:(0,ez.parseAccountUsd)(nZ?.maintenanceMarginUsd),aS=ax?n1?.openPositions??0:nZ?.openPositions??0,ak=null!==ag&&ag>0,aN=null===n5||null===n7?null:n5+n7,aP=parseFloat(rF)||0,aT="add"===rE&&null!==n7&&(0,eA.isCollateralInsufficient)(aP,n7),aC="withdraw"===rE&&null!==ag&&aP>ag,aM=!(ax&&n1?.liquidationPending)&&aP>0&&!aT&&!aC&&!("withdraw"===rE&&!ak)&&!rD&&!iZ,a_=e7??e9,aA=rB&&a_?a_:parseFloat(rU)||0,aE=e=>"limit"===t9&&aA>0?aA:e.markPrice,aL=e=>e&&sz?.95*(0,eH.computePhoenixAddHeadroom)(e.pos,{maxLeverage:nh??sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},aE(e),ap>0?ap:0).maxAddSizeUsd:null;aL(ny),aL(nw);let aF=e=>{if(!e||!sz)return null;let t={...e.pos,collateralUsd:e.pos.seatCollateralUsd};return(0,eH.computePhoenixAddHeadroom)(t,{maxLeverage:sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},aE(e),ap>0?ap:0).maxAddSizeUsd},aR=aF(ny),aD=aF(nw),aI=(0,C.isJupiterMarket)(_);(0,o.useEffect)(()=>{if(!aI||!tu)return;let e=async()=>{let e=await (0,P.fetchJupiterPoolInfo)(_);e&&it(e)};e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[_,aI,tu]);let aU=L.VENUE_UNDERWRITER_BYTE[sM],aO=se?.lastActionAt??"none",aB=st?.lastActionAt??"none",az=`${_}|${ad}|${nf}|${r5}|${aU}|${aO}|${aB}|${t9}`,a$=(0,o.useRef)(null),[aV,aH]=(0,o.useState)(0),aW=sA?sI(e8.symbol):void 0,[aq,aK]=(0,o.useState)(0);(0,o.useEffect)(()=>(0,G.subscribeGmTradeRegistry)(()=>aK(e=>e+1)),[]);let aG=(0,o.useMemo)(()=>
2{if(!sA)return;let e=(0,G.resolveGmTradeMarket)(e8.symbol);return!e||(0,G.getGmTradeCollateralMintForSide)(e,"long").toBase58()!==G.GMTRADE_USDC_MINT_STR},[sA,e8.symbol,aq]);(0,o.useEffect)(()=>{let e;if(!nY||!am){ii(null),ia(null),ih(null),im(null);return}let t=a$.current?.signature===az?a$.current.preview:null,r=t&&2===aU&&(e=t.long?.fee??t.short?.fee)&&null!=e.phoenixTakerFeeBps&&null!=e.phoenixMakerFeeBps?{takerBps:e.phoenixTakerFeeBps,makerBps:e.phoenixMakerFeeBps}:null,i="limit"===t9?"limit":"market",s=(0,T.computeLocalPreview)({collateralUsd:ad,leverage:nf,marketPrice:e9,underwriter:aU,poolInfo:ie,existingLongSizeUsd:se?.sizeUsd?parseFloat(se.sizeUsd):void 0,existingLongOpenTime:se?.lastActionAt,existingShortSizeUsd:st?.sizeUsd?parseFloat(st.sizeUsd):void 0,existingShortOpenTime:st?.lastActionAt,gmTradeFees:aW,gmTradeLongRequiresSwap:aG,orderType:i,phoenixLiveFees:r,wallet:nY?.toBase58(),openFeeRate:sV?.open,closeFeeRate:sV?.close,hasCollateralSwap:sV?.hasCollateralSwap,borrowRateHourlyPct:sV?.borrowRateHourlyPct});ii(t?.long?.quote??s?.long?.quote??null),ia(t?.short?.quote??s?.short?.quote??null),ih(t?.long?.fee??s?.long?.fee??null),im(t?.short?.fee??s?.short?.fee??null)},[nY,ad,nf,am,e9,aU,ie,se,st,az,aV,aW,aG,t9,sV]);let aY=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(iF.current&&clearTimeout(iF.current),aY.current?.abort(),!nY||!am||0!==aU&&2!==aU){a$.current=null;return}if(!tu)return;a$.current&&a$.current.signature!==az&&(a$.current=null);let e=new AbortController;aY.current=e;let t=0,r=!1,i=async()=>{if(r)return;r=!0;let i=++t,s={walletAddress:nY.toBase58(),marketMint:_,collateralUsd:ad,leverage:nf,slippageBps:r5,underwriter:aU,marketPrice:e9,existingLongSizeUsd:se?.sizeUsd?parseFloat(se.sizeUsd):void 0,existingLongOpenTime:se?.lastActionAt,existingShortSizeUsd:st?.sizeUsd?parseFloat(st.sizeUsd):void 0,existingShortOpenTime:st?.lastActionAt,orderType:"limit"===t9?"limit":"market"};try{let r=await (0,P.fetchTradePreview)(s,e.signal).catch(e=>(e?.name,null));if(e.signal.aborted||!r||i!==t)return;a$.current={signature:az,preview:r},aH(e=>e+1)}finally{r=!1}};iF.current=setTimeout(i,500);let s=setInterval(i,6e3);return()=>{iF.current&&clearTimeout(iF.current),clearInterval(s),e.abort()}},[nY,_,ad,nf,am,r5,aU,se,st,az,t9,tu]),(0,o.useEffect)(()=>()=>{aY.current?.abort()},[]),(0,o.useEffect)(()=>{if("limit"!==t9||!nY){io(null),ic(null);return}let e=rB&&a_?a_:parseFloat(rU)||0;if(e<=0||!am){io(null),ic(null);return}let t=rB||!e9||e<=e9,r=rB||!e9||e>=e9;if(t||io(null),r||ic(null),!t&&!r)return;let i=ad*nf,s=t=>{let{priceUsd:r}=(0,j.estimateLiqPrice)({venue:sM,isLong:t,entryPrice:e,sizeUsd:i,collateralUsd:ad}),s=i*(sV?.open??6e-4);return{entryPriceUsd:e.toString(),leverage:nf.toString(),liquidationPriceUsd:null===r?"":r.toString(),openFeeUsd:s.toFixed(2),outstandingBorrowFeeUsd:"0",priceImpactFeeUsd:"0",priceImpactFeeBps:"0",positionCollateralSizeUsdAfterFees:(ad-s).toFixed(2),positionCollateralSizeUsdBeforeFees:ad.toString(),positionSizeUsd:i.toString(),positionSizeTokenAmount:(i/e).toString(),sizeUsdDelta:i.toString()}};io(t?s(!0):null),ic(r?s(!1):null)},[t9,rU,ad,nf,am,nY,_,e9,e7,rB,sV]);let aX=(tw=parseFloat(rU)||0)>0?tw:e9??0;(0,o.useEffect)(()=>{rf.current||rh(tR(parseFloat(rd)||0,rp,aX))},[rd,rp,aX]);let aQ=i7?"size":r_,aJ=()=>{rL(null),rR("")},aZ=async()=>{if(!ar()||!rE)return;let e=parseFloat(rF)||0;if(e<=0||rD)return;let t="add"===rE;if(t&&null!==n7&&(0,eA.isCollateralInsufficient)(e,n7)||!t&&(null===ag||e>ag))return;let r=t&&null!==n7?(0,eA.clampCollateral)(e,n7):e;rI(!0);try{if(t&&s_&&!await a9())return void X.toast.error(t0("phoenixActivateFailed"));if(!ar())return;if(t){let e=await an(r,!1,null);if(null===e)return;r=e}if(!ar())return;let e=t?iq:iK;if(!await av({requestedUsd:r,cancelled:()=>!ar(),readMargin:ax&&!t&&nY&&null!=i0?()=>(0,e1.fetchSunriseMargin)(nY.toBase58(),i0,null):void 0,submit:()=>ar()?e({positionPubkey:ax||t?void 0:nZ?.traderAccount,marketMint:_,side:ro?"long":"short",collateralAmount:r,underwriter:ax?"sunrise":"phoenix",sunriseMarginMode:ax?"cross":void 0,profileIndex:i0??void 0,currentPrice:e9??0}):Promise.resolve(null)}))return;X.toast.success(t?t0("marginAdded",{amount:`$${t6.number(r)}`}):t0("marginRemoved",{amount:`$${t6.number(r)}`})),aJ(),ax?n2():n0(),tl?.()}catch(e){(0,Q.isUserRejection)(e)||(console.error("[margin] seat edit failed",e),X.toast.error(ax?(0,J.displayClientError)(e):(0,Z.chainActionError)(e,t?t0("marginAddFailed"):t0("marginRemoveFailed"),"passthrough")))}finally{rI(!1)}},a0=e=>{let t=parseFloat(rd)||0,r=parseFloat(rC)||0;if(e<=0)return{sizeUsd:t,collateralUsd:r};if(i7){let r=nm>0?t/nm:0,i=r*Math.min(e,np);return rc(i>0?i.toFixed(2):""),rh(i>0?tR(i,rp,aX):""),{sizeUsd:i,collateralUsd:r}}let i=r*e;return rc(i>0?i.toFixed(2):""),{sizeUsd:i,collateralUsd:r}},a1=(e,t="input")=>{rv();let r=(0,eF.sanitizeDecimalInput)(e,t8);rM(r),al.current={value:r,balanceAtSet:n3,source:t,time:Date.now()};let i=(parseFloat(r)||0)*rV;rc(i>
20?i.toFixed(2):"")};(0,s.useLeverageCapSync)({leverageKey:r$,leverage:rV,maxLeverage:np,capKnown:s1.length>0&&void 0!==s0(sM)&&(!s_||Number.isFinite(sz?.maxLeverage)&&(sz?.maxLeverage??0)>0),onClamp:e=>{fetch("/api/log-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"leverage_change",source:"clamp_effect",prev:rV,next:e,delta:rV-e,maxLeverage:np,marketMint:_,compact:tc??!1})}).catch(()=>{}),rH(e);try{localStorage.setItem(r$,String(e))}catch{}a0(e)}}),(0,o.useEffect)(()=>{if(r1.current)return;let e=se??st,t=e?.leverageX??e?.maxLeverageX,r=null!=t?parseFloat(t):NaN;if(!isFinite(r)||r<eU.LEVERAGE_MIN)return;let i=Math.min(Math.round(r),np),s=`${_}:${i}`;r2.current!==s&&(r2.current=s,rH(i),a0(i))},[se,st,_,np,rC]);let a2=(e,t)=>{r1.current=!0,rH(e),e!==rV&&rJ.current&&(0,eb.popValue)(rJ.current);try{localStorage.setItem(r$,String(e))}catch{}let r=a0(e);fetch("/api/log-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"leverage_change",source:t??"unknown",prev:rV,next:e,delta:Math.abs(e-rV),maxLeverage:np,collateral:r.collateralUsd,size:r.sizeUsd,marketMint:_,popoverOpen:!1,compact:tc??!1})}).catch(()=>{})},a5=e=>(0,eL.minimumOrderCollateral)({minimumUsd:10,isUnifiedMargin:i7,side:e,asset:e8.symbol,profileIndex:i0,positions:sn}),a3=a5(re),a4=ie?.longAvailableLiquidity?parseFloat(ie.longAvailableLiquidity):null,a6=ie?.shortAvailableLiquidity?parseFloat(ie.shortAvailableLiquidity):null,a8=nE.length>0,a9=async()=>{if("phoenix"!==sM||null===i0||!nY)return!0;let e=`phoenix_registered_${nY.toBase58()}_${i0}`;if("1"===localStorage.getItem(e))return!0;let t=await ss(i0);if(t&&1)try{localStorage.setItem(e,"1")}catch{}return t},a7=(0,o.useCallback)((e,t)=>{if(!s_||"market"!==t9||!te)return null;let r=e7??e9;return r?(0,eH.quotePhoenixMarketOrder)(te.asks,te.bids,e,r,t,r5,tt,tn):null},[s_,t9,te,tt,tn,e7,e9,r5]),{book:le,receivedAtMs:lt}=(0,e2.useSunriseOrderbook)(e8.symbol,sM),lr=(0,o.useCallback)((e,t)=>"armada"===sM&&"market"===t9?(0,e5.quoteSunriseMarketOrder)(le,e,t,r5,lt):null,[sM,t9,le,r5,lt]),li=(0,o.useCallback)((e,t)=>"armada"===sM&&"market"===t9?lr(e,t)?.fillPrice:s_&&"market"===t9?a7(e,t)?.fillPrice:e9,[sM,s_,t9,lr,a7,e9]),ls=()=>{let e=parseFloat(rC)||0,t=null!==n7?(0,eA.clampCollateral)(e,n7):e,r=i7?1/0:t>0&&isFinite(np)?t*np:1/0,i=Math.min(parseFloat(rd)||0,r),s=rB&&a_?a_:parseFloat(rU)||0,n=i7?(null!==n7?(0,eA.clampCollateral)(ap,n7):ap)+(ah-au):t;return{collateralNum:t,sizeNum:i,limitPriceValue:s,submitCollateral:n}},ln=(0,o.useRef)(!1),la=(0,o.useRef)(async()=>{}),ll=async e=>{if(!ln.current&&ar()){ln.current=!0;try{let t;if(nY&&tj(nY.toBase58(),i0)){let r=await dg(e);if(!r)return;t=r}if(!ar())return;await la.current(e,t)}finally{ln.current=!1}}},lo=async(e,t)=>{let r=()=>{if(!ar())return!1;if(!t)return!0;let e=rn.current;return!!tN(t,e.intentKey)&&!!e.quoteAvailable||(X.toast.error(t4("changed")),!1)};if(!r())return;let i=Date.now();rv();let{collateralNum:s,limitPriceValue:l,submitCollateral:o,sizeNum:d}=ls(),c=d;if(c<=0||!e9||sE||!i7&&s<=0||s<a5(e?"long":"short"))return;if(s_&&"market"===t9&&!a7(c,e))return void X.toast.error(t0("phoenixExecutableQuoteUnavailable"));if(!await a9())return void X.toast.error(t0("phoenixActivateFailed"));if(!r())return;(0,eP.gtagEvent)("open_position_submit",{side:e?"long":"short",order_type:t9,size_usd:c,collateral_usd:s,leverage:rV,mode:"passthrough",value:c,currency:"USD"}),sF({order_type:t9,side:e?"long":"short",size_usd:c,collateral_usd:s});let u=oW(e,c,l),h=nE.map(t=>{if(("tp"===t.type||"sl"===t.type)&&void 0!==t.triggerPercent){let r=u*(1+((0,ep.mustBeAbove)(t.type,e)?1:-1)*t.triggerPercent/100);return{...t,triggerPrice:r}}return t});if(a8){let t=oq(e,c,l),{armsAtEntry:r}=t,i=t.triggerBasis??0,s=r?t0("basisEntryPrice"):t0("basisCurrentPrice");if(!(i>0))return void X.toast.error(t0("tpSlNeedsEntryPrice"));let o=oE("limit"===t9?e?il:id:e?ir:is,e?se:st,"limit"===t9?l:li(c,e),e,c,af);for(let t of h){if("sl"===t.type){let r=(0,n.stopLossLiquidationError)(e,t.triggerPrice,o);if(r)return void X.toast.error((0,a.tradingValidationError)(r))}if(("tp"===t.type||"sl"===t.type)&&!(t.triggerPrice>0))return void X.toast.error("tp"===t.type?t0("invalidTakeProfitPercent"):t0("invalidStopLossPercent"));if(("tp"===t.type||"sl"===t.type)&&!(0,ep.onRightSide)(t.type,t.triggerPrice,i,e))return void X.toast.error(t0("tp"===t.type?e?"tpAboveForLongs":"tpBelowForShorts":e?"slBelowForLongs":"slAboveForShorts",{basis:s}))}}if("limit"===t9&&l<=0)return;if(s_&&"market"===t9&&!a7(c,e))return void X.toast.error(t0("phoenixExecutableQuoteUnavailable"));if(!r())return;let p=await an(o,"limit"===t9&&nU,{clickedAt:i,stillValid:t=>i7?t>=o:t>=a5(e?"long":"short")});if(null!==p&&r()){if(t&&p<o)return void X.toast.error(t4("fundingChanged"));
2if(!i7&&p<o&&(c=c*p/o),"limit"===t9)if(await iB({marketMint:_,side:e?"long":"short",sizeUsd:c,collateralAmount:p,leverage:nm,triggerPrice:l,closeOrders:a8?h:void 0,deferFunding:nU||void 0,underwriter:sM,loanLeg:lV(e?"long":"short")})){t&&nY&&null!==i0&&tS(nY.toBase58(),i0),(0,eP.gtagEvent)("open_position_success",{side:e?"long":"short",order_type:"limit",size_usd:c,mode:"passthrough",value:c,currency:"USD"});let r=iY();r&&r.length>0?rb("partialTpSl"):(nI(),rP(e?"long":"short","order")),rM(""),rc(""),tl?.()}else rT();else{let r=a7(c,e);if(s_&&!r)return void X.toast.error(t0("phoenixExecutableQuoteUnavailable"));if(r?.exceedsAutoWiden)return void X.toast.error(t0("bookTooFarToFill",{symbol:e8.symbol,gap:t6.number(Math.abs(r.fillVsIndexBps)/100),direction:r.fillVsIndexBps<0?"below":"above"}));let i=lr(c,e);if("armada"===sM&&!i)return void X.toast.error(t0("sunriseExecutableQuoteUnavailable"));let n=await iO({marketMint:_,side:e?"long":"short",sizeUsd:c,collateralAmount:p,currentPrice:i?.fillPrice??r?.fillPrice??e9,slippageBps:i?.slippageBps??r?.slippageBps??r5,underwriter:sM,assetSymbol:e8.symbol,loanLeg:lV(e?"long":"short"),closeOrders:a8?h:void 0,preloadedData:{protocolFeeRecipient:s5.protocolFeeRecipient??void 0,feeSettings:s5.feeSettings??void 0,userAccountExists:s5.userAccountExists,userFundingAtaExists:s5.userFundingAtaExists,protocolFeeAtaExists:s5.protocolFeeAtaExists,projectAlt:s5.projectAlt??void 0,walletCollateralBalance:s5.walletCollateralBalance}});if(n){t&&nY&&null!==i0&&tS(nY.toBase58(),i0),(0,eP.gtagEvent)("open_position_success",{side:e?"long":"short",order_type:t9,size_usd:c,mode:"passthrough",value:c,currency:"USD"}),(0,I.setSavedLeverage)(e8.symbol,rV),(0,I.setSavedSize)(e8.symbol,c),nY&&nJ({id:n,market:(0,et.pendingMarketKey)(_),marketId:_,owner:nY,type:(e?sr:si)?"increasing":"opening",isLong:e,size:c,collateral:s,timestamp:Date.now(),status:"pending",venue:sM,settledAtSubmit:(0,L.settlesSynchronously)(sM),asset:e8.symbol,profileIndex:i0??0,loanSlTriggerPriceUsd:nH(e?"long":"short",e9,c,s)?.toString()});let r=iY();r&&r.length>0?rb("partialTpSl"):(nI(),rP(e?"long":"short","position")),rM(""),rc(""),"armada"===sM&&n6(),tl?.()}else rT()}}},ld=()=>!!sE&&(X.toast.error(sL),!0),lc=async(e,t)=>{if(!ar())return null;let r=await an(e.collateralAmount,!!e.deferFunding,{clickedAt:t,stillValid:t=>i7?t>=e.collateralAmount:t>=a5(e.side)});if(null===r||!ar())return null;if(r>=e.collateralAmount)return e;let i=i7||null==e.sizeUsd?e.sizeUsd:e.sizeUsd*r/e.collateralAmount;return{...e,collateralAmount:r,sizeUsd:i}},lu=async e=>{let t=Date.now();if(ld())return!1;let r=await lc(e,t);if(!r||!ar())return!1;let i=r.sizeUsd??r.collateralAmount*r.leverage;(0,eP.gtagEvent)("open_order_submit",{order_type:"ratchet_entry",side:r.side,size_usd:i,collateral_usd:r.collateralAmount,value:i,currency:"USD"}),sF({order_type:"ratchet_entry",side:r.side,size_usd:i,collateral_usd:r.collateralAmount});let s=await iz({...r,underwriter:sM,loanLeg:lV(r.side)});return s&&((0,eP.gtagEvent)("open_order_success",{order_type:"ratchet_entry",side:r.side,size_usd:i,value:i,currency:"USD"}),tl?.(),rN(r.side,"order")),!!s},lh=async e=>{let t=Date.now();if(ld())return!1;let r=await lc(e,t);if(!r||!ar())return!1;let i=r.sizeUsd??r.collateralAmount*r.leverage;(0,eP.gtagEvent)("open_order_submit",{order_type:"indicator",side:r.side,size_usd:i,collateral_usd:r.collateralAmount,value:i,currency:"USD"}),sF({order_type:"indicator",side:r.side,size_usd:i,collateral_usd:r.collateralAmount});let s=await i$({...r,underwriter:sM,loanLeg:lV(r.side)});return s&&((0,eP.gtagEvent)("open_order_success",{order_type:"indicator",side:r.side,size_usd:i,value:i,currency:"USD"}),tl?.(),rN(r.side,"order")),!!s},lp=async e=>{let t=Date.now();if(ld())return!1;let r=await lc(e,t);if(!r||!ar())return!1;let i=r.sizeUsd??r.collateralAmount*r.leverage;(0,eP.gtagEvent)("open_order_submit",{order_type:"dca",side:r.side,size_usd:i,collateral_usd:r.collateralAmount,value:i,currency:"USD"}),sF({order_type:"dca",side:r.side,size_usd:i,collateral_usd:r.collateralAmount});let s=await iV({...r,underwriter:sM,loanLeg:lV(r.side)});return s&&((0,eP.gtagEvent)("open_order_success",{order_type:"dca",side:r.side,size_usd:i,value:i,currency:"USD"}),tl?.(),rN(r.side,"order")),!!s},lm=async e=>{let t=Date.now();if(ld())return!1;let r=await lc(e,t);if(!r||!ar())return!1;let i=r.sizeUsd??r.collateralAmount*r.leverage;(0,eP.gtagEvent)("open_order_submit",{order_type:"dca_time",side:r.side,size_usd:i,collateral_usd:r.collateralAmount,value:i,currency:"USD"}),sF({order_type:"dca_time",side:r.side,size_usd:i,collateral_usd:r.collateralAmount});let s=await iH({...r,underwriter:sM,loanLeg:lV(r.side)});return s&&((0,eP.gtagEvent)("open_order_success",{order_type:"dca_time",side:r.side,size_usd:i,value:i,currency:"USD"}),tl?.(),rN(r.side,"order")),!!s},lf=async e=>{let t=Date.now();if(ld())return!1;let r=await lc(e,t);if(!r||!ar())return!1;let i=r.sizeUsd??r.collateralAmount*r.leverage;(0,eP.gtagEvent)("open_order_submit",{order_type:"dca_ratchet",side:r.side,size_usd:i,collateral_usd:r.collateralAmount,value:i,currency:"USD"}),sF({order_type:"dca_ratchet",side:r.side,size_usd:i,collateral_usd:r.collateralAmount});let s=await iW({...r,underwriter:sM,loanLeg:lV(r.side)});return s&&((0,eP.gtagEvent)("open_order_success",{order_type:"dca_ratchet",side:r.side,size_usd:i,value:i,currency:"USD"}),tl?.(),rN(r.side,"order")),!!s},lx=rB&&a_?a_:parseFloat(rU)||0,lg="limit"===t9&&lx>0&&e9,lb=ad>0&&ad<a3,lv=null!==n7&&(0,eA.isCollateralInsufficient)(ap,n7),ly=!!nY&&lv,lw=nQ?t0("getDepositAddress"):t0("depositToTrade");!i7&&lv&&ad>0&&null!==n3&&1>Math.abs(ad-n3)&&console.warn("[collateral-debug] insufficient balance triggered near boundary",{collateral:rC,collateralNum:ad,usdcBalance:n3,diff:ad-n3,displayedBalance:Math.round(100*n3)/100,collateralSetEvent:al.current,balanceHistory:aa.current.slice()});let lj=sn.filter(e=>e.profileIndex===i0&&"open"===e.status).length>0,lS=lv&&lj&&"market"!==t9,lk=nU||"armada"===sM&&"market"!==t9?0:Math.max(0,ap-(n8??0)),lN=(0,o.useMemo)(()=>null===n3||null===i0?[]:(0,eE.ordersStrandedBySpend)(sl,i0,n3,lk),[sl,i0,n3,lk]);(0,o.useEffect)(()=>{lS||nO(!1)},[lS]);let lP=iu?parseFloat(iu.interestUsd):0,lT=ip?parseFloat(ip.interestUsd):0,lC=sr&&ad>0&&ad<Math.max(0,lP),lM=si&&ad>
20&&ad<Math.max(0,lT),l_=parseFloat(rd)||0,lA=se?.sizeUsd?parseFloat(se.sizeUsd):0,lE=st?.sizeUsd?parseFloat(st.sizeUsd):0,lL=lA+l_,lF=lE+l_,lR=sA?sU(e8.symbol):void 0,lD=lR?.longAvailableUsd??null,lI=lR?.shortAvailableUsd??null,lU=l_*("market"===t9?1:1.2),lO="dca"!==t9&&"trailing"!==t9&&"indicator"!==t9,lB=(e,t)=>{var r;let i,s,n;if(!e||!sz||!lO||!(l_>0)||!sy)return 0;let a=sy.perMarket.find(e=>e.symbol===e8.symbol);if(!a||!a.enabled)return 0;let l={maxLeverage:sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},o=ad>0?ad:0,d=aE(e),c={...e.pos,collateralUsd:e.pos.seatCollateralUsd},u=(0,eH.computePhoenixAddHeadroom)(c,l,d,o),h=l_<=u.maxAddSizeUsd;if(h&&!(e.pos.borrowedPrincipalUsd>0))return 0;let p=0;if(!h){let e={maxLeverage:.98*sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro};if((p=(0,eH.computePhoenixMinLoanForAdd)(c,e,d,o,l_))<=0)return 0}let m=s3/1e6*l_,f=e.pos.collateralUsd+Math.max(0,o-m);if(!(f>0))return 0;let x=u.currentNotionalUsd+l_,g=(a.maxLeverageMicro??0)/1e6;if(g>0&&x/f>g)return 0;let b=Math.max(0,e.pos.borrowedPrincipalUsd)+Math.max(0,e.pos.accruedInterestUsd),v=Math.max(p,(r=u.currentNotionalUsd,i=e.pos.loanOriginationNotionalUsd>0?e.pos.loanOriginationNotionalUsd:r,n=Math.max(0,i*(s=(0,U.minLoanBpsFor)(a,"phoenix")/1e4)-Math.max(0,e.pos.borrowedPrincipalUsd)),l_*s+n));return v<=0?0:v<=(0,U.maxLoanForMarket)(sy,a,f,b)?v:0},lz=(0,o.useMemo)(()=>lB(ny,"long"),[ny,l_,ad,t9,s_,sz,s3,e8.symbol,_,i0,sM,sy,sn,aA]),l$=(0,o.useMemo)(()=>lB(nw,"short"),[nw,l_,ad,t9,s_,sz,s3,e8.symbol,_,i0,sM,sy,sn,aA]),lV=e=>{if(i7)return;let t="long"===e?lz:l$;return t>0?{loanAmountUsd:t}:nV(e)},lH=(()=>
2{if(n$&&(void 0!==nV("long")||void 0!==nV("short")))return nW({loanUsd:n$.loanAmountUsd,ourRateBps:n$.ourRateBps,isReach:"reach"===n$.mode,venueLeverage:n$.venueLeverage,whyLine:"reach"===n$.mode?t0("loanWhyReach"):t0("loanWhySaferLiq")});let e=lz>0?"long":l$>0?"short":null;if(!e||!sy)return null;let t="long"===e?lz:l$,r="long"===e?ny:nw,i=sy.perMarket.find(e=>e.symbol===e8.symbol);if(!r||!i)return null;let s=(0,U.liveBucketRateBps)(sy,i,e),n=aE(r),a=ad>0?ad:0,l=r.pos.sizeUsd*n/r.pos.entryPrice+l_,o=(0,eW.blendedEntryPrice)(r.pos,n,l_)??n,d=(0,U.loanSlTriggerPriceUsd)({isLong:"long"===e,entryPrice:o,ownedCollateralUsd:r.pos.collateralUsd+a,notionalUsd:l,premiumBps:sR}),c="long"===e?aR:aD;return nW({loanUsd:t,ourRateBps:s,isReach:!1,whyLine:null!==c&&l_<=c?t0("loanWhyFloor"):t0("loanWhyTopUp"),loanSlLiq:d})})(),lW=lO&&l_>0&&null!==aR&&l_>aR&&lz<=0,lq=lO&&l_>0&&null!==aD&&l_>aD&&l$<=0,lK=(e,t)=>{if(!e||!lO||!(l_>0)||t>0||!(e.pos.borrowedPrincipalUsd>0))return!1;let r=sy?.perMarket.find(e=>e.symbol===e8.symbol);if(!r)return!1;let i=e.pos.sizeUsd*aE(e)/e.pos.entryPrice;return Math.max(0,((e.pos.loanOriginationNotionalUsd>0?e.pos.loanOriginationNotionalUsd:i)+l_)*((0,U.minLoanBpsFor)(r,"phoenix")/1e4)-Math.max(0,e.pos.borrowedPrincipalUsd))>0},lG=!lW&&lK(ny,lz),lY=!lq&&lK(nw,l$),lX=e=>{if(!e||!sz||!(l_>0))return null;let t={...e.pos,collateralUsd:e.pos.seatCollateralUsd},r=(0,eH.computePhoenixMinLoanForAdd)(t,{maxLeverage:sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},aE(e),ad>0?ad:0,l_);return r>0?Math.ceil(1.02*r*100)/100:null},lQ=lX(ny),lJ=lX(nw),lZ=l_>0&&("jupiter"===sM&&null!==a4&&lL>a4||s_&&null!==ng&&lL>ng||sA&&null!==lD&&(lU>lD||lD<500)),l0=l_>0&&("jupiter"===sM&&null!==a6&&lF>a6||s_&&null!==ng&&lF>ng||sA&&null!==lI&&(lU>lI||lI<500)),l1=!lg||rB||lx<=e9,l2=!lg||rB||lx>=e9,l5=[];"number"==typeof s$&&s$>0&&l5.push("phoenix"),"number"==typeof sH&&sH>0&&l5.push("gmtrade"),"number"==typeof sQ&&sQ>0&&l5.push("jupiter"),sG&&(0,e3.sunriseListsSymbol)(e8.symbol)&&l5.push("armada");let l3=l5.length>0&&l5.every(e=>i2.includes(e)),l4=l5.filter(e=>!B.OPENS_PAUSED_VENUES.has(e)),l6=a7(l_,ro),l8=s_&&"market"===t9,l9=lr(l_,ro),l7="armada"===sM&&"market"===t9,oe=l7?l9?.fillPrice:l8?l6?.fillPrice:e9,ot=l7?!l9&&l_>0?t0("sunriseExecutableQuoteUnavailable"):null:l8&&!l6&&l_>0?t0("phoenixExecutableQuoteUnavailable"):l6&&Math.abs(l6.fillVsIndexBps)>=50?t0("bookTradingVsIndex",{gap:t6.number(Math.abs(l6.fillVsIndexBps)/100),direction:l6.fillVsIndexBps<0?"under":"over"}):null,or=i7?(i3?.venues??[]).includes(sM)?s_&&sz?.isolatedOnly?t0("isolatedOnlyOnPhoenix",{symbol:e8.symbol}):null:t0("unifiedVenueUnavailable"):null,oi=(0,eQ.pickMissingLabel)([[sE,sL],[!!or,or??""],[i7?ao<=0:ad<=0,"size"===aQ?t0("setSize"):t0("setCollateral")],[i7&&lv,t0("addMargin")],["limit"===t9&&lx<=0,t0("setLimitPrice")],[l3,t0("allowedVenuesUnsupported")]]),os=ro?l1:l2,on=ro?sr:si,oa=ro?lC:lM,ol=ro?lZ:l0,oo=ro?lW:lq,od=ro?lG:lY,oc=os&&!iZ&&null===oi&&!lb&&!(lv&&!nU)&&!oa&&!ol&&!oo&&!od&&(!l7||null!==l9)&&(!l8||null!==l6),ou=ro?t0("mustBeBelowMarket"):t0("mustBeAboveMarket"),oh="market"===t9||"limit"===t9,op=oh&&(sr||si),om=ra&&op,of=ro?st:se,[ox,og]=(0,o.useState)(null),[ob,ov]=(0,o.useState)(null),[oy,ow]=(0,o.useState)(null),oj=(0,o.useRef)(null);(0,o.useEffect)(()=>{let e=oj.current;e&&0!==e.scrollTop&&e.scrollTo({top:0})},[t9,tu]);let oS=(0,o.useRef)(0),ok=(0,o.useCallback)(()=>{oS.current||(oS.current=requestAnimationFrame(()=>{oS.current=0;let e=oj.current;if(!e)return;let t=e.scrollTop+e.clientHeight<e.scrollHeight-1;t!==e.hasAttribute("data-scroll-more")&&(t?e.setAttribute("data-scroll-more",""):e.removeAttribute("data-scroll-more"))}))},[]);(0,o.useEffect)(()=>{if(!tc)return;let e=oj.current;if(!e)return;ok();let t=new ResizeObserver(ok);for(let r of(t.observe(e),e.children))t.observe(r);return()=>{t.disconnect(),cancelAnimationFrame(oS.current),oS.current=0}},[tc,t9,tu,ok]);let oN=e=>{a2(Math.max(eU.LEVERAGE_MIN,Math.min(np,Math.round(rV)+e)),"hotkey_step")},oP=(s_?ng:sA?ro?lD:lI:ro?a4:a6)??0,oT=e=>{if(i7||null===n7||n7<=0)return;let t=Math.floor(n7*e+1e-7)/100;a1(t>0?t.toFixed(2):"","preset")},oC=!i7&&null!==n7&&n7>0;(0,eJ.useHotkey)("side-long",()=>rt("long"),tp),(0,eJ.useHotkey)("side-short",()=>rt("short"),tp),(0,eJ.useHotkey)("order-type-market",()=>{t7("market"),nz(!1)},tp),(0,eJ.useHotkey)("order-type-limit",()=>{t7("limit"),nz(!1)},tp),(0,eJ.useHotkey)("size-preset-25",()=>oT(25),tp&&oh),(0,eJ.useHotkey)("size-preset-50",()=>oT(50),tp&&oh),(0,eJ.useHotkey)("size-preset-75",()=>oT(75),tp&&oh),(0,eJ.useHotkey)("size-preset-100",()=>oT(100),tp&&oh),(0,eJ.useHotkey)("leverage-down",()=>oN(-1),tp&&!i7&&np>eU.LEVERAGE_MIN),(0,eJ.useHotkey)("leverage-up",()=>oN(1),tp&&!i7&&np>eU.LEVERAGE_MIN),(0,eJ.useHotkey)("focus-size",()=>{rx.current?.focus(),rx.current?.select()},tp&&oh),(0,eJ.useHotkey)("submit-order",()=>{nY?oc&&ll(ro):(0,eC.promptConnectWallet)()},tp&&oh&&!om);let oM=nE.find(e=>"sl"===e.type),o_=[50,100,200,500],oA=(e,t,r,i)=>{let s=i>0?i:parseFloat(e?.sizeUsdDelta??"0"),n=(0,eW.blendedEntryPrice)(t,r,s);return null===n?null:n.toString()},oE=(e,t,r,i,s,n,a=!1)=>
2{if("armada"===sM){let l=sW?.find(e=>e.symbol===e8.symbol)?.liquidation;if(!l||!r)return null;if(n1?.primeBound||Number(t?.borrowedCollateralUsd??0)>0)return t?.liquidationPrice??null;if(i7&&n1?.openPositions!==0)return e?.liquidationPriceUsd||t?.liquidationPrice||null;let o=a?0:nV(i?"long":"short")?.loanAmountUsd??0;if(o>0&&!na)return null;let d=Number(t?.sizeUsd??0),c=d>0?n1?.maintenanceMarginBps:l.maintenanceMarginBps;if(null==c)return null;let u=Number(t?.collateralUsd??0),h=Number(t?.totalFeesUsd??0),p=(0,eW.blendedEntryPrice)(t,r,s),{priceUsd:m}=(0,S.estimateArmadaLiq)({isLong:i,entryPrice:p??r,sizeUsd:d+s,collateralUsd:i7?(n1?.effectiveCollateralUsd??NaN)+ap:u+n+o,debtUsd:o,feesUsd:h+s*l.fee1e6/1e6,maintenanceMarginBps:c,reserveBps:o>0?na?.gminBps??l.reserveCapBps:l.reserveCapBps});return m?.toString()??null}if(!a){let e=nH(i?"long":"short",r,s,n);if(null!==e)return e.toString()}if(!e||!r)return e?.liquidationPriceUsd??null;let l=s_&&sz&&sz.maxLeverage>0;if(!t?.sizeUsd||!t?.collateralUsd||!t?.entryPrice){if(l&&s>0&&n>0){let e=(0,eH.computePhoenixLiquidationPrice)({side:i?"long":"short",sizeUsd:s,entryPrice:r,collateralUsd:n},{maxLeverage:sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},r);if(null!==e)return e.toString()}return e.liquidationPriceUsd}let o=parseFloat(t.sizeUsd),d=parseFloat(t.collateralUsd),c=parseFloat(t.totalFeesUsd||"0"),u=s>0?s:parseFloat(e.sizeUsdDelta),h=n>0?n:parseFloat("positionCollateralSizeUsdAfterFees"in e?e.positionCollateralSizeUsdAfterFees:e.positionCollateralSizeUsd)-d;if(u<=0||h<=0)return e.liquidationPriceUsd;let p=o+u,m=d+h,f=(0,eW.blendedEntryPrice)(t,r,u)??r;if(l&&p>0&&m>0&&f>0){let e=(0,eH.computePhoenixLiquidationPrice)({side:i?"long":"short",sizeUsd:p,entryPrice:f,collateralUsd:m},{maxLeverage:sz.maxLeverage,takerFeeMicro:sz.takerFeeMicro},f);if(null!==e)return e.toString()}let{priceUsd:x}=(0,j.estimateLiqPrice)({venue:sM,isLong:i,entryPrice:f,sizeUsd:p,collateralUsd:m,accruedFeesUsd:c});return null===x?null:x.toString()},oL=e=>{if(null==e||""===e)return"—";let t=parseFloat(e);return!Number.isFinite(t)||t<=0?"—":`$${t6.number(t)}`},oF="armada"!==sM&&n$?.mode==="safer-liq",oR=oF&&null!==nH("long",e9,l_,ad),oD=oF&&null!==nH("short",e9,l_,ad),oI=ro?ir:is,oU=ro?il:id,oO=ro?se:st,oB=ro?iu:ip,oz=ro?oR:oD,o$=ro?"text-side-long":"text-side-short",oV="font-mono font-semibold tabular-nums text-secondary-foreground",oH=ro?"text-side-long/85":"text-side-short/85",oW=(e,t,r)=>{let i=e?"limit"===t9?il:ir:"limit"===t9?id:is,s=e?se:st,n="limit"===t9?r:li(t,e);if(!n||n<=0)return 0;let a=oA(i,s,n,t);return a?parseFloat(a):n},oq=(e,t,r)=>{let i="limit"===t9&&!(e?se:st),s=i?oW(e,t,r)||r:e9;return{armsAtEntry:i,triggerBasis:s,awaitsLimitPrice:i&&"limit"===t9}},oK=oq(ro,l_,lx),oG=(()=>{if("limit"===t9)return lx>0?lx:null;let e=parseFloat(oA(oI,oO,oe,l_)??"0");return e>0?e:oe??null})(),oY=oB?parseFloat(oB.totalFeesUsd):0,oX="limit"===t9?os&&oU?oE(oU,oO,lx,ro,l_,af):null:oI?oE(oI,oO,oe,ro,l_,af):null,oQ=(0,t.jsx)("span",{className:oz?"text-sky-400 font-mono tabular-nums":oV,children:oL(oX)}),oJ=(0,N.shouldPublishEstLiq)({publishChartPreview:tm,active:tu,sizeUsd:l_})?(0,k.chartLinePrice)(oX):null,oZ=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!tm)return;let e=oZ.current??Date.now();oZ.current=e;let t=setTimeout(()=>{oZ.current=null,(0,N.setEstLiqPreview)(null===oJ?null:{market:_,price:oJ})},(0,N.publishDelayMs)(Date.now(),e));return()=>clearTimeout(t)},[oJ,_,tm]),(0,o.useEffect)(()=>{if(tm)return()=>(0,N.setEstLiqPreview)(null)},[tm]);let o0=(0,t.jsx)("span",{className:oV,children:t6.percent((l6?.slippageBps??r5)/100,1)}),o1=oF?(0,t.jsx)(ev.TooltipProvider,{children:(0,t.jsxs)(ev.Tooltip,{children:[(0,t.jsx)(ev.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{className:"cursor-help underline decoration-dotted underline-offset-2 decoration-leader-strong",children:oQ})}),(0,t.jsx)(ev.TooltipContent,{side:"top",className:"font-mono text-xs",children:(0,t.jsxs)("div",{className:"grid grid-cols-[auto_auto] gap-x-4 gap-y-1 whitespace-nowrap",children:[(0,t.jsx)("span",{}),(0,t.jsx)("span",{className:`text-right text-3xs ${o$}`,children:ro?t0("sideLong"):t0("sideShort")}),(0,t.jsx)("span",{className:"text-sky-400",children:t0("withLoan")}),(0,t.jsx)("span",{className:"text-right tabular-nums text-sky-400",children:(tU="limit"===t9?ro?il:id:ro?ir:is)&&("limit"!==t9||(ro?l1:l2))?oL(oE(tU,ro?se:st,"limit"===t9?lx:li(l_,ro),ro,l_,af)):"—"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("venueAlone")}),(0,t.jsx)("span",{className:"text-right tabular-nums text-muted-foreground",children:(tO="limit"===t9?ro?il:id:ro?ir:is)&&("limit"!==t9||(ro?l1:l2))?oL(oE(tO,ro?se:st,"limit"===t9?lx:li(l_,ro),ro,l_,af,!0)):"—"})]})})]})}):oQ,o2=(0,t.jsxs)("span",{className:oV,children:[oB?`$${t6.number(parseFloat(oB.borrowRateHourlyUsd))}`:"—",(0,t.jsx)("span",{className:"font-normal text-muted-foreground",children:"/hr"})]}),o5=n$&&(void 0!==nV("long")||void 0!==nV("short"))&&n$?(tz=(tB=n$.loanAmountUsd)<1e3?`$${t6.fixed(tB,2)}`:`$${t6.numberShort(tB)}
2`,t$=t6.fixed(n$.ourRateBps/100,1),tV=h.VENUE_LABELS[sM],(0,t.jsxs)("div",{className:"space-y-1 whitespace-nowrap",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-6",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("venueBorrow",{venue:tV})}),o2]}),(0,t.jsxs)("div",{className:"flex justify-between gap-6 border-t border-border pt-1",children:[(0,t.jsx)("span",{className:"text-sky-400",children:t0("loanInterest")}),(0,t.jsx)("span",{className:"text-sky-400 tabular-nums",children:t0("aprAndAmount",{apr:t$,amount:tz})})]})]})):null,o3=sS>0&&sf>0&&void 0!==ns&&s_&&isFinite(tH=ns*(1+sj/sf))&&tH>eU.LEVERAGE_MIN?tH:null,o4=nV("long")??nV("short"),o6=sS>0&&o4?Math.max(0,o4.loanAmountUsd-sj)*sS/1e4:0,o8=(()=>{if(!(o6>0)||!o4)return null;let e=sw?.pointsPerUsdCap!=null?parseFloat(sw.pointsPerUsdCap):NaN;if(!isFinite(e)||e<=0)return null;let t=Math.max(0,o4.loanAmountUsd-sj);return t>0?Math.ceil(t*e):null})(),o9=o6>0?(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)(ev.TooltipProvider,{children:(0,t.jsxs)(ev.Tooltip,{children:[(0,t.jsx)(ev.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{className:"text-amber-400 whitespace-nowrap cursor-help underline decoration-dotted underline-offset-2 decoration-amber-400/40",children:t0("leveragePremium")})}),(0,t.jsx)(ev.TooltipContent,{side:"top",className:"text-xs max-w-[15rem]",children:t0("leveragePremiumHelp")})]})}),(0,t.jsxs)("span",{className:"font-mono tabular-nums text-right",children:[(0,t.jsxs)("span",{className:"text-amber-400 whitespace-nowrap",children:["+$",t6.number(o6)]}),null!=o8&&(0,t.jsxs)("span",{className:"text-label-muted whitespace-nowrap",children:[" ",t0("pointsToWaive",{points:o8>=1e3?t6.numberShort(o8):o8})]})]})]}):null,o7=e=>null!==e&&parseFloat(e)>0?`$${t6.number(parseFloat(e))}`:"—",de=on?t0("blendedAvgEntry"):t0("estEntryPrice"),dt="limit"===t9?os&&oU?o7(oA(oU,oO,lx,l_)):"—":l7&&!l9?"—":oI||l6||l9?o7(oA(oI,oO,oe,l_)):"—",dr=e=>{let t=e?.estCloseFeeUsd!=null?parseFloat(e.estCloseFeeUsd):NaN;return Number.isFinite(t)?t:0},di=iu?parseFloat(iu.totalFeesUsd)+o6+dr(iu):null,ds=ip?parseFloat(ip.totalFeesUsd)+o6+dr(ip):null,dn=ro?di:ds,da=oB?.estCloseFeeUsd!=null?parseFloat(oB.estCloseFeeUsd):null,{sizeNum:dl,submitCollateral:dd}=ls(),dc=lV(re),du="limit"===t9?100:l9?.slippageBps??l6?.slippageBps??r5,dh=sy?.perMarket.find(e=>e.symbol===e8.symbol),dp=dc?n$?.ourRateBps??(sy&&dh?(0,U.liveBucketRateBps)(sy,dh,re):null):null,dm=tk({wallet:nY?.toBase58()??"",profile:i0,marketMint:_,executionIdentity:e,side:re,orderType:t9,active:tu,reduceOnly:ra,venue:sM,marginMode:i5,collateral:rC,size:rd,leverage:nm,submittedCollateral:dd,submittedSize:dl,limitPrice:"limit"===t9?lx:null,bboActive:rB,slippageBps:r5,effectiveSlippageBps:du,deferFunding:nU,closeOrderItems:nE,loan:dc,loanRateBps:dp,minimumCollateral:a3,maxLeverage:np}),df=!!nY&&null!==i0&&am&&null!==oG&&Number.isFinite(oG)&&oG>0&&null!==dn&&Number.isFinite(dn)&&("limit"===t9?null!==oU:!!(oI||l6||l9))&&("market"!==t9||!s_||!!l6&&!l6.exceedsAutoWiden)&&(!l7||null!==l9)&&(!l8||null!==l6);(0,o.useLayoutEffect)(()=>{rn.current={intentKey:dm,quoteAvailable:df},la.current=lo});let dx=e=>{let t=rs.current;!t||(!e||rr&&oc&&df&&rr.quoteAvailable&&tN(rr.intentKey,dm))&&(rs.current=null,ri(null),t(e?rr.intentKey:null))},dg=e=>{if(!nY||null===i0||e!==ro||rs.current)return Promise.resolve(null);let t=e=>`${t6.grouped(e,{maximumFractionDigits:6})}`,r=e=>null!==e&&Number.isFinite(e)&&e>0?`$${t(e)}`:t4("unavailable"),i=i6.find(e=>e.index===i0),s=[[t4("account"),i?.name||t4("accountNumber",{index:i0})],[t4("market"),`${e8.symbol}-PERP \xb7 ${t4(i7?"unified":"isolated")}`],[t4("direction"),t4(re)],[t4("orderType"),t4("limit"===t9?"limit":"marketOrder")],[t4("venue"),h.VENUE_LABELS[sM]],[t4(i7?"accountTopUp":"collateral"),`${t(dd)} USDC`],...i7?[]:[[t4("leverage"),`${t(nm)}\xd7`]],[t4("size"),`${t(dl)} USD`],[t4("minimumCollateral"),`${t(a3)} USDC`],[t4("entry"),r(oG)],[t4("liquidation"),r(null===oX?null:parseFloat(oX))],[t4("fee"),null!==dn?`$${t(dn)}`:t4("unavailable")],[t4("slippage"),t6.percent(du/100,2)]];if("limit"===t9&&s.push([t4("limitPrice"),r(lx)]),oB){let e=parseFloat(oB.borrowRateHourlyUsd);s.push([t4("hourlyCost"),Number.isFinite(e)?`$${t(e)}`:t4("unavailable")])}nU&&s.push([t4("funding"),t4("deferredFunding")]),dc&&(s.push([t4("loan"),`${t(dc.loanAmountUsd)} USDC`]),s.push([t4("loanApr"),null===dp?t4("unavailable"):t6.percent(dp/100,2)])),nE.length>0&&s.push([t4("closeSlippage"),t6.percent(3,1)]);let n={tp:t4("close.tp"),sl:t4("close.sl"),ratchet:t4("close.ratchet"),fib_ratchet:t4("close.fib_ratchet"),rsi:t4("close.rsi"),dca_close:t4("close.dca_close"),dca_time_close:t4("close.dca_time_close"),dca_ratchet_close:t4("close.dca_ratchet_close")},a={triggerPrice:t4("fields.triggerPrice"),triggerPercent:t4("fields.triggerPercent"),sizePercent:t4("fields.sizePercent"),worstPrice:t4("fields.worstPrice"),ratchetSize:t4("fields.ratchetSize"),reverse:t4("fields.reverse"),timeframeCode:t4("fields.timeframeCode"),condition:t4("fields.condition"),thresholdValue:t4("fields.thresholdValue"),startPrice
2:t4("fields.startPrice"),endPrice:t4("fields.endPrice"),numLegs:t4("fields.numLegs"),weightingType:t4("fields.weightingType"),priceLimit:t4("fields.priceLimit"),intervalSeconds:t4("fields.intervalSeconds"),startDelaySeconds:t4("fields.startDelaySeconds")},l=oW(e,dl,lx);for(let r of nE){let i=Object.entries(("tp"===r.type||"sl"===r.type)&&void 0!==r.triggerPercent?{...r,triggerPrice:l*(1+((0,ep.mustBeAbove)(r.type,e)?1:-1)*r.triggerPercent/100)}:r).filter(([e,t])=>"id"!==e&&"type"!==e&&void 0!==t).map(([e,r])=>{let i="condition"===e?t4(0===r?"below":"above"):"weightingType"===e?t4(0===r?"even":1===r?"front":"back"):"timeframeCode"===e?["1m","5m","15m","1H","4H","1D"][Number(r)]:"boolean"==typeof r?t4(r?"yes":"no"):"number"==typeof r?t(r):String(r);return`${a[e]??e}: ${i}`});s.push([n[r.type],i.join(" · ")])}return 0===nE.length&&s.push([t4("protection"),t4("noProtection")]),ri({intentKey:dm,wallet:nY.toBase58(),profileIndex:i0,side:re,collateralLabel:t(dd),rows:s,quoteAvailable:df,unifiedMargin:i7}),new Promise(e=>{rs.current=e})},db=(0,t.jsxs)("button",{onClick:()=>ig(!ix),"aria-expanded":ix,className:`focus-ring w-full flex items-baseline gap-2 hover:bg-surface-interactive rounded px-1 -mx-1 transition-colors ${tc?"":"py-[3px] leading-[18px]"}`,children:[(0,t.jsxs)("span",{className:"text-muted-foreground flex items-center gap-1",children:[t0("payFees"),(0,t.jsx)(ei.ChevronDown,{className:`w-3 h-3 transition-transform ${ix?"rotate-180":""}`})]}),!tc&&(0,t.jsx)("i",{"aria-hidden":!0,className:eQ.SUMMARY_LEADER_CLASS}),(0,t.jsx)("span",{className:`${oV} ${tc?"ml-auto":""}`,children:null!=dn?`$${t6.number(dn)}`:"—"})]}),dv=ix?(0,t.jsxs)("div",{className:"space-y-1 text-label-muted",children:[lH,o9,(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:t0("platformFee")}),(0,t.jsx)("span",{className:oH,children:oB?`$${t6.number(parseFloat(oB.platformFeeUsd))}`:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:t0("slippage")}),(0,t.jsx)("span",{className:"text-label-muted",children:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:t0("interest")}),(0,t.jsx)("span",{className:oH,children:oB?`$${t6.number(parseFloat(oB.interestUsd))}`:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:t0("openFee")}),(0,t.jsx)("span",{className:oH,children:oB?`$${t6.number(parseFloat(oB.openCloseFeeUsd))}`:"—"})]}),null!=da&&(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:t0("estCloseFee")}),(0,t.jsx)("span",{className:oH,children:`$${t6.number(da)}`})]})]}):null,dy=(0,t.jsxs)("div",{children:[db,ix&&(0,t.jsx)("div",{className:"mt-2 ml-2",children:dv})]}),dw=async e=>{if(!iT){if(e===i5)return void i_(!1);if("unified"!==e||null===dA){if(null===i0)return void X.toast.error(t0("selectProfileFirst"));iC(!0);try{await i4(i0,e)}catch(e){console.error("[margin-mode] toggle failed",e),X.toast.error((0,Z.chainActionError)(e,t0("marginModeChangeFailed")))}finally{iC(!1),i_(!1)}}}},dj={activeUnderwriter:i1,resolvedVenue:sM,routedVenue:sb,supportedVenues:l4,excludedVenues:i2,manualVenue:sP?.manualVenue[e8.symbol]??null,hasStickyPosition:sX,lockedReason:i7?t0("crossMarginVenueRequirement"):null,allowedVenues:i7?l4.filter(ne):null,referenceHoldHours:sm,routingNotional:sx>0?sx:(0,I.getReferenceNotional)(e8.symbol),sizeNum:l_,perVenueMaxLeverage:e=>{let t=s0(e);return"number"!=typeof t||!isFinite(t)||t<=0?null:s7(e,t)},onManualVenue:e=>sC?.(e8.symbol,e),onManageVenues:()=>nT(!0),compact:tc},dS=[{key:"trailing",label:t0("orderTypeTrailing"),desc:t0("orderTypeTrailingDesc"),icon:tA},{key:"dca",label:"DCA",desc:t0("orderTypeDcaDesc"),icon:tE},{key:"indicator",label:t0("orderTypeIndicator"),desc:t0("orderTypeIndicatorDesc"),icon:tL}],dk=dS.find(e=>e.key===t9)?.label??null,dN=nB?(0,t.jsx)("div",{className:"space-y-1",children:dS.map(e=>{let r="dca"===e.key&&sA;return(0,t.jsxs)("button",{type:"button",disabled:r,onClick:()=>{r||(t7(e.key),nz(!1))},className:`flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors ${r?"cursor-not-allowed opacity-40":"hover:bg-surface-interactive"}`,children:[(0,t.jsx)("span",{className:`mt-0.5 shrink-0 ${t9===e.key?"text-primary":"text-secondary-foreground"}`,children:e.icon}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:`block text-sm font-semibold ${t9===e.key?"text-primary":"text-foreground"}`,children:e.label}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:r?t0("notSupportedOnVenue",{venue:h.VENUE_
2LABELS[sM]}):e.desc})]}),t9===e.key&&(0,t.jsx)(es.Check,{className:"mt-1 h-4 w-4 shrink-0 text-primary"})]},e.key)})}):null,dP=e=>`relative flex items-center gap-1 rounded-chip ${tc?"text-[14px] font-medium":"min-w-0 justify-center text-[13px] font-semibold"} transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${e?`text-foreground after:absolute after:inset-x-0 after:bg-primary ${tc?"after:bottom-0 after:h-px":"after:-bottom-px after:h-0.5"}`:`${tc?"text-foreground/50":"text-muted-foreground"} hover:text-secondary-foreground`}`,dT=e=>(0,t.jsxs)("button",{type:"button",role:"tab","aria-selected":!oh,"aria-haspopup":"dialog",tabIndex:oh?-1:0,onClick:e?()=>nz(!0):void 0,className:dP(!oh),children:[tc?(0,t.jsx)("span",{className:"whitespace-nowrap",children:dk??t0("orderTypePro")}):(0,t.jsxs)("span",{className:"grid whitespace-nowrap",children:[[t0("orderTypePro"),...dS.map(e=>e.label)].map(e=>(0,t.jsx)("span",{"aria-hidden":"true",className:"invisible col-start-1 row-start-1",children:e},e)),(0,t.jsx)("span",{className:"col-start-1 row-start-1",children:dk??t0("orderTypePro")})]}),(0,t.jsx)(ei.ChevronDown,{className:"h-3 w-3 shrink-0"})]}),dC=t5((0,eZ.marginModeLabelKey)(i5)),dM=t0("marginModeChipLabel",{mode:dC}),d_=(0,e0.crossMarginAvailability)({phoenixMarket:sz,phoenixPending:sB,sunriseListed:(sW??[]).some(e=>e.symbol.toUpperCase()===e8.symbol.toUpperCase()),sunrisePending:sq||sK||!sW?.length,sunriseAllowed:sG}),dA="available"===d_?null:"loading"===d_?t0("marginModeCrossLoading"):t0("marginModeCrossUnavailable",{symbol:e8.symbol}),dE=(0,t.jsx)(eX.MarginModePicker,{current:i5,crossUnavailableReason:dA,accountName:i6.find(e=>e.index===i0)?.name??null,pending:iT,onSelect:e=>void dw(e)}),dL=(0,t.jsxs)("button",{ref:iA,"data-ticket-margin":!0,type:"button",onClick:tc?()=>i_(e=>!e):void 0,disabled:iT,"aria-haspopup":tc?void 0:"dialog","aria-controls":tc?tP:void 0,"aria-expanded":iM,"aria-label":dM,className:`hit-target flex items-center transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 disabled:opacity-60 ${tc?`h-9 w-full justify-center rounded-control bg-surface-interactive px-[9px] text-[10.5px] font-semibold hover:bg-surface-interactive/80 ${i7?"text-primary":"text-secondary-foreground"}`:`h-8 w-full justify-center rounded-control bg-transparent px-[9px] text-[10.5px] font-semibold hover:text-foreground ${i7?"text-primary":"text-secondary-foreground"}`}`,children:[dC,(0,t.jsx)(ei.ChevronDown,{className:"ml-1 h-3 w-3 opacity-70","aria-hidden":"true"})]}),dF=tc?dL:(0,t.jsxs)(ex.Popover,{open:iM,onOpenChange:e=>{(e||iI)&&i_(e)},children:[(0,t.jsx)(ex.PopoverTrigger,{asChild:!0,children:dL}),(0,t.jsx)(ex.PopoverContent,{side:"bottom",align:"end",sideOffset:6,onEscapeKeyDown:e=>{iI||e.preventDefault()},className:"w-[320px] p-3.5 shadow-[0_14px_36px_rgba(0,0,0,0.55)]",children:dE})]}),dR="text-3xs font-semibold uppercase tracking-[0.12em] text-muted-foreground",dD=tc?null:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("h6",{className:dR,children:t0("showInSummary")}),[{labelKey:"entryPrice",value:iv,setter:iy,key:"showEntryPrice"},{labelKey:"liqPriceAbbrev",value:iw,setter:ij,key:"showLiqPrice"},{labelKey:"borrowRate",value:iS,setter:ik,key:"showBorrowRate"},{labelKey:"payFees",value:iN,setter:iP,key:"showPayFees"}].map(({labelKey:e,value:r,setter:i,key:s})=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2.5 text-secondary-foreground",children:[(0,t.jsx)("span",{children:t0(e)}),(0,t.jsx)(ek.Switch,{"aria-label":t0(e),checked:r,onCheckedChange:e=>{i(e),localStorage.setItem(s,String(e))}})]},s)),(0,t.jsx)("div",{className:"h-px bg-border"})]}),dI=(0,o.useMemo)(()=>o_.map(e=>t6.percent(e/100,1)),[t6]),dU=(0,o.useMemo)(()=>t6.percent(r5/100,1),[t6,r5]),dO=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2.5 text-secondary-foreground",children:[(0,t.jsx)("span",{children:t0("slippage")}),(0,t.jsxs)("label",{className:`${!tc?m.default.inputField:""} flex items-center justify-end rounded-[8px] border border-border-strong bg-surface px-2.5 font-mono font-semibold text-foreground focus-within:border-primary/60 ${tc?`h-[34px] w-[104px] ${tD}`:"h-[30px] w-[84px] text-xs"}`,children:[(0,t.jsx)("input",{ref:r8,type:"text",inputMode:"decimal","data-keypad-unit":"percent",value:r9,placeholder:dU,"aria-label":t0("custom"),onChange:e=>{var t;let r;return r7(t=(0,eF.sanitizeDecimalInput)(e.target.value,t8)),void(!isNaN(r=parseFloat(t))&&r>0&&r<=50&&r3(Math.round(100*r)))},onWheel:e=>e.currentTarget.blur(),className:"w-full min-w-0 bg-transparent text-right placeholder:text-muted-foreground focus:outline-none"}
2),r9&&(0,t.jsx)("span",{"aria-hidden":!0,className:"pl-0.5 font-medium text-label-muted",children:"%"})]})]}),(0,t.jsx)("div",{className:"grid grid-cols-4 gap-1.5",children:o_.map((e,r)=>{let i;return(0,t.jsx)("button",{type:"button",onClick:()=>{r3(e),r7("")},className:(i=r5===e&&!r9,`flex h-[30px] items-center justify-center rounded-[8px] border font-mono text-xs transition-colors focus-ring ${i?"border-border-strong bg-surface-interactive text-foreground":"border-border text-muted-foreground hover:text-foreground"}`),children:dI[r]},e)})}),r5>=500&&(0,t.jsx)("p",{className:"text-3xs leading-tight text-amber-200",children:t0("slippageHighWarning")})]}),dB=(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-2.5 pl-2",children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(u.VenueInlineSelector,{...dj,desktopOrderSettings:tc?void 0:(0,t.jsxs)("div",{className:"grid gap-2.5 text-xs",children:[(0,t.jsx)("p",{className:"text-label-muted leading-5",children:t0("routingOrderSettingsSaved")}),dO,(0,t.jsx)("div",{className:"h-px bg-border"}),dD]})},`${nY?.toBase58()??"disconnected"}:${i0}:${_}`),!tc&&(r5>=200||!!r9)&&(0,t.jsx)("span",{"aria-hidden":"true",className:"pointer-events-none absolute right-0 top-0.5 h-2 w-2 rounded-full border-2 border-surface bg-imperial-gold"})]}),tc&&(0,t.jsxs)(ex.Popover,{open:r4,onOpenChange:r6,children:[(0,t.jsx)(ex.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":t0("orderSettings"),"aria-haspopup":"dialog",title:t0("orderSettings"),className:`hit-target flex items-center justify-center transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${tc?`h-[26px] w-[26px] rounded-[7px] ${r4?"text-primary":"text-muted-foreground hover:text-foreground"}`:`h-7 w-7 rounded-[7px] ${r4?"text-primary":"text-muted-foreground hover:text-foreground"}`}`,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:tc?"h-[19px] w-[19px]":"h-[18px] w-[18px]",children:[(0,t.jsx)("path",{d:"M3 7h9m6 0h3M3 17h3m6 0h9"}),(0,t.jsx)("circle",{cx:"15",cy:"7",r:"2"}),(0,t.jsx)("circle",{cx:"9",cy:"17",r:"2"})]}),(r5>=200||!!r9)&&(0,t.jsx)("span",{"aria-hidden":!0,className:"absolute -right-[3px] -top-[3px] h-2 w-2 rounded-full border-2 border-surface bg-imperial-gold"})]})}),(0,t.jsxs)(ex.PopoverContent,{side:"bottom",align:"end",sideOffset:6,onOpenAutoFocus:e=>{e.preventDefault(),(0,eg.focusKeypadField)(r8.current)},className:"grid w-[300px] gap-2.5 px-3.5 py-3 text-xs shadow-[0_14px_36px_rgba(0,0,0,0.55)]",children:[(0,t.jsx)("h6",{className:dR,children:t0("orderSettings")}),dO,(0,t.jsx)("div",{className:"h-px bg-border"}),dD]})]})]}),dz=(0,t.jsxs)("div",{role:"tablist","aria-label":t0("orderTypeHeading"),onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll('[role="tab"]')),r=t.indexOf(document.activeElement);if(-1===r)return;e.preventDefault();let i="Home"===e.key?0:"End"===e.key?t.length-1:(r+("ArrowRight"===e.key?1:t.length-1))%t.length;t[i].focus()},className:tc?"flex min-w-0 items-stretch gap-[18px] overflow-x-auto [&>*]:shrink-0":"grid w-full min-w-0 grid-cols-[1fr_1fr_minmax(max-content,1fr)] items-stretch",children:[[{key:"market",label:t0("orderTypeMarket"),hotkey:"M"},{key:"limit",label:t0("orderTypeLimit"),hotkey:"L"}].map(e=>(0,t.jsx)("button",{type:"button",role:"tab","aria-selected":t9===e.key,tabIndex:t9===e.key?0:-1,onClick:()=>t7(e.key),title:tp?`${e.label} \xb7 ${e.hotkey}`:void 0,className:dP(t9===e.key),children:e.label},e.key)),tc?dT(!0):(0,t.jsxs)(ex.Popover,{open:nB,onOpenChange:nz,children:[(0,t.jsx)(ex.PopoverTrigger,{asChild:!0,children:dT(!1)}),(0,t.jsxs)(ex.PopoverContent,{side:"bottom",align:"start",sideOffset:6,className:"w-[320px] p-2",children:[(0,t.jsx)("div",{className:`px-3 pb-1 pt-2 ${dR}`,children:t0("orderTypeHeading")}),dN]})]}),tc&&(0,t.jsx)(ef.Sheet,{open:nB,onOpenChange:nz,children:(0,t.jsxs)(ef.SheetContent,{side:"bottom",className:"bg-canvas border-t border-border rounded-t-xl px-4 pb-8 pt-4",children:[(0,t.jsx)(ef.
2SheetTitle,{className:"text-foreground text-lg font-semibold mb-4",children:t0("orderTypeHeading")}),dN]})})]}),d$=(0,t.jsxs)("div",{"data-ticket-order-tabs":!0,className:`${tc?"-mx-[7px] h-11 border-y px-[10px]":"-mx-2 h-[38px] border-b px-2"} flex items-stretch border-border`,children:[!tc&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(f.DesktopWorkspacePanelTools,{}),(0,t.jsx)(i.DesktopChartLinkBadge,{})]}),tc?dz:dF,dB]}),dV=(0,t.jsx)(ej.TradeStrength,{className:tc?"mt-[9px]":void 0,floatingDetails:!tc,asset:e8.symbol,side:ro?"long":"short",action:(ro?se:st)?"increase":"open",collateralUsd:ad,leverage:rV,orderType:"limit"===t9?"limit":"market",limitPrice:"limit"===t9&&lx>0?lx:void 0}),dH={items:nE,onItemsChange:e=>{nL(e),rb(e=>"partialTpSl"===e?null:e)},error:"partialTpSl"===rg,marketPrice:e9??null,isLong:ro,entryPrice:oG,triggerBasis:oK.triggerBasis??null,awaitsLimitPrice:oK.awaitsLimitPrice,sizeUsd:l_,collateralUsd:ad,feesUsd:oY,dense:!tc},dW=(0,o.useMemo)(()=>(0,eU.leverageStops)(np).map(e=>({value:e,label:t_(e,t6.intlTag),leftPct:100*(0,eU.leverageFraction)(e,np)})),[np,t6.intlTag]),dq=(0,o.useMemo)(()=>t_(rV,t6.intlTag),[rV,t6.intlTag]),dK=rW?rK:tF(rV),dG=(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{"data-ticket-leverage":!0,className:"pt-[7px]",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:tc?"text-[14px] font-medium text-foreground/70":"text-sm font-medium text-foreground/70",children:t5("leverage.full")}),(0,t.jsxs)("div",{className:"ml-auto flex items-center gap-1.5",children:[np>eU.LEVERAGE_MIN&&(0,t.jsx)("button",{type:"button","aria-label":t0("leverageLower"),title:tp?"[":void 0,disabled:r
2V<=eU.LEVERAGE_MIN+1e-9,onClick:()=>oN(-1),className:`relative flex shrink-0 items-center justify-center rounded-full border text-foreground/70 transition-colors hover:text-foreground disabled:opacity-35 after:absolute after:top-1/2 after:left-1/2 after:h-11 after:w-[38px] after:-translate-x-1/2 after:-translate-y-1/2 after:rounded-full after:content-[''] ${tc?"size-[26px] border-foreground/10 bg-foreground/8":"size-7 border-border-strong bg-surface-raised"}`,children:(0,t.jsx)(eo.Minus,{className:"size-3.5","aria-hidden":!0})}),(0,t.jsxs)("span",{ref:rJ,className:`flex w-max items-center font-bold tabular-nums text-foreground focus-within:border-primary/60 ${tc?`h-[26px] rounded-[9px] border border-foreground/10 bg-foreground/8 px-2 font-sans ${tD}`:"h-7 rounded-[8px] border border-border-strong bg-surface-raised px-2 font-mono text-[13px]"}`,children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal",style:{width:`${Math.min(6,Math.max(3,dK.length))}ch`},maxLength:6,value:dK,"data-keypad-unit":"multiplier","aria-label":t5("leverage.full"),onFocus:e=>{rG(tF(rV)),rq(!0);let t=e.currentTarget;requestAnimationFrame(()=>t.select())},onChange:e=>rG((0,eF.sanitizeDecimalInput)(e.target.value,t8)),onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()},onBlur:()=>{rq(!1);let e=parseFloat(rK),t=Number.isFinite(e)?Math.min(np,Math.max(eU.LEVERAGE_MIN,e)):rV;Number.isFinite(e)&&t!==e&&rQ(t0("leverageCapped",{max:t_(t,t6.intlTag)})),Math.abs(t-rV)>1e-9&&a2(t,"input")},className:"min-w-0 bg-transparent text-right focus:outline-none"}),(0,t.jsx)("span",{"aria-hidden":!0,className:"pl-0.5 font-medium text-label-muted",children:"x"})]}),np>eU.LEVERAGE_MIN&&(0,t.jsx)("button",{type:"button","aria-label":t0("leverageRaise"),title:tp?"]":void 0,disabled:r
2V>=np-1e-9,onClick:()=>oN(1),className:`relative flex shrink-0 items-center justify-center rounded-full border text-foreground/70 transition-colors hover:text-foreground disabled:opacity-35 after:absolute after:top-1/2 after:left-1/2 after:h-11 after:w-[38px] after:-translate-x-1/2 after:-translate-y-1/2 after:rounded-full after:content-[''] ${tc?"size-[26px] border-foreground/10 bg-foreground/8":"size-7 border-border-strong bg-surface-raised"}`,children:(0,t.jsx)(ed.Plus,{className:"size-3.5","aria-hidden":!0})})]})]}),np>eU.LEVERAGE_MIN&&(0,t.jsxs)("div",{className:"mt-[19px]",children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(eS.Slider,{value:[(0,eU.leverageToSliderPos)(rV,np)],min:0,max:eU.LEVERAGE_SLIDER_STEPS,step:1,onValueChange:e=>{var t;return t=(0,eU.stepLeverageFromSlider)(e[0],rV,np),void(r1.current=!0,rH(t),a0(t))},onValueCommit:e=>a2((0,eU.stepLeverageFromSlider)(e[0],rV,np),"slider"),"aria-label":t5("leverage.full"),thumbProps:{"aria-valuemin":eU.LEVERAGE_MIN,"aria-valuemax":np,"aria-valuenow":rV,"aria-valuetext":dq},title:tp?"[ / ]":void 0,className:tc?"py-1 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:border-0 [&_[data-slot=slider-track]]:bg-foreground
2/15 [&_[data-slot=slider-track]]:shadow-none [&_[data-slot=slider-range]]:bg-[image:var(--gradient-leverage)] [&_[data-slot=slider-thumb]]:size-[18px] [&_[data-slot=slider-thumb]]:bg-[#0D0804] [&_[data-slot=slider-thumb]]:border-[#FFE5C7]":"py-1"}),null!==o3&&o3>1.2&&o3<np&&(0,t.jsx)("span",{role:"img","aria-label":t0("leveragePremiumHelp"),title:t0("leveragePremiumHelp"),className:"absolute top-1/2 h-3 w-0.5 -translate-y-1/2 cursor-help rounded bg-imperial-gold",style:{left:`${100*(0,eU.leverageFraction)(o3,np)}%`}})]}),(0,t.jsx)("div",{className:`mt-5 grid gap-1.5 ${tc?"text-[12px] font-medium":"font-mono text-3xs tabular-nums"}`,style:{gridTemplateColumns:`repeat(${dW.length}, minmax(0, 1fr))`},children:dW.map(e=>{let r=.05>Math.abs(rV-e.value);return(0,t.jsx)("button",{type:"button",onClick:()=>{var t;a2(t=e.value,"stop"),rQ(t0("leverageSetTo",{value:t_(t,t6.intlTag)}))},className:`flex h-9 items-center justify-center rounded-[7px] border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${r?"border-border-strong text-foreground":"border-[var(--phone-card-border)] text-foreground/40 hover:border-border-strong hover:text-foreground"}`,children:e.label},e.value)})}),(0,t.jsxs)("span",{className:"sr-only","aria-live":"polite",children:[rY.text,rY.n%2?" ":""]}),!i7&&nx&&rV>=np-.05&&(0,t.jsxs)("button",{type:"button",onClick:()=>{if(!nx)return;let e=nx.underwriter;if((0,E.isAutoUnderwriter)(i1)&&l5.includes(e)&&!sJ.has(e))return void sC?.(e8.symbol,e);let t=i6.filter(t=>!t.excludedVenues.includes(e));1===t.length?i8(t[0].index):nM(!0)},className:"mt-1 rounded bg-primary/15 px-2 py-0.5 text-3xs font-semibold text-primary transition-colors hover:bg-primary/25",children:[t0("upToLeverage",{leverage:`${n
2x.maxLeverage}x`})," · ",h.VENUE_LABELS[nx.underwriter]]})]})]})}),dY="size"===aQ,dX=dY&&"base"===rp,dQ=dX?parseFloat(ru)||0:dY?l_:ad,dJ=dX?`${t6.number(dQ)} ${e8.symbol}`:`$${t6.number(dQ)}`,dZ=dY?t5("size.full"):t0("collateral"),d0=(0,t.jsx)(v.Button,{"data-ticket-submit":!0,onClick:()=>{if(!rk.current&&!iZ){if(!nY)return void(0,eC.promptConnectWallet)();if(ly)return void nN();ll(ro)}},disabled:!ry&&!!nY&&!ly&&!oc&&!iZ,title:tp?"⇧↵":void 0,"aria-busy":iZ,variant:"outline",className:`w-full ${tc?"h-[45px] text-[14px] font-semibold":"h-11 rounded-control text-sm font-bold"} ${ry?ro?`${tc?"rounded-[5px] ":""}border-0 bg-side-long text-canvas saturate-[1.15]`:`${tc?"rounded-[5px] ":""}border-0 bg-side-short text-canvas saturate-[1.15]`:!nY||ly?`${tc?"rounded-[6px] ":""}border-0 bg-[image:var(--gradient-cta-wide)] text-[var(--on-cta-wide)] hover:brightness-105`:oc||iZ?`${tc?"rounded-[5px] ":""}border-0 bg-[var(--confirm-pad)] text-primary hover:brightness-110`:`${tc?"rounded-[5px] ":""}border-0 bg-surface-interactive text-muted-foreground cursor-not-allowed`}`,children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[iZ&&(0,t.jsx)(e_.Spinner,{className:"size-3.5"}),ry?`✓ ${ro?t0("openedLong"):t0("openedShort")}`:nY?ly?lw:iZ?iJ?t1("movingFundsArmadaWait"):t0("submitting"):oi||(ai&&os?t1("armadaFundsReadyConfirm"):os?(0,t.jsxs)(t.Fragment,{children:[tc?t0(ro?"confirmLong":"confirmShort"):on?ro?t0("increaseLong"):t0("increaseShort"):ro?t0("openLong"):t0("openShort"),dQ>0&&(0,t.jsxs)("span",{className:tc?"tabular-nums":"font-mono tabular-nums",children:[tc?" - ":" — ",dJ,(0,t.jsx)("span",{className:"ml-1 font-sans text-[9px] font-medium uppercase tracking-wide opacity-60",children:dZ})]})]}):ou):t1("connectWallet"),sg?.wouldExtend&&nY&&os&&!iZ&&!ly&&(0,t.jsx)(en.Flame,{className:"w-3.5 h-3.5 text-primary"})]})}),d1=()=>{oC?oT(100):nN()},d2=so.SOL,d5=(()=>{if(!nY||null===n7||i7&&!tc)return null;let e=t0.rich("balanceReadout",{amount:t6.usdNumber(n7),asset:"USDC",strong:e=>(0,t.jsx)("span",{className:"font-mono tabular-nums text-foreground",children:e})}),r=t0("useFullBalance");return n7>0?(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5 whitespace-nowrap text-xs text-muted-foreground",children:[i7?(0,t.jsx)("span",{className:"cursor-default",children:e}):(0,t.jsx)("button",{type:"button",onClick:d1,title:r,"aria-label":r,className:"cursor-pointer transition-colors hover:text-secondary-foreground",children:e}),sc&&(0,t.jsx)(eu.ProfileSyncButton,{size:"sm",onSync:sc,syncStatus:sd,hasNonUsdcBalance:su})]}):n7<=0&&null!==d2&&d2<=q.NON_USDC_THRESHOLD_SOL?(0,t.jsx)("button",{type:"button",onClick:nN,className:"rounded-md bg-primary/15 px-2 py-0.5 text-xs font-semibold text-primary transition-colors hover:bg-primary/25",children:t0("deposit")}):null})(),d3=ad<=0?"":i7?t6.usdNumber(ad):`$${t6.number(ad)} \xb7 ${dq}`;t0("costAmountLine",{amount:`$${t6.number(ad)}`});let d4=t0("sizeAmountLine",{amount:`$${t6.number(l_)}`}),d6="flex h-[26px] shrink-0 items-center gap-1 rounded-chip border border-foreground
2/10 bg-foreground/8 px-2 text-[14px] font-bold text-foreground",d8=(0,t.jsx)("input",{ref:rx,"data-money-field":"",enterKeyHint:"done",autoComplete:"off",onKeyDown:e=>{tc&&"Enter"===e.key&&(e.preventDefault(),e.currentTarget.blur())},"data-keypad-unit":"size"===aQ&&"base"===rp?"plain":"money",type:"text",inputMode:"decimal",value:"size"===aQ?ru:rC,onChange:e=>{(0,eb.popValue)(e.currentTarget),"size"===aQ?(e=>{rv();let t=(0,eF.sanitizeDecimalInput)(e,t8);rh(t);let r=parseFloat(t)||0,i="base"===rp&&aX>0?r*aX:r;if(rc(i>0?i.toFixed(2):""),!i7&&rV>0){let e=i/rV;rM(e>0?e.toFixed(2):"")}})(e.target.value):a1(e.target.value,"input")},onFocus:()=>{rf.current=!0},onBlur:()=>{rf.current=!1,rh(tR(parseFloat(rd)||0,rp,aX))},onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"font-sans text-[22px] font-bold text-foreground/70 tabular-nums bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),d9="size"===aQ&&aX>0?(0,t.jsxs)("button",{type:"button",onPointerDown:tc?eg.holdKeypadFocus:void 0,onClick:()=>{let e="usd"===rp?"base":"usd";rm(e),localStorage.setItem("sizeDisplayUnit",e),rh(tR(parseFloat(rd)||0,e,aX))},title:t0("switchToUnit",{unit:"usd"===rp?e8.symbol:"USDC"}),className:`${d6}
2 transition-colors hover:bg-foreground/12 focus-ring`,children:["usd"===rp?"USDC":e8.symbol,(0,t.jsx)(ea.ArrowRightLeft,{className:"h-3 w-3 text-primary"})]}):(0,t.jsx)("span",{className:d6,children:"USDC"}),d7="flex h-full min-w-0 flex-1 items-center gap-1.5 rounded-md px-2.5 text-xs font-semibold",ce=[lb&&{key:"min",text:tc?t0("minimumCostIs",{amount:`$${a3}`}):t0("minimumCollateralIs",{amount:`$${a3}`})},oa&&{key:"interest",text:t0("collateralBelowInterest",{amount:`$${t6.number(ro?lP:lT)}`,side:ro?"long":"short"})},oo&&{key:"phoenixAdd",text:(ro?lQ:lJ)!==null?t0("phoenixAddNeedsCollateral",{amount:`$${t6.number((ro?lQ:lJ)??0)}`}):t0("phoenixAddOverHeadroom")},od&&{key:"phoenixFloor",text:t0("loanFloorBlockedIntro",{symbol:e8.symbol,side:ro?"long":"short"})},ol&&oP>0&&{key:"liquidity",text:t0("positionExceedsLiquidity",{side:ro?"long":"short",amount:`$${t6.numberShort(oP)}`})}].filter(Boolean),ct=lv&&null!==n7?Math.max(0,Math.ceil((ap-n7)*100)/100):null,cr=e=>(0,t.jsx)("div",{"data-ticket-status":!0,className:`my-2 flex h-7 min-w-0 items-center${e?" empty:hidden":""}`,children:rg?(0,t.jsxs)("div",{className:`${d7} ${"failure"===rg?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-300"}`,children:[(0,t.jsx)(er.AlertTriangle,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"failure"===rg?t0("submitFailedShort"):t0("tpSlLegFailedShort")})]}):ce.length>0?(0,t.jsxs)("div",{className:`${d7} bg-destructive/10 text-destructive`,title:ce.map(e=>e.text).join(" · "),children:[(0,t.jsx)(er.AlertTriangle,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:ce[0].text}),ce.length>1&&(0,t.jsxs)("span",{className:"ml-auto shrink-0 rounded-[7px] border border-current px-[5px] py-px font-mono text-3xs font-semibold opacity-60",children:["+",ce.length-1]})]}):null!==ct&&ct>0&&!nU?(0,t.jsx)("div",{className:"flex h-full min-w-0 flex-1 items-center rounded-md bg-foreground
2/5 px-2.5 text-xs font-medium text-secondary-foreground",children:(0,t.jsx)("span",{className:"truncate",children:t0.rich("needMoreBalance",{need:t6.usdNumber(ct),balance:t6.usdNumber(n7??0),strong:e=>(0,t.jsx)("span",{className:"font-mono font-semibold tabular-nums text-foreground",children:e})})})}):lN.length>0?(0,t.jsxs)("div",{className:`${d7} bg-amber-500/10 text-amber-300`,title:t0("strandsPendingOrdersTitle"),children:[(0,t.jsx)(er.AlertTriangle,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:t0("strandsPendingOrders",{count:lN.length})})]}):sg&&!tc?(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-1.5 text-2xs text-muted-foreground",children:[(0,t.jsx)(en.Flame,{className:"h-3 w-3 shrink-0 text-primary"}),(0,t.jsx)("span",{className:"truncate",children:sg.message})]}):null}),ci=lS?(0,t.jsxs)("label",{className:"my-2 flex cursor-pointer items-center gap-2 rounded-md border border-border px-2.5 py-[7px]",children:[(0,t.jsx)("input",{type:"checkbox",checked:nU,onChange:e=>nO(e.target.checked),className:"h-3.5 w-3.5 rounded-[4px] border-[1.5px] border-border-strong bg-surface text-primary focus:ring-primary/50"}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground",title:t0("deferFundingTitle"),children:t0("deferFundingNote")})]}):null,cs=(0,t.jsxs)(t.Fragment,{children:[sb?.availabilityNotice&&sb.venue===sM&&(0,t.jsx)("div",{role:"status",className:"text-2xs text-amber-400 leading-tight",children:sb.availabilityNotice}),sb?.exclusionOverridden&&void 0!==sb.leverDownToLeverage&&(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)("div",{className:"text-2xs text-amber-400 leading-tight",children:t0("excludedVenueOverride",{venue:h.VENUE_LABELS[sb.venue],leverage:`${rV}x`,symbol:e8.symbol,target:t_(sb.leverDownToLeverage,t6.intlTag)})}),(0,t.jsx)("button",{type:"button",onClick:()=>a2(sb.leverDownToLeverage,"excluded_venue_lever_down"),className:"self-start px-2.5 py-1 text-2xs font-medium rounded bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 transition-colors",children:t0("leverDownTo",{leverage:t_(sb.leverDownToLeverage,t6.intlTag)})})]}),ro&&lW&&(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)("div",{className:"text-2xs text-amber-400 leading-tight",children:null!==lQ?t0("phoenixAddNeedsCollateral",{amount:`$${t6.number(lQ)}`}):t0("phoenixAddOverHeadroom")}),null!==lQ&&se&&(0,t.jsx)("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("imperial:add-collateral",{detail:{marketMint:_,side:"long",amountUsd:lQ}})),className:"self-start min-h-6 px-2.5 py-1 text-2xs font-medium rounded bg-cyan-500/15 text-cyan-300 hover:bg-cyan-500/25 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:t0("addCollateralCta",{amount:`$${t6.number(lQ)}`})})]}),!ro&&lq&&(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)("div",{className:"text-2xs text-amber-400 leading-tight",children:null!==lJ?t0("phoenixAddNeedsCollateral",{amount:`$${t6.number(lJ)}`}):t0("phoenixAddOverHeadroom")}),null!==lJ&&st&&(0,t.jsx)("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("imperial:add-collateral",{detail:{marketMint:_,side:"short",amountUsd:lJ}})),className:"self-start min-h-6 px-2.5 py-1 text-2xs font-medium rounded bg-cyan-500/15 text-cyan-300 hover:bg-cyan-500/25 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:t0("addCollateralCta",{amount:`$${t6.number(lJ)}`})})]}),od&&(tW=(e=>{if(!e||!(e.pos.borrowedPrincipalUsd>0))return null;let t=sy?.perMarket.find(e=>e.symbol===e8.symbol);if(!t)return null;let r=(0,U.minLoanBpsFor)(t,"phoenix");if(r<=0)return null;let i=e.pos.loanOriginationNotionalUsd>0?e.pos.loanOriginationNotionalUsd:e.pos.sizeUsd*aE(e)/e.pos.entryPrice,s=Math.floor((1e4*e.pos.borrowedPrincipalUsd/r-i)*100)/100;return s>0?s:null})(ro?ny:nw),tq=i7?nf:rV,tK=null!==tW&&tq>0?Math.floor(tW/tq*100)/100:0,tY=null!==(tG=i7?tW:tK*rV)&&tG>0&&tG<l_&&tK>=a3,(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsxs)("div",{className:"text-2xs text-amber-400 leading-tight",children:[t0("loanFloorBlockedIntro",{symbol:e8.symbol,side:ro?"long":"short"})," ",tY?t0("loanFloorReduceSize",{amount:`$${t6.number(tG)}`}):t0("loanFloorCloseToRepay")]}),tY&&(0,t.jsx)("button",{type:"button",onClick:()=>{i7?(rv(),rc(tG.toFixed(2))):a1(tK.toFixed(2),"loan_floor_reduce_size")},className:"self-start min-h-6 px-2.5 py-1 text-2xs font-medium rounded bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:t0("loanFloorReduceSizeCta")})]}))]}),cn=(0,t.jsxs)("div",{"data-ticket-side":!0,className:tc?"flex h-[53px] items-center rounded-[9px] bg-black/40 p-1":"grid grid-cols-2 gap-2",children:[(0,t.jsx)("button",{type:"button",onClick:()=>rt("long"),"data-side":"long",title:tp?`${t0("sideLong")} \xb7 B`:void 0,"aria-pressed":ro,className:`${tc?"h-[45px] flex-1 rounded-[6px] text-[15px] font-medium":"h-10 rounded-control text-base font-bold"} transition-colors duration-150 ${ro?tr:tc?ts:`${ts} bg-surface-interactive/40 hover:bg-surface-interactive/70`}`,children:t0("sideLong")}),(0,t.jsx)("button",{type:"button",onClick:()=>rt("short"),"data-side":"short",title:tp?`${t0("sideShort")} \xb7 S`:void 0,"aria-pressed":!ro,className:`${tc?"h-[45px] flex-1 rounded-[6px] text-[15px] font-medium":"h-10 rounded-control text-base font-bold"} transition-colors duration-150 ${!ro?ti:tc?ts:`${ts} bg-surface-interactive/40 hover:bg-surface-interactive/70`}`,children:t0("sideShort")})]});return(0,t.jsxs)("div",{ref:iL,onKeyDown:e=>{"Escape"===e.key&&iR&&!iT&&(e.stopPropagation(),i_(!1))},"data-ticket":tc?"compact":"desktop",className:tc?"flex flex-col flex-1 min-h-0":m.default.ticket,children:[rr&&(0,t.jsx)(tg,{snapshot:rr,matchesCurrent:tu&&tN(rr.intentKey,dm),quoteAvailable:df&&oc,onConfirm:()=>dx(!0),onCancel:()=>dx(!1)}),tc?(0,t.jsxs)("div",{className:"shrink-0 bg-[var(--phone-drawer-crown)] px-[7px] pb-[11px]",children:[d$,(0,t.jsx)("div",{className:"pt-[11px]",children:dF}),(0,t.jsx)("div",{className:"pt-[11px]",hidden:iR,children:cn})]}):(0,t.jsxs)(t.Fragment,{children:[d$,(0,t.jsx)("div",{"data-ticket-order-type-row":!0,className:"flex h-[30.67px] shrink-0 items-stretch rounded-[7.156px] bg-[#1d1f21] px-[9px]",children:dz}),cn]}),iR&&(0,t.jsx)("div",{id:tP,role:"dialog","aria-labelledby":eX.MARGIN_PICKER_HEADING_ID,ref:iE,tabIndex:-1,
2className:tc?`${tT} pt-1 focus:outline-none`:"pt-1 focus:outline-none",children:dE}),(0,t.jsx)("div",{"aria-live":"assertive",role:"status",className:"sr-only",children:rj}),(0,t.jsxs)("div",{ref:oj,"data-ticket-body":!0,onScroll:tc?ok:void 0,className:tc?`${tT} pt-[8.7px] pb-3 space-y-[11px] flex flex-col`:m.default.body,hidden:iR,children:[op&&(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2.5 text-xs text-secondary-foreground",children:[(0,t.jsx)("span",{title:t0("reduceOnlyHelp",{side:t2(ro?"short":"long")}),children:t0("reduceOnly")}),(0,t.jsx)(ek.Switch,{"aria-label":t0("reduceOnly"),checked:ra,onCheckedChange:rl})]}),iD&&(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(g.ProOrderForm,{leverageSlot:dG,statusSlot:cr(!0),maxSlippageSlot:o0,underwriter:aU,activeTab:t9,marketPrice:e9??null,minCollateral:10,maxLeverage:np,walletBalance:n7,onSubmitRatchetEntry:lu,onSubmitIndicator:lh,onSubmitDca:lp,onSubmitDcaTime:lm,onSubmitDcaRatchet:lf,submitting:iZ,submittingLabel:iJ?t1("movingFundsArmadaWait"):void 0,readyLabel:ai?t1("armadaFundsReadyConfirm"):void 0,disableLong:lZ,disableShort:l0,marketMint:_,onDepositClick:nN,chartResolution:td,oraclePriceToleranceBps:s5.feeSettings?.oraclePriceToleranceBps,deferFunding:nU,onDeferFundingChange:nO,canDeferFunding:lS,leverage:nf,phoenixDcaBlocked:nj,isUnifiedMargin:i7,availableMarginUsd:n5,pinCta:tc,compact:tc,desktopLayout:!tc,footerHost:ob,actionHost:oy,ctaHost:ox,side:ro?"long":"short"})}),(0,t.jsx)(tC,{open:nS,onOpenChange:nk}),(0,t.jsx)(tM,{open:nP,onOpenChange:nT}),("market"===t9||"limit"===t9)&&om&&(of?(0,t.jsx)(ew.ReduceOnlyTicket,{lifecycle:of,symbol:e8.symbol,orderType:t9,marketMint:_,markPrice:e9??0,compact:tc,ctaHost:ox,actionHost:oy,summaryHost:ob,onPositionChange:tl},of.id):(0,t.jsx)("p",{className:"rounded-md border border-border bg-surface-raised px-3 py-2 text-xs text-muted-foreground",children:t0("reduceOnlyNoPosition",{side:t2(ro?"short":"long")})})),("market"===t9||"limit"===t9)&&!om&&(0,t.jsxs)(t.Fragment,{children:["limit"===t9&&(0,t.jsxs)("div",{"data-ticket-limit":!0,className:"flex h-10 items-center gap-2 rounded-md border border-border bg-surface-raised px-3",children:[(0,t.jsx)("span",{className:"text-3xs font-semibold uppercase tracking-wider text-muted-foreground",children:t0("orderTypeLimit")}),rB?(0,t.jsx)("button",{type:"button",onClick:()=>rz(!1),className:`min-w-0 flex-1 text-left font-mono font-medium tabular-nums text-primary ${tc?tD:"text-[15px]"}`,children:"BBO"}):(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:rU,onChange:e=>{(0,eb.popValue)(e.currentTarget),rv(),rz(!1),rO((0,eF.sanitizeDecimalInput)(e.target.value,t8))},onWheel:e=>e.currentTarget.blur(),placeholder:e9?t6.number(e9):"0.00",className:`min-w-0 flex-1 bg-transparent font-mono tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none ${tc?tD:"text-[15px]"}`}),(0,t.jsx)("button",{type:"button",onClick:()=>{rB?rz(!1):a_&&rz(!0)},className:`rounded px-2 py-0.5 text-3xs font-semibold transition-colors ${rB?"bg-primary/15 text-primary hover:bg-primary/20":"bg-surface-interactive text-muted-foreground hover:text-foreground"}`,children:"BBO"})]}),i7&&(s_||ax)&&(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[ax&&n1?.liquidationPending&&(0,t.jsx)("p",{className:"text-sm text-amber-400",children:"Liquidation is in progress. Collateral is reserved until the position closes."}),(0,t.jsx)(eV.AccountHealthRow,{compact:tc,effectiveUsd:aw,maintenanceUsd:aj,initialUsd:ay,legInitialUsd:ad,legMaintenanceUsd:ax?n1?.maintenanceMarginBps==null?null:ao*n1.maintenanceMarginBps/1e4:void 0,depositUsd:ap}),nY&&(0,t.jsxs)(ex.Popover,{children:[(0,t.jsx)(ex.PopoverTrigger,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:"flex w-full items-baseline justify-between gap-2 text-xs transition-colors hover:text-foreground",children:[(0,t.jsx)("span",{className:"text-muted-foreground underline decoration-dotted underline-offset-2",children:t0("availableToTrade")}),(0,t.jsx)("span",{className:"font-mono tabular-nums text-foreground",children:null===aN?"—":t6.usdNumber(aN)})]})}),(0,t.jsxs)(ex.PopoverContent,{side:"bottom",align:"end",className:"w-[260px] space-y-2 p-3 text-xs",children:[(0,t.jsxs)("div",{className:"space-y-1 font-mono tabular-nums",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("availableToTradeMarginAccount")}
2),(0,t.jsx)("span",{children:null===n5?"—":t6.usdNumber(n5)})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("availableToTradeWallet")}),(0,t.jsx)("span",{children:null===n7?"—":t6.usdNumber(n7)})]}),null!=ay&&ay>0&&(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border pt-1",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("marginAccountUsed")}),(0,t.jsx)("span",{children:t6.usdNumber(ay)})]})]}),(0,t.jsx)("p",{className:"text-muted-foreground",children:t0("availableToTradeExplainer")}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("button",{type:"button",onClick:nN,className:"flex-1 rounded-control bg-surface-interactive px-2 py-1.5 font-medium hover:bg-surface-raised",children:t0("deposit")}),ak&&(0,t.jsx)("button",{type:"button",onClick:()=>{rL("withdraw"),rR("")},className:"flex-1 rounded-control bg-surface-interactive px-2 py-1.5 font-medium hover:bg-surface-raised",children:t0("availableToTradeWithdraw")})]})]})]}),null!=ab&&ab>0&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:t0("marginArriving",{amount:`$${t6.number(ab)}`,seconds:(0,e1.armadaWithdrawWaitSecs)(n1)})}),rE&&(0,t.jsxs)("div",{"data-ticket-field":!0,className:"flex flex-col gap-2 rounded-[5px] border border-primary/50 trading-control-surface px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-3xs text-label-muted",children:"add"===rE?t0("addMargin"):t0("removeMargin")}),(0,t.jsx)("button",{type:"button",onClick:aJ,className:"text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:t3("cancel")})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{ref:eg.autoFocusKeypadField,type:"text",inputMode:"decimal","data-keypad-unit":"money",value:rF,onChange:e=>{(0,eb.popValue)(e.currentTarget),rR((0,eF.sanitizeDecimalInput)(e.target.value,t8,6))},onKeyDown:e=>{"Enter"===e.key&&aZ()},onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"text-base text-foreground bg-transparent border-none focus:outline-none flex-1 min-w-0"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:"USDC"}),"withdraw"===rE&&ak&&(0,t.jsx)("button",{type:"button",onClick:()=>rR((0,eR.percentToDecimalString)(ag??0,100,6)),className:"text-2xs text-muted-foreground hover:text-foreground transition-colors flex-shrink-0 cursor-pointer",children:t0("max")}),(0,t.jsx)("button",{type:"button",onClick:aZ,disabled:!aM,className:(0,y.cn)("text-xs font-medium px-2.5 py-1 rounded border transition-colors flex-shrink-0",aM?"border-primary/60 text-primary hover:text-foreground cursor-pointer":"border-border text-muted-foreground cursor-not-allowed"),children:rD?"add"===rE?t0("adding"):t0("removing"):"add"===rE?t0("add"):t0("remove")})]}),aT&&(0,t.jsx)("span",{className:"text-2xs text-destructive",children:t0("moreThanYourBalance",{balance:t6.usdNumber(n7??0)})}),"withdraw"===rE&&(null===ag?(0,t.jsx)("span",{className:"text-2xs text-amber-400/80",children:t0("marginAmountUnavailable")}):aC?(0,t.jsx)("span",{className:"text-2xs text-destructive",children:t0("mostYouCanRemoveIs",{amount:`$${t6.number(ag)}`})}):ag<=0?(0,t.jsx)("span",{className:"text-2xs text-amber-400/80",children:t0("openPositionsNeedBalance")}):(0,t.jsx)("span",{className:"text-2xs text-muted-foreground",children:t0("mostYouCanRemove",{amount:`$${t6.number(ag)}`})})),"withdraw"===rE&&aS>0&&(0,t.jsx)("span",{className:"text-2xs text-muted-foreground",children:t0("removeMarginLiquidationWarning")})]})]}),(0,t.jsxs)("div",{"data-money-context":!0,"data-keypad-reveal":tc?"":void 0,className:tc?"space-y-[11px] mt-[8.7px]":"space-y-2",children:[(0,t.jsx)("div",{"data-keypad-reveal":!0,className:`rounded-field border-[0.5px] border-border-strong h-[73px] px-[15px] pb-3 pt-[13px] flex flex-col justify-between focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40 ${tc?"bg-[var(--phone-chip)]":"bg-input"}`,children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[i7?(0,t.jsx)("span",{className:"min-w-0 truncate text-[12px] font-medium text-foreground
2/50",children:d4}):(0,t.jsxs)("button",{type:"button",onPointerDown:tc?eg.holdKeypadFocus:void 0,onClick:()=>{let e="size"===r_?"cost":"size";rA(e);try{localStorage.setItem("tradeInputMode",e)}catch{}},title:"size"===aQ?t0("switchToCostInput"):t0("switchToInput",{mode:"size"}),"aria-label":"size"===aQ?t0("switchToCostInput"):t0("switchToInput",{mode:"size"}),className:"-my-1 -ml-1 flex min-w-0 items-center gap-1 rounded px-1 py-1 text-[12px] font-medium text-foreground/50 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[(0,t.jsx)("span",{className:"min-w-0 truncate",children:"size"===aQ?t5("size.full"):t0("collateral")}),(0,t.jsx)(el.ArrowDownUp,{className:"h-3 w-3 shrink-0 text-primary"})]}),d5]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[d8,d9]})]})}),!i7&&(0,t.jsx)("div",{className:"px-[15px] text-[12px] font-medium text-foreground/50",children:"size"===aQ?t0.rich("costLine",{amount:`$${t6.number(ad)}`,strong:e=>(0,t.jsx)("span",{className:"text-foreground",children:e})}):t0.rich("sizeLine",{amount:`$${t6.number(l_)}`,strong:e=>(0,t.jsx)("span",{className:"text-foreground",children:e})})}),!i7&&(0,t.jsx)(eh.SizePresetButtons,{maxUsd:n7??0,valueUsd:ad,onSelect:oT,disabled:!nY,hotkeyTitles:tp,compact:tc})]}),dG,(0,t.jsx)("div",{"data-ticket-tpsl":!0,className:tc?"rounded-[11.4px] border-[0.85px] border-[var(--phone-card-border)] bg-[var(--phone-chip)]":"rounded-float border border-border-strong",children:(0,t.jsx)(ey.InlineTpSl,{...dH},nF)}),tc&&cs,tc&&(0,t.jsxs)("div",{children:["armada"===sM&&(0,t.jsx)(p.ArmadaFeesSaved,{wallet:nY?.toBase58()??null,className:"mb-3"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-x-[9px] gap-y-[10px] px-1 text-[10.66px] font-medium [&_.font-mono]:font-sans [&_.text-secondary-foreground]:text-[#D9DBE0]",children:[(!i7||d3)&&(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("margin")}),(0,t.jsx)("span",{className:"font-mono tabular-nums text-secondary-foreground",children:d3})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:de}),(0,t.jsx)("span",{className:oV,children:dt})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("estLiqPrice")}),o1]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("maxLossToSl")}),(0,t.jsx)("span",{children:oM?(tX=parseFloat("limit"===t9?os&&oU?oA(oU,oO,lx,l_)??"0":"0":oA(oI,oO,oe,l_)??"0"),tQ=oB?parseFloat(oB.totalFeesUsd):0,tJ=void 0!==oM.triggerPercent?tX*(1+(ro?-1:1)*oM.triggerPercent/100):oM.triggerPrice,tZ=tX>0?Math.abs(tX-tJ)/tX*l_+tQ:0,(0,t.jsx)("span",{className:oV,children:tX>0?`$${t6.number(tZ)}`:"—"})):(0,t.jsx)("span",{className:"text-label-muted",children:t0("noSl")})})]}),db,iS&&(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("borrowRate")}),o2]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:t0("maxSlippage")}),o0]})]}),ix&&(0,t.jsx)("div",{ref:ib,className:"mt-2.5 rounded-float border border-border-strong bg-popover p-3 text-xs",children:dv}),ci,cr(!0),dV]})]}),!tc&&(0,t.jsxs)("div",{"data-ticket-desktop-info":!0,className:m.default.info,children:[(iD||om)&&(0,t.jsx)("div",{ref:ov,"data-ticket-pro-footer":!0,hidden:iR,className:m.default.proFooter}),oh&&!om&&(0,t.jsxs)("div",{"data-ticket-summary":!0,hidden:iR,className:m.default.summary,children:["armada"===sM&&(0,t.jsx)(p.ArmadaFeesSaved,{wallet:nY?.toBase58()??null,className:m.default.feeRow}),(0,t.jsxs)("div",{"data-ticket-estimates":!0,className:"flex flex-col pb-2 pt-0.5 text-xs",children:[(!i7||d3)&&(0,t.jsx)(eQ.SummaryRow,{label:t0("margin"),children:(0,t.jsx)("span",{className:oV,children:d3})}),iv&&(0,t.jsx)(eQ.SummaryRow,{label:de,children:(0,t.jsx)("span",{className:oV,children:dt})}),ot&&(0,t.jsx)("div",{className:"text-amber-300",children:ot}),iw&&(0,t.jsx)(eQ.SummaryRow,{label:t0("estLiqPrice"),children:o1}),iS&&(0,t.jsx)(eQ.SummaryRow,{label:t0("borrowRate"),children:o5?(0,t.jsx)(ev.TooltipProvider,{children:(0,t.jsxs)(ev.Tooltip,{children:[(0,t.jsx)(ev.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("span",{className:"cursor-help underline decoration-dotted underline-offset-2 decoration-leader-strong",children:o2})}),(0,t.jsx)(ev.TooltipContent,{side:"top",className:"font-mono text-xs max-w-xs",children:o5})]})}):o2}),iN&&dy,(0,t.jsx)(eQ.SummaryRow,{label:t0("maxSlippage"),children:o0})]})]})]})]}),!tc&&(0,t.jsx)("div",{"data-ticket-desktop-footer":!0,hidden:iR,className:m.default.footer,children:(0,t.jsx)("div",{className:m.default.actions,children:oh&&!om?(0,t.jsx)(x.TerminalActionSection,{before:(0,t.jsxs)(t.Fragment,{children:[cr(!0),cs,ci]}),after:dV,children:d0}):(0,t.jsx)("div",{ref:ow,"data-ticket-action-host":!0,className:m.default.actionHost})})}),tc&&(0,t.jsx)("div",{"data-ticket-footer":!0,hidden:iR,className:"shrink-0 rounded-t-[9px] border-x border-t border-border bg-[image:var(--gradient-phone-footer)] px-2.5 pb-2.5 pt-2.5",children:(0,t.jsx)("div",{className:"relative",children:oh&&!om?(0,t.jsxs)(t.Fragment,{children:[ot&&(0,t.jsx)("div",{className:"mb-1 text-xs text-amber-300",children:ot}),d0]}):(0,t.jsx)("div",{ref:og,className:"min-h-[45px]"})})}),nC&&nx&&(0,t.jsx)(eG.Dialog,{open:nC,onOpenChange:nM,children:(0,t.jsxs)(eG.DialogContent,{className:"max-w-sm p-6",children:[(0,t.jsx)(eG.DialogTitle,{className:"text-lg font-semibold",children:t0("higherLeverageOnVenue",{venue:h.VENUE_
2LABELS[nx.underwriter]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:t0("higherLeverageDetail",{symbol:e8.symbol,venueLeverage:`${nx.maxLeverage}x`,venue:h.VENUE_LABELS[nx.underwriter],currentLeverage:`${np}x`})}),(0,t.jsxs)("div",{className:"space-y-2 mt-2",children:[i6.filter(e=>!e.excludedVenues.includes(nx.underwriter)).map(e=>(0,t.jsxs)("button",{onClick:()=>{nM(!1),i8(e.index)},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface hover:bg-surface-interactive transition-colors",children:[(0,t.jsx)("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium bg-surface-interactive text-secondary-foreground",children:e.index+1}),(0,t.jsx)("span",{className:"font-medium text-sm flex-1 text-left",children:e.name})]},e.index)),i9&&(0,t.jsx)("button",{onClick:()=>{nM(!1),nA(!0)},className:"w-full flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border border-border-strong hover:border-border-strong text-secondary-foreground hover:text-foreground transition-colors text-sm",children:t0("createNewProfile")})]})]})}),(0,t.jsx)(eY.CreateProfileDialog,{open:n_,onOpenChange:nA,defaultExcludedVenues:nx?L.ALL_VENUES.filter(e=>e!==nx.underwriter):void 0})]})}e.s(["hasUnverifiedAccountUpdate",0,function(e){return"unknown"===e.status&&null===e.metadata&&null===e.error&&null===e.lastReadAt&&null===e.lastSuccessAt&&0===e.exits.length&&"number"==typeof e.lastTransportSuccessAt&&Number.isFinite(e.lastTransportSuccessAt)&&e.lastTransportSuccessAt>=0}],51559);var tU=e.i(989714);e.s(["HistoryReadControls",0,function({view:e}){let r=(0,c.useTranslations)("positions"),i=e.hasOlderPages&&e.olderStale,s=1e3*(0,tU.useTickingNowSecs)(i);return i?(0,t.jsx)("button",{type:"button",className:"m-3 text-xs underline disabled:opacity-50",disabled:e.olderLoading||(e.olderAvailability?.retryAt??0)>s,onClick:e.refreshOlder,children:r("accountReadRefreshOlder")}):null}],718177)},838580,e=>{e.v({card:"market-quick-cards-module__pSkvSq__card",cards:"market-quick-cards-module__pSkvSq__cards",change:"market-quick-cards-module__pSkvSq__change",favorite:"market-quick-cards-module__pSkvSq__favorite",identity:"market-quick-cards-module__pSkvSq__identity",leverage:"market-quick-cards-module__pSkvSq__leverage",metric:"market-quick-cards-module__pSkvSq__metric",metricLabel:"market-quick-cards-module__pSkvSq__metricLabel",metricValue:"market-quick-cards-module__pSkvSq__metricValue",metrics:"market-quick-cards-module__pSkvSq__metrics",price:"market-quick-cards-module__pSkvSq__price",quote:"market-quick-cards-module__pSkvSq__quote",select:"market-quick-cards-module__pSkvSq__select",symbol:"market-quick-cards-module__pSkvSq__symbol"})},240001,742503,e=>{"use strict";e.s(["AccountDrawer",()=>Y],240001);var t=e.i(394390),r=e.i(183023),i=e.i(807956),s=e.i(942553),n=e.i(491135),a=e.i(457395),l=e.i(303745),o=e.i(319522),d=e.i(993628),c=e.i(146895),u=e.i(685576),h=e.i(679555),p=e.i(219979),m=e.i(894771),f=e.i(419636),x=e.i(987752),g=e.i(124593),b=e.i(875574),v=e.i(347554),y=e.i(803817),w=e.i(719367),j=e.i(299959),S=e.i(153517),k=e.i(162388),N=e.i(679758),P=e.i(100555),T=e.i(580873),C=e.i(843276),M=e.i(673028),_=e.i(987363),A=e.i(394802),E=e.i(87602),L=e.i(872429),F=e.i(822371),R=e.i(657645);let D=["deposit","withdraw","transfer"];function I({amountRef:e,segments:r,mode:i,onModeChange:n,onClose:a,contentClassName:l,accountLabel:o,venues:d,destinations:c,onPickDestination:h,amount:p,onAmountChange:m,maxLabel:f,maxCaption:x,onMax:g,settling:b,secondaryBalanceLabel:v,hideAmount:y,depositAddress:w,addressDefaultExpanded:j,notices:k,cta:P,hint:T,rescue:C}){let M=(0,s.useTranslations)("wallet");return(0,t.jsxs)("div",{translate:"no",className:"mx-[2px] mt-[8.7px] min-h-0 flex-1 overflow-y-auto rounded-[9px] bg-[var(--phone-row)] px-[7px] pb-[8px] pt-[1px]",children:[(0,t.jsx)(N.FundModeControl,{segments:r.length?r:D,value:i,onSelect:n,className:"-mx-[7px]",trailing:(0,t.jsx)(u.SheetCloseChip,{onClick:a,className:"relative ml-[4px] mr-[2px] h-[30px] w-[30px] shrink-0 rounded-[5px] border-[0.93px] border-[var(--phone-outline)] bg-transparent text-foreground"})}),(0,t.jsxs)("div",{className:l,children:[(0,t.jsx)("div",{className:"mt-[14px] text-[12.08px] font-bold leading-none text-foreground",children:o}),(0,t.jsx)("div",{className:"mt-[15px]",children:(0,t.jsx)(L.UnderwriterSelector,{size:"phone",excluded:d.excluded,onChange:d.onChange,disabled:d.disabled})}),T,"transfer"===i&&(0,t.jsxs)("div",{className:"mt-[15px]",children:[(0,t.jsx)("div",{className:"text-[8.5px] font-medium leading-none text-[var(--phone-explainer-ink)]",children:M("transferTo")}),(0,t.jsx)("div",{className:"mt-[8px] space-y-[4px]",children:c.map(e=>(0,t.jsxs)("button",{type:"button",onPointerDown:R.holdKeypadFocus,onClick:()=>h(e.index),"aria-pressed":e.selected,className:(0,S.cn)("focus-ring flex h-[44px] w-full items-center gap-[12.4px] rounded-[5px] border-[0.93px] pl-[13.7px] pr-[14px] text-left transition-colors",e.selected?"border-[var(--phone-accent-ink)] bg-[var(--phone-accent-pad)]":"border-transparent bg-[var(--phone-address-row)]"),children:[(0,t.jsx)("span",{"aria-hidden":!0,
2className:"flex h-[18.65px] w-[18.65px] shrink-0 items-center justify-center rounded-[4.35px] bg-[var(--phone-avatar)] text-[9.95px] font-semibold text-[var(--phone-avatar-ink)]",children:e.index+1}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate text-[11.19px] font-semibold text-foreground",children:e.label}),(0,t.jsx)("span",{className:"text-[12.43px] font-semibold tabular-nums text-foreground",children:e.balanceLabel})]},e.index))})]}),!y&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{"data-keypad-reveal":!0,className:"relative mt-[15px] h-[54.4px] rounded-[3.72px] bg-[var(--phone-chip)] px-[11.2px] pt-[10.4px] transition-shadow focus-within:outline focus-within:outline-1 focus-within:-outline-offset-1 focus-within:outline-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsx)("label",{htmlFor:"fund-panel-amount",className:"block text-[8.94px] font-medium leading-none text-white/50",children:M("amount")}),(0,t.jsx)("input",{ref:e,id:"fund-panel-amount",...F.DECIMAL_INPUT_PROPS,"data-keypad-unit":"money",value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.currentTarget.blur())},onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"mt-[5px] block w-[190px] bg-transparent text-[16.79px] font-bold leading-none tabular-nums text-white/70 placeholder:text-white/30 focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"}),(0,t.jsx)("button",{type:"button",onPointerDown:R.holdKeypadFocus,onClick:g,className:"focus-ring absolute right-[11px] top-[8.9px] text-[8.94px] font-medium leading-none text-white/50",children:x??M("fundBalanceMax",{amount:f})}),(0,t.jsx)("span",{className:"absolute right-[17px] top-[27.6px] text-[10.43px] font-bold leading-none text-foreground",children:"USDC"})]}),b,v&&(0,t.jsx)("div",{className:"mt-[5.6px] text-[8.94px] leading-none text-white/50",children:v})]}),w&&(0,t.jsx)("div",{className:"mt-[10px]",children:(0,t.jsx)(E.ProfileAddressCard,{size:"phone",address:w,defaultExpanded:j})}),k.map((e,r)=>(0,t.jsxs)("div",{className:"ml-[2px] mt-[8px] flex min-h-[26px] items-center gap-[6px] rounded-[5.37px] border-[0.67px] border-[var(--phone-warn-edge)] bg-[var(--phone-warn-pad)] px-[9px] py-[4px] text-[7.61px] font-medium leading-[10px] text-[var(--phone-warn-ink)]",children:[(0,t.jsx)(A.AlertTriangle,{className:"h-[8px] w-[8px] shrink-0","aria-hidden":!0}),(0,t.jsx)("div",{children:e})]},r)),C,!P.hidden&&(0,t.jsx)("button",{type:"button",onClick:P.onClick,disabled:P.disabled,className:"focus-ring mt-[13px] flex h-[36px] w-full items-center justify-center rounded-[6px] bg-[var(--phone-accent-pad)] text-[12px] font-medium text-[var(--phone-accent-ink)] transition-colors disabled:cursor-not-allowed disabled:opacity-40",children:P.label})]})]})}var U=e.i(873029),O=e.i(575146),B=e.i(538712);function z(){let e=(0,s.useTranslations)("wallet"),t=(0,j.useFormatters)(),i=(0,r.useCallback)(e=>null==e?null:(0,B.formatSettlingTime)(e,Date.now(),t.intlTag),[t.intlTag]),n=(0,r.useCallback)(e=>`$${t.fixed(e,2)}`,[t]);return{line:(0,r.useCallback)(t=>{if("moreShortly"===t.kind)return e("moreAvailableShortly");let r=i(t.availableAt);return r?e("settlingAvailableAt",{amount:n(t.heldUsd),time:r}):e("settlingAmount",{amount:n(t.heldUsd)})},[e,i,n]),note:(0,r.useCallback)(t=>{if("moreShortly"===t.kind)return e("moreAvailableShortly");let r=i(t.availableAt);return r?e("settlingExceedsAt",{amount:n(t.heldUsd),time:r}):e("settlingExceeds",{amount:n(t.heldUsd)})},[e,i,n]),usd:n}}function $({className:e,iconClassName:r}){let i=(0,s.useTranslations)("wallet");return(0,t.jsxs)(O.Popover,{children:[(0,t.jsx)(O.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":i("settlingInfoLabel"),className:(0,S.cn)("inline-flex items-center text-label-muted hover:text-foreground transition-colors",e),children:(0,t.jsx)(U.Info,{className:(0,S.cn)("size-3",r),"aria-hidden":"true"})})}),(0,t.jsx)(O.PopoverContent,{side:"top",align:"end",className:"max-w-[240px] text-xs",children:i("settlingInfo")})]})}function V({open:e,initialMode:r,onModeChange:i,onClose:n,contentClassName:a}){let l=(0,s.useTranslations)("wallet"),o=(0,s.useTranslations)("positions"),d=(0,j.useFormatters)(),c=(0,P.useProfileFunding)({open:e,initialMode:r}),u=(0,T.useVenueExclusionEditor)(),h=z();if(null===c.activeProfileIndex)return null;let p=0!==c.activeProfileIndex||c.activeProfile?.name?c.profileLabel:o("mobileAccountMain"),m=(0,N.fundSegmentsFor)(c.createdProfiles.length),f=e=>null==e?"—":d.fixed(e,2),x="deposit"===c.mode?l("profileAmountUsdc",{amount:f(c.profileBalance)}):"withdraw"===c.mode?l("walletAmountUsdc",{amount:f(c.walletBalance)}):null,g="deposit"===c.mode?void 0:l("withdraw"===c.mode?"availableToWithdraw":"availableToTransfer",{amount:null==c.maxAmount?"—":h.usd(c.maxAmount)}),b=c.amountNote?(0,t.jsx)("div",{role:"status",className:"mt-[5.6px] text-[8.94px] leading-[11px] text-[var(--phone-warn-ink)]",children:h.note(c.amountNote)}):c.settlingLine?(0,t.jsxs)("div",{className:"mt-[5.6px] flex items-center gap-[4px] text-[8.94px] leading-none text-white/50",children:[(0,t.jsx)("span",{children:h.line(c.settlingLine)}),"settling"===c.settlingLine.kind&&(0,t.jsx)($,{className:"-m-[4px] p-[4px] text-white/50",iconClassName:"size-[10px]"})]}):null,v="transfer"===c.mode?c.createdProfiles.filter(e=>e.index!==c.activeProfileIndex).map(e=>({index:e.index,label:e.name??l("profileFallback",{index:String(e.index+1)}),balanceLabel:`${f(c.allProfileBalances.get(e.index))} USDC`,selected:c.destProfileIndex===e.index})):[],w=c.notices.map(e=>{switch(e){case"noProfile":return l("finishAccountBeforeDeposit");case"loanBlocksWithdraw":return l("withdrawBlockedByLoan");case"loanBlocksTransfer":return l("transferBlockedByLoan");case"jwtWithdraw":return l("mobileSessionCannotWithdraw");case"jwtTransfer":return l("mobileSessionCannotTransfer");case"battleLock":return l.rich("depositLockedByBattle",{battle:c.lockedBattle?.title??"",link:e=>(0,t.jsx)(y.Link,{href:"/competition",className:"underline underline-offset-2",children:e})})}}),S=c.armadaStep?l("transfer"===c.mode?"movingFundsArmadaWait":"withdrawingArmadaWait"):c.isProcessing?"transfer"===c.mode?l("transferring"):l("deposit"===c.mode?"depositing":"withdrawing"):l("deposit"===c.mode?"fundDepositUsd":"withdraw"===c.mode?"fundWithdrawUsd":"fundTransferUsd",{amount:c.amount||"0"});return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(C.GmTradeWarningDialog,{open:null!==u.pendingGmEnable,onConfirm:()=>void u.confirmGmEnable(),onCancel:u.cancelGmEnable}),(0,t.jsx)(I,{amountRef:c.amountRef,segments:m,mode:c.mode,onModeChange:e=>{c.switchMode(e),i?.(e)},onClose:n,contentClassName:a,accountLabel:p,venues:{excluded:u.excluded,onChange:e=>void u.handleExclusionsChange(e),disabled:u.isUpdating},destinations:v,onPickDestination:c.setDestProfileIndex,amount:c.amount,onAmountChange:c.onAmountInput,maxLabel:f(c.maxAmount),maxCaption:g,onMax:c.handleMax,settling:b,secondaryBalanceLabel:x,hideAmount:c.receiveOnlyDeposit,depositAddress:"deposit"===c.mode?c.activeProfilePda:null,addressDefaultExpanded:c.receiveOnlyDeposit,notices:w,cta:{hidden:c.receiveOnlyDeposit,disabled:c.submitDisabled,label:S,onClick:()=>void c.handleSubmit()},hint:(0,t.jsx)(M.UsdtHintRow,{onSwapSuccess:c.fetchTokenBalance}),rescue:"withdraw"===c.mode&&c.activeProfilePda&&c.publicKey?(0,t.jsx)(_.ProfileTokenRescueList,{profilePda:c.activeProfilePda,profileIndex:c.activeProfileIndex,walletPubkey:c.publicKey,isActive:!0,onRescueDone:c.fetchTokenBalance}):null})]})}e.s(["SettlingInfo",0,$,"useWithdrawSettlingText",0,z],742503);let H=(0,i.default)(()=>e.A(898027).then(e=>({default:e.CreateProfileDialog})),{loadableGenerated:{modules:[649043]},ssr:!1}),W=(0,i.default)(()=>e.A(297078).then(e=>({default:e.VenueSettingsDialog})),{loadableGenerated:{modules:[251512]},ssr:!1}),q=(0,i.default)(()=>e.A(607222).then(e=>({default:e.ManagePrivyWalletDialog})),{loadableGenerated:{modules:[433537]},ssr:!1}),K="focus-ring flex h-11 items-center border-t-[0.93px] border-[var(--phone-card-border)] text-[11.8px] font-medium text-foreground";function G(e){return"opening"===e?"open":"closing"===e?"idle":e}function Y({open:e,openWith:i,onClose:n,returnFocusRef:a}){let l=(0,s.useTranslations)("wallet"),{isPrivyWallet:o,publicKey:d}=(0,b.useUnifiedWalletContext)(),h=(0,x.useOnboarding)(),m=(0,r.useRef)(!1),f=(0,r.useRef)(null),g=(0,r.useRef)(null),[v,y]=(0,r.useState)(null),[w,j]=(0,r.useState)("deposit"),S=e=>{j(e),y(e)},[k,N]=(0,r.useState)(e);k!==e&&(N(e),e&&(i?S(i):y(null)));let[P,T]=(0,r.useState)(!1),[C,M]=(0,r.useState)(!1),[_,A]=(0,r.useState)(!1),[E,L]=(0,r.useState)(!1);return(0,p.useFocusAfterSlide)(e,f,"button"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(u.Sheet,{open:e,onOpenChange:e=>{e||n()},children:(0,t.jsxs)(u.SheetContent,{ref:f,side:"right",hideClose:!0,className:`${u.SHEET_PHONE_DRAWER} w-[80.8%] gap-0 overflow-hidden border-l-[0.5px] border-white/20 bg-[var(--phone-drawer)] px-[13px] pb-[calc(env(safe-area-inset-bottom)+19px)] pt-0 shadow-[-6.2px_0_18.65px_rgba(0,0,0,0.5)]`,onOpenAutoFocus:e=>e.preventDefault(),"data-keypad-no-lift":!0,onCloseAutoFocus:e=>{if(e.preventDefault(),m.current){m.current=!1;return}a?.current?.focus()},children:[(0,t.jsxs)("div",{className:"flex h-[44px] shrink-0 items-center",children:[(0,t.jsx)(u.SheetTitle,{className:"text-[16.16px] font-semibold leading-none text-foreground",children:l("navAccount")}
2),(0,t.jsx)(u.SheetCloseChip,{onClick:n,className:"relative ml-auto mr-[3.5px] h-[30px] w-[30px] rounded-[5px] border-[0.93px] border-[var(--phone-outline)] bg-transparent text-foreground"})]}),(0,t.jsx)(X,{onFund:S,onSetupRequired:()=>{m.current=!0,h.open({intent:"funding",ownerWallet:d?.toBase58()??null,fromAccountDrawer:!0,returnFocus:a?.current??null}),n()},lastFundMode:w,fundMode:v,onCloseFund:()=>{y(null),requestAnimationFrame(()=>g.current?.querySelector("button")?.focus())},controlRef:g,onCreate:()=>T(!0),onManageWallet:()=>A(!0),onVenueSettings:()=>M(!0),onDisconnect:()=>L(!0)})]})}),P&&(0,t.jsx)(H,{open:!0,onOpenChange:T}),C&&(0,t.jsx)(W,{open:!0,onOpenChange:M}),o&&_&&(0,t.jsx)(q,{open:!0,onOpenChange:A}),E&&(0,t.jsx)(c.DisconnectConfirmDialog,{open:!0,onOpenChange:L})]})}function X({onFund:e,onSetupRequired:i,lastFundMode:c,fundMode:u,onCloseFund:p,controlRef:x,onCreate:P,onManageWallet:T,onVenueSettings:C,onDisconnect:M}){let _=(0,s.useTranslations)("wallet"),A=(0,s.useTranslations)("settings"),E=(0,j.useFormatters)(),{publicKey:L,isPrivyWallet:F,walletName:D}=(0,b.useUnifiedWalletContext)(),{createdProfiles:I,activeProfileIndex:U,setActiveProfileIndex:O,canCreateMore:B,hasLoadedProfiles:z}=(0,m.useProfile)(),$=(0,f.useFundingEntry)(e,i),{isPro:H}=(0,g.useProWhitelist)(),{profiles:W,global:q,isStale:Y,isLoading:Q}=(0,v.usePortfolioValues)(),J=L?.toBase58()??null,{unpinned:Z,explainerDismissed:ee}=(0,o.useAccountPins)(J),et=(0,r.useMemo)(()=>new Map(I.map(e=>[e.index,e.pda.toBase58()])),[I]),er=I.some(e=>e.index===U),ei=!z,es=null===U?void 0:W.get(U)?.unrealizedValue,en=e=>void 0===e||Q?w.UNKNOWN_VALUE:`$${E.numberShort(e)}`,ea=Y?"opacity-60":"",el=null!==u&&er,eo=(0,k.useReducedMotion)(),[ed,ec]=(0,r.useState)(el?"open":"idle"),[eu,eh]=(0,r.useState)(el);eu!==el&&(eh(el),ec(el?eo?"open":"opening":eo?"idle":"closing"));let ep="opening"===ed||"closing"===ed;(0,r.useEffect)(()=>{if("opening"!==ed&&"closing"!==ed)return;let e=window.setTimeout(()=>ec(G),450);return()=>window.clearTimeout(e)},[ed]);let em="open"===ed;(0,r.useEffect)(()=>{let e=document.activeElement;em&&e&&(0,R.requestKeypadReveal)(e)},[em]);let ef=em?I.filter(e=>e.index===U):I,ex="opening"===ed?"anim-fade-out":"closing"===ed?"anim-fade-in":void 0,eg=(0,r.useRef)(null),eb=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{if(!ep)return;let e=eg.current?.offsetHeight;void 0!==e&&eb.current?.style.setProperty("--rise",`calc(100% - ${e}px)`)},[ep,ed]),(0,r.useLayoutEffect)(()=>{if("opening"!==ed&&"open"!==ed)return;let e=document.activeElement;(e===document.body||x.current?.contains(e))&&eb.current?.querySelector("button[aria-pressed='true'], button")?.focus({preventScroll:!0})},[ed]),(0,t.jsxs)(t.Fragment,{children:[J&&(0,t.jsxs)("div",{className:"mt-[17px] flex shrink-0 items-center",children:[(0,t.jsxs)("button",{type:"button",onClick:()=>(0,o.copyAddress)(J,_("addressCopied")),className:"focus-ring hit-target flex items-center gap-[6px] text-[11.8px] font-semibold leading-none text-foreground [--hit:32px]",children:[(0,S.shortAddress)(J),(0,t.jsx)(a.Copy,{className:"h-2 w-2 text-muted-foreground","aria-hidden":!0})]}),D&&(0,t.jsx)("span",{className:"ml-[14px] text-[10.57px] leading-none text-muted-foreground",children:D})]}),(0,t.jsxs)("div",{className:"mt-[13px] grid h-[64.3px] shrink-0 grid-cols-2 rounded-[5px] border-[0.5px] border-border-strong bg-[var(--phone-chip)]",children:[(0,t.jsxs)("div",{className:"px-[14.6px] pt-[10.6px]",children:[(0,t.jsx)("span",{className:"block text-[10.29px] font-medium leading-none text-white/50",children:_("drawerTradingAccount")}),(0,t.jsx)("span",{className:`mt-[9.5px] block text-[18.79px] font-bold leading-none tabular-nums text-white/70 ${ea}`,children:en(es)})]}),(0,t.jsxs)("div",{className:"border-l-[0.5px] border-white/20 px-[14.6px] pt-[10.6px]",children:[(0,t.jsx)("span",{className:"block text-[10.29px] font-medium leading-none text-white/50",children:_("drawerWalletToken",{token:"USDC"})}),(0,t.jsx)("span",{className:`mt-[9.5px] block text-[18.79px] font-bold leading-none tabular-nums text-white/70 ${ea}`,children:en(q.walletCashBalance)})]})]}),(0,t.jsx)("h2",{className:"mt-[8.5px] shrink-0 text-[9.33px] font-medium uppercase leading-none tracking-[1.12px] text-label-muted",children:_("accounts")}),(0,t.jsxs)("div",{className:(0,S.cn)("relative isolate -mx-[5px] mt-[9px] flex min-h-0 flex-1 flex-col px-[5px]",em&&"overflow-y-auto",ep&&"[clip-path:inset(0)]"),children:[(0,t.jsx)("div",{className:em?"shrink-0":"min-h-0 flex-1 overflow-y-auto",children:ei?(0,t.jsxs)("div",{className:"space-y-1","aria-busy":"true",children:[(0,t.jsx)(h.Skeleton,{className:"h-[56px] w-full rounded-[5px]"}),(0,t.jsx)(h.Skeleton,{className:"h-[56px] w-full rounded-[5px]"})]}):(0,t.jsx)(o.AccountsPopoverBody,{phone:!0,profiles:ef,activeIndex:U,unpinned:Z,addr58:et,values:W,valuesStale:Y,explainerDismissed:0===I.length||em||ee,canCreate:!em&&B&&H,extrasClassName:ex,onPick:e=>{e!==U&&O(e),J&&(0,d.pinStored)(J,e)},onDismissExplainer:()=>
2J&&(0,d.writeExplainerDismissed)(J),onCreate:P})}),(0,t.jsxs)("div",{className:"relative mt-auto flex shrink-0 flex-col",children:["open"!==ed&&(0,t.jsxs)("div",{ref:eg,className:(0,S.cn)("flex flex-col","opening"===ed&&"anim-fade-out pointer-events-none","closing"===ed&&"anim-fade-in"),inert:"opening"===ed,children:[(0,t.jsx)(N.FundModeControl,{ref:x,segments:0===I.length?["deposit"]:(0,N.fundSegmentsFor)(I.length),value:0===I.length?"deposit":c,onSelect:e=>void $.startFunding(e),disabled:$.disabled,className:"-ml-[5px] mt-[8px]"}),!ei&&!er&&(0,t.jsx)("p",{role:"status",className:"mt-[6px] shrink-0 text-[10.5px] font-medium text-muted-foreground",children:_($.pending?"creating":"depositSetupHint")})]}),"idle"!==ed&&(0,t.jsx)("div",{ref:eb,className:(0,S.cn)("flex min-h-0 shrink-0 flex-col",!em&&"absolute inset-x-0 bottom-0 z-20 [&>div]:flex-none","opening"===ed&&"anim-panel-rise","closing"===ed&&"anim-panel-sink pointer-events-none"),onAnimationEnd:e=>{e.target===e.currentTarget&&ec(G)},children:(0,t.jsx)(V,{open:el,initialMode:u??c,onModeChange:e,onClose:p,contentClassName:"opening"===ed?"anim-panel-body-in":"closing"===ed?"anim-panel-body-out":void 0})})]}),(0,t.jsxs)("div",{className:"mt-[4px] shrink-0",children:[J&&(0,t.jsxs)(y.Link,{href:`/profile/${J}`,replace:!0,className:K,children:[_("drawerProfilePoints"),(0,t.jsx)(n.ChevronRight,{className:"-mr-[2px] ml-auto h-3 w-3 text-muted-foreground","aria-hidden":!0})]}),F&&(0,t.jsxs)("button",{type:"button",onClick:T,className:`${K} w-full`,children:[_("manageWallet"),(0,t.jsx)(n.ChevronRight,{className:"-mr-[2px] ml-auto h-3 w-3 text-muted-foreground","aria-hidden":!0})]}),(0,t.jsxs)("button",{type:"button",onClick:C,className:`${K} w-full`,children:[A("venueSettings"),(0,t.jsx)(n.ChevronRight,{className:"-mr-[2px] ml-auto h-3 w-3 text-muted-foreground","aria-hidden":!0})]})]})]}),(0,t.jsxs)("button",{type:"button",onClick:M,className:"focus-ring mt-[7px] flex h-[38.5px] shrink-0 items-center justify-center gap-[10px] rounded-control border-[0.93px] border-[var(--phone-danger-edge)] bg-[var(--phone-danger-pad)] text-[12.43px] font-semibold text-[var(--phone-danger-ink)]",children:[(0,t.jsx)(l.LogOut,{className:"h-3 w-3","aria-hidden":!0}),_("disconnect")]})]})}},679758,e=>{"use strict";var t=e.i(394390),r=e.i(942553),i=e.i(153517),s=e.i(657645);let n=["deposit","withdraw"],a=["deposit","withdraw","transfer"];e.s(["FundModeControl",0,function({segments:e,value:n,onSelect:a,disabled:l,className:o,trailing:d,ref:c}){let u=(0,r.useTranslations)("wallet");return(0,t.jsxs)("div",{ref:c,role:"group",className:(0,i.cn)("flex h-[42px] shrink-0 items-center rounded-[9px] bg-[var(--phone-chip)] p-[3px]",o),children:[e.map(e=>{let r=e===n;return(0,t.jsx)("button",{type:"button",disabled:l,"aria-pressed":r,onPointerDown:s.holdKeypadFocus,onClick:()=>a(e),className:(0,i.cn)("focus-ring h-full flex-1 rounded-[6px] text-[15px] font-medium transition-colors disabled:opacity-40",r?"bg-[var(--phone-accent-pad)] text-[var(--phone-accent-ink)]":"text-label-muted"),children:u(e)},e)}),d]})},"fundSegmentsFor",0,function(e){return e>1?a:n}])},275927,179730,33623,519052,711599,219979,280864,504421,725102,789382,723181,96970,708853,101034,178655,237073,e=>{"use strict";e.s(["MobileChartView",()=>ei],275927),e.s(["default",()=>q],179730);var t=e.i(394390),r=e.i(183023),i=e.i(815),s=e.i(967678),n=e.i(650883),a=e.i(460174),l=e.i(900165),o=e.i(807956),d=e.i(394802),c=e.i(942553),u=e.i(631797),h=e.i(376260),p=e.i(737866),m=e.i(612483),f=e.i(691054),x=e.i(308759),g=e.i(731926),b=e.i(894771),v=e.i(555641),y=e.i(190459);function w(e){return"phoenix"===e||"gmtrade"===e||"armada"===e?e:"pyth"}class j{state={front:null,back:null,retiring:null,failedKey:null};listeners=new Set;nextId=1;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;create(e,t,r,i){return{id:this.nextId++,key:e,venue:t,datafeed:r,initialState:i,handle:{current:null}}}alive(){let{front:e,back:t,retiring:r}=this.state;return[e,t,r].filter(Boolean).length}replaceFront(e){let{front:t}=this.state;t!==e&&(t?.datafeed.destroy(),this.set({front:e}))}setBack(e){e&&this.state.retiring&&this.retire();let{back:t}=this.state;t!==e&&(t?.datafeed.destroy(),this.set({back:e}))}abandonBack(){this.setBack(null)}promote(){let{front:e,back:t,retiring:r}=this.state;return!!t&&(r?.datafeed.destroy(),this.set({front:t,back:null,retiring:e,failedKey:null}),!0)}retire(){let{retiring:e}=this.state;e&&(e.datafeed.destroy(),this.set({retiring:null}))}markFailed(e){this.setBack(null),this.set({failedKey:e})}clearFailed(){null!==this.state.failedKey&&this.set({failedKey:null})}destroyAll(){let{front:e,back:t,retiring:r}=this.state;for(let i of[e,t,r])i?.datafeed.destroy();this.set({front:null,back:null,retiring:null})}set(e){for(let t of(this.state={...this.state,...e},this.listeners))t()}}var S=e.i(599059),k=e.i(637226),N=e.i(777180),P=e.i(568299);let T=new Map,C=new Set;function M(e,t){if(T.get(e)!==t)for(let r of(T.set(e,t),C))r()}function _(e){return C.add(e),()=>{C.delete(e)}}var A=e.i(955370),E=e.i(875722);function L(e){let t=(0,r.useSyncExternalStore)(E.subscribeProviderHealth,E.getProviderHealthVersion,()=>0),[,i]=(0,r.useState)(0);return(0,r.useEffect)(()=>
2{if(!e)return;let t=(0,E.getProviderRecoveryAt)(e);if(null===t)return;let r=setTimeout(()=>i(e=>e+1),Math.max(100,t-Date.now()+100));return()=>clearTimeout(r)},[e,t]),!!e&&(0,E.isProviderDown)(e)}var F=e.i(142910),R=e.i(585554),D=e.i(137421);let I=new class{busy=!1;queue=[];acquire(e){return new Promise(t=>{if(e.aborted)return void t(null);let r=()=>{this.queue=this.queue.filter(e=>e!==i),t(null)},i=()=>{if(e.removeEventListener("abort",r),e.aborted){t(null),this.next();return}this.busy=!0;let i=!1;t(()=>{i||(i=!0,this.busy=!1,this.next())})};e.addEventListener("abort",r,{once:!0}),this.busy?this.queue.push(i):i()})}next(){this.busy||this.queue.shift()?.()}};var U=e.i(142981);function O({message:e}){let r=(0,c.useTranslations)("trading");return(0,t.jsx)(u.MarkProgress,{label:e??r("loadingChart"),className:"h-full w-full bg-surface"})}let B=(0,o.default)(()=>e.A(872672).then(e=>e.TradingViewChart),{loadableGenerated:{modules:[255704]},ssr:!1,loading:()=>(0,t.jsx)(O,{})}),z={SOL:"So11111111111111111111111111111111111111112",ETH:"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",BTC:"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh"},$=["phoenix","gmtrade","jupiter"];function V(e){let t=$.indexOf(e);return t<0?$.length:t}
2function H({symbol:e,onRoute:t}){let i=(0,N.useRoutedVenue)({asset:e,side:"long",record:!1}),s=i?.venue??null;return(0,r.useEffect)(()=>t(e,s),[e,s,t]),null}function W({layer:e,visible:i,foreground:s,zIndex:n=0,onReady:a,common:l,priceMode:o}){let d=(0,r.useCallback)(()=>a?.(e.id),[a,e.id]),[c]=(0,r.useState)(l.interval),[u]=(0,r.useState)(l.overrideSavedInterval),h=(0,x.barsQuotedInUsd)({priceMode:o});return(0,t.jsx)("div",{className:"absolute inset-0",style:{zIndex:n},children:(0,t.jsx)(B,{...l,interval:c,overrideSavedInterval:u,onResolutionChange:s?l.onResolutionChange:void 0,positionLines:h?l.positionLines:void 0,datafeed:e.datafeed,executionActive:s&&l.executionActive,persistenceActive:s,theme:"dark",autosize:!0,visible:i,onReady:d,initialState:e.initialState,handleRef:e.handle})})}let q=(0,r.memo)(function({chartId:i,executionActive:s=!0,onActivate:n,initialResolution:o="60",inheritLegacyLayout:u=!1,symbol:x,mintAddress:N,underwriters:C,onResolutionChange:E,positionLines:B,tradeMarkers:$,hiddenLineIds:q,onHideLine:K,labelMode:G,onLabelModeChange:Y,onLineDragged:X,onToggleDepth:Q,depthOpen:J,hideHeader:Z,desktopLayout:ee,actionsRef:et}){var er;let ei=(0,c.useTranslations)("trading"),es=(0,r.useRef)(10*!!s);es.current=10*!!s,(0,r.useEffect)(()=>{e.A(547047);let t=document.createElement("link");return t.rel="preload",t.as="script",t.href=R.TRADINGVIEW_LIBRARY_SRC,document.head.appendChild(t),()=>t.remove()},[]);let{priceMode:en,solPrice:ea}=(0,g.usePriceDisplay)(),{activeProfileUnderwriter:el,activeProfileExcludedVenues:eo}=(0,b.useProfile)(),ed=z[x]??N,ec=(0,P.useRoutingContext)(),[eu,eh]=(0,r.useState)(null),ep=(0,r.useCallback)((e,t)=>{eh(r=>r?.symbol===e&&r.venue===t?r:{symbol:e,venue:t})},[]),em=s&&eu?.symbol===x?eu.venue:void 0,ef=s?ec?.lastRoutedVenue?.[x]:void 0,ex=(0,D.chartStorageScope)(i,x),eg=ex??x,eb=(0,r.useSyncExternalStore)(_,()=>T.get(eg),()=>void 0),ev=ef&&(0,y.isVenueValue)(ef)?ef:null,ey=ed?(0,v.resolveConcreteUnderwriter)(el,ed,eo):"jupiter",ew=(0,k.useChartFocus)(),ej=(0,r.useRef)(null),eS=s&&!!ew&&ew.symbol.toUpperCase()===x.toUpperCase()&&(0,k.shouldJump)(ew);(0,r.useLayoutEffect)(()=>{eS&&ew&&(ej.current=ew.id)},[eS,ew]);let ek=!!ew&&(eS||ej.current===ew.id),eN=s&&ek&&ew&&ew.symbol.toUpperCase()===x.toUpperCase()&&(0,y.isVenueValue)(ew.venue)&&(0,k.isVenuePinActive)(ew)?ew.venue:null,[eP,eT]=(0,A.useChartDataMode)(ex);(0,r.useEffect)(()=>{eS&&ew&&(0,k.isVenuePinActive)(ew)&&eT("mark")},[eS,ew,eT]);let eC="oracle"===(0,A.effectiveMode)(ed,eP),{venue:eM}=(er={focusVenue:eN,executingVenue:ev,routeDefault:em??void 0,profileFallback:ey}).focusVenue?{venue:er.focusVenue,rule:"focus"}:er.executingVenue?{venue:er.executingVenue,rule:"executing"}:er.routeDefault?{venue:er.routeDefault,rule:"route"}:{venue:er.profileFallback,rule:"profile"},e_=s?eM:eb??ey;(0,r.useEffect)(()=>{eb||M(eg,e_)},[eg,eb,e_]);let eA=eb??e_,eE=L("gmtrade"),eL=L("phoenix"),eF=L("jupiter"),eR=L("armada"),eD=(0,r.useMemo)(()=>({gmtrade:eE,phoenix:eL,jupiter:eF,armada:eR}),[eE,eL,eF,eR]),eI=(0,r.useCallback)(e=>{if(eC||!eD[e])return e;let t=(C??[]).filter(t=>t!==e).sort((e,t)=>V(e)-V(t));return t.find(e=>!eD[e])??t[0]??e},[eC,C,eD]),eU=eI(eA),eO=eI(e_),eB=eU!==eA,ez=(0,r.useSyncExternalStore)(F.subscribeFeedRegistry,F.getFeedRegistryVersion,()=>0),e$=(0,r.useMemo)(()=>ed?(0,F.getLazerSymbol)(ed)??(0,F.getLazerSymbolByAssetSymbol)(x):void 0,[ed,x,ez]),eV="phoenix"===eU||"phoenix"===eO,[eH,eW]=(0,r.useState)(0),eq=(0,r.useMemo)(()=>eV?(ed?(0,F.getSchedule)(ed):void 0)??(0,F.getScheduleBySymbol)(x):void 0,[eV,ed,x,ez]),eK=(0,r.useMemo)(()=>eq&&!(0,U.is24x7)(eq)?(0,U.parseSchedule)(eq):null,[eq]);(0,r.useEffect)(()=>{if(!eK)return;let e=setInterval(()=>eW(e=>e+1),6e4);return()=>clearInterval(e)},[eK]);let eG=(0,r.useMemo)(()=>!!eK&&!(0,U.isMarketOpenAt)(eK,new Date),[eK,eH]),eY=(0,r.useRef)(o),eX=(0,r.useRef)(!1),eQ=(0,r.useRef)(0),[eJ,eZ]=(0,r.useState)(0),e0=(0,r.useCallback)(e=>{let t=`${ed??""}|${x}|${e$??""}`;return eC&&ed&&(0,A.hasOracleCoverage)(ed)?`${t}|oracle`:"phoenix"===e?`${t}|phoenix|${eG?"last":"mark"}`:`${t}|${e}`},[ed,x,e$,eC,eG]),e1=e0(eU),e2=e0(eO),[e5]=(0,r.useState)(()=>new j),{front:e3,back:e4,retiring:e6,failedKey:e8}
2=(0,r.useSyncExternalStore)(e5.subscribe,e5.getSnapshot,e5.getSnapshot),e9=(0,r.useRef)(null),e7=(0,r.useCallback)(e=>{if(eX.current=!0,eY.current!==e){eY.current=e,eQ.current+=1;let t=!!e5.getSnapshot().back;e5.abandonBack(),t||e5.getSnapshot().retiring||(e9.current?.(),e9.current=null),eZ(eQ.current)}E?.(e)},[e5,E]);(0,r.useEffect)(()=>{e4||e6||(e9.current?.(),e9.current=null)},[e4,e6]),(0,r.useEffect)(()=>()=>{e5.destroyAll(),e9.current?.(),e9.current=null},[e5]),(0,r.useEffect)(()=>{if(!et)return;let e=()=>e5.getSnapshot().front?.handle.current??null;return et.current={setResolution:t=>e()?.setResolution(t),executeAction:t=>e()?.executeAction(t),restorePanes:()=>e()?.restorePanes()},()=>{et.current=null}},[et,e5]);let[te,tt]=(0,r.useState)(null),tr=(0,a.useOnScreen)(te),ti=(0,l.useChartLayerRecovery)(e5,tr),ts=(0,r.useRef)(0),tn=(0,r.useCallback)((e,t,r)=>{if(eC&&ed&&(0,A.hasOracleCoverage)(ed)){let i=new h.MemeTokenDatafeed(ed,x,"regular",en,ea,"Pyth",void 0,void 0,!1);return i.setHistoryPriority(es.current),i.prefetchBars(eY.current),e5.create(e,t,i,r)}if("gmtrade"===t){let i=new f.GmTradeDatafeed(x);return i.setHistoryPriority(es.current),e5.create(e,t,i,r)}if("phoenix"===t){let i=new m.PhoenixDatafeed(x,{useLastPrice:eG});return i.setHistoryPriority(es.current),e5.create(e,t,i,r)}if(!ed)return null;let i=S.VENUE_LABELS[t],s=new h.MemeTokenDatafeed(ed,x,"regular",en,ea,i,t,"armada"===t?(0,p.createSunriseChartSource)(x):void 0,"armada"===t);return s.setHistoryPriority(es.current),s.prefetchBars(eY.current),e5.create(e,t,s,r)},[e5,eC,ed,x,eG,e$]);(0,r.useEffect)(()=>{let e=e5.getSnapshot();if(e.front?.key!==e1){if(e.back?.key===e1)return void e5.promote();e5.abandonBack(),e5.retire(),e5.replaceFront(tn(e1,eU))}},[e5,e1]),(0,r.useEffect)(()=>{if(!e6)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>e5.retire())});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[e5,e6]),(0,r.useEffect)(()=>{if(e2===e1||!ti)return void e5.abandonBack();let e=e5.getSnapshot();if(null!==e.failedKey&&e.failedKey!==e2&&e5.clearFailed(),e.back?.key===e2||e.failedKey===e2)return;e.back&&e.back.key!==e2&&e5.abandonBack();let t=!1,r=eQ.current,s=new AbortController,n=setTimeout(()=>{(async()=>{let e=i?await I.acquire(s.signal):()=>{};if(!e)return;if(t||eQ.current!==r)return e();e9.current=e;let n=await e5.getSnapshot().front?.handle.current?.save()??void 0;if(t||eQ.current!==r){e9.current===e&&(e9.current=null),e();return}let a=tn(e2,eO,n);if(!a){e5.markFailed(e2),e9.current=null,e();return}ts.current=Date.now(),e5.setBack(a)})()},Math.max(400,3e3-(Date.now()-ts.current)));return()=>{t=!0,s.abort(),clearTimeout(n)}},[e5,e2,e1,e8,ti,i,eJ]);let ta=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{ta.current&&clearTimeout(ta.current)},[]);let tl=(0,r.useCallback)((e,t)=>{let r=e5.getSnapshot();if(r.back?.id!==e)return;let i=r.front?.handle.current;if(i?.isPointerDown()&&Date.now()-t<1e4){ta.current=setTimeout(()=>tl(e,t),250);return}let s=()=>{let t=e5.getSnapshot();t.back?.id===e&&M(eg,t.back.venue)},n=i?.getUserLineToolsState()??null,a=r.back.handle.current;n&&a?a.replaceUserLineTools(n).catch(()=>void 0).then(s):s()},[e5,eg]),to=(0,r.useCallback)(e=>tl(e,Date.now()),[tl]);(0,r.useEffect)(()=>{for(let e of[e3,e4])e?.datafeed.setHistoryPriority(10*!!s)},[e3,e4,s]),(0,r.useEffect)(()=>{for(let e of[e3,e4])e?.datafeed instanceof h.MemeTokenDatafeed&&e.datafeed.updatePriceMode(en,ea)},[e3,e4,en,ea]);let td=eC||eB||!ev||w(ev)===w(eU)?null:ev,tc=null!==e8&&e8===e2?eO:null,tu=ti&&e2!==e1&&null===tc?null:tc?ei("chartFailedVenueNotice",{venue:S.VENUE_LABELS[tc],chartVenue:S.VENUE_LABELS[eU]}):td?ei("chartRoutedVenueNotice",{chartVenue:S.VENUE_LABELS[eU],routedVenue:S.VENUE_LABELS[td]}):eB?ei("chartFallbackFeedNotice",{fallbackVenue:S.VENUE_LABELS[eU],primaryVenue:S.VENUE_LABELS[eA]}):null,th={symbol:x,chartId:i,executionActive:s,onActivate:n,inheritLegacyLayout:u,positionLines:B,tradeMarkers:$,hiddenLineIds:q,onHideLine:K,labelMode:G,onLabelModeChange:Y,onResolutionChange:e7,onLineDragged:X,mintAddress:ed??"",onToggleDepth:Q,depthOpen:J,hideHeader:Z,desktopLayout:ee,interval:eY.current,overrideSavedInterval:eX.current,focusRequestReady:e1===e2&&"mark"===eP};if(!ed)return(0,t.jsx)("div",{className:"h-full w-full flex items-center justify-center bg-surface",children:(0,t.jsx)("span",{className:"text-label-muted text-sm",children:ei("chartNotAvailableFor",{symbol:x})})});let tp=[e3&&{layer:e3,visible:!0,zIndex:20,onReady:void 0},e6&&{layer:e6,visible:!0,zIndex:10,onReady:void 0},e4&&{layer:e4,visible:!1,zIndex:0,onReady:to}].flatMap(e=>e?[e]:[]).sort((e,t)=>
2e.layer.id-t.layer.id);return(0,t.jsxs)("div",{ref:tt,className:`flex flex-col h-full w-full overflow-hidden ${Z?"bg-[var(--phone-ground)]":"bg-surface"}`,children:[s&&(0,t.jsx)(H,{symbol:x,onRoute:ep}),tu&&(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-amber-950/80 border-b border-amber-700/60 text-amber-200 text-xs",role:"status",children:[(0,t.jsx)(d.AlertTriangle,{className:"w-3.5 h-3.5 flex-shrink-0"}),(0,t.jsx)("span",{children:tu}),tc&&(0,t.jsx)("button",{type:"button",onClick:()=>e5.clearFailed(),className:"ml-auto shrink-0 rounded-chip px-1.5 py-0.5 font-semibold underline decoration-dotted underline-offset-2 hover:bg-amber-900/60 focus-ring",children:ei("chartRetryVenue",{venue:S.VENUE_LABELS[tc]})})]}),(0,t.jsxs)("div",{className:"relative isolate flex-1 min-h-0",children:[!e3&&!e6&&(0,t.jsx)(O,{}),tp.map(e=>(0,t.jsx)(W,{layer:e.layer,visible:e.visible,foreground:e.layer===e3,zIndex:e.zIndex,onReady:e.onReady,common:th,priceMode:en},e.layer.id))]})]})});var K=e.i(504458);let G=(0,K.default)("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),Y=(0,K.default)("maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]),X=(0,K.default)("minimize",[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]);var Q=e.i(312076);e.s(["MoreHorizontal",()=>Q.default],33623);var Q=Q,J=e.i(626074),Z=e.i(786258);let ee=[{resolution:"1",label:"1m"},{resolution:"5",label:"5m"},{resolution:"15",label:"15m"},{resolution:"60",label:"1h"},{resolution:"240",label:"4h"},{resolution:"1D",label:"D"}],et="relative flex h-[22px] w-3 items-start justify-center text-muted-foreground transition-colors hover:text-foreground before:absolute before:-inset-x-3 before:-top-4 before:-bottom-1 before:content-[''] focus-ring",er=(0,r.memo)(function({resolution:e,actions:r,expanded:i,onToggleExpanded:s,expandDisabled:n}){let a=(0,c.useTranslations)("trading"),[l]=(0,A.useChartDataMode)(),o=(0,Z.useTradeMarkersEnabled)();return(0,t.jsxs)("div",{"data-slot":"chart-toolbar",className:"flex h-[34px] shrink-0 items-end border-b border-[var(--phone-hairline)] pl-[13px] pr-[22px]",children:[(0,t.jsx)("div",{role:"group","aria-label":a("chartInterval"),className:"flex items-end gap-3 min-[360px]:gap-4",children:ee.map(i=>{let s=i.resolution===e;return(0,t.jsx)("button",{type:"button","aria-pressed":s,onClick:()=>r.current?.setResolution(i.resolution),className:`relative flex h-[22px] items-start text-[11.36px] font-medium leading-[14px] text-muted-foreground transition-colors before:absolute before:-inset-x-2 before:-top-4 before:-bottom-1 before:content-[''] focus-ring ${s?"text-primary after:absolute after:-inset-x-1 after:bottom-px after:h-[1.8px] after:rounded-[1.2px] after:bg-primary after:content-['']":"hover:text-foreground"}`,children:i.label},i.resolution)})}),(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-end gap-[21px]",children:[(0,t.jsx)("button",{type:"button","aria-label":a(i?"chartExitExpanded":"chartExpand"),"aria-pressed":i,disabled:n,onClick:s,className:`${et} disabled:opacity-40`,children:i?(0,t.jsx)(X,{className:"h-3 w-3"}):(0,t.jsx)(Y,{className:"h-3 w-3"})}),(0,t.jsx)("button",{type:"button","aria-label":a("chartIndicators"),onClick:()=>r.current?.executeAction("insertIndicator"),className:et,children:(0,t.jsx)(G,{className:"h-3 w-3",strokeWidth:1.5})}),(0,t.jsxs)(J.DropdownMenu,{children:[(0,t.jsx)(J.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":a("chartMore"),className:et,children:(0,t.jsx)(Q.default,{className:"h-3 w-3"})})}),(0,t.jsxs)(J.DropdownMenuContent,{align:"end",sideOffset:6,className:"w-52 text-xs",children:[(0,t.jsx)(J.DropdownMenuCheckboxItem,{checked:"oracle"===l,onCheckedChange:e=>(0,A.setChartDataMode)(e?"oracle":"mark"),children:a("chartOracleCandles")}),(0,t.jsx)(J.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:()=>(0,Z.toggleTradeMarkers)(),children:a("chartFillMarkers")}),(0,t.jsx)(J.DropdownMenuSeparator,{}),(0,t.jsx)(J.DropdownMenuItem,{onSelect:()=>r.current?.restorePanes(),children:a("chartRestorePanes")})]})]})]})]})});
2function ei({symbol:e,mintAddress:a,underwriters:l,resolution:o,onResolutionChange:d,positionLines:c,tradeMarkers:u,hiddenLineIds:h,onHideLine:p,labelMode:m,onLabelModeChange:f,onLineDragged:x,parked:g=!1}){let b=(0,r.useRef)(null),v=(0,r.useRef)(null),[y,w]=(0,r.useState)(!1);(0,i.useBackToClose)(y,()=>w(!1),"imperialChartExpanded"),(0,r.useEffect)(()=>{if(!y||!v.current)return;let e=v.current,t=document.body.style.overflow;document.body.style.overflow="hidden";let r=[],i=e;for(;i.parentElement;){for(let e of i.parentElement.children)e!==i&&e instanceof HTMLElement&&(r.push({element:e,inert:e.inert}),e.inert=!0);if(i.parentElement===document.body)break;i=i.parentElement}let s=e=>{"Escape"!==e.key||e.defaultPrevented||w(!1)},n=new Set,a=()=>{for(let t of e.querySelectorAll("iframe"))try{let e=t.contentDocument;if(!e||n.has(e))continue;e.addEventListener("keydown",s),n.add(e)}catch{}};return a(),e.addEventListener("load",a,!0),window.addEventListener("keydown",s),()=>{for(let{element:e,inert:i}of(document.body.style.overflow=t,r))e.inert=i;for(let t of(e.removeEventListener("load",a,!0),n))t.removeEventListener("keydown",s);window.removeEventListener("keydown",s)}},[y]);let j=(0,r.useRef)(null),[S,k]=(0,r.useState)(void 0);return(0,r.useEffect)(()=>{let e=j.current;if(!e||g||y)return;let t=t=>{let r=t?.[0]?.borderBoxSize?.[0]?.blockSize??e.getBoundingClientRect().height;r>0&&k(Math.round(r))};t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[g,y]),(0,t.jsxs)("div",{ref:v,"data-slot":"mobile-chart-view","data-expanded":y,className:y?"fixed inset-0 z-[100] flex h-dvh w-full flex-col bg-[var(--phone-ground)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)]":"flex flex-1 min-h-0 flex-col",children:[(0,t.jsx)(er,{resolution:o,actions:b,expanded:y,onToggleExpanded:()=>w(e=>!e),expandDisabled:g}),(0,t.jsx)("div",{ref:j,className:g?s.PARKED_OFFSCREEN:"relative flex-1 min-h-0",style:g?{height:S}:void 0,inert:g,"aria-hidden":g,children:(0,t.jsx)(n.ErrorBoundary,{children:(0,t.jsx)(q,{symbol:e,mintAddress:a,underwriters:l,onResolutionChange:d,positionLines:c,tradeMarkers:u,hiddenLineIds:h,onHideLine:p,labelMode:m,onLabelModeChange:f,onLineDragged:x,hideHeader:!0,actionsRef:b})})})]})}var es=e.i(575146);let en="imperial.mobile-chart-height.v1";function ea(e,t){return Math.min(t.max,Math.max(t.min,(e??1)*t.max))}e.s(["MobileChartBand",0,function({active:e,inert:i=!1,resizable:n=!1,resizeEnabled:a=!0,resizeLabel:l,resizeActions:o,children:d}){let c=(0,r.useRef)(null),u=(0,r.useRef)(null),[h,p]=(0,r.useState)(null),m=(0,r.useRef)(null),[f,x]=(0,r.useState)(()=>{try{var e=window.localStorage.getItem(en);if(!e)return null;try{let t=JSON.parse(e);return t?.version===1&&"number"==typeof t.ratio&&Number.isFinite(t.ratio)&&t.ratio>0&&t.ratio<=1?t.ratio:null}catch{return null}}catch{return null}}),[g,b]=(0,r.useState)(null),[v,y]=(0,r.useState)(null),[w,j]=(0,r.useState)(!1),[S,k]=(0,r.useState)(!1),[N,P]=(0,r.useState)(!1),T=(0,r.useRef)(!1),C=e&&n&&a&&!i,M=(0,r.useCallback)(()=>{let e=c.current?.parentElement;if(!e)return m.current?.cancel(),null;let t=e.querySelector('[data-slot="home-shelf"] [data-slot="tabs-list"]'),r=t?t.getBoundingClientRect().height+1:45,i=function(e,t=45){let r=Math.max(0,(Number.isFinite(e)?e:0)-(Number.isFinite(t)?Math.max(0,t):45));return{min:Math.min(260,r),max:r}}(e.clientHeight,r);return m.current?.rebase(i,e.clientWidth),b(e=>e?.min===i.min&&e.max===i.max?e:i),i},[]);function _(e){if(e&&!N){let e=u.current?.getBoundingClientRect();if(!e)return;p({left:e.left,top:e.top,width:e.width,height:e.height})}P(e)}function A(e,t){if(t.max<=0)return;let r=Math.min(1,Math.max(0,e/t.max));x(r);try{window.localStorage.setItem(en,JSON.stringify({version:1,ratio:r}))}catch{}}(0,r.useEffect)(()=>{if(!e||!n)return;let t=c.current?.parentElement;if(!t)return;let r=t.querySelector('[data-slot="home-shelf"] [data-slot="tabs-list"]'),i=new ResizeObserver(M);return i.observe(t),r&&i.observe(r),()=>i.disconnect()},[e,n,M]),(0,r.useEffect)(()=>
2{if(C)return;m.current?.cancel();let e=requestAnimationFrame(()=>P(!1));return()=>cancelAnimationFrame(e)},[C]),(0,r.useEffect)(()=>()=>m.current?.cancel(),[]),(0,r.useEffect)(()=>{if(!N)return;let e=c.current?.parentElement,t=()=>P(!1),r=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let r=e.target;r?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"])')||!(" "===e.key&&r?.closest?.('button, [role="button"]'))&&["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&t()};return e?.addEventListener("wheel",t,{passive:!0}),e?.addEventListener("touchmove",t,{passive:!0}),document.addEventListener("keydown",r),window.addEventListener("resize",t),()=>{e?.removeEventListener("wheel",t),e?.removeEventListener("touchmove",t),document.removeEventListener("keydown",r),window.removeEventListener("resize",t)}},[N]);let E=g?v??ea(f,g):void 0,L=!!g&&(E??0)>g.min,F=!!g&&(E??0)<g.max,R=F||null!==f&&1!==f;return(0,t.jsxs)("div",{ref:c,"data-slot":"chart-band","aria-hidden":!e,inert:!e||i,className:e?"relative flex shrink-0 flex-col overflow-hidden border-b border-border":`${s.PARKED_OFFSCREEN} h-[var(--app-vh,100svh)] flex flex-col`,style:e?{height:n?E??"max(0px, calc(100% - 45px))":"clamp(260px, calc(100% - 9rem), 560px)"}:void 0,children:[(0,t.jsx)("div",{className:"relative flex flex-1 min-h-0 flex-col",children:d}),e&&n&&(0,t.jsxs)(es.Popover,{open:N&&C,onOpenChange:_,children:[(0,t.jsx)(es.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("div",{ref:u,role:"separator","aria-orientation":"horizontal","aria-label":l,"aria-valuemin":Math.round(g?.min??0),"aria-valuemax":Math.round(g?.max??0),"aria-valuenow":Math.round(E??0),"aria-disabled":!C||!g||g.max<=g.min,tabIndex:C?0:-1,"data-slot":"mobile-chart-resize","data-resizing":w||void 0,className:`flex h-6 shrink-0 cursor-row-resize items-center justify-center bg-[var(--phone-ground)] text-muted-foreground select-none touch-none ${S?"outline-none":"focus-ring-inset"}`,style:{WebkitUserSelect:"none",WebkitTouchCallout:"none",WebkitTapHighlightColor:"transparent"},onPointerDown:e=>{!m.current&&e.isPrimary&&0===e.button&&(T.current=!1,k(!0),function(e){if(!C||!e.isPrimary||0!==e.button||m.current)return;let t=M();if(!t||t.max<=t.min)return;let r=e.currentTarget,i=c.current;if(!i)return;try{r.setPointerCapture(e.pointerId)}catch{return}let s=ea(f,t),n=null,a={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,anchorHeight:s,height:s,bounds:t,axis:"pending",lastX:e.clientX,lastY:e.clientY,width:i.parentElement?.clientWidth??0,cancel:()=>{},rebase:()=>{}},l=document.createElement("style");l.textContent='[data-slot="chart-band"], [data-slot="chart-band"] * { user-select: none !important; -webkit-user-select: none !important; } [data-slot="chart-band"] iframe { pointer-events: none !important; }',document.head.appendChild(l);let o=i.querySelectorAll("iframe"),d=()=>{for(let e of(window.getSelection()?.removeAllRanges(),o))try{e.contentWindow?.getSelection()?.removeAllRanges()}catch{}},u=e=>e.preventDefault(),h=()=>{m.current===a&&(m.current=null,null!==n&&cancelAnimationFrame(n),window.removeEventListener("pointermove",w,!0),window.removeEventListener("pointerup",S,!0),window.removeEventListener("pointercancel",x,!0),window.removeEventListener("blur",p),document.removeEventListener("keydown",g,!0),document.removeEventListener("visibilitychange",b),r.removeEventListener("lostpointercapture",x),i.removeEventListener("selectstart",u,!0),i.removeEventListener("dragstart",u,!0),"pending"!==a.axis&&d(),l.remove(),r.hasPointerCapture(a.pointerId)&&r.releasePointerCapture(a.pointerId),j(!1),y(null))},p=()=>h(),x=e=>{e.pointerId===a.pointerId&&p()},g=e=>{"Escape"===e.key&&(e.preventDefault(),p())},b=()=>{document.hidden&&p()},v=e=>{var t,r;a.lastX=e.clientX,a.lastY=e.clientY;let i=e.clientY-a.startY,s=a.axis;t=a.axis,r=e.clientX-a.startX,a.axis="pending"!==t?t:6>Math.max(Math.abs(r),Math.abs(i))?"pending":Math.abs(r)>1.2*Math.abs(i)?"horizontal":Math.abs(i)>1.2*Math.abs(r)?"vertical":"pending","pending"===s&&"pending"!==a.axis&&d(),"pending"!==a.axis&&(T.current=!0,P(!1)),"vertical"===a.axis&&(a.height=Math.max(a.bounds.min,Math.min(a.bounds.max,a.anch
2orHeight+i)))},w=e=>{m.current!==a||e.pointerId!==a.pointerId||((1&e.buttons)==0?p():(M(),m.current!==a||(v(e),"vertical"===a.axis&&(e.preventDefault(),null===n&&(n=requestAnimationFrame(()=>{n=null,m.current===a&&(j(!0),y(a.height))}))))))},S=e=>{if(m.current!==a||e.pointerId!==a.pointerId||(M(),m.current!==a))return;v(e);let t="vertical"===a.axis&&Math.abs(a.height-ea(f,a.bounds))>=1;h(),t&&A(a.height,a.bounds)};a.cancel=p,a.rebase=(e,t)=>{t!==a.width||e.max<=0?p():(e.min!==a.bounds.min||e.max!==a.bounds.max)&&(a.bounds=e,a.height="vertical"===a.axis?Math.max(e.min,Math.min(e.max,a.height)):ea(f,e),a.anchorHeight=a.height,a.startX=a.lastX,a.startY=a.lastY,"vertical"===a.axis&&(j(!0),y(a.height)))},m.current=a,window.addEventListener("pointermove",w,{capture:!0,passive:!1}),window.addEventListener("pointerup",S,!0),window.addEventListener("pointercancel",x,!0),window.addEventListener("blur",p),document.addEventListener("keydown",g,!0),document.addEventListener("visibilitychange",b),r.addEventListener("lostpointercapture",x),i.addEventListener("selectstart",u,!0),i.addEventListener("dragstart",u,!0)}(e))},onClick:e=>{(T.current||!C)&&e.preventDefault()},onBlur:()=>k(!1),onKeyDown:e=>{if(k(!1),C&&("Enter"===e.key||" "===e.key)){e.preventDefault(),T.current=!1,_(!N);return}if(!C||!g||!["ArrowUp","ArrowDown","Home","End"].includes(e.key))return;e.preventDefault();let t=ea(f,g),r="Home"===e.key?g.min:"End"===e.key?g.max:Math.max(g.min,Math.min(g.max,t+("ArrowUp"===e.key?-1:1)*(e.shiftKey?40:20)));r!==t&&A(r,g)},children:(0,t.jsx)("span",{"aria-hidden":!0,className:`h-0.5 w-8 rounded-full ${w?"bg-primary":"bg-border-strong"}`})})}),(0,t.jsx)(es.PopoverAnchor,{"aria-hidden":"true","data-mobile-chart-resize-anchor":"",style:{position:"fixed",pointerEvents:"none",left:h?.left??0,top:h?.top??0,width:h?.width??0,height:h?.height??0}}),(0,t.jsx)(es.PopoverContent,{side:"top",align:"center",className:"w-auto max-w-[calc(100vw-24px)] p-1","aria-label":l,children:(0,t.jsxs)("div",{className:"flex gap-1",children:[(0,t.jsx)("button",{type:"button",className:"min-h-9 rounded px-3 text-xs focus-ring-inset aria-disabled:opacity-40","aria-disabled":!L,onClick:()=>{L&&g&&A(Math.max(g.min,(E??0)-40),g)},children:o.shrink}),(0,t.jsx)("button",{type:"button",className:"min-h-9 rounded px-3 text-xs focus-ring-inset aria-disabled:opacity-40","aria-disabled":!R,onClick:()=>{R&&g&&A(g.max,g)},children:o.reset}),(0,t.jsx)("button",{type:"button",className:"min-h-9 rounded px-3 text-xs focus-ring-inset aria-disabled:opacity-40","aria-disabled":!F,onClick:()=>{F&&g&&A(Math.min(g.max,(E??0)+40),g)},children:o.expand})]})})]})]})}],519052);var el=e.i(946422);function eo({name:e,className:r=""}){return(0,t.jsxs)("svg",{"data-mobile-nav-icon":e,"aria-hidden":"true",focusable:"false",viewBox:"0 0 24 24",width:"24",height:"24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:`${el.default.icon} ${r}`,children:["perps"===e&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("g",{className:el.default.candleLow,children:[(0,t.jsx)("path",{d:"M7 4v5m0 8v4"}),(0,t.jsx)("rect",{x:"4.75",y:"9",width:"4.5",height:"8",rx:".75"})]}),(0,t.jsxs)("g",{className:el.default.candleHigh,children:[(0,t.jsx)("path",{d:"M17 2v3m0 8v6"}),(0,t.jsx)("rect",{x:"14.75",y:"5",width:"4.5",height:"8",rx:".75"})]})]}),"points"===e&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("path",{d:"m13 2.7 6.5 3.75a2 2 0 0 1 1 1.73v7.64a2 2 0 0 1-1 1.73L13 21.3a2 2 0 0 1-2 0l-6.5-3.75a2 2 0 0 1-1-1.73V8.18a2 2 0 0 1 1-1.73L11 2.7a2 2 0 0 1 2 0Z"}),(0,t.jsx)("path",{className:el.default.rewardStar,d:"m12 7 1.5 3.05 3.36.49-2.43 2.37.57 3.34L12 14.67l-3 1.58.57-3.34-2.43-2.37 3.36-.49Z",fill:"currentColor",stroke:"none"})]}),"packs"===e&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("g",{children:[(0,t.jsx)("path",{d:"M4.5 6.25V20.6q0 .65 .65 .65h13.7q.65 0 .65-.65V6.25M4.5 17.75h15"}),(0,t.jsx)("path",{d:"M8 20v1.25M12 20v1.25M16 20v1.25",strokeWidth:"1.2"})]}),(0,t.jsxs)("g",{className:el.default.packLid,children:[(0,t.jsx)("path",{d:"M4.5 6.25V3.4q0-.65 .65-.65h13.7q.65 0 .65.65v2.85Z"}),(0,t.jsx)("path",{d:"M8 2.75V4M12 2.75V4M16 2.75V4",strokeWidth:"1.2"})]}),(0,t.jsx)("path",{className:el.default.packEmblem,d:"m12 8.5 2.75 3.5-2.75 3.5L9.25 12Z",fill:"currentColor",stroke:"none"})]}),"more"===e&&(0,t.jsxs)("g",{fill:"currentColor",stroke:"none",children:[(0,t.jsx)("circle",{className:el.default.dotLeft,cx:"5",cy:"12",r:"1.7"}),(0,t.jsx)("circle",{className:el.default.dotMiddle,cx:"12",cy:"12",r:"1.7"}),(0,t.jsx)("circle",{className:el.default.dotRight,cx:"19",cy:"12",r:"1.7"})]})]})}function ed(){let e=(0,r.useRef)(new Map);return(0,r.useEffect)(()=>{let t=e.current,r=()=>{for(let[e,r]of t)clearTimeout(r),e.classList.remove(el.default.playing);t.clear()},i=window.matchMedia("(prefers-reduced-motion: reduce)"),s=()=>{i.matches&&r()};
2return i.addEventListener("change",s),()=>{i.removeEventListener("change",s),r()}},[]),(0,r.useCallback)(t=>{if(0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||!(t.target instanceof Element))return;let r=t.target.closest("a,button");if(!r||!t.currentTarget.contains(r))return;let i=r.querySelector("svg[data-mobile-nav-icon]");!i||(clearTimeout(e.current.get(i)),e.current.delete(i),i.classList.remove(el.default.playing),window.matchMedia("(prefers-reduced-motion: reduce)").matches||(i.getBoundingClientRect(),i.classList.add(el.default.playing),e.current.set(i,setTimeout(()=>{i.classList.remove(el.default.playing),e.current.delete(i)},600))))},[])}e.s(["MobileNavIcon",0,eo,"useMobileNavIconMotion",0,ed],711599);var ec=e.i(491135),eu=e.i(845165),eh=e.i(685576);function ep(e,t,i){(0,r.useEffect)(()=>{if(!e)return;let r=setTimeout(()=>{let e=t.current;if(!e)return;let r=document.activeElement;r!==e&&e.contains(r)||e.querySelector(i)?.focus()},260);return()=>clearTimeout(r)},[e,t,i])}e.s(["useFocusAfterSlide",0,ep],219979);var em=e.i(637740);e.i(875574);var ef=e.i(142298),ex=e.i(762745);function eg(){let[e,t]=(0,r.useState)(!0),[i,s]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{"false"===localStorage.getItem("imperial_sound_enabled")&&t(!1),s(!0)},[]),{soundEnabled:e,setSoundEnabled:(0,r.useCallback)(e=>{t(e),(0,ex.setSoundEnabled)(e)},[]),isLoaded:i}}e.s(["useSoundPreferences",0,eg],280864);var eb=e.i(116082),ev=e.i(999069),ey=e.i(37952);function ew(){let e=(0,c.useTranslations)("common"),{isSponsorMode:t,logout:i}=(0,ev.useSponsorGas)(),{enroll:s,loading:n,canEnroll:a}=(0,ey.useSponsorGasEnroll)(),l=(0,r.useCallback)(async()=>{if(t){await i(),eb.toast.info(e("oneClickTradingDisabled"));return}await s()&&eb.toast.success(e("oneClickTradingEnabled"))},[t,i,s,e]);return{isSponsorMode:t,toggle:l,loading:n,canEnroll:a}}e.s(["useSponsorToggle",0,ew],504421);var ej=e.i(554580),eS=e.i(803817),ek=e.i(430232),eN=e.i(153517);let eP="https://docs.imperial.space",eT="https://docs.imperial.space/legal/terms-of-service",eC="https://docs.imperial.space/legal/privacy-policy",eM="https://x.com/imperialperps",e_="https://discord.gg/K249JgDtN7";e.s(["DISCORD_URL",0,e_,"DOCS_URL",0,eP,"PRIVACY_POLICY_URL",0,eC,"TERMS_OF_SERVICE_URL",0,eT,"X_URL",0,eM],725102);var eA=e.i(407340),eE=e.i(872501);let eL=[{href:"/leaderboard",labelKey:"leaderboard"},...eA.PAWN_NAV_VISIBLE?[{href:"/lending",labelKey:"pawn"}]:[],...eE.RIP_NAV_VISIBLE?[{href:"/rip",labelKey:"rip"}]:[],{href:"/referrals",labelKey:"referrals"}],eF=[{href:eP,labelKey:"documentation"},{href:eM,labelKey:"xTwitter"},{href:e_,labelKey:"discord"}],eR=[...eF,{href:eT,labelKey:"terms"},{href:eC,labelKey:"privacy"}];e.s(["MORE_DESTINATIONS",0,eL,"MORE_RESOURCES",0,eR,"NAV_RESOURCES",0,eF],789382);let eD=(0,o.default)(()=>e.A(297078).then(e=>({default:e.VenueSettingsDialog})),{loadableGenerated:{modules:[251512]},ssr:!1}),eI=(0,o.default)(()=>e.A(171547).then(e=>({default:e.TradeStrengthSettingsDialog})),{loadableGenerated:{modules:[370546]},ssr:!1}),eU="more-menu-sheet",eO=`${s.PHONE_ROW} gap-2.5 px-3`,eB=`focus-ring ${eO} w-full`,ez="shrink-0 overflow-hidden rounded-xl border border-border bg-surface-raised divide-y divide-border",e$="shrink-0 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground";function eV({onClose:e,onOpenAccount:r,onVenueSettings:i,onTradeStrength:s}){let n=(0,c.useTranslations)("nav"),a=(0,c.useTranslations)("settings"),l=(0,c.useTranslations)("common"),o=(0,c.useTranslations)("trading"),{range:d}=(0,ej.useTradeStrengthRange)(),u=(0,ej.useStrengthRangeLabel)(d),h=(0,c.useTranslations)("wallet"),{publicKey:p,connected:m}=(0,ef.useUnifiedWallet)(),{soundEnabled:f,setSoundEnabled:x,isLoaded:g}=eg(),{isSponsorMode:b,toggle:v,loading:y}=ew(),w=p?.toBase58()??"";return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:ez,children:[m&&w&&(0,t.jsxs)(eS.Link,{href:`/profile/${w}`,replace:!0,className:eB,children:[n("profile"),(0,t.jsx)(ec.ChevronRight,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]}),eL.map(({href:e,labelKey:r})=>(0,t.jsxs)(eS.Link,{href:e,replace:!0,className:eB,children:[n(r),(0,t.jsx)(ec.ChevronRight,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]},e))]}),m?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("h2",{className:e$,children:a("title")}),(0,t.jsxs)("div",{className:ez,children:[r&&(0,t.jsxs)("button",{type:"button",onClick:r,className:eB,children:[h("navAccount"),(0,t.jsx)("span",{className:"ml-auto font-mono text-xs text-muted-foreground",children:(0,eN.shortAddress)(w)}),(0,t.jsx)(ec.ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]}),(0,t.jsxs)("div",{className:eO,children:[l("oneClickTrading"),
2(0,t.jsx)(em.Switch,{checked:b,disabled:y,onCheckedChange:()=>void v(),"aria-label":l("oneClickTrading"),className:"ml-auto"})]}),(0,t.jsxs)("div",{className:eO,children:[a("soundEffects"),(0,t.jsx)(em.Switch,{checked:f,disabled:!g,onCheckedChange:x,"aria-label":a("soundEffects"),className:"ml-auto"})]}),(0,t.jsxs)("button",{type:"button",onClick:i,className:eB,children:[a("venueSettings"),(0,t.jsx)(ec.ChevronRight,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]}),(0,t.jsxs)("button",{type:"button",onClick:s,className:eB,children:[a("tradeStrength"),(0,t.jsx)("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:u}),(0,t.jsx)(ec.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0})]})]})]}):(0,t.jsx)("button",{type:"button",onClick:()=>{e(),(0,ek.promptConnectWallet)()},className:"focus-ring flex h-11 items-center justify-center rounded-xl bg-primary text-[13px] font-bold text-primary-foreground",children:h("getStarted")}),(0,t.jsx)("h2",{className:e$,children:n("sectionResources")}),(0,t.jsx)("div",{className:ez,children:eR.map(({href:e,labelKey:r})=>(0,t.jsxs)("a",{href:e,target:"_blank",rel:"noreferrer",className:eB,children:["terms"===r?o("termsOfService"):"privacy"===r?o("privacyPolicy"):n(r),(0,t.jsx)(eu.ExternalLink,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]},e))})]})}function eH({count:e}){return e<=0?null:(0,t.jsx)("span",{"aria-hidden":!0,className:"absolute -right-[10px] -top-[7px] flex h-[15px] min-w-[15px] items-center justify-center rounded-full bg-primary px-[3px] font-mono text-[9px] font-bold leading-none tabular-nums text-white",children:e>9?"9+":e})}e.s(["MORE_MENU_SHEET_ID",0,eU,"MoreMenuSheet",0,function({open:e,onClose:i,onOpenAccount:s,returnFocusRef:n}){let a=(0,c.useTranslations)("nav"),l=(0,r.useRef)(null),[o,d]=(0,r.useState)(!1),[u,h]=(0,r.useState)(!1);return ep(e,l,"a,button"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eh.Sheet,{open:e,onOpenChange:e=>{e||i()},children:(0,t.jsxs)(eh.SheetContent,{ref:l,id:eU,side:"bottom",hideClose:!0,className:`${eh.SHEET_MOTION} gap-2.5 overflow-y-auto border-border-strong px-3.5 pt-0 focus:outline-none focus-visible:outline-none`,onOpenAutoFocus:e=>e.preventDefault(),onCloseAutoFocus:e=>{e.preventDefault(),n?.current?.focus()},children:[(0,t.jsx)(eh.SheetTitle,{className:"sr-only",children:a("more")}),(0,t.jsx)(eV,{onClose:i,onOpenAccount:s,onVenueSettings:()=>d(!0),onTradeStrength:()=>h(!0)})]})}),o&&(0,t.jsx)(eD,{open:!0,onOpenChange:d}),u&&(0,t.jsx)(eI,{open:!0,onOpenChange:h})]})}],723181),e.s(["NavCountBadge",0,eH],96970);let eW=s.NAV_CELL,eq=s.NAV_CELL_ACTIVE,eK=s.NAV_LABEL;e.s(["MobileBottomNav",0,function({activeTab:e,onTabChange:r,moreOpen:i,toolbarInset:n=0}){let a,l,o,d,u=(0,c.useTranslations)("nav"),h=ed(),p=(e,r,i,s,n,a)=>(0,t.jsxs)(eS.Link,{href:e,className:`${eW} ${n}`,"aria-label":a>0?u("openPositionsBadge",{label:r,count:a}):void 0,children:[(0,t.jsx)(eo,{name:i,className:s}),(0,t.jsxs)("span",{className:"relative flex min-w-0",children:[(0,t.jsx)("span",{className:eK,children:r}),(0,t.jsx)(eH,{count:a})]})]});return(0,t.jsx)("div",{className:s.NAV_BAR_IN_SHELL,style:n?{bottom:`${n}px`,paddingBottom:0}:void 0,children:(0,t.jsxs)("div",{className:"flex items-stretch",style:{height:s.NAV_ROW_PX},onClickCapture:h,children:[(a="trade"===e||"chart"===e||"book"===e,l=u("perps"),o=s.NAV_ICON_PERPS,d=s.NAV_TONE_IDLE,(0,t.jsxs)("button",{type:"button",onClick:()=>r("trade"),"aria-current":a?"page":void 0,className:`${eW} ${a?eq:d}`,children:[(0,t.jsx)(eo,{name:"perps",className:o}),(0,t.jsx)("span",{className:eK,children:l})]})),p("/points",u("points"),"points",s.NAV_ICON_POINTS,s.NAV_TONE_IDLE,0),eE.RIP_NAV_VISIBLE&&p("/rip",u("rip"),"packs",s.NAV_ICON_PACKS,s.NAV_TONE_DIM,0),(0,t.jsxs)("button",{type:"button",onClick:()=>r("more"),"aria-expanded":i,"aria-controls":eU,className:`${eW} ${i||"more"===e?eq:s.NAV_TONE_DIM}`,children:[(0,t.jsx)(eo,{name:"more",className:s.NAV_ICON_MORE}),(0,t.jsx)("span",{className:eK,children:u("more")})]})]})})}],708853);let eG=(0,K.default)("arrow-left-right",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);e.s(["ArrowLeftRight",0,eG],101034);let eY=(0,K.default)("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);e.s(["FileText",0,eY],178655);let eX=(0,K.default)("gem",[["path",{d:"M10.5 3 8 9l4 13 4-13-2.5-6",key:"b3dvk1"}],["path",{d:"M17 3a2 2 0 0 1 1.6.8l3 4a2 2 0 0 1 .013 2.382l-7.99 10.986a2 2 0 0 1-3.247 0l-7.99-10.986A2 2 0 0 1 2.4 7.8l2.998-3.997A2 2 0 0 1 7 3z",key:"7w4byz"}],["path",{d:"M2 9h20",key:"16fsjt"}]]);e.s(["Gem",0,eX],237073)},225806,508972,807702,319136,884722,921575,88783,441253,528277,623984,462503,e=>{"use strict";let t;e.s(["PortfolioValueBreakdown",()=>tT],462503),e.s(["MobileMarketSelector",()=>tg],225806),e.s(["MarketSelectorTable",()=>tf,"MobileMarketSelectorTable",()=>tx,"displayName",()=>te],921575),e.s(["PairCarryEntryRow",()=>q,"PairCarryPanel",()=>K],508972),e.s(["useMarketSelectionEligibility",()=>eJ],884722);var r=e.i(394390),i=e.i(183023),s=e.i(815),n=e.i(859394),a=e.i(942553),l=e.i(685576),o=e.i(219979),d=e.i(457058),c=e.i(58596),u=e.i(394802),h=e.i(440736),p=e.i(242150),m=e.i(522973),f=e.i(599179),x=e.i(92065),g=e.i(967090),b=e.i(109650),v=e.i(116082),y=e.i(268680);e.i(965155);var w=e.i(22156),j=e.i(541043),S=e.i(828845),k=e.i(578866),N=e.i(634692),P=e.i(907169),T=e.i(390431),C=e.i(599059),M=e.i(652538),_=e.i(491135),A=e.i(943494),E=e.i(5364),L=e.i(665757),F=e.i(438495),R=e.i(375290),D=e.i(937626),I=e.i(124431),U=e.i(706405),O=e.i(656526),B=e.i(153517),z=e.i(821043),$=e.i(299959);let V="text-imperial-gold";function H(e){return`${e>=0?"+":""}${e.toFixed(4)}%`}function W(e){let t=e.longLeg.notionalUsd+e.shortLeg.notionalUsd;return t>0?e.netCarryPerDayUsd/24/t*100:0}function q({pairs:e,isLoading:t=!1,onOpen:i}){let s=(0,a.useTranslations)("carry");return 0!==e.length||t?(0,r.jsx)("div",{className:"border-b border-imperial-gold/20",children:(0,r.jsxs)("button",{type:"button",onClick:i,className:(0,B.cn)("pair-suggestion flex w-full items-center gap-3 px-3 py-2 text-left","transition-colors hover:bg-imperial-gold/10"),
2children:[(0,r.jsx)(E.Percent,{className:(0,B.cn)("h-4 w-4 shrink-0",V)}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("div",{className:(0,B.cn)("text-sm font-semibold",V),children:"Carry"}),(0,r.jsx)("div",{className:"text-[11px] text-text-muted",children:0===e.length&&t?(0,r.jsxs)("span",{className:"pair-dots","aria-label":s("findingPairs"),children:[(0,r.jsx)("i",{}),(0,r.jsx)("i",{}),(0,r.jsx)("i",{})]}):s("entrySubtitle",{count:e.length})})]}),(0,r.jsx)(_.ChevronRight,{className:(0,B.cn)("h-4 w-4 shrink-0",V)})]})}):null}function K({onBack:e,onOpened:t,onBrowseAll:s}){let n=(0,a.useTranslations)("carry"),[l,o]=(0,i.useState)(null),{pairs:d,candidates:c,isLoading:u}=(0,T.useTopPairs)(!0,3,l),{mintFor:h,legMarketFor:p,priceFor:m,maxLeverageFor:f}=(0,O.usePairOpenResolvers)(),[x,g]=(0,i.useState)(null);(0,i.useEffect)(()=>{null===x&&d.length>0&&g(d.map(e=>e.key))},[x,d]);let b=(0,i.useMemo)(()=>{if(!x)return d;let e=new Map(c.map(e=>[e.key,e])),t=new Map(d.map(e=>[e.key,e]));return x.map(r=>e.get(r)??t.get(r)).filter(e=>!!e)},[x,c,d]),[v,y]=(0,i.useState)(null),w=v??b[0]?.key??null,j=b.find(e=>e.key===w)??null;return(0,r.jsxs)("div",{className:"flex max-h-full flex-col gap-3 overflow-y-auto p-4",children:[(0,r.jsxs)("div",{className:"flex items-start gap-2",children:[(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":n("backToMarkets"),className:"mt-0.5 rounded p-1 text-text-muted transition-colors hover:bg-surface-raised hover:text-text-primary",children:(0,r.jsx)(M.ChevronLeft,{className:"h-4 w-4"})}),(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsxs)("div",{className:(0,B.cn)("flex items-center gap-2 text-lg",V),children:[(0,r.jsx)(E.Percent,{className:"h-4 w-4"}),"Carry"]}),(0,r.jsx)("p",{className:"text-muted-foreground text-sm",children:n("panelBlurb")})]})]}),0===b.length&&u&&(0,r.jsx)(G,{}),0===b.length&&!u&&(0,r.jsx)("p",{className:"text-sm text-text-muted",children:n("noneAtThisSize")}),b.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(F.SlidingUnderline,{activeKey:w??"",className:"flex items-center gap-1 overflow-x-auto border-b border-imperial-gold/20",barClassName:"bg-imperial-gold",children:b.map(e=>(0,r.jsxs)("button",{type:"button","data-tab":!0,"data-active":e.key===w,title:`${e.longSymbol}/${e.shortSymbol}`,onClick:()=>y(e.key),className:(0,B.cn)("flex shrink-0 flex-col items-start gap-0.5 px-3 pt-1 pb-2 text-left transition-colors",e.key===w?"text-text-primary":"text-text-muted hover:text-text-primary"),children:[(0,r.jsxs)("span",{className:"flex items-center gap-1 text-xs font-semibold whitespace-nowrap",children:[(0,r.jsx)("span",{className:"text-side-long",children:e.longSymbol}),(0,r.jsx)("span",{className:"text-text-muted",children:"/"}),(0,r.jsx)("span",{className:"text-side-short",children:e.shortSymbol})]}),(0,r.jsxs)("span",{className:(0,B.cn)("text-xs font-mono tabular-nums",V),children:[H(W(e)),"/h"]})]},e.key))}),j&&(0,r.jsx)(Y,{pair:j,onOpened:t,mintFor:h,legMarketFor:p,priceFor:m,maxLeverageFor:f,sizing:l,onSizingChange:o},j.key)]}),(0,r.jsx)("button",{type:"button",onClick:()=>s(j),className:"self-center text-xs text-text-muted underline-offset-2 transition-colors hover:text-text-primary hover:underline",children:n("wantMorePairs")})]})}function G(){return(0,r.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,r.jsx)("div",{className:"flex items-center gap-4 border-b border-imperial-gold/20 pb-2",children:[0,1,2].map(e=>(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsx)("div",{className:"pair-skeleton h-3 w-14 rounded"}),(0,r.jsx)("div",{className:"pair-skeleton h-2.5 w-10 rounded"})]},e))}),(0,r.jsxs)("div",{className:"rounded-lg border border-imperial-gold/15 bg-imperial-gold/[0.03] px-3 py-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsx)("div",{className:"pair-skeleton h-4 w-28 rounded"}),(0,r.jsx)("div",{className:"pair-skeleton h-5 w-16 rounded"})]}),(0,r.jsxs)("div",{className:"mt-2 grid grid-cols-2 gap-x-3",children:[(0,r.jsx)("div",{className:"pair-skeleton h-3 w-full rounded"}),(0,r.jsx)("div",{className:"pair-skeleton h-3 w-full rounded"})]}),(0,r.jsx)("div",{className:"pair-skeleton mt-2 h-3 w-3/4 rounded"})]})]})}function Y({pair:e,onOpened:t,mintFor:i,legMarketFor:s,priceFor:n,maxLeverageFor:a,sizing:l,onSizingChange:o}){return(0,r.jsxs)("div",{className:"animate-in fade-in-0 duration-150 motion-reduce:animate-none rounded-lg border border-imperial-gold/25 bg-imperial-gold/[0.04]",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-2 px-3 pt-3 pb-2.5",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-base whitespace-nowrap",children:[(0,r.jsx)("span",{className:"font-semibold text-side-long",children:e.longSymbol}),(0,r.jsx)("span",{className:"text-text-muted",children:"/"}),(0,r.jsx)("span",{className:"font-semibold text-side-short",children:e.shortSymbol})]}),(0,r.jsxs)("div",{className:"text-right",children:[(0,r.jsxs)("div",{className:(0,B.cn)("text-xl leading-tight font-bold font-mono tabular-nums",V),children:[H(W(e)),(0,r.jsx)("span",{className:"text-sm font-normal text-text-muted",children:"/h"})]}),(0,r.jsx)("div",{className:"text-[10px] text-text-muted",children:"net funding"})]})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-x-3 text-sm tabular-nums",children:[(0,r.jsx)(Q,{label:`Long ${e.longSymbol}
2 \xb7 ${C.VENUE_LABELS[e.longLeg.underwriter]}`,pct:e.longLeg.carryPctPerHour}),(0,r.jsx)(Q,{label:`Short ${e.shortSymbol} \xb7 ${C.VENUE_LABELS[e.shortLeg.underwriter]}`,pct:e.shortLeg.carryPctPerHour})]}),(0,r.jsxs)("div",{className:"text-xs text-text-muted",children:[(e.wABps/100).toFixed(0),"/",(e.wBBps/100).toFixed(0)," split",!e.betaIsFallback&&` \xb7 β ${e.beta.toFixed(2)}`,` \xb7 hedges ${(100*e.hedgeQuality).toFixed(0)}%`,null!==e.breakEvenHours&&` \xb7 breaks even in ${(0,R.formatBreakEven)(e.breakEvenHours)}`]})]}),(0,r.jsx)(X,{pair:e,onOpened:t,mintFor:i,legMarketFor:s,priceFor:n,maxLeverageFor:a,sizing:l,onSizingChange:o})]})}function X({pair:e,onOpened:t,mintFor:s,legMarketFor:n,priceFor:l,maxLeverageFor:o,sizing:d,onSizingChange:c}){let u=(0,$.useFormatters)(),h=(0,a.useTranslations)("carry"),p=(0,D.usePairTicket)(),{balances:m}=(0,I.useProfileBalance)(),{createPair:f,isSubmitting:x}=(0,U.useCreatePair)(),g=d?.collateralUsd??p.collateralUsd,b=d?.leverage??p.leverage,[v,y]=(0,i.useState)(g>0?String(g):""),[w,j]=(0,i.useState)(b>0?String(b):""),[S,k]=(0,i.useState)(!1);(0,i.useEffect)(()=>{S||(y(p.collateralUsd>0?String(p.collateralUsd):""),j(p.leverage>0?String(p.leverage):""))},[S,p.collateralUsd,p.leverage]);let N=(e,t)=>{k(!0);let r=parseFloat(e)||0,i=parseFloat(t)||0;r>0&&i>0&&c({collateralUsd:r,leverage:i})},P=g*b,T=P*e.wABps/1e4,C=P*e.wBBps/1e4,M=s(e.longSymbol)&&n(e.longSymbol,e.longLeg.underwriter)?s(e.shortSymbol)&&n(e.shortSymbol,e.shortLeg.underwriter)?null:e.shortSymbol:e.longSymbol,_=null!==m.USDC&&g>m.USDC?g-m.USDC:null,E=o(e.longSymbol,e.longLeg.underwriter),F=o(e.shortSymbol,e.shortLeg.underwriter),R=null!==E&&null!==F?Math.min(E,F):null,O=null===R?null:R===E?e.longSymbol:e.shortSymbol,V=null!==R&&b>R,H=g>0&&b>0&&!M&&!_&&!V&&!x,W=async()=>{await f({pair:e,collateralUsd:g,leverage:b,mintFor:s,legMarketFor:n,priceFor:l})&&t()};return(0,r.jsxs)("div",{className:"flex flex-col gap-3 border-t border-imperial-gold/20 px-3 py-3",children:[(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,r.jsxs)("label",{className:"flex flex-col gap-1",children:[(0,r.jsx)("span",{className:"text-[10px] text-text-muted",children:h("collateralBothLegs")}),(0,r.jsx)(L.Input,{value:v,onChange:e=>{let t=(0,z.sanitizeDecimalInput)(e.target.value,u.decimalSeparator);y(t),N(t,w)},inputMode:"decimal",placeholder:"0.00",className:"h-8 text-sm font-mono tabular-nums"})]}),(0,r.jsxs)("label",{className:"flex flex-col gap-1",children:[(0,r.jsxs)("span",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[10px] text-text-muted",children:h("leverage")}),null!==R&&(0,r.jsx)("button",{type:"button",onClick:()=>{j(String(R)),N(v,String(R))},className:"text-[10px] tabular-nums text-text-muted underline-offset-2 hover:text-text-primary hover:underline",children:h("maxLeverage",{max:R})})]}),(0,r.jsx)(L.Input,{value:w,onChange:e=>{let t=(0,z.sanitizeDecimalInput)(e.target.value,u.decimalSeparator);j(t),N(v,t)},inputMode:"decimal",placeholder:"3",className:(0,B.cn)("h-8 text-sm font-mono tabular-nums",V&&"border-red-400/60 text-red-400")})]})]}),(0,r.jsxs)("div",{className:"flex items-center justify-between text-[11px] tabular-nums",children:[(0,r.jsxs)("span",{className:"text-text-muted",children:["Long ",e.longSymbol," ",(0,r.jsx)("span",{className:"text-side-long",children:u.usd(T)})]}),(0,r.jsxs)("span",{className:"text-text-muted",children:["Short ",e.shortSymbol," ",(0,r.jsx)("span",{className:"text-side-short",children:u.usd(C)})]})]}),(0,r.jsxs)("button",{type:"button",disabled:!H,onClick:W,className:(0,B.cn)("flex h-9 items-center justify-center gap-2 rounded-md text-sm font-medium","bg-imperial-gold text-black transition-colors hover:bg-[#f0d585]","disabled:cursor-not-allowed disabled:opacity-40"),children:[x&&(0,r.jsx)(A.Loader2,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none"}),h(x?"openingBothLegs":"openPair")]}),(0,r.jsx)("p",{className:(0,B.cn)("text-[10px] leading-tight text-text-muted",V&&"text-red-400"),children:M?h("notListed",{symbol:M}):_?h("needsMoreUsdc",{amount:u.usd(_)}):V?h("overPairCap",{symbol:O??"",max:R??0}):h("placesTwoOrdersSplitNote")})]})}function Q({label:e,pct:t}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-text-muted truncate",children:e}),(0,r.jsxs)("span",{className:t>=0?"text-side-long":"text-side-short",children:[H(t),(0,r.jsx)("span",{className:"text-text-muted",children:"/h"})]})]})}var J=e.i(824088),Z=e.i(403628),ee=e.i(76990),et=e.i(468602),er=e.i(988408);e.i(875574);var ei=e.i(142298),es=e.i(687229);e.i(654249);var en=e.i(71917),ea=e.i(759550),el=e.i(942289),eo=e.i(678872);let ed="imperial_favorite_markets",ec=new Set,eu=ec,eh=!1,ep=new Set;function em(e){if(!e)return new Set;try{let t=JSON.parse(e);if(!Array.isArray(t))return new Set;return new Set(t.filter(e=>"string"==typeof e))}catch{return new Set}}function ef(){for(let e of ep)e()}function ex(e){e.key===ed&&(eu=em(e.newValue),ef())}function eg(e){return 0===ep.size&&window.addEventListener("storage",ex),ep.add(e),eh||(eu=em(localStorage.getItem(ed)),eh=!0,ef()),(
2)=>{ep.delete(e),0===ep.size&&window.removeEventListener("storage",ex)}}function eb(e){let t=new Set(eu);t.has(e)?t.delete(e):t.add(e),eu=t,localStorage.setItem(ed,JSON.stringify([...t])),ef()}function ev(){return{favorites:(0,i.useSyncExternalStore)(eg,()=>eu,()=>ec),toggleFavorite:eb,isLoaded:(0,i.useSyncExternalStore)(eg,()=>eh,()=>!1)}}e.s(["useFavoriteMarkets",0,ev],807702);let ey="imperial.market-highlights.v1",ew=!1,ej=new Set;function eS(){try{let e;return e=localStorage.getItem(ey),"false"!==e}catch{return}}function ek(){return void 0===t&&(t=eS()??!0),t}function eN(){ej.forEach(e=>e())}function eP(e){if(e.key===ey||null===e.key){try{if(e.storageArea&&e.storageArea!==localStorage)return}catch{}ew=!1,t=null===e.key||"false"!==e.newValue,eN()}}function eT(e){return 0===ej.size&&(ew||(t=eS()??t??!0),window.addEventListener("storage",eP)),ej.add(e),()=>{ej.delete(e),0===ej.size&&window.removeEventListener("storage",eP)}}function eC(e){t=e;try{localStorage.setItem(ey,String(e)),ew=!1}catch{ew=!0}eN()}var eM=e.i(43690),e_=e.i(362221);let eA=e=>null!=e&&Number.isFinite(e)?e:null,eE=e=>{let t=eA(e);return null!=t&&t>=0?t:null},eL=e=>{let t=eA(e);return null!=t&&t>0?t:null};async function eF(){let e=await fetch("https://api.imperial.space/api/v1/phoenix/volumes");if(!e.ok)throw Error("Failed to fetch Phoenix market stats");return(await e.json()).map(e=>({...e,symbol:(0,e_.phoenixToCanonicalSymbol)(e.symbol)}))}function eR(e,t){let r=(0,N.useSunriseOpensAllowed)()&&!t.includes("armada"),s=(0,eM.useQuery)({queryKey:["phoenix-market-stats"],queryFn:eF,enabled:e,staleTime:25e3,refetchInterval:3e4}),n=(0,k.useSunriseMarkets)();return{stats:(0,i.useMemo)(()=>(function(e,t,r){let i=new Map,s=new Set(r.map(e=>e.symbol.toUpperCase()));for(let n of e?[...r,...r.length>0?t.filter(e=>!s.has(e.symbol.toUpperCase())):[]]:t){let e,t=eA("openInterest"in n?n.imperialFundingRate1hPct:n.fundingRate1hPct);if("openInterest"in n){let r=eL(n.markPrice),i=eE(n.openInterest);e={avgRate8h:null==t?0:8*t/100,hasFunding:null!=t,totalOiUsd:null!=i&&null!=r?eE(i*r):null,volume24hUsd:eE(n.dailyQuoteTokenVolume),price:r,change24h:eA(n.dailyPriceChange)}}else e={avgRate8h:null==t?0:8*t/100,hasFunding:null!=t,totalOiUsd:eE(n.openInterestUsd),volume24hUsd:eE(n.volume24hUsd),price:eL(n.markPrice),change24h:eA(n.change24hPct)};i.set(n.symbol.toUpperCase(),e)}return i})(r,s.isError?[]:s.data??[],n.isError?[]:n.data??[]),[r,s.data,s.isError,n.data,n.isError]),isPending:s.isPending||r&&(n.isPending||n.isPlaceholderData)}}e.s(["useVenueMarketStats",0,eR],319136),e.i(889723);var eD=e.i(465217),eI=e.i(406470),eU=e.i(305916),eO=e.i(894771),eB=e.i(972015),ez=e.i(591872),e$=e.i(364589),eV=e.i(555641),eH=e.i(828047),eW=e.i(331613);function eq(e){return"jupiter"===e||"phoenix"===e||"gmtrade"===e?e:null}function eK(e){if(!e)return{isLow:!1,isNone:!1};let t=[e.longAvailableUsd??null,e.shortAvailableUsd??null].filter(e=>null!=e);if(0===t.length)return{isLow:!1,isNone:!1};let r=t.every(e=>0===e);return{isLow:r||t.some(e=>e<1e3),isNone:r}}function eG(e,t){return 0!==e.length&&e.every(e=>"gmtrade"===e&&eK(t).isLow)}function eY(e,t,r,i,s,n,a,l){let o=e.underwriters??[];if(0===o.length)return null;if((0,eO.isAutoUnderwriter)(t)){let d=(0,el.buildCapabilities)({asset:e.symbol,phoenixMarket:r?{maxLeverage:r.maxLeverage,takerFeeMicro:r.takerFeeMicro,makerFeeMicro:r.makerFeeMicro}:null,gmTradeMarket:n.listed?{maxLeverage:n.maxLeverage,openFeePositivePercent:n.fees?.openFeePositivePercent,openFeeNegativePercent:n.fees?.openFeeNegativePercent,longNetRatePerHourPercent:n.fees?.longNetRatePerHourPercent,shortNetRatePerHourPercent:n.fees?.shortNetRatePerHourPercent,longAvailableUsd:n.liquidity?.longAvailableUsd,shortAvailableUsd:n.liquidity?.shortAvailableUsd}:null,jupiterSupported:o.includes("jupiter")}),c=(0,e$.getSavedLeverage)(e.symbol)??3,u=(0,e$.getReferenceNotional)(e.symbol),h={};if(i&&i.symbol===e.symbol&&(h.phoenix={priceImpactBps:(e,t,r)=>{let s="long"===("open"===r?t:"long"===t?"short":"long")?i.asks:i.bids;return(0,eB.bookWalkPriceImpactBps)(s,i.mid,e)}}),n.listed&&n.liquidity){let e=n.liquidity;h.gmtrade={priceImpactBps:(t,r,i)=>{if("open"===i){let i="long"===r?e.longAvailableUsd:e.shortAvailableUsd;if(null!=i&&isFinite(i)&&t>i)return 1/0}return(0,eB.gmtradePositionImpactBps)(e.totalOiLongUsd,e.totalOiShortUsd,t,r,i,e.positionImpactExponent,e.positionImpactPositiveFactor,e.positionImpactNegativeFactor)}}}let p=(0,ez.computeRoute)({asset:e.symbol,side:"long",notional:u,desiredLeverage:c,holdHours:(0,er.resolveHoldHours)(s,e.symbol),subaccountDefaultVenue:eq(t),stickyVenue:a,capabilities:d,liquidity:h,excludedVenues:l});return p?p.venue:(0,eV.resolveConcreteUnderwriter)(t,e.mint,l)}if(a&&o.includes(a))return a;
2if(!(0,eO.isAutoUnderwriter)(t)&&o.includes(t))return t;let d=["phoenix","gmtrade","jupiter"],c=new Set(l);return d.find(e=>o.includes(e)&&!c.has(e))??d.find(e=>o.includes(e))??o[0]}function eX(e,t){return(0,el.anyVenueAcceptsOpens)(e.underwriters)||t.has(e.symbol)}function eQ(e,t,r){return function(e,t,r,i,s){if(r.has(e))return!0;let n=t.get(e);return!!n&&!n.isolatedOnly||i&&s(e)}(e,t,r,(0,eW.sunriseOpensAllowed)(),eH.sunriseListsSymbol)}function eJ(e={}){let t=(0,eO.useProfile)(),r=e.activeProfileUnderwriter??t.activeProfileUnderwriter,s=e.activeProfileExcludedVenues??t.activeProfileExcludedVenues,{publicKey:n}=(0,ei.useUnifiedWallet)(),{data:a}=(0,er.useTradingStats)(n?.toBase58()),{positions:l}=(0,es.useUnifiedPositions)(),{data:o}=(0,ee.usePhoenixMarkets)(),{data:d}=(0,et.usePhoenixDepthSummary)(),{data:c}=(0,Z.useGmTradeMarkets)(),{getMarketLiquidity:u,getMaxLeverage:h,getMarketFees:p,symbols:m}=(0,J.useGmTradeWs)(),{stickyVenueByAsset:f,openAssets:x}=(0,i.useMemo)(()=>(function(e,t){let r=new Map,i=new Set;for(let s of e){if("open"===s.status&&(s.profileIndex??null)===(t??null)&&i.add(s.asset),null===t||s.profileIndex!==t||"open"!==s.status&&"pending"!==s.status&&"closing"!==s.status)continue;let e=eq(s.underwriter);e&&r.set(s.asset,e)}return{stickyVenueByAsset:r,openAssets:i}})(l,t.activeProfileIndex),[l,t.activeProfileIndex]),g=(0,i.useMemo)(()=>new Map((o??[]).map(e=>[e.symbol,e])),[o]),b=(0,i.useMemo)(()=>{let e=new Map;for(let t of c??[])e.set(t.symbol,(e.get(t.symbol)??!1)||!t.closed);return e},[c]),v=(0,i.useCallback)(e=>!1!==e.allowOpenPosition&&eX(e,x)&&("unified"!==t.activeProfileMarginMode||eQ(e.symbol,g,x)),[x,t.activeProfileMarginMode,g]),y=(0,i.useCallback)(e=>{var t,i;let n,l,o=u(e.symbol),c=eY(e,r,g.get(e.symbol),d?.snapshots[e.symbol],a,{listed:(e.underwriters??[]).includes("gmtrade")||(b.get(e.symbol)??m.includes(e.symbol)),maxLeverage:h(e.symbol),fees:p(e.symbol),liquidity:o},f.get(e.symbol)??null,s);return t=(0,eO.isAutoUnderwriter)(r),i=x.has(e.symbol),l=eG(n=t?Array.from(new Set([...(e.underwriters??[]).filter(e=>!s.includes(e)),...c?[c]:[]])):c?[c]:[],n.includes("gmtrade")?o:void 0),{venue:c,liquiditySnapshot:"gmtrade"===c?o:void 0,isFullyIlliquid:l,isDisabled:l&&!i}},[r,s,g,d,a,b,m,h,p,u,f,x]),w=(0,i.useCallback)(e=>v(e)&&!y(e).isDisabled,[v,y]);return{isMarketListed:v,isMarketSelectable:w,getMarketAccess:y,phoenixMarkets:o,phoenixMarketsBySymbol:g}}function eZ(e,t,r,i,s=0,n=4){return e<=0||t<=0||i<=0||r+i<=s||r>=s+e*t?{start:0,end:0}:{start:Math.max(0,Math.floor((r-s)/t)-n),end:Math.min(e,Math.ceil((r+i-s)/t)+n)}}function e0(e,t,r,i){let s="ArrowUp"===r||"End"===r,n="Home"===r?0:"End"===r?e.length-1:t<0?s?e.length-1:0:(t+(s?-1:1)+e.length)%e.length;for(let t=0;t<e.length;t++){let r=(n+(s?-t:t)+e.length)%e.length;if(i(e[r]))return r}return -1}let e1='button:not(:disabled):not([tabindex="-1"]), a[href]:not([tabindex="-1"])',e2={position:"absolute",width:1,height:1,overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap"};function e5({rows:e,rowKey:t,rowHeight:s,scrollRef:n,renderRow:a,ref:l,onFocusLost:o}){let d=(0,i.useRef)(null),[c]=(0,i.useState)(()=>{let t=eZ(e.length,s,0,480),r=new Set;return{read:()=>t,subscribe:e=>(r.add(e),()=>{r.delete(e)}),publish(e){if(t.start!==e.start||t.end!==e.end)for(let i of(t=e,r))i()}}}),u=(0,i.useSyncExternalStore)(c.subscribe,c.read,c.read),[h,p]=(0,i.useState)(null),m=(0,i.useRef)(null),f=(0,i.useRef)(null),x=(0,i.useCallback)(()=>{let e=n.current,t=d.current;return e&&t?{scroll:e,listTop:t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,height:e.clientHeight}:null},[n]),g=(0,i.useCallback)(()=>{let t=x();if(!t)return;let r=eZ(e.length,s,t.scroll.scrollTop,t.height,t.listTop);c.publish(r)},[x,s,e.length,c]);(0,i.useLayoutEffect)(()=>{let e=n.current,t=d.current;if(!e||!t)return;let r=null,i=()=>{null===r&&(r=requestAnimationFrame(()=>{r=null,g()}))},s=new ResizeObserver(i);for(let r of(s.observe(e),s.observe(t),e.children))s.observe(r);return e.addEventListener("scroll",i,{passive:!0}),g(),()=>{null!==r&&cancelAnimationFrame(r),s.disconnect(),e.removeEventListener("scroll",i)}},[n,g]),(0,i.useLayoutEffect)(()=>{g()});let b=(0,i.useCallback)((e,t,r)=>{let i=d.current?.querySelector(`[data-windowed-market-row="${e}"]`),s=i?.querySelectorAll(t),n=s?.[r?s.length-1:0];return!!n&&(f.current=null,n.focus({preventScroll:!0}),!0)},[]),v=(0,i.useCallback)((r,i="[data-market-select]",n=!1)=>{let a=e[r],l=x();if(!a||!l)return;let o=t(a);f.current={key:o,selector:i,last:n},l.scroll.scrollTop=function(e,t,r,i,s=0){let n=s+e*t;return n<r?n:n+t>r+i?Math.max(0,n+t-i):r}(r,s,l.scroll.scrollTop,l.height,l.listTop),p(o),g(),b(r,i,n)},[e,t,s,x,g,b]);(0,i.useImperativeHandle)(l,()=>({focusRow:v}),[v]),(0,i.useLayoutEffect)(()=>{let r=f.current;r&&b(e.findIndex(e=>t(e)===r.key),r.selector,r.last),m.current&&!m.current.isConnected&&(m.current=null,document.activeElement===document.body&&o?.())});let y=[];for(let t=u.start;t<Math.min(u.end,e.length);t++)y.push(t);let w=null===h?-1:e.findIndex(e=>t(e)===h);return w>=0&&!y.includes(w)&&y.push(w),y.sort((e,t)=>
2e-t),(0,r.jsxs)("div",{ref:d,role:"list","data-windowed-market-list":!0,style:{position:"relative",height:e.length*s,overflowAnchor:"none"},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||(p(null),m.current=null)},children:[(0,r.jsx)("span",{"data-market-window-entry":"first",tabIndex:e.length>0&&w<0?0:-1,style:{...e2,top:0},onFocus:()=>v(0,e1)}),y.map(i=>(0,r.jsx)("div",{role:"listitem","aria-posinset":i+1,"aria-setsize":e.length,"data-windowed-market-row":i,style:{position:"absolute",top:i*s,width:"100%",height:s},onFocusCapture:r=>{p(t(e[i])),m.current=r.target},onKeyDown:t=>{if("Tab"!==t.key||t.altKey||t.ctrlKey||t.metaKey)return;let r=t.currentTarget.querySelectorAll(e1),s=r[t.shiftKey?0:r.length-1],n=i+(t.shiftKey?-1:1);t.target!==s||n<0||n>=e.length||(t.preventDefault(),v(n,e1,t.shiftKey))},children:a(e[i],i)},t(e[i]))),(0,r.jsx)("span",{"data-market-window-entry":"last",tabIndex:e.length>0&&w<0?0:-1,style:{...e2,bottom:0},onFocus:()=>v(e.length-1,e1,!0)})]})}function e3(e,t,r){let i=new Map;for(let t of e)i.has(t.mint)||i.set(t.mint,t);let s=[...i.values()].map((e,i)=>{let s=r(e);return{market:e,index:i,favorite:t.has(e.mint),volume:null!=s&&Number.isFinite(s)&&s>=0?s:null}});return s.sort((e,t)=>e.favorite!==t.favorite?e.favorite?-1:1:null==e.volume&&null!=t.volume?1:null!=e.volume&&null==t.volume?-1:(t.volume??0)-(e.volume??0)||e.index-t.index),s.map(({market:e})=>e.mint)}var e4=e.i(838580);function e6(e,t,r){if(t)return{key:"noLiquidityAvailable"};if(!e)return null;let i=e.longAvailableUsd??0,s=e.shortAvailableUsd??0;return{key:"lowLiquidity",values:{long:e8(i,r),short:e8(s,r)}}}function e8(e,t){return e>=1e9?`$${(0,eI.formatFixed)(e/1e9,2,t)}B`:e>=1e6?`$${(0,eI.formatFixed)(e/1e6,1,t)}M`:e>=1e3?`$${(0,eI.formatFixed)(e/1e3,1,t)}K`:`$${(0,eI.formatFixed)(e,0,t)}`}let e9={XAU:["gold"],XAUt:["gold"],XAG:["silver"],ZEC:["zcash"],XAGt:["silver"],XCU:["copper"],XPT:["platinum"],EUR:["euro"],GBP:["pound","sterling"],JPY:["yen"],CNH:["yuan","renminbi","rmb"],USDMXN:["peso","mexican peso","mexico","mxn"],CRUDEOIL:["oil","crude","wti"],"CRUDE-OIL":["oil","crude","wti"],WTIOIL:["oil","crude","wti"],NATGAS:["gas","
2natural gas"],BTC:["bitcoin"],ETH:["ethereum","ether"],SOL:["solana"],HBAR:["hedera"],ANSEM:["black bull","blackbull","the black bull"],CASHCAT:["cash cat"],SPX6900:["spx","spx 6900","s&p 6900"],USELESS:["useless coin"],CATE:["catecoin","cate coin"],ANSEMCASHCAT:["ansem","cashcat","cash cat","black bull"],DOGE:["dogecoin"],XRP:["ripple"],BNB:["binance"],SUI:["sui"],TAO:["bittensor"],BONK:["bonk"],PENGU:["penguin","pudgy"],SPY:["s&p","sp500","index"],OPENAI:["open ai","chatgpt"],ANTHROPIC:["claude"],NVDA:["nvidia"],TSLA:["tesla"],AAPL:["apple"],ADBE:["adobe"],AMD:["amd"],AMZN:["amazon"],PLTR:["palantir"],TXN:["texas instruments"],TSM:["taiwan semiconductor","tsmc"],LLY:["eli lilly","lilly"],SNDK:["sandisk"],QCOM:["qualcomm"],IREN:["iris energy","iren"],CRWD:["crowdstrike","crowd strike"],MRNA:["moderna"],MRVL:["marvell","marvell technology"],NET:["cloudflare"],NFLX:["netflix"],IWM:["russell 2000","ishares","small cap"],SONY:["sony"],AAVE:["aave"],WIF:["dogwifhat"],TRUMP:["trump"],HYPE:["hyperliquid"]},e7={AUD:"AUD/USD",EUR:"EUR/USD",GBP:"GBP/USD",NZD:"NZD/USD",USDJPY:"USD/JPY",USDCHF:"USD/CHF",USDCAD:"USD/CAD",USDCNH:"USD/CNH",USDMXN:"USD/MXN",JPY:"USD/JPY",CNH:"USD/CNH",EURUSD:"EUR/USD",GBPUSD:"GBP/USD",AUDUSD:"AUD/USD",NZDUSD:"NZD/USD",USDKRW:"USD/KRW",USDHKD:"USD/HKD",BRENTOIL:"Brent Crude",WTI:"WTI Crude"};function te(e){return e7[e]??e}function tt(e,t,r,i,s){if(null==e||!i||s.includes("phoenix"))return e;let n=r&&r.maxLeverage>0&&isFinite(r.maxLeverage)?r.maxLeverage:void 0;if(null==n)return e;let a=(0,en.loanAwareMaxLeverage)(n,i,t);return null!=a?Math.max(e,(0,el.floorTo2)(a)):e}function tr(e,t,r){if(e.toLowerCase().includes(r)||t.toLowerCase().includes(r)||te(e).toLowerCase().includes(r))return!0;let i=e9[e];return!!i?.some(e=>e.includes(r))}let ti=`${eU.CHIP} font-semibold`,ts="grid grid-cols-[20px_1fr_78px_68px] gap-x-1",tn="grid grid-cols-[22px_minmax(120px,1fr)_90px_120px_80px_80px_80px] gap-x-2",ta="text-[10px] font-medium text-muted-foreground bg-surface-raised rounded-chip px-1 py-0.5 flex-shrink-0",tl=[{id:"default",labelKey:"sortDefault"},{id:"volume",labelKey:"sortVolume"},{id:"oi",labelKey:"openInterest.abbrev"},{id:"funding",labelKey:"sortFunding"},{id:"change24h",labelKey:"sortChange24h"}];function to(e,t,r){switch(e){case"change24h":return r??null;case"funding":return t?.hasFunding?t.avgRate8h:null;case"volume":return t?.volume24hUsd??null;case"oi":return t?.totalOiUsd??null}}function td(e,t,r,i,s){if(!t)return e;let n="desc"===r?-1:1;return[...e].sort((e,r)=>{let a=to(t,i.get(e.symbol),s.get(e.mint)),l=to(t,i.get(r.symbol),s.get(r.mint));return null==a&&null==l?0:null==a?1:null==l?-1:n*(a-l)})}function tc(e,t){if(0===t.size)return e;let r=[],i=[];for(let s of e)t.has(s.mint)?r.push(s):i.push(s);return[...r,...i]}function tu({active:e,direction:t}){return e?"desc"===t?(0,r.jsx)(p.ArrowDown,{className:"w-3 h-3 text-primary"}):(0,r.jsx)(h.ArrowUp,{className:"w-3 h-3 text-primary"}):(0,r.jsx)(m.ArrowUpDown,{className:"w-3 h-3 opacity-40"})}function th(e,t,r){let s=(0,N.useSunriseOpensAllowed)(),{data:n}=(0,k.useSunriseMarkets)();return(0,i.useMemo)(()=>{if(s)return null;let i=new Set(r.map(e=>e.symbol.toUpperCase())),a=t.toLowerCase();return(n??[]).filter(t=>!i.has(t.symbol.toUpperCase())&&(e===S.ALL_CATEGORY_ID||(0,S.matchesCategory)(t.symbol,e))&&(!a||tr(t.symbol,t.symbol,a))).sort((e,t)=>(t.dailyQuoteTokenVolume??0)-(e.dailyQuoteTokenVolume??0))},[s,e,r,t,n])}function tp({markets:e,grid:t,phone:i=!1,scrollRef:s,onDismiss:n}){let l=(0,a.useTranslations)("markets"),o=(0,$.useFormatters)(),c=(0,P.useArmadaAccess)(),u=()=>{n?.(),requestAnimationFrame(c.open)},h=(0,r.jsx)("span",{className:"text-right text-sm text-muted-foreground",children:"—"}),p=e=>(0,r.jsxs)("button",{type:"button",style:i?void 0:{height:44},onClick:u,disabled:!c.available,"aria-haspopup":"dialog","aria-label":`${te(e.symbol)}: ${l("unlockArmada")}`,className:`w-full ${t} items-center text-left transition-colors enabled:hover:bg-surface-interactive disabled:cursor-default ${i?"rounded-control px-2 py-3":"px-4 py-2.5"}`,children:[(0,r.jsx)("span",{className:"flex items-center justify-center",children:(0,r.jsx)(x.Lock,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"})}),(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-2.5",children:[(0,r.jsx)(d.default,{src:(0,eD.getFlashTokenImage)(e.symbol),alt:"",width:24,height:24,className:"rounded-full flex-shrink-0 opacity-70",unoptimized:!0,onError:eD.handleTokenImageError}),(0,r.jsx)("span",{className:"truncate text-sm font-semibold text-secondary-foreground",children:te(e.symbol)})]}),(0,r.jsx)("span",{className:"truncate text-right text-sm font-mono tabular-nums text-secondary-foreground",children:null!=e.markPrice?o.number(e.markPrice):"—"}),null!=e.dailyPriceChange?(0,r.jsxs)("span",{className:`truncate text-right text-sm font-mono tabular-nums ${e.dailyPriceChange>=0?"text-emerald-400":"text-red-400"}`,children:[e.dailyPriceChange>=0?"+":"",o.percent(e.dailyPriceChange,3)]}):h,!i&&(0,r.jsxs)(r.Fragment,{children:[h,h,h]})]},e.symbol);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:`flex items-center justify-between gap-3 border-b border-border/60 py-2.5 ${i?"px-2":"px-4"}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-2 text-xs text-secondary-foreground",children:[(0,r.jsx)(x.Lock,{className:"h-3.5 w-3.5 flex-shrink-0 text-[#e5bb78]","aria-hidden":"true"}),l("armadaLockedNote")]}),(0,r.jsx)("button",{type:"button",onClick:u,disabled:!c.available,"aria-haspopup":"dialog",className:"focus-ring flex min-h-8 flex-shrink-0 items-center rounded-control px-2 text-xs font-semibold text-[#e5bb78] enabled:hover:bg-white/5 disabled:opacity-50",children:l("unlockArmada")})]}),s?(0,r.jsx)(e5,{rows:e,rowKey:e=>e.symbol,rowHeight:44,scrollRef:s,renderRow:p}):e.map(p)]})}function tm({markets:e,marketMint:t,favorites:s,ready:n,visible:l,statsMap:o,changeMap:c,getMarketAccess:u,leverageFor:h,onSelect:p,onToggleFavorite:m,onFocusLost:x}){let g=(0,a.useTranslations)("markets"),b=(0,$.useFormatters)(),[v,y]=(0,i.useState)(()=>n?e3(e,s,e=>o.get(e.symbol)?.volume24hUsd):null);null===v&&n&&y(e3(e,s,e=>o.get(e.symbol)?.volume24hUsd));let w=(0,i.useId)(),j=(0,i.useRef)(null),S=(0,i.useMemo)(()=>l&&v?function(e,t,r){let i=new Map(e.map(e=>[e.mint,e])),s=new Set,n=[],a=e=>{if(s.has(e))return;s.add(e);let t=i.get(e);t&&r(t)&&n.push(t)};for(let e of t)if(a(e),6===n.length)return n;for(let t of e)if(a(t.mint),6===n.length)break;return n}(e,v,e=>!u(e).isDisabled):[],[e,v,l,u]);if((0,i.useLayoutEffect)(()=>{j.current&&!j.current.isConnected&&(j.current=null,document.activeElement===document.body&&x())}),!S.length)return null;let k=e=>null!=e&&Number.isFinite(e)&&e>=0?e8(e,b.intlTag):"—";return(0,r.jsx)("div",{className:e4.default.cards,"data-market-quick-cards":!0,onFocusCapture:e=>{j.current=e.target},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||(j.current=null)},children:S.map((e,i)=>{let n=o.get(e.symbol),a=n?.price,l=null!=a&&Number.isFinite(a)&&a>0?`$${b.number(a)}`:"—",x=c.get(e.mint),v=null!=x&&Number.isFinite(x)?x:null,y=h(e),j=s.has(e.mint);return(0,r.jsxs)("div",{className:e4.default.card,"data-quick-market":e.mint,children:[(0,r.jsxs)("button",{type:"button","data-quick-market-select":!0,className:e4.default.select,"aria-label":`${g("desktopSelectMarket",{symbol:e.symbol})}: ${e.name}`,"aria-current":e.mint===t?"true":void 0,"aria-describedby":`${w}-${i}-quote ${w}-${i}-metrics`,onClick:()=>{u(e).isDisabled||p(e.mint,e)},children:[(0,r.jsxs)("span",{className:e4.default.identity,children:[(0,r.jsx)(d.default,{src:e.image,alt:"",width:20,height:20,className:"shrink-0 rounded-full",unoptimized:!0,onError:eD.handleTokenImageError}),(0,r.jsx)("span",{className:e4.default.symbol,children:te(e.symbol)}),null!=y&&Number.isFinite(y)&&y>0&&(0,r.jsxs)("span",{className:e4.default.leverage,children:[Math.round(y),"x"]})]}),(0,r.jsxs)("span",{id:`${w}-${i}-quote`,className:`${e4.default.quote} tabular-nums`,children:[(0,r.jsx)("span",{className:e4.default.price,children:l}),(0,r.jsx)("span",{className:`${e4.default.change} ${null==v?"text-muted-foreground":v>=0?"text-side-long":"text-side-short"}`,children:null==v?"—":`${v>=0?"+":""}${b.percent(v,2)}`})]}),(0,r.jsxs)("span",{id:`${w}-${i}-metrics`,className:e4.default.metrics,children:[(0,r.jsxs)("span",{className:e4.default.metric,children:[(0,r.jsx)("span",{className:e4.default.metricLabel,children:g("columnVolume24h")}),(0,r.jsx)("span",{className:`${e4.default.metricValue} tabular-nums`,children:k(n?.volume24hUsd)})]}),(0,r.jsxs)("span",{className:e4.default.metric,children:[(0,r.jsx)("span",{className:e4.default.metricLabel,children:g("openInterest.abbrev")}),(0,r.jsx)("span",{className:`${e4.default.metricValue} tabular-nums`,children:k(n?.totalOiUsd)})]})]})]}),(0,r.jsx)("button",{type:"button",className:`${e4.default.favorite} focus-ring`,"aria-label":`${j?g("removeFromFavorites"):g("addToFavorites")}: ${e.symbol}`,"aria-pressed":j,onClick:()=>
2m(e.mint),children:(0,r.jsx)(f.Star,{"aria-hidden":!0,className:`size-3.5 ${j?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})]},e.mint)})})}function tf({allMarkets:e,marketMint:t,onSelect:s,enabled:l=!0,activeProfileUnderwriter:o="imperial",activeProfileExcludedVenues:h=[],initialCategory:p,onOpenCarry:m,showCarry:x=!0,onDismiss:v,refinedDesktop:N=!1,searchLabel:P,showQuickCards:C=!0}){let M=(0,a.useTranslations)("markets"),_=(0,$.useFormatters)(),[A,E]=(0,i.useState)(""),L=(0,i.useRef)(null),F=(0,i.useRef)(null),R=(0,i.useId)(),[D,I]=(0,i.useState)(!1),U=(0,i.useRef)(null);function O(){L.current&&(L.current.scrollTop=0)}let[B,z]=(0,i.useState)(p??S.ALL_CATEGORY_ID);(0,n.useRouter)();let{pairs:V,isLoading:H}=(0,T.useTopPairs)(l&&x),[W,K]=(0,i.useState)(null),[G,Y]=(0,i.useState)("desc"),{prices:X}=(0,w.useAllMarketsPricesThrottled)(),{getPrice:Q}=(0,J.useGmTradeWs)(),{getMarketAccess:Z,isMarketListed:ee,phoenixMarkets:et,phoenixMarketsBySymbol:er}=eJ({activeProfileUnderwriter:o,activeProfileExcludedVenues:h});(0,i.useCallback)(t=>e.find(e=>e.symbol.toUpperCase()===t.toUpperCase())?.mint??null,[e]);let ei=function(){let{data:e}=(0,k.useSunriseMarkets)();return(0,i.useMemo)(()=>{let t=new Map;for(let r of e??[]){let e=r.markPrice;null!=e&&Number.isFinite(e)&&e>0&&t.set(r.symbol.toUpperCase(),e)}return t},[e])}();(0,i.useCallback)(t=>{let r=e.find(e=>e.symbol.toUpperCase()===t.toUpperCase());return r?X[j.MINT_TO_PYTH_SYMBOL[r.mint]??r.symbol]??Q(r.symbol)??ei.get(r.symbol.toUpperCase())??null:null},[e,X,Q,ei]),(0,i.useCallback)(e=>(et??[]).find(t=>t.symbol.toUpperCase()===e.toUpperCase())?.orderbook??null,[et]);let{data:es}=(0,eo.useLendingPoolState)(),en=(0,i.useMemo)(()=>es?(0,ea.toRouterPoolState)(es):null,[es]),{favorites:el,toggleFavorite:ed,isLoaded:ec}=ev(),{highlightsShown:eu,setHighlightsShown:eh}={highlightsShown:(0,i.useSyncExternalStore)(eT,ek,()=>!0),setHighlightsShown:eC},ep=e=>{O(),W===e?Y("desc"===G?"asc":"desc"):(K(e),Y("desc"))},em=eR(l,h).stats,ef=(0,i.useMemo)(()=>new Map(e.map(e=>[e.mint,em.get(e.symbol)?.change24h??null])),[e,em]),ex=(0,i.useMemo)(()=>e.filter(ee),[e,ee]),eg=(0,i.useMemo)(()=>ex.some(e=>{let t=em.get(e.symbol)?.volume24hUsd;return null!=t&&Number.isFinite(t)&&t>=0}),[ex,em]),eb=(0,i.useMemo)(()=>{let e=ex;if(B!==S.ALL_CATEGORY_ID&&(e=e.filter(e=>(0,S.matchesCategory)(e.symbol,B))),D&&(e=e.filter(e=>el.has(e.mint))),A.trim()){let t=A.trim().toLowerCase();e=e.filter(e=>tr(e.symbol,e.name,t))}return tc(td(e,W,G,em,ef),el)},[ex,A,B,W,G,em,ef,el,D]);function ey(e,t){let r=e0(eb,t?eb.findIndex(e=>e.mint===t):-1,e,e=>!Z(e).isDisabled);r>=0&&U.current?.focusRow(r)}let ew=th(B,A,e),ej=!D&&!!ew?.length,eS=0===eb.length&&!ej;return(0,r.jsxs)("div",{className:"flex max-h-[calc(var(--radix-popover-content-available-height,100dvh)-2px)] w-full flex-col overflow-hidden",children:[(0,r.jsxs)("div",{className:"shrink-0 p-3",children:[N&&(0,r.jsxs)("div",{className:"mb-2 flex h-5 items-center justify-between gap-2",children:[(0,r.jsx)("label",{htmlFor:R,className:"text-xs font-medium text-secondary-foreground",children:P??M("desktopSearchMarkets")}),C&&(0,r.jsx)("button",{type:"button","data-market-highlights-toggle":!0,"aria-label":M(eu?"desktopHideHighlights":"desktopShowHighlights"),title:M(eu?"desktopHideHighlights":"desktopShowHighlights"),className:"focus-ring flex h-5 items-center gap-1.5 rounded px-1 text-[11px] text-muted-foreground hover:bg-surface-interactive hover:text-foreground",onClick:()=>eh(!eu),children:eu?(0,r.jsx)(g.X,{size:13,"aria-hidden":!0}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(b.LayoutGrid,{size:12,"aria-hidden":!0}),(0,r.jsx)("span",{children:M("desktopShowHighlightsShort")})]})})]}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(c.Search,{"aria-hidden":!0,className:"absolute left-3 top-1/2 -translate-y-1/2 size-4 text-label-muted"}),(0,r.jsx)("input",{ref:F,id:R,type:"search",autoComplete:"off",spellCheck:!1,value:A,onChange:e=>{O(),E(e.target.value)},"aria-label":P??M("desktopSearchMarkets"),onKeyDown:e=>{if(!e.nativeEvent.isComposing&&(("ArrowDown"===e.key||"ArrowUp"===e.key)&&
2(e.preventDefault(),ey(e.key)),"Enter"===e.key)){let t,r;e.preventDefault(),t=e0(eb,-1,"Home",e=>!Z(e).isDisabled),(r=eb[t])&&s(r.mint,r)}},placeholder:M("searchCoinsPlaceholder"),className:"w-full rounded-[5px] border border-border-strong bg-surface-raised py-2 pl-9 pr-10 text-sm text-foreground placeholder:text-label-muted outline-none focus-visible:ring-2 focus-visible:ring-muted-foreground/60 [&::-webkit-search-cancel-button]:hidden",autoFocus:!0}),A&&(0,r.jsx)("button",{type:"button","aria-label":M("desktopClearSearch"),className:"focus-ring absolute right-1 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-surface-interactive hover:text-foreground",onClick:()=>{O(),E(""),F.current?.focus()},children:(0,r.jsx)(g.X,{size:14,"aria-hidden":!0})})]})]}),N&&C&&ec&&(0,r.jsx)(tm,{markets:ex,marketMint:t,favorites:el,ready:eg,visible:eu&&!A.trim()&&!D&&B===S.ALL_CATEGORY_ID,statsMap:em,changeMap:ef,getMarketAccess:Z,leverageFor:e=>tt(e.maxLeverage,e.symbol,er.get(e.symbol),en,h),onSelect:s,onToggleFavorite:ed,onFocusLost:()=>F.current?.focus()}),(0,r.jsxs)("div",{className:`${eU.CHIP_RAIL} shrink-0 px-3 pb-1.5`,children:[N&&(0,r.jsxs)("button",{type:"button","aria-pressed":D,onClick:()=>{O(),I(e=>!e)},className:`${ti} focus-ring flex items-center gap-1.5 ${D?"bg-surface-raised text-foreground":"text-label-muted hover:text-foreground"}`,children:[(0,r.jsx)(f.Star,{size:12,"aria-hidden":!0}),M("desktopFavorites")]}),S.MARKET_CATEGORIES.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":B===e.id,onClick:()=>{O(),z(e.id)},className:`${ti} focus-ring ${B===e.id?"bg-surface-raised text-foreground":"text-label-muted hover:text-secondary-foreground"}`,children:e.labelKey?M(e.labelKey):e.label},e.id))]}),(0,r.jsxs)("div",{className:`${tn} shrink-0 px-4 py-2 text-[11px] text-label-muted font-medium border-b border-border/60`,children:[(0,r.jsx)("span",{"aria-hidden":"true"}),(0,r.jsx)("span",{className:"flex items-center",children:M("columnToken")}),(0,r.jsx)("span",{className:"flex items-center justify-end",children:M("columnMarkPrice")}),(0,r.jsxs)("button",{onClick:()=>ep("change24h"),className:"flex items-center justify-end gap-1 hover:text-secondary-foreground transition-colors",children:[(0,r.jsx)("span",{children:M("columnChange24h")}),(0,r.jsx)(tu,{active:"change24h"===W,direction:G})]}),(0,r.jsxs)("button",{onClick:()=>ep("funding"),className:"flex items-center justify-end gap-1 hover:text-secondary-foreground transition-colors",children:[(0,r.jsx)("span",{children:M("columnFunding8h")}),(0,r.jsx)(tu,{active:"funding"===W,direction:G})]}),(0,r.jsxs)("button",{onClick:()=>ep("volume"),className:"flex items-center justify-end gap-1 hover:text-secondary-foreground transition-colors",children:[(0,r.jsx)("span",{children:M("columnVolume24h")}),(0,r.jsx)(tu,{active:"volume"===W,direction:G})]}),(0,r.jsxs)("button",{onClick:()=>ep("oi"),className:"flex items-center justify-end gap-1 hover:text-secondary-foreground transition-colors",children:[(0,r.jsx)("span",{children:M("openInterest.full")}),(0,r.jsx)(tu,{active:"oi"===W,direction:G})]})]}),(0,r.jsxs)("div",{ref:L,className:"min-h-0 max-h-[min(480px,55dvh)] overflow-y-auto overscroll-y-contain",children:[x&&!A&&!D&&B===S.ALL_CATEGORY_ID&&(0,r.jsx)(q,{pairs:V,isLoading:H,onOpen:()=>m?.()}),(0,r.jsx)(e5,{ref:U,rows:eb,rowKey:e=>e.mint,rowHeight:48,scrollRef:L,onFocusLost:()=>F.current?.focus(),renderRow:e=>{let i,n=em.get(e.symbol)?.price,a=em.get(e.symbol),l=ef.get(e.mint)??null,o=e.mint===t,{liquiditySnapshot:c,isFullyIlliquid:p,isDisabled:m}=Z(e),{isNone:x}=eK(c),g=el.has(e.mint),b=(0,r.jsxs)("div",{style:{height:48},className:`relative w-full whitespace-nowrap ${tn} px-4 py-2.5 items-center transition-colors ${m?"opacity-40":o?"bg-surface-raised":"hover:bg-surface-interactive focus-within:bg-surface-interactive"}`,children:[(0,r.jsx)("button",{type:"button","data-market-select":!0,"aria-disabled":m,"aria-label":M("desktopSelectMarket",{symbol:e.symbol}),"aria-current":o?"true":void 0,tabIndex:m?-1:0,onClick:m?void 0:()=>s(e.mint,e),onKeyDown:t=>{!m&&["ArrowDown","ArrowUp","Home","End"].includes(t.key)&&(t.preventDefault(),ey(t.key,e.mint))},className:`absolute inset-0 rounded-sm focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-muted-foreground ${m?"curs
2or-not-allowed":"cursor-pointer"}`}),(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),ed(e.mint)},className:"focus-ring relative z-10 flex items-center justify-center size-7 rounded-control hover:bg-white/5 transition-colors","aria-label":g?M("removeFromFavorites"):M("addToFavorites"),children:(0,r.jsx)(f.Star,{className:`w-3.5 h-3.5 transition-colors ${g?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-muted-foreground"}`})}),(0,r.jsxs)("div",{className:"pointer-events-none flex items-center gap-2.5 min-w-0",children:[(0,r.jsx)(d.default,{src:e.image,alt:e.symbol,width:24,height:24,className:"rounded-full flex-shrink-0",unoptimized:!0,onError:eD.handleTokenImageError}),(0,r.jsx)("span",{className:"font-semibold text-foreground text-sm truncate",children:te(e.symbol)}),e.maxLeverage&&(0,r.jsxs)("span",{className:ta,children:[Math.round(tt(e.maxLeverage,e.symbol,er.get(e.symbol),en,h)),"x"]}),p&&(0,r.jsx)("span",{className:"flex-shrink-0",children:(0,r.jsx)(u.AlertTriangle,{className:`w-3.5 h-3.5 ${x?"text-red-400":"text-amber-400"}`})})]}),(0,r.jsx)("span",{className:"text-right text-sm font-mono tabular-nums text-foreground",children:null!=n?_.number(n):"—"}),null!=l?(0,r.jsxs)("span",{className:`text-right text-sm font-mono tabular-nums ${l>=0?"text-emerald-400":"text-red-400"}`,children:[l>=0?"+":"",_.percent(l,3)]}):(0,r.jsx)("span",{className:"text-right text-sm text-muted-foreground",children:"—"}),a?.hasFunding?(0,r.jsx)("span",{className:`text-right text-sm font-mono tabular-nums ${a.avgRate8h>=0?"text-emerald-400":"text-red-400"}`,children:_.percent(100*a.avgRate8h,4)}):(0,r.jsx)("span",{className:"text-right text-sm text-muted-foreground",children:"—"}),(0,r.jsx)("span",{className:"text-right text-sm font-mono tabular-nums text-secondary-foreground",children:a?.volume24hUsd!=null?e8(a.volume24hUsd,_.intlTag):"—"}),(0,r.jsx)("span",{className:"text-right text-sm font-mono tabular-nums text-secondary-foreground",children:a?.totalOiUsd!=null?e8(a.totalOiUsd,_.intlTag):"—"})]},e.mint);return p?(0,r.jsxs)(y.Tooltip,{children:[(0,r.jsx)(y.TooltipTrigger,{asChild:!0,children:b}),(0,r.jsx)(y.TooltipContent,{children:(i=e6(c,x,_.intlTag))?M(i.key,i.values):""})]},e.mint):b}}),ej&&(0,r.jsx)(tp,{markets:ew,grid:tn,scrollRef:L,onDismiss:v}),eS&&(0,r.jsxs)("div",{className:"text-center text-label-muted text-sm py-8",children:[D?M("desktopNoFavorites"):M("noMarketsFound"),(A||D||B!==S.ALL_CATEGORY_ID)&&(0,r.jsx)("button",{type:"button",className:"focus-ring mx-auto mt-3 block rounded px-3 py-1.5 text-foreground hover:bg-surface-interactive",onClick:()=>{O(),E(""),I(!1),z(S.ALL_CATEGORY_ID),F.current?.focus()},children:M("desktopResetFilters")})]})]}),N&&(0,r.jsxs)("div",{className:"flex shrink-0 items-center justify-between border-t border-border px-4 py-2 text-[11px] text-muted-foreground",children:[(0,r.jsx)("span",{role:"status",children:M("desktopResultCount",{count:eb.length+(ej?ew?.length??0:0)})}),(0,r.jsx)("span",{children:M("desktopSearchKeys")})]})]})}function tx({allMarkets:e,marketMint:t,onSelect:s,enabled:o=!0,activeProfileUnderwriter:m="imperial",activeProfileExcludedVenues:x=[],initialCategory:g,onOpenCarry:b,onClose:y}){let k=(0,a.useTranslations)("markets"),N=(0,$.useFormatters)(),[P,C]=(0,i.useState)("");(0,n.useRouter)();let[M,_]=(0,i.useState)(g??S.ALL_CATEGORY_ID),[A,E]=(0,i.useState)(null),[L,F]=(0,i.useState)("desc"),{prices:R}
2=(0,w.useAllMarketsPricesThrottled)(),{getPrice:D,getMarketLiquidity:I,getMaxLeverage:U,getMarketFees:O,symbols:B}=(0,J.useGmTradeWs)(),{data:z}=(0,Z.useGmTradeMarkets)(),V=(0,i.useMemo)(()=>{let e=new Map;for(let t of z??[]){let r=e.get(t.symbol)??!1;e.set(t.symbol,r||!t.closed)}return e},[z]),{publicKey:H}=(0,ei.useUnifiedWallet)(),{data:W}=(0,er.useTradingStats)(H?.toBase58()),{positions:K}=(0,es.useUnifiedPositions)(),{activeProfileIndex:G,activeProfileMarginMode:Y}=(0,eO.useProfile)(),X="unified"===Y,Q=(0,i.useMemo)(()=>{let e=new Map;if(null===G)return e;for(let t of K){if(t.profileIndex!==G||"open"!==t.status&&"pending"!==t.status&&"closing"!==t.status)continue;let r=eq(t.underwriter);r&&!el.OPENS_PAUSED_VENUES.has(r)&&e.set(t.asset,r)}return e},[K,G]),en=(0,i.useMemo)(()=>{let e=new Set;for(let t of K)"open"===t.status&&(t.profileIndex??null)===(G??null)&&e.add(t.asset);return e},[K,G]),{data:ed}=(0,ee.usePhoenixMarkets)(),{pairs:ec,isLoading:eu}=(0,T.useTopPairs)(o);(0,i.useCallback)(t=>e.find(e=>e.symbol.toUpperCase()===t.toUpperCase())?.mint??null,[e]),(0,i.useCallback)(e=>(ed??[]).find(t=>t.symbol.toUpperCase()===e.toUpperCase())?.orderbook??null,[ed]),(0,i.useCallback)(t=>{let r=e.find(e=>e.symbol.toUpperCase()===t.toUpperCase());return r?R[j.MINT_TO_PYTH_SYMBOL[r.mint]??r.symbol]??D(r.symbol)??null:null},[e,R,D]);let{data:eh}=(0,et.usePhoenixDepthSummary)(),ep=(0,i.useMemo)(()=>{let e=new Map;for(let t of ed??[])e.set(t.symbol,t);return e},[ed]),{data:em}=(0,eo.useLendingPoolState)(),ef=(0,i.useMemo)(()=>em?(0,ea.toRouterPoolState)(em):null,[em]),{favorites:ex,toggleFavorite:eg}=ev(),eb=eR(o,x).stats,ey=(0,i.useMemo)(()=>new Map(e.map(e=>[e.mint,eb.get(e.symbol)?.change24h??null])),[e,eb]),ew=(0,i.useMemo)(()=>{let t=e.filter(e=>!1!==e.allowOpenPosition&&eX(e,en));if(X&&(t=t.filter(e=>eQ(e.symbol,ep,en))),M!==S.ALL_CATEGORY_ID&&(t=t.filter(e=>(0,S.matchesCategory)(e.symbol,M))),P){let e=P.toLowerCase();t=t.filter(t=>tr(t.symbol,t.name,e))}return tc(td(t,A,L,eb,ey),ex)},[e,P,M,A,L,eb,ey,ex,X,ep,en]),ej=th(M,P,e),eS=0===ew.length&&!ej?.length,ek=e=>{"default"===e?E(null):A===e?F("desc"===L?"asc":"desc"):(E(e),F("desc"))};return(0,r.jsxs)("div",{className:"flex min-h-0 flex-col h-full",children:[(0,r.jsxs)("div",{className:"mb-2.5 flex h-11 items-center gap-2",children:[(0,r.jsxs)("div",{className:"relative flex min-w-0 flex-1 items-center",children:[(0,r.jsx)(c.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-label-muted"}),(0,r.jsx)("input",{type:"text",value:P,onChange:e=>C(e.target.value),placeholder:k("searchCoinsPlaceholder"),className:"h-9 w-full rounded-field border border-border-strong bg-surface-raised pl-9 pr-3 text-[13px] text-foreground placeholder:text-label-muted focus:border-primary/50 focus:outline-none transition-colors"})]}),y&&(0,r.jsx)(l.SheetCloseChip,{onClick:y,className:"relative shrink-0"})]}),(0,r.jsx)("div",{className:`${eU.CHIP_RAIL} px-1 pb-1.5`,children:S.MARKET_CATEGORIES.map(e=>(0,r.jsx)("button",{onClick:()=>_(e.id),className:`${ti} bg-surface-raised ${M===e.id?"text-foreground":"text-label-muted hover:text-secondary-foreground"}`,children:e.labelKey?k(e.labelKey):e.label},e.id))}),(0,r.jsxs)("div",{className:`${eU.CHIP_RAIL} px-1 pb-2`,children:[(0,r.jsx)("span",{className:"flex h-7 items-center pl-1 text-3xs text-label-muted",children:k("sort")}),tl.map(({id:e,labelKey:t})=>{let i="default"===e?null===A:A===e;return(0,r.jsxs)("button",{onClick:()=>ek(e),className:`${ti} ${i?"bg-surface-raised text-foreground":"text-label-muted hover:text-secondary-foreground"}`,children:[k(t),"default"!==e&&(0,r.jsx)("span",{className:"flex w-2.5 shrink-0 items-center justify-center",children:i&&("desc"===L?(0,r.jsx)(p.ArrowDown,{className:"h-2.5 w-2.5 text-primary"}):(0,r.jsx)(h.ArrowUp,{className:"h-2.5 w-2.5 text-primary"}))})]},e)})]}),(0,r.jsxs)("div",{className:`${ts} px-2 py-2 text-[11px] text-label-muted font-medium`,children:[(0,r.jsx)("span",{"aria-hidden":"true"}),(0,r.jsx)("span",{className:"flex items-center",children:k("columnToken")}),(0,r.jsx)("span",{className:"flex items-center justify-end",children:k("columnMarkPrice")}),(0,r.jsxs)("button",{onClick:()=>ek("change24h"),className:"flex items-center justify-end gap-1 hover:text-secondary-foreground transition-colors",children:[(0,r.jsx)("span",{children:k("sortChange24h")}),(0,r.jsx)(tu,{active:"change24h"===A,direction:L})]})]}),(0,r.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-y-contain -mx-1",children:(0,r.jsxs)("div",{className:"px-1",children:[!P&&M===S.ALL_CATEGORY_ID&&(0,r.jsx)(q,{pairs:ec,isLoading:eu,onOpen:()=>b?.()}),ew.map(e=>{var i;let n,a,l=eb.get(e.symbol)?.price,o=ey.get(e.mint)??null,c=e.mint===t,h=eY(e,m,ep.get(e.symbol),eh?.snapshots[e.symbol],W,{listed:(e.underwriters??[]).includes("gmtrade")||(i=e.symbol,void 0!==(n=V.get(i))?n:B.includes(i)),maxLeverage:U(e.symbol),fees:O(e.symbol),liquidity:I(e.symbol)},Q.get(e.symbol)??null,x),p="gmtrade"===h?I(e.symbol):void 0,{isNone:g}=eK(p),b=e.underwriters??[],y=(0,eO.isAutoUnderwriter)(m)?Array.from(new Set([...b.filter(e=>!x.includes(e)),...h?[h]:[]])):h?[h]:[],w=eG(y,y.includes("gmtrade")?I(e.symbol):void 0),j=ex.has(e.mint),S=()=>{s(e.mint,e),C("")},P=en.has(e.symbol),T=w&&!P;return(0,r.jsxs)("div",{role:"button","aria-disabled":T,tabIndex:T?-1:0,onClick:T?()=>v.toast.error(k("noLiquidityForMarket")):S,onKeyDown:e=>
2{T||("Enter"===e.key||" "===e.key)&&(e.preventDefault(),S())},className:`w-full ${ts} px-2 py-3 items-center transition-colors rounded-control ${T?"opacity-40":c?"bg-surface-raised":"hover:bg-surface-interactive active:bg-surface-interactive"}`,children:[(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),eg(e.mint)},className:"flex items-center justify-center w-5 h-5 rounded-control hover:bg-white/5 transition-colors","aria-label":j?k("removeFromFavorites"):k("addToFavorites"),children:(0,r.jsx)(f.Star,{className:`w-3.5 h-3.5 transition-colors ${j?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})}),(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,r.jsx)(d.default,{src:e.image,alt:e.symbol,width:24,height:24,className:"rounded-full flex-shrink-0",unoptimized:!0,onError:eD.handleTokenImageError}),(0,r.jsxs)("div",{className:"flex h-6 min-w-0 flex-1 flex-wrap content-start items-center gap-x-1.5 overflow-hidden",children:[(0,r.jsx)("span",{className:"block h-6 truncate font-semibold text-sm leading-6 text-foreground",children:e.symbol}),w&&(0,r.jsx)(u.AlertTriangle,{className:`w-3.5 h-3.5 flex-shrink-0 ${g?"text-red-400":"text-amber-400"}`,"aria-label":(a=e6(p,g,N.intlTag))?k(a.key,a.values):""}),e.maxLeverage&&(0,r.jsxs)("span",{className:ta,children:[Math.round(tt(e.maxLeverage,e.symbol,ep.get(e.symbol),ef,x)),"x"]})]})]}),(0,r.jsx)("span",{className:"truncate text-right text-sm font-mono tabular-nums text-foreground",children:null!=l?N.number(l):"—"}),null!=o?(0,r.jsxs)("span",{className:`truncate text-right text-sm font-mono tabular-nums ${o>=0?"text-emerald-400":"text-red-400"}`,children:[o>=0?"+":"",N.percent(o,3)]}):(0,r.jsx)("span",{className:"text-right text-sm text-muted-foreground",children:"—"})]},e.mint)}),!!ej?.length&&(0,r.jsx)(tp,{markets:ej,grid:ts,phone:!0,onDismiss:y}),eS&&(0,r.jsx)("div",{className:"text-center text-label-muted text-sm py-8",children:k("noMarketsFound")})]})})]})}function tg({open:e,onOpenChange:t,allMarkets:d,marketMint:c,onSelect:u,activeProfileUnderwriter:h,activeProfileExcludedVenues:p,initialCategory:m,carryOpen:f=!1,onCarryOpenChange:x,returnFocusRef:g,ownsHistory:b=!0}){let v=(0,n.useRouter)(),y=(0,a.useTranslations)("positions"),w=(0,i.useRef)(null);return(0,s.useBackToClose)(e&&b,()=>t(!1),"imperialDrawer"),(0,o.useFocusAfterSlide)(e,w,"input"),(0,i.useEffect)(()=>{!e&&f&&x?.(!1)},[e,f,x]),(0,r.jsx)(l.Sheet,{open:e,onOpenChange:t,children:(0,r.jsxs)(l.SheetContent,{ref:w,side:"right",hideClose:!0,className:`${l.SHEET_PHONE_DRAWER} px-3.5 pt-0`,onOpenAutoFocus:e=>e.preventDefault(),onCloseAutoFocus:e=>{e.preventDefault(),g?.current?.focus()},children:[(0,r.jsx)(l.SheetTitle,{className:"sr-only",children:y("mobileSelectMarket")}),f?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(l.SheetCloseChip,{onClick:()=>t(!1),className:"right-3.5 top-1"}),(0,r.jsx)(K,{onBack:()=>x?.(!1),onOpened:()=>{x?.(!1),t(!1)},onBrowseAll:e=>{x?.(!1),t(!1),v.replace(e?`/pair-finder?long=${e.longSymbol}&short=${e.shortSymbol}`:"/pair-finder")}})]}):(0,r.jsx)(tx,{onClose:()=>t(!1),allMarkets:d,marketMint:c,onSelect:(e,r)=>{u(e,r),t(!1)},onOpenCarry:()=>x?.(!0),enabled:e,activeProfileUnderwriter:h,activeProfileExcludedVenues:p,initialCategory:m})]})})}var tb=e.i(504458);let tv=(0,tb.default)("arrow-down-to-line",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);e.s(["ArrowDownToLine",0,tv],88783);let ty=(0,tb.default)("arrow-up-from-line",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]]);e.s(["ArrowUpFromLine",0,ty],441253);let tw=(0,tb.default)("credit-card",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);e.s(["CreditCard",0,tw],528277);var tj=e.i(972342),tS=e.i(562334),tS=tS;e.s(["useOnramp",0,function(){let{authenticated:e}=(0,tj.usePrivy)(),{publicKey:t}=(0,ei.useUnifiedWallet)(),{fundWallet:r}=(0,tS.u)(),[s,n]=(0,i.useState)(!1);return{available:e&&!!t,isOpening:s,buy:(0,i.useCallback)(async i=>{if(t&&e){n(!0);try{await r({address:t.toBase58(),options:{asset:"USDC",amount:void 0===i?void 0:i.toFixed(2),card:{preferredProvider:"coinbase"}}})}finally{n(!1)}}},[e,r,t])}}],623984);var tk=e.i(803817);e.i(347554);var tN=e.i(985433),tP=e.i(282027);function tT({values:e,walletAddress:t,inline:i=!1}){let s=(0,a.useTranslations)("common"),n=(0,a.useTranslations)("nav"),l=(0,a.useTranslations)("wallet"),o=(0,$.useFormatters)(),{global:d,isLoading:c,isStale:u}=e,h=e=>{var t;return c?"$…":`$${t=o.fixed,e>=1e6?`${t(e/1e6,2)}M`:e>=1e3?`${t(e/1e3,2)}K`:t(e,2)}`},p=i&&!c&&d.cashUnknown?"—":h(d.totalUnrealizedValue);return(0,r.jsxs)("div",{className:i?"space-y-2 text-xs":"space-y-1","data-
2portfolio-breakdown":!0,children:[i&&(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 pb-1",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:l("allAccountsAndWallet")}),(0,r.jsx)("span",{className:(0,B.cn)("text-xl font-semibold tabular-nums",u?"text-muted-foreground":"text-foreground"),children:p})]}),u&&(0,r.jsxs)("div",{role:"status",className:"flex items-start gap-1.5 pb-1 text-amber-400",children:[(0,r.jsx)(tP.TriangleAlert,{"aria-hidden":!0,className:"mt-0.5 size-3 shrink-0"}),(0,r.jsx)("span",{children:l("balanceStale")})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:s("positions")}),(0,r.jsx)("span",{children:h(d.totalInvestedValue)})]}),d.totalLockedInOrders>0&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:s("orders")}),(0,r.jsx)("span",{children:h(d.totalLockedInOrders)})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:s("deposited")}),(0,r.jsx)("span",{children:!c&&d.cashUnknown?"—":h(d.totalCashBalance)})]}),d.walletCashBalance>0&&(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:s("wallet")}),(0,r.jsx)("span",{children:h(d.walletCashBalance)})]}),!i&&(0,r.jsxs)("div",{className:"mt-1 flex justify-between gap-4 border-t border-border pt-1 font-medium",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:s("total")}),(0,r.jsx)("span",{children:p})]}),i&&t&&(0,r.jsxs)(tk.Link,{href:`/profile/${t}`,className:"focus-ring flex items-center justify-between border-t border-border pt-2 text-brand-orange",children:[(0,r.jsx)("span",{children:n("portfolio")}),(0,r.jsx)(tN.ArrowRight,{"aria-hidden":!0,className:"size-3.5"})]})]})}},772604,146895,328771,e=>{"use strict";e.s(["MobileMoreTab",()=>em],772604);var t=e.i(394390),r=e.i(183023),i=e.i(942553),s=e.i(807956),n=e.i(803817),a=e.i(116082),l=e.i(789382),o=e.i(101034),d=e.i(202647),c=e.i(491135),u=e.i(457395),h=e.i(845165),p=e.i(178655),m=e.i(670258),f=e.i(151357),x=e.i(237073),g=e.i(865076),b=e.i(741436),v=e.i(943494),y=e.i(303745),w=e.i(695109),j=e.i(409686),S=e.i(205702),k=e.i(370051),N=e.i(525107),P=e.i(884629),T=e.i(72226),C=e.i(343877),M=e.i(282027),_=e.i(351747),A=e.i(462430),E=e.i(183799),L=e.i(308294);e.i(875574);var F=e.i(142298),R=e.i(504421),D=e.i(894771),I=e.i(763402),U=e.i(124593),O=e.i(347554),B=e.i(417059),z=e.i(744900),$=e.i(280864),V=e.i(554580),H=e.i(641879),W=e.i(333379),q=e.i(277590),K=e.i(148292),G=e.i(153517),Y=e.i(407340),X=e.i(872501),Q=e.i(299959),J=e.i(541983),Z=e.i(213076),ee=e.i(623075),et=e.i(616861),er=e.i(999069);function ei({open:e,onOpenChange:r}){let s=(0,i.useTranslations)("wallet"),n=(0,i.useTranslations)("common"),{endSession:a,disconnectWallet:l,offersBothExits:o,isJWTMode:d}=function(){let{disconnect:e,isJWTMode:t}=(0,F.useUnifiedWallet)(),{logout:r}=(0,et.useMobileAuth)(),{isSponsorMode:i,logout:s}=(0,er.useSponsorGas)();return{endSession:i?s:t?r:e,disconnectWallet:e,offersBothExits:(i||t)&&!!e,isJWTMode:t}}();return(0,t.jsx)(ee.Dialog,{open:e,onOpenChange:r,children:(0,t.jsxs)(ee.DialogContent,{className:"gap-0 shadow-xl sm:max-w-[380px]",children:[(0,t.jsxs)(ee.DialogHeader,{className:"flex-col items-start gap-2 border-b-0 px-5 pb-2 pt-5",children:[(0,t.jsx)(ee.DialogTitle,{className:"text-foreground",children:s("disconnectTitle")}),(0,t.jsx)(ee.DialogDescription,{className:"leading-relaxed text-muted-foreground",children:s(d?"disconnectJwtBody":"disconnectBody")})]}),(0,t.jsxs)(ee.DialogFooter,{className:(0,G.cn)("gap-2 px-5 pb-5 pt-3",o?"flex-col sm:flex-col":"flex-row-reverse"),children:[(0,t.jsx)(Z.Button,{variant:"destructive",onClick:()=>{r(!1),a?.()},className:"w-full flex-1 rounded-control",children:s(d?"endMobileSession":"disconnect")}),o&&(0,t.jsx)(Z.Button,{variant:"outline",onClick:()=>{r(!1),l?.()},className:"w-full flex-1 rounded-control text-destructive hover:bg-destructive/10",children:s("disconnectWallet")}),(0,t.jsx)(Z.Button,{variant:"outline",onClick:()=>r(!1),className:"w-full flex-1 rounded-control",children:n("cancel")})]})]})})}e.s(["DisconnectConfirmDialog",0,ei],146895);var es=e.i(637740),en=e.i(814276),ea=e.i(831979);function el({className:e}
2){return(0,t.jsx)("svg",{viewBox:"0 0 24 24",className:e,fill:"currentColor","aria-hidden":!0,children:(0,t.jsx)("path",{d:"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"})})}e.s(["DiscordIcon",0,el,"TelegramIcon",0,function({className:e}
2){return(0,t.jsx)("svg",{viewBox:"0 0 24 24",className:e,fill:"currentColor","aria-hidden":!0,children:(0,t.jsx)("path",{d:"M9.417 15.181l-.397 5.584c.568 0 .814-.244 1.109-.537l2.663-2.545 5.518 4.041c1.012.564 1.725.267 1.998-.931L23.93 3.821l.001-.001c.321-1.496-.541-2.081-1.527-1.714l-21.29 8.151c-1.453.564-1.431 1.374-.247 1.741l5.443 1.693L18.953 5.2c.543-.339 1.038-.152.63.218L9.417 15.18z"})})}],328771);let eo=(0,s.default)(()=>e.A(256705).then(e=>({default:e.DepositWithdrawDialog})),{loadableGenerated:{modules:[172739]},ssr:!1}),ed=(0,s.default)(()=>e.A(898027).then(e=>({default:e.CreateProfileDialog})),{loadableGenerated:{modules:[649043]},ssr:!1}),ec=(0,s.default)(()=>e.A(386060).then(e=>({default:e.EditProfileDialog})),{loadableGenerated:{modules:[434869]},ssr:!1}),eu=(0,s.default)(()=>e.A(607222).then(e=>({default:e.ManagePrivyWalletDialog})),{loadableGenerated:{modules:[433537]},ssr:!1}),eh=(0,s.default)(()=>e.A(297078).then(e=>({default:e.VenueSettingsDialog})),{loadableGenerated:{modules:[251512]},ssr:!1}),ep=(0,s.default)(()=>e.A(171547).then(e=>({default:e.TradeStrengthSettingsDialog})),{loadableGenerated:{modules:[370546]},ssr:!1});function em(){let e,s,Z,ee=(0,i.useTranslations)("common"),et=(0,i.useTranslations)("nav"),er=(0,i.useTranslations)("rewards"),em=(0,i.useTranslations)("settings"),ex=(0,i.useTranslations)("wallet"),eg=(0,i.useTranslations)("trading"),eb=(0,Q.useFormatters)(),{publicKey:ev,connected:ey,isJWTMode:ew,wallet:ej,isPrivyWallet:eS}=(0,F.useUnifiedWallet)(),{isSponsorMode:ek,toggle:eN,loading:eP}=(0,R.useSponsorToggle)(),{createdProfiles:eT,activeProfileIndex:eC,setActiveProfileIndex:eM,canCreateMore:e_,username:eA,referralCode:eE}=(0,D.useProfile)(),{isPro:eL}=(0,U.useProWhitelist)(),{profiles:eF,global:eR,isStale:eD}=(0,O.usePortfolioValues)(),{soundEnabled:eI,setSoundEnabled:eU,isLoaded:eO}=(0,$.useSoundPreferences)(),eB=ev?.toBase58()??"",ez=(0,K.usePrimaryDomain)(eB),e$=(0,z.useSeasonPoints)(eB||void 0),{formattedPoints:eV}=(0,B.useUserPoints)(ev,e$.data?.seasonOnChainId),eH=(0,z.useCurrentWeekPoints)(eB||void 0),eW=(0,H.useTimeUntilUtcMidnight)(),eq=(0,W.useMyClan)(eB||void 0),eK=(0,W.useClanLeaderboard)("week","desc","",null,100),{data:eG}=(0,q.useProfileStats)(eB),eY=(0,n.useRouter)(),[eX,eQ]=(0,r.useState)(!1),[eJ,eZ]=(0,r.useState)(!1),[e0,e1]=(0,r.useState)(!1),[e2,e5]=(0,r.useState)("deposit"),[e3,e4]=(0,r.useState)(!1),[e6,e8]=(0,r.useState)(!1),[e9,e7]=(0,r.useState)(!1),[te,tt]=(0,r.useState)(!1),[tr,ti]=(0,r.useState)(!1),[ts,tn]=(0,r.useState)(!1),{range:ta}=(0,V.useTradeStrengthRange)(),tl=(0,V.useStrengthRangeLabel)(ta),to=e=>{null===eC&&eT[0]&&eM(eT[0].index),e5(e),e1(!0)},td=ev?`${ev.toBase58().slice(0,4)}...${ev.toBase58().slice(-4)}`:"",tc={documentation:p.FileText,xTwitter:ea.XIcon,discord:el,terms:S.ScrollText,privacy:N.ShieldCheck},tu=l.MORE_RESOURCES.map(({href:e,labelKey:t})=>({href:e,icon:tc[t],label:"terms"===t?eg("termsOfService"):"privacy"===t?eg("privacyPolicy"):et(t)})),th=(0,t.jsxs)("div",{className:"px-4 pb-3",children:[(0,t.jsx)("div",{className:"text-sm font-medium text-muted-foreground mb-2",children:et("sectionResources")}),(0,t.jsx)("div",{className:"bg-surface border border-border rounded-lg overflow-hidden divide-y divide-border",children:tu.map(({href:e,icon:r,label:i})=>(0,t.jsxs)("a",{href:e,target:"_blank",rel:"noreferrer",className:"flex items-center justify-between px-4 py-3 hover:bg-surface-interactive/50 transition-colors",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(r,{className:"w-4 h-4 text-label-muted"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:i})]}),(0,t.jsx)(h.ExternalLink,{className:"w-3.5 h-3.5 text-muted-foreground"})]},e))})]});if(!ey)return(0,t.jsxs)("div",{className:"flex flex-col min-h-full bg-canvas",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 py-12 px-4",children:[(0,t.jsx)("p",{className:"text-muted-foreground text-sm",children:ex("connectToStart")}),(0,t.jsx)(J.UnifiedWallet,{})]}),th]});let tp=eH.data,tm=e$.data?.currentWeek,tf=eq.data,tx=tf?eK.data?.entries.find(e=>e.clanId===tf.clan.id):void 0,tg=eT.find(e=>e.index===eC),tb=tg?.name??(tg?ex("profileFallback",{index:tg.index+1}):null),tv=tg?eF.get(tg.index)?.unrealizedValue:void 0;return(0,t.jsxs)("div",{className:"flex flex-col min-h-full bg-canvas pb-4",children:[(0,t.jsx)("div",{className:"px-4 pt-4 pb-3",children:(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 min-w-0",children:[(0,t.jsx)("button",{onClick:()=>eY.push(`/profile/${eB}`),children:(0,t.jsx)(en.Avatar,{address:ev,imageUrl:eG?.profilePictureUrl,size:40})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-foreground font-medium",children:td}),(0,t.jsx)("button",{onClick:()=>
2{ev&&(navigator.clipboard.writeText(ev.toBase58()),eQ(!0),a.toast.success(ex("addressCopied")),setTimeout(()=>eQ(!1),2e3))},className:"text-label-muted hover:text-foreground transition-colors",children:eX?(0,t.jsx)(d.Check,{className:"w-3.5 h-3.5 text-side-long"}):(0,t.jsx)(u.Copy,{className:"w-3.5 h-3.5"})})]}),(0,t.jsx)("div",{className:"flex items-center gap-2 text-sm mt-0.5",children:eA||ez?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{onClick:()=>eY.push(`/profile/${eB}`),className:"text-secondary-foreground font-medium hover:text-foreground transition-colors truncate",children:eA||ez}),(0,t.jsx)("button",{onClick:()=>e8(!0),"aria-label":ex("editUsername"),title:ex("editUsername"),className:"text-label-muted hover:text-foreground transition-colors shrink-0",children:(0,t.jsx)(w.Pencil,{className:"w-3 h-3"})})]}):(0,t.jsx)("button",{onClick:()=>e8(!0),className:"text-primary font-medium",children:er("setUsername")})})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[(0,t.jsxs)("button",{onClick:()=>{eE?(navigator.clipboard.writeText(`${window.location.origin}/refer/${encodeURIComponent(eE)}`),eZ(!0),a.toast.success(er("referralLinkCopiedEarn")),setTimeout(()=>eZ(!1),2e3)):a.toast.error(er("referralCodeUnavailable"))},disabled:!eE,className:"flex items-center gap-1.5 h-8 px-3 rounded-lg border border-border-strong bg-surface text-foreground text-xs font-medium hover:bg-surface-interactive transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[eJ?(0,t.jsx)(d.Check,{className:"w-3.5 h-3.5 text-side-long"}):(0,t.jsx)(b.Link,{className:"w-3.5 h-3.5 text-primary"}),er("inviteTraders")]}),(0,t.jsx)("button",{onClick:()=>e7(!0),"aria-label":ex("disconnect"),title:ex("disconnect"),className:"hit-target p-2 rounded-lg text-label-muted hover:text-destructive hover:bg-destructive/10 transition-colors",children:(0,t.jsx)(y.LogOut,{className:"w-4 h-4"})})]})]})}),(0,t.jsx)("div",{className:"px-4 pb-3",children:(0,t.jsx)(I.SetupChecklistInline,{})}),(0,t.jsx)("div",{className:"px-4 pb-3",children:(0,t.jsxs)(n.Link,{href:"/points",className:"block bg-surface border border-border rounded-lg p-4 hover:border-border-strong transition-colors",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs text-primary",children:[(0,t.jsx)(T.Sparkles,{className:"w-3.5 h-3.5"}),er("imperialPoints")]}),(0,t.jsx)(c.ChevronRight,{className:"w-4 h-4 text-label-muted"})]}),(0,t.jsxs)("div",{className:"mt-2 flex items-baseline gap-2",children:[(0,t.jsx)("span",{className:"text-2xl font-bold font-mono tabular-nums text-foreground",children:eV??"0"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"pts"})]}),(0,t.jsx)("div",{className:"mt-1 text-[11px] text-label-muted",children:(0,t.jsx)("span",{className:"text-muted-foreground",children:tp?.projectedPayoutMicros!=null?er("projectedThisWeek",{points:(0,z.formatPoints)(tp.projectedPayoutMicros,eb.intlTag)}):er("projectedThisWeekEmpty")})}),tm&&(s=!(e=tm.dailyStreakCount>0)&&tm.dailyStreakPending>0,Z=e?tm.dailyStreakCount:tm.dailyStreakPending,(0,t.jsxs)("div",{className:"mt-3 pt-3 border-t border-border space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(m.Flame,{className:`w-3.5 h-3.5 shrink-0 ${e?"text-primary":s?"text-primary/60":"text-muted-foreground"}`,fill:e?"currentColor":"none"}),e?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[(0,t.jsx)("span",{className:"text-foreground font-semibold font-mono tabular-nums",children:Z})," ",er("streakDayLabel")]}):s?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[(0,t.jsxs)("span",{className:"text-orange-200/80 font-semibold font-mono tabular-nums",children:[Z,"d"]})," ",er("pending")]}):(0,t.jsx)("span",{className:"text-muted-foreground",children:er("noDailyStreak")})]}),tm.dailyVolumeTodayUsdMicros/1e6>=100?(0,t.jsxs)("span",{className:"flex items-center gap-1 font-medium text-side-long",children:[(0,t.jsx)(d.
2Check,{className:"w-3 h-3 shrink-0"}),er("dailyGoalHit")]}):(0,t.jsxs)("span",{className:"tabular-nums text-primary",children:["$",Math.floor(tm.dailyVolumeTodayUsdMicros/1e6),"/$",100," today"]})]}),(0,t.jsxs)("div",{className:"text-[10px] text-label-muted",children:[er("dailyResetsInLabel")," ",(0,t.jsx)("span",{className:"font-mono tabular-nums text-muted-foreground",children:eW})]})]})),tf&&(0,t.jsxs)("div",{className:"mt-3 pt-3 border-t border-border flex items-center gap-2 text-xs",children:[(0,t.jsx)(k.Shield,{className:"w-3.5 h-3.5 text-side-long shrink-0"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:er("clanLabel")}),(0,t.jsxs)("span",{className:"font-mono text-secondary-foreground px-1.5 py-0.5 rounded bg-surface-interactive/10 border border-border-strong/30 text-[10px]",children:["[",tf.clan.tag,"]"]}),(0,t.jsx)("span",{className:"text-foreground font-medium truncate",children:tf.clan.name}),tx&&(0,t.jsxs)("span",{className:"ml-auto text-amber-300 font-semibold shrink-0",children:["#",tx.rank]})]})]})}),(0,t.jsx)("div",{className:"px-4 pb-3",children:(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg p-4",children:[(0,t.jsx)("div",{className:"text-xs text-label-muted mb-1",children:ex("totalPortfolioValue")}),(0,t.jsxs)("div",{className:(0,G.cn)("text-2xl font-bold font-mono tabular-nums",eD?"text-muted-foreground":"text-foreground"),children:["$",eb.numberShort(eR.totalUnrealizedValue)]}),eD&&(0,t.jsxs)("div",{className:"mt-1 flex items-center gap-1.5 text-[11px] text-amber-400",children:[(0,t.jsx)(M.TriangleAlert,{className:"w-3 h-3 shrink-0"}),(0,t.jsx)("span",{children:ex("balanceStale")})]}),tg&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between px-3 py-2 rounded-md bg-primary/5 border border-primary/20",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,t.jsx)("div",{className:"w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold bg-primary text-primary-foreground shrink-0",children:tg.index+1}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:ex("depositingTo")}),(0,t.jsx)("span",{className:"text-xs font-semibold text-foreground truncate",children:tb})]}),(0,t.jsx)("span",{className:"text-xs text-secondary-foreground font-mono tabular-nums shrink-0",children:void 0===tv?"—":`$${eb.numberShort(tv)}`})]}),(0,t.jsxs)("div",{className:"mt-2 flex gap-2",children:[(0,t.jsx)("button",{onClick:()=>to("deposit"),className:"flex-1 py-2.5 rounded-lg bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-sm transition-colors",children:ex("depositWithdraw")}),eT.length>1&&(0,t.jsx)("button",{onClick:()=>to("transfer"),className:"flex items-center justify-center w-11 rounded-lg border border-border-strong text-muted-foreground hover:text-foreground hover:border-primary/30 transition-colors",children:(0,t.jsx)(o.ArrowLeftRight,{className:"w-4 h-4"})})]})]})}),(0,t.jsxs)("div",{className:"px-4 pb-3",children:[(0,t.jsx)("div",{className:"flex items-center justify-between mb-2",children:(0,t.jsx)("span",{className:"text-sm font-medium text-muted-foreground",children:ex("accounts")})}),(0,t.jsxs)("div",{className:"space-y-2",children:[eT.map(e=>{let r=e.index===eC,i=eF.get(e.index),s=i?.unrealizedValue;return(0,t.jsxs)("button",{onClick:()=>{r?to("deposit"):eM(e.index)},className:(0,G.cn)("w-full flex items-center justify-between px-4 py-2.5 rounded-lg border transition-colors",r?"border-primary/40 bg-primary/10":"border-border bg-surface hover:border-border-strong"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:(0,G.cn)("w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold",r?"bg-primary text-primary-foreground":"bg-surface-interactive text-secondary-foreground"),children:e.index+1}),(0,t.jsxs)("div",{className:"text-left",children:[(0,t.jsx)("div",{className:(0,G.cn)("text-sm font-medium",r?"text-primary":"text-foreground"),children:e.name??ex("profileFallback",{index:e.index+1})}),(0,t.jsx)("div",{className:"text-xs text-label-muted",children:(e.underwriter??"jupiter").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-sm text-foreground font-mono tabular-nums",children:void 0===s?"—":`$${eb.numberShort(s)}`}),(0,t.jsx)(c.ChevronRight,{className:"w-4 h-4 text-muted-foreground"})]})]},e.index)}),e_&&eL&&(0,t.jsxs)("button",{onClick:()=>e4(!0),className:"w-full flex items-center gap-3 px-4 py-2.5 rounded-lg border border-dashed border-border-strong text-label-muted hover:text-foreground hover:border-primary/30 transition-colors",children:[(0,t.jsx)(j.Plus,{className:"w-5 h-5"}),(0,t.jsx)("span",{className:"text-sm",children:ex("addAccount")}
2)]})]})]}),(0,t.jsxs)("div",{className:"px-4 pt-1 pb-3",children:[(0,t.jsx)("div",{className:"text-sm font-medium text-muted-foreground mb-2",children:et("sectionImperial")}),(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg overflow-hidden divide-y divide-border",children:[(0,t.jsx)(ef,{href:"/leaderboard",label:et("leaderboard"),icon:C.Trophy}),Y.PAWN_NAV_VISIBLE&&(0,t.jsx)(ef,{href:"/lending",label:et("pawn"),icon:x.Gem}),X.RIP_NAV_VISIBLE&&(0,t.jsx)(ef,{href:"/rip",label:et("rip"),icon:T.Sparkles}),(0,t.jsx)(ef,{href:"/referrals",label:et("referrals"),icon:g.Gift})]})]}),(0,t.jsxs)("div",{className:"px-4 pb-3",children:[(0,t.jsx)("div",{className:"text-sm font-medium text-muted-foreground mb-2",children:em("title")}),(0,t.jsxs)("div",{className:"bg-surface border border-border rounded-lg overflow-hidden divide-y divide-border",children:[!ew&&(0,t.jsxs)("div",{className:(0,G.cn)("w-full px-4 py-3 flex items-center justify-between",(eP||!ej?.publicKey)&&"opacity-50"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[eP?(0,t.jsx)(v.Loader2,{className:"w-4 h-4 text-muted-foreground animate-spin"}):(0,t.jsx)(L.Zap,{className:(0,G.cn)("w-4 h-4",ek?"text-primary fill-current":"text-label-muted")}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:ee("oneClickTrading")})]}),(0,t.jsx)(es.Switch,{checked:ek,onCheckedChange:()=>eN(),disabled:eP||!ej?.publicKey,className:"data-[state=checked]:bg-primary"})]}),(0,t.jsxs)("div",{className:"w-full px-4 py-3 flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[eI?(0,t.jsx)(_.Volume2,{className:"w-4 h-4 text-primary"}):(0,t.jsx)(A.VolumeX,{className:"w-4 h-4 text-label-muted"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:em("soundEffects")})]}),eO&&(0,t.jsx)(es.Switch,{checked:eI,onCheckedChange:eU,className:"data-[state=checked]:bg-primary"})]}),eS&&(0,t.jsxs)("button",{onClick:()=>tt(!0),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-surface-interactive/50 transition-colors text-left",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,t.jsx)(E.Wallet,{className:"w-4 h-4 text-label-muted"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:ex("manageWallet")})]}),(0,t.jsx)(c.ChevronRight,{className:"w-3.5 h-3.5 text-muted-foreground"})]}),(0,t.jsxs)("button",{onClick:()=>ti(!0),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-surface-interactive/50 transition-colors text-left",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,t.jsx)(P.SlidersHorizontal,{className:"w-4 h-4 text-label-muted"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:em("venueSettings")})]}),(0,t.jsx)(c.ChevronRight,{className:"w-3.5 h-3.5 text-muted-foreground"})]}),(0,t.jsxs)("button",{onClick:()=>tn(!0),className:"w-full flex items-center justify-between gap-3 px-4 py-3 hover:bg-surface-interactive/50 transition-colors text-left",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,t.jsx)(f.Gauge,{className:"w-4 h-4 text-label-muted"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:em("tradeStrength")})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-1.5",children:[(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:tl}),(0,t.jsx)(c.ChevronRight,{className:"w-3.5 h-3.5 shrink-0 text-muted-foreground"})]})]}),(0,t.jsx)("button",{onClick:()=>e7(!0),className:"w-full flex items-center px-4 py-3 hover:bg-destructive/10 transition-colors text-left",children:(0,t.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,t.jsx)(y.LogOut,{className:"w-4 h-4 text-destructive"}),(0,t.jsx)("span",{className:"text-sm text-destructive",children:ex("disconnectWallet")})]})})]})]}),th,(0,t.jsx)(eo,{open:e0,onOpenChange:e1,initialMode:e2}),(0,t.jsx)(ed,{open:e3,onOpenChange:e4}),(0,t.jsx)(ec,{open:e6,onOpenChange:e8,currentPictureUrl:eG?.profilePictureUrl}),eS&&(0,t.jsx)(eu,{open:te,onOpenChange:tt}),(0,t.jsx)(eh,{open:tr,onOpenChange:ti}),(0,t.jsx)(ep,{open:ts,onOpenChange:tn}),(0,t.jsx)(ei,{open:e9,onOpenChange:e7})]})}function ef({href:e,label:r,icon:i}){return(0,t.jsxs)(n.Link,{href:e,className:"flex items-center justify-between px-4 py-3 hover:bg-surface-interactive/50 transition-colors",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-muted-foreground"}),(0,t.jsx)("span",{className:"text-sm text-foreground",children:r})]}),(0,t.jsx)(c.ChevronRight,{className:"w-3.5 h-3.5 text-muted-foreground"})]})}},784010,637740,459,142981,912881,464992,765918,134042,984457,670964,227456,546642,937626,e=>{"use strict";var t=e.i(394390),r=e.i(684446),i=e.i(183023),s=e.i(679278),n=e.i(873029),a=e.i(116082),l=e.i(942553),o=e.i(213076),d=e.i(268680),c=e.i(489980),u=e.i(375039),h=e.i(541078),p=e.i(204095),m=e.i(327494),f=e.i(575856),x=e.i(671454),g="Switch",[b,v]=(0,h.createContextScope)(g),[y,w]=b(g),j=i.forwardRef((e,r)=>{let{__scopeSwitch:s,name:n,checked:a,defaultChecked:l,required:o,disabled:d,value:h="on",onCheckedChange:m,form:f,...b}=e,[v,w]=i.useState(null),j=(0,u.useComposedRefs)(r,e=>w(e)),S=i.useRef(!1),k=!v||f||!!v.closest("form"),[T,C]=(0,p.useControllableState)({prop:a,defaultProp:l??!1,onChange:m,caller:g});return(0,t.jsxs)(y,{scope:s,checked:T,disabled:d,children:[(0,t.jsx)(x.Primitive.button,{type:"button",role:"switch","aria-checked":T,"aria-required":o,"data-state":P(T),"data-disabled":d?"":void 0,disabled:d,value:h,...b,ref:j,onClick:(0,c.composeEventHandlers)(e.onClick,e=>{C(e=>!e),k&&(S.current=e.isPropagationStopped(),S.current||e.stopPropagation())})}),k&&(0,t.jsx)(N,{control:v,bubbles:!S.current,name:n,value:h,checked:T,required:o,disabled:d,form:f,style:{transform:"translateX(-100%)"}})]})});j.displayName=g;var S="SwitchThumb",k=i.forwardRef((e,r)=>{let{__scopeSwitch:i,...s}=e,n=w(S,i);return(0,t.jsx)(x.Primitive.span,{"data-state":P(n.checked),"data-disabled":n.disabled?"":void 0,...s,ref:r})});k.displayName=S;var N=i.forwardRef(({__scopeSwitch:e,control:r,checked:s,bubbles:n=!0,...a},l)=>{let o=i.useRef(null),d=(0,u.useComposedRefs)(o,l),c=(0,m.usePrevious)(s),h=(0,f.useSize)(r);return i.useEffect(()=>{let e=o.current;if(!e)return;let t=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"checked").set;if(c!==s&&t){let r=new Event("click",{bubbles:n});t.call(e,s),e.dispatchEvent(r)}},[c,s,n]),(0,t.jsx)("input",{type:"checkbox","aria-hidden":!0,defaultChecked:s,...a,tabIndex:-1,ref:d,style:{...a.style,...h,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});function P(e){return e?"checked":"unchecked"}N.displayName="SwitchBubbleInput";var T=e.i(153517);function C({className:e,style:r,trackPx:i=32,...s}){return(0,t.jsx)(j,{"data-slot":"switch",style:{"--switch-travel":`${i-2-16}px`,...r},className:(0,T.cn)("peer data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=unchecked]:bg-surface-raised focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-border-strong shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...s,children:(0,t.jsx)(k,{"data-slot":"switch-thumb",className:"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0"})})}e.s(["Switch",0,C],637740);let M={0:"1m",1:"5m",2:"15m",3:"1H",4:"4H",5:"1D"},_=[0,1],A={0:"conditionBelow",1:"conditionAbove"},E=[0,1,2],L={0:"weightingEven",1:"weightingFront",2:"weightingBack"};e.s(["CONDITION_LABEL_KEYS",0,A,"CONDITION_OPTIONS",0,_,"TIMEFRAME_LABELS",0,M,"WEIGHTING_LABEL_KEYS",0,L,"WEIGHTING_OPTIONS",0,E,"conditionLabelKey",0,function(e){if(null==e)return;if(/^\d+$/.test(String(e)))return A[Number(e)];let t=String(e).toLowerCase();return"below"===t?"conditionBelow":"above"===t?"conditionAbove":void 0}],459);var F=e.i(653982);e.i(875574);var R=e.i(142298),D=e.i(430232),I=e.i(596331),U=e.i(905843);let O="imperial_dca_time_style";var B=e.i(719367);function z(e){let t=e.trim();return"O"===t?"open":"C"===t?"closed":t.split("&").map(e=>{let[t,r]=e.split("-");return{startMinutes:60*parseInt(t.substring(0,2))+parseInt(t.substring(2,4)),endMinutes:60*parseInt(r.substring(0,2))+parseInt(r.substring(2,4))}})}function $(e){let t=e.split(";"),r=t[0],i=t[1].split(","),s=t[2]||"",n=i.map(z),a=new Map;if(s.trim())for(let e of s.split(",")){let t=e.indexOf("/");if(-1===t)continue;let r=e.substring(0,t),i=e.substring(t+1);a.set(r,z(i))}return{timezone:r,weeklyRanges:n,holidays:a}}function V(e,t){return"open"===e||"closed"!==e&&e.some(e=>t>=e.startMinutes&&t<e.endMinutes)}function H(e,t){var r;let i,s,n,a,l,o,d,{dayOfWeek:c,minuteOfDay:u,mmdd:h}=(r=e.timezone,i=new Intl.DateTimeFormat("en-US",{timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1,weekday:"short"}).formatToParts(t),n=(s=e=>i.find(t=>t.type===e)?.value??"")("weekday"),a=parseInt(s("hour")),l=parseInt(s("minute")),o=s("month"),d=s("day"),{dayOfWeek:({Mon:0,Tue:1,Wed:2,Thu:3,Fri:4,Sat:5,Sun:6})[n]??0,minuteOfDay:(24===a?0:a)*60+l,mmdd:`${o}${d}`}),p=e.holidays.get(h);return void 0!==p?V(p,u):V(e.weeklyRanges[c],u)}function W(e){let t=$(e);return t.weeklyRanges.every(e=>"open"===e)&&0===t.holidays.size}function q(e){let t=0,r=0;for(let i=0;i<14;i++){let s=i%7,n=e.weeklyRanges[s],a=function(e){if("open"===e)return 0;if("closed"===e)return 1440;let t=0;
2for(let r of e)t+=r.endMinutes-r.startMinutes;return 1440-t}(n);if(1440===a)r+=1440;else if(a>0&&"open"!==n&&"closed"!==n){let e=n[0].startMinutes;(r+=1440-n[n.length-1].endMinutes)>t&&(t=r),r=e}else r>t&&(t=r),r=0}return r>t&&(t=r),60*t*1e3}e.s(["formatReopenTime",0,function(e,t){return e.toLocaleString((0,B.intlTag)(t),{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})},"getLongestClosedWindowMs",0,q,"is24x7",0,W,"isMarketOpenAt",0,H,"nextOpenTime",0,function(e,t=new Date){let r=new Date(t.getTime()+12096e5),i=new Date(t.getTime());for(i.setSeconds(0,0),i.setTime(i.getTime()+6e4);i<r;){if(H(e,i))return i;i.setTime(i.getTime()+6e4)}return null},"parseSchedule",0,$],142981);var K=e.i(142910),G=e.i(43690),Y=e.i(299959);function X({market:e,timeframe:r,underwriter:s,threshold:n,condition:a,trailing:o,deferred:d}){let c,u=(0,l.useTranslations)("trading"),h=(0,Y.useFormatters)(),[p,m]=(0,i.useState)(Date.now);(0,i.useEffect)(()=>{let e=setInterval(()=>m(Date.now()),1e3);return()=>clearInterval(e)},[]);let f=(0,G.useQuery)({queryKey:["rsi-preview",e,r,14,s],queryFn:async({signal:t})=>{let i=new URLSearchParams({market:e,timeframe:String(r),period:"14",underwriter:String(s)}),n=await fetch(`https://api.imperial.space/api/v1/indicator/rsi?${i}`,{signal:t,cache:"no-store"});if(!n.ok)throw Error("RSI unavailable");return n.json()},refetchInterval:5e3,staleTime:0,retry:!1}),x=f.data,g=f.isError||x?.market!==e||x.timeframe!==r||14!==x.period?null:function(e,t){if(!e||null===e.value||null===e.updated_at)return null;let r=t/1e3-e.updated_at;return Number.isFinite(e.value)&&e.value>=0&&e.value<=100&&r>=-2&&r<=15?e.value:null}(x,p),b=(c=Number(n),null!==g&&""!==n.trim()&&!!Number.isFinite(c)&&!(c<=0)&&!(c>=100)&&(0===a?g<c:1===a&&g>c));return(0,t.jsx)("p",{className:(0,T.cn)("text-xs",b?"text-amber-400":"text-muted-foreground"),role:"status",children:null===g?u(f.isPending?"rsiPreviewLoading":"rsiPreviewUnavailable"):(0,t.jsxs)(t.Fragment,{children:[u("rsiPreviewNow",{value:h.number(g,{maximumFractionDigits:1,minimumFractionDigits:1})}),b&&(0,t.jsxs)(t.Fragment,{children:[" — ",u(0===a?"rsiPreviewBelow":"rsiPreviewAbove",{threshold:n}),". ",u(d?"rsiPreviewDeferred":o?"rsiPreviewTrailing":"rsiPreviewImmediate")]})]})})}var Q=e.i(340053);function J({onSync:e,syncStatus:r,hasNonUsdcBalance:i,size:s="md",className:n}){let a=(0,l.useTranslations)("trading");return(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("button",{onClick:t=>{t.preventDefault(),t.stopPropagation(),e()},disabled:"syncing"===r,"aria-label":a("syncProfile"),className:`rounded p-0.5 transition-colors hover:bg-surface-interactive disabled:opacity-50 ${i?"text-amber-400 hover:text-amber-300":"text-label-muted hover:text-muted-foreground"} ${n??""}`,children:(0,t.jsx)(Q.RefreshCw,{className:`${"sm"===s?"h-3 w-3":"h-3.5 w-3.5"} ${"syncing"===r?"animate-spin":""}`})})}),(0,t.jsx)(d.TooltipContent,{side:"bottom",sideOffset:4,showArrow:!1,className:"text-xs px-2 py-1",children:a("syncing"===r?"syncing":"queued"===r?"sweepQueued":"syncProfile")})]})}function Z({balance:e,onDepositClick:r,onUseBalance:i,disabled:s,syncStatus:n,onSync:a,hasNonUsdcBalance:o}){let d=(0,l.useTranslations)("trading"),c=(0,Y.useFormatters)();return(0,t.jsxs)("span",{className:"text-sm text-muted-foreground flex items-center gap-1.5 whitespace-nowrap",children:[(0,t.jsx)("button",{type:"button",disabled:s||!(i||r),className:"text-left transition-colors enabled:cursor-pointer enabled:hover:text-secondary-foreground disabled:cursor-default focus-ring",onClick:i??r,"aria-label":i?d("useFullBalance"):void 0,title:i?d("useFullBalance"):void 0,children:d.rich("balanceLine",{amount:null==e?"—":c.usdNumber(e),strong:e=>(0,t.jsx)("span",{className:"text-foreground font-mono tabular-nums",children:e})})}),a&&(0,t.jsx)(J,{className:"ml-1",onSync:a,syncStatus:n,hasNonUsdcBalance:o})]})}e.s(["BalanceDisplay",0,Z,"ProfileSyncButton",0,J],912881);var ee=e.i(657645);let et=[25,50,75,100];function er({maxUsd:e,valueUsd:r,onSelect:i,disabled:s=!1,hotkeyTitles:n=!1,compact:a=!1}){let o=(0,l.useTranslations)("trading"),d=s||e<=0,c=e>0?Math.round(r/e*100):0;return(0,t.jsx)("div",{className:`grid grid-cols-4 ${a?"gap-[9px]":"gap-2"} ${d?"opacity-50":""}`,children:et.map((e,s)=>{let l=!d&&r>0&&c===e,u=100===e?o("max"):`${e}%`;return(0,t.jsx)("button",{type:"button",title:n?`${u} \xb7 ${s+1}`:void 0,disabled:d,onPointerDown:a?ee.holdKeypadFocus:void 0,onClick:()=>i(e),className:`border transition-colors disabled:cursor-default ${a?"h-[29px] rounded-[7px] bg-[var(--phone-chip)] text-[10.8px] font-semibold":"h-[29px] rounded-control text-[11px] font-semibold"} ${l?a?"border-border-strong text-foreground":"border-border-strong bg-surface-interactive text-foreground":a?"border-[var(--phone-card-border)] text-muted-foreground hover:border-border-strong hover:text-foreground":"border-border text-muted-foreground hover:border-border-strong hover:text-foreground"}`,children:u},e)})})}function ei(e,t){return e>t+.01}function es(e,t){return Math.min(e,t)}function en(e,t,r){let i=null===r?t:Math.max(0,t-r);return{walletUsd:i,collateralAmountUsd:"armada"===e?t:i}}e.s(["SizePresetButtons",0,er],464992),e.s(["clampCollateral",0,es,"isCollateralInsufficient",0,ei],765918),e.s(["armadaAccountDrawForTicket",0,function(e,t,r,i){return"armada"!==e||t||r?null:i}
2,"crossMarginAvailability",0,function({phoenixMarket:e,phoenixPending:t,sunriseListed:r,sunrisePending:i,sunriseAllowed:s}){return e&&!e.isolatedOnly||s&&r?"available":t||s&&i?"loading":"unavailable"},"crossMarginFreeCollateralUsd",0,function(e,t,r){let i="phoenix"===e?t:"armada"===e?r:null;return null!==i&&Number.isFinite(i)?Math.max(0,i):null},"crossTicketFunding",0,en,"positionMatchesMarginMode",0,function(e,t){return(e.directVenue?.marginMode==="cross"||!0===e.isPhoenixCrossSeat||!0===e.isSunriseCrossMargin||"sunrise"===e.underwriter&&null===e.sunriseMarginSeat)==("unified"===t)}],134042);var ea=e.i(190459),el=e.i(821043),eo=e.i(631797),ed=e.i(943494);function ec({className:e,...r}){return(0,t.jsx)(ed.Loader2,{"aria-hidden":!0,"data-slot":"spinner",className:(0,T.cn)("size-4 shrink-0 animate-spin",e),...r})}e.s(["Spinner",0,ec],984457);var eu=e.i(665757);function eh(e,t){let r=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set;r?.call(e,t),e.dispatchEvent(new Event("input",{bubbles:!0}))}e.s(["setNativeInputValue",0,eh],670964);let ep="touch-pan-y h-2.5 bg-surface-raised border border-border-strong rounded-full shadow-xs appearance-none cursor-pointer focus-ring [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-border-strong [&::-webkit-slider-thumb]:shadow-md [&::-webkit-slider-thumb]:cursor-pointer",em=new Map;function ef(e,t){let r=Number(""===e.min?0:e.min),i=Number(""===e.max?100:e.max),s=Number(e.value),n=e.getBoundingClientRect();if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(s)||i<=r||n.width<=20)return!0;let a=Math.min(1,Math.max(0,(s-r)/(i-r)));return 10>=Math.abs(t-(n.left+10+a*(n.width-20)))}let ex={ref:function(e){if(!e)return;let t=t=>{let r=t.touches[0];r&&!ef(e,r.clientX)&&t.preventDefault()};return e.addEventListener("touchstart",t,{passive:!1}),()=>e.removeEventListener("touchstart",t)},onPointerDown:function(e){let t=e.currentTarget;(em.delete(e.pointerId),ef(t,e.clientX))?em.set(e.pointerId,{el:t,value:t.value}):e.preventDefault()},onPointerUp:function(e){em.delete(e.pointerId)},onPointerCancel:function(e){let t=em.get(e.pointerId);em.delete(e.pointerId),t&&t.el===e.currentTarget&&t.el.isConnected&&t.el.value!==t.value&&eh(t.el,t.value)}};function eg({title:e,hint:r,children:i,desktop:s=!1}){return(0,t.jsxs)("div",{className:(0,T.cn)("flex flex-col items-center text-center",s?"min-h-40 flex-1 shrink-0 justify-center gap-[6.2px] px-4 pt-3 font-[family-name:var(--font-inter)]":"gap-1 py-12"),children:[!s&&(0,t.jsx)(eo.ImperialMark,{className:"mb-1.5 h-5 w-auto text-foreground/90"}),(0,t.jsx)("span",{className:s?"text-[16.357px] font-medium leading-[20px] text-[#d9dbde]":"text-sm text-secondary-foreground",children:e}),(0,t.jsx)("span",{className:s?"text-[13.29px] font-normal leading-[16px] text-[#80858c]":"text-xs text-label-muted",children:r}),i]})}function eb(e){for(let[t,r]of e)if(t)return r;return null}e.s(["RANGE_SLIDER_CLASSES",0,ep,"THUMB_ONLY_SLIDER",0,ex],227456);let ev="flex-1 -translate-y-[3px] border-b border-dotted border-leader";function ey({label:e,children:r}){return(0,t.jsxs)("div",{className:"flex items-baseline gap-2 py-[3px] leading-[18px]",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:e}),(0,t.jsx)("i",{"aria-hidden":!0,className:ev}),r]})}e.s(["EstimateRow",0,function({label:e,value:r}){return(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs bg-surface-raised border border-border-strong rounded-lg px-3 py-2",children:[(0,t.jsx)("span",{className:"text-label-muted",children:e}),r]})},"FormActions",0,function({onCancel:e,onSubmit:r,submitLabel:i,submitting:s=!1,disabled:n=!1,variant:a="submit"}){let o=(0,l.useTranslations)("positions"),d=(0,l.useTranslations)("common");return(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("button",{onClick:e,disabled:s,className:"flex-1 py-2.5 text-sm font-medium rounded-md border border-border text-secondary-foreground hover:bg-surface-interactive hover:text-foreground disabled:opacity-50",children:d("cancel")}),(0,t.jsxs)("button",{onClick:r,disabled:s||n,"aria-busy":s,className:(0,T.cn)("flex-1 py-2.5 text-sm rounded-md font-semibold text-primary-foreground disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5","close"===a?"bg-amber-500 hover:bg-amber-600":"bg-primary hover:bg-primary/90"),children:[s&&(0,t.jsx)(ec,{}),i??o("submit")]})]})},"LabeledField",0,function({label:e,children:r,hint:i}){return(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between min-h-[18px]",children:[(0,t.jsx)("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:e}),i]}),r]})}
2,"OrderFormInput",0,function({value:e,onChange:r,placeholder:i,unit:s="USD",disabled:n,inputMode:a="decimal",filter:l}){let o=(0,Y.useDecimalSeparator)();return(0,t.jsxs)("div",{className:"flex-1 flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2",children:[(0,t.jsx)(eu.Input,{type:"text",inputMode:a,"data-keypad-unit":"USD"===s?"money":void 0,value:e,onChange:e=>{let t=e.target.value,i="decimal"===a?(0,el.sanitizeDecimalInput)(t,o):t;r(l?i.replace(l,""):i)},onWheel:e=>e.currentTarget.blur(),disabled:n,placeholder:i,className:(0,T.cn)("bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus:border-none focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",n&&"opacity-40")}),(0,t.jsx)("span",{className:"text-xs text-label-muted ml-2",children:s})]})},"OrderTypeBadge",0,function({label:e,colorClass:r}){return(0,t.jsx)("div",{className:"inline-flex items-center gap-1.5 bg-surface-raised border border-border-strong rounded px-3 py-1.5",children:(0,t.jsx)("span",{className:(0,T.cn)("text-xs font-medium",r),children:e})})},"PnlPctPresets",0,function({value:e,onChange:r,orderType:i,presets:s=[10,25,50,100]}){let n="tp"===i?"bg-side-long/20 text-side-long border-side-long/40":"bg-side-short/20 text-side-short border-side-short/40",a="tp"===i?200:100,l=parseInt(e)||0,o=Math.min(a,Math.max(0,l));return(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)("input",{type:"range",...ex,min:0,max:a,step:1,value:o,onChange:e=>r(e.target.value),className:(0,T.cn)(ep,"w-full","tp"===i?"[&::-webkit-slider-thumb]:bg-side-long":"[&::-webkit-slider-thumb]:bg-side-short")}),(0,t.jsx)("div",{className:"flex items-center gap-1",children:s.map(e=>{let s=l===e;return(0,t.jsxs)("button",{onClick:()=>r(String(e)),className:(0,T.cn)("flex-1 px-2 py-1 text-[11px] rounded border transition-colors font-mono tabular-nums",s?n:"bg-surface-raised text-muted-foreground border-border-strong hover:border-border-strong"),children:["tp"===i?"+":"-",e,"%"]},e)})})]})},"SUMMARY_LEADER_CLASS",0,ev,"SizeSlider",0,function({value:e,onChange:r,presets:i=[25,50,75,100],max:s=100}){(0,l.useTranslations)("positions");let n=(0,l.useTranslations)("terms"),a=Math.max(1,Math.min(100,s)),o=i.filter(e=>e<=a),d=a<100&&!o.includes(a);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted w-7",children:n("size.abbrev")}),(0,t.jsx)("input",{type:"range",...ex,min:1,max:a,value:Math.min(e,a),onChange:e=>r(parseInt(e.target.value)),className:(0,T.cn)(ep,"flex-1 [&::-webkit-slider-thumb]:bg-primary")}),(0,t.jsxs)("span",{className:"text-xs text-foreground w-10 font-mono tabular-nums",children:[e,"%"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[o.map(i=>(0,t.jsxs)("button",{onClick:()=>r(i),className:(0,T.cn)("px-2 py-0.5 text-xs rounded font-mono tabular-nums",e===i?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-muted-foreground"),children:[i,"%"]},i)),d&&(0,t.jsxs)("button",{onClick:()=>r(a),className:(0,T.cn)("px-2 py-0.5 text-xs rounded font-mono tabular-nums",e===a?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-muted-foreground"),children:[a,"%"]})]})]})},"SummaryRow",0,ey,"TabConnectEmptyState",0,function({title:e,hint:r,desktop:i=!1}){let s=(0,l.useTranslations)("wallet");return(0,t.jsx)(eg,{title:e,hint:r,desktop:i,children:(0,t.jsx)(o.Button,{variant:"link",size:"sm",onClick:D.promptConnectWallet,className:"hit-target mt-1 text-xs font-semibold underline decoration-dotted",children:s("connectWallet")})})},"TabEmptyState",0,eg,"TpSlToggle",0,function({value:e,onChange:r}){let i=(0,l.useTranslations)("positions");return(0,t.jsxs)("div",{className:"flex items-center gap-0",children:[(0,t.jsx)("button",{onClick:()=>r("tp"),className:(0,T.cn)("px-3 py-1.5 text-xs font-medium rounded-l border transition-colors","tp"===e?"bg-side-long/20 text-side-long border-side-long/40":"bg-surface-raised text-muted-foreground border-border-strong hover:border-border-strong"),children:i("takeProfit")}),(0,t.jsx)("button",{onClick:()=>r("sl"),className:(0,T.cn)("px-3 py-1.5 text-xs font-medium rounded-r border border-l-0 transition-colors","sl"===e?"bg-side-short/20 text-side-short border-side-short/40":"bg-surface-raised text-muted-foreground border-border-strong hover:border-border-strong"),children:i("stopLoss")})]})},"pickMissingLabel",0,eb],546642);var ew=e.i(59392),ej=e.i(160480);let eS={1:0,5:1,15:2,60:3,240:4,"1D":5},ek=[0,1,2,3,4,5],eN="h-[45px] w-full rounded-[6px] border-0 bg-[image:var(--gradient-cta-wide)] text-[14px] font-semibold text-[var(--on-cta-wide)] hover:brightness-105",eP="h-12 w-full rounded-control border-0 bg-[image:var(--gradient-cta-wide)] font-semibold text-[var(--on-cta-wide)] hover:brightness-105";e.s(["ProOrderForm",0,function({activeTab:e,marketPrice:c,minCollateral:u,maxLeverage:h,walletBalance:p,onSubmitRatchetEntry:m,onSubmitIndicator:f,onSubmitDca:x,onSubmitDcaTime:g,onSubmitDcaRatchet:b,submitting:v,submittingLabel:y,readyLabel:w,disableLong:j,disableShort:S,pinCta:k=!1,compact:N=!1,desktopLayout:P=!1,footerHost:B=null,actionHost:z=null,leverageSlot:V=null,statusSlot:H=null,maxSlippageSlot:G=null,ctaHost:Q=null,side:J="long",marketMint:ee,underwriter:et,onDepositClick:eo,chartResolution:ed,oraclePriceToleranceBps:ec,deferFunding:eu,onDeferFundingChange:eh,canDeferFunding:ep,leverage:em,phoenixDcaBlocked:ef,isUnifiedMargin:ex=!1,availableMarginUsd:eg=null}){let ev,eT,eC,eM,e_,eA,eE,eL,eF,eR=P&&!N,eD=(0,i.useRef)(null),eI=(0,l.useTranslations)("trading"),eU=(0,l.useTranslations)("terms"),eO=(0,l.useTranslations)("wallet"),eB=(0,Y.useFormatters)(),ez=(0,Y.useDecimalSeparator)(),{isJWTMode:e$,publicKey:eV}=(0,R.useUnifiedWallet)(),eH=(0,K.getSchedule)(ee),eW=(0,i.useMemo)(()=>ee===F.BTC_MINT.toBase58()?"500":ee===F.ETH_MINT.toBase58()?"50":"0.50",[ee]),[eq,eK]=(0,r.useDesktopTicketDraftState)("pro.size",""),[eG,eY]=(0,r.useDesktopTicketDraftState)("pro.collateral",""),[eX,eQ]=(0,r.useDesktopTicketDraftState)("pro.worstPrice",""),[eJ,eZ]=(0,r.useDesktopTicketDraftState)("pro.ratchetSize",""),[e0,e1]=(0,r.useDesktopTicketDraftState)("pro.longDragPrice",""),[e2,e5]=(0,r.useDesktopTicketDraftState)("pro.shortDragPrice",""),e3=(0,i.useRef)("worstPrice"),[e4,e6]=(0,r.useDesktopTicketDraftState)("pro.timeframe",3),[e8,e9]=(0,r.useDesktopTicketDraftState)("pro.indicatorCondition",0),[e7,te]=(0,r.useDesktopTicketDraftState)("pro.threshold","30"),[tt,tr]=(0,r.useDesktopTicketDraftState)("pro.rsiRatchetEnabled",!1),[ti,ts]=(0,r.useDesktopTicketDraftState)("pro.rsiRatchetSize",""),[tn,ta]=(0,r.useDesktopTicketDraftState)("pro.dcaStartPrice",""),[tl,to]=(0,r.useDesktopTicketDraftState)("pro.dcaEndPrice",""),[td,tc]=(0,r.useDesktopTicketDraftState)("pro.dcaNumLegs",5),[tu,th]=(0,r.useDesktopTicketDraftState)("pro.dcaNumLegsInput",""),[tp,tm]=(0,r.useDesktopTicketDraftState)("pro.dcaWeightingType",0),[tf,tx]=(0,r.useDesktopTicketDraftState)("pro.dcaOpenMode","price"),[tg,tb]=(0,r.useDesktopTicketDraftState)("pro.dcaPriceLimitInput",""),[tv,ty]=(0,r.useDesktopTicketDraftState)("pro.dcaIntervalSeconds",3600),[tw,tj]=(0,r.useDesktopTicketDraftState)("pro.dcaRatchetSizeInput",""),{style:tS,setStyle:tk}=function(){let[e,t]=(0,i.useState)("interval");return(0,i.useEffect)(()=>{let e=localStorage.getItem(O);("duration"===e||"interval"===e)&&t(e)},[]),{style:e,setStyle:(0,i.useCallback)(e=>{t(e),localStorage.setItem(O,e)},[])}}(),[tN,tP]=(0,r.useDesktopTicketDraftState)("pro.dcaDurationHours","6"),[tT,tC]=(0,r.useDesktopTicketDraftState)("pro.dcaDurationMinutes","0"),[tM,t_]=(0,r.useDesktopTicketDraftState)("pro.dcaFrequencySeconds",3600),tA=(0,i.useMemo)(()=>3600*(parseInt(tN)||0)+60*(parseInt(tT)||0),[tN,tT]),tE=(0,i.useMemo)(()=>tM<=0||tA<=0?0:Math.floor(tA/tM),[tA,tM]),[tL,tF]=(0,r.useDesktopTicketDraftState)("pro.dcaStartDelayHours","0"),[tR,tD]=(0,r.useDesktopTicketDraftState)("pro.dcaStartDelayMinutes","0"),tI=(0,i.useMemo)(()=>Math.max(0,3600*(parseInt(tL)||0)+60*(parseInt(tR)||0)),[tL,tR]),tU="trailing"===e,tO="indicator"===e,tB="dca"===e;(0,i.useEffect)(()=>{eR&&tB&&eD.current?.closest("[data-ticket-body]")?.scrollTo({top:0})},[eR,tB,tf,tS]);let tz=`${tS}|${tM}|${tE}|${tf}`,[t$,tV]=(0,i.useState)(tz);t$!==tz&&(tV(tz),tB&&"time"===tf&&"duration"===tS&&(ty(tM),tE>=U.MIN_DCA_LEGS&&tE<=U.MAX_DCA_LEGS&&(tc(tE),th(""))));let[tH,tW]=(0,i.useState)(ee),tq=tH!==ee;tq&&(tW(ee),eK(""),eY(""),eQ(""),eZ(""),e1(""),e5(""),ta(""),to(""),tb(""),tj(""),ts(""));let tK=(0,r.useDesktopTicketDraftHas)("pro.timeframe"),[tG,tY]=(0,i.useState)(()=>tK?ed:void 0);tG!==ed&&(tY(ed),ed&&ed in eS&&e6(eS[ed]));let[tX,tQ]=(0,i.useState)(J);tX!==J&&(tQ(J),e1(""),e5(""),eQ(""),ta(""),to(""));let[tJ,tZ]=(0,i.useState)(e);tJ!==e&&(tZ(e),tO&&!e7&&te("30"));let t0=parseFloat(eG)||0,t1=parseFloat(eq)||0,t2=ex&&em>0?t1/em:0,{walletUsd:t5,collateralAmountUsd:t3}
2=en((0,ea.venueFromUnderwriterByte)(et),t2,eg),t4=ex?t5:t0,t6=tB&&td>=2&&t1>0&&(ex?t3:t0)<=0,t8=ex?t1>0:t0>0,[t9,t7]=(0,i.useState)(em);if(t9!==em){t7(em);let e=tq?0:parseFloat(eG)||0;if(e>0){let t=e*em;eK(t>0?t.toFixed(2):"")}}let re=!!eV&&null!=p&&ei(t4,p),rt=re&&ep,rr=re&&!eu&&!!eo;(0,i.useEffect)(()=>{rt||eh(!1)},[rt,eh]);let ri=!ex&&t0>0&&t0<u,rs=Number(eX)||0,rn=Number(eJ||eW)||0,ra=Number(e7)||0,rl=Number(ti)||0,ro=Number(tn)||0,rd=Number(tl)||0,rc=rs>0&&rn>0&&t8,ru=t8&&ra>0&&ra<=100&&(!tt||rl>0&&rl<ra),rh=(0,i.useMemo)(()=>{if(!tB||!t8||td<2||t1<=0)return!1;let e=Math.floor(1e6*t0),t=Math.floor(1e6*t1),r=e>0;if(r){let t=1===tp?td-1:0;if(0===I.PassthroughClient.calculateDcaLegCollateral(e,td,tp,t))return!0}let i=1/0;for(let s=0;s<td;s++){let n=I.PassthroughClient.calculateDcaLegCollateral(e,td,tp,s);if(r&&0===n)return!0;let a=I.PassthroughClient.calculateDcaLegSizeUsd(t,e,td,tp,s);a<i&&(i=a)}return i<U.MIN_DCA_LEG_SIZE_USD},[tB,t8,t0,t1,td,tp]),rp=(0,i.useMemo)(()=>!!tB&&!!ec&&!(td<2)&&!(ro<=0)&&!(rd<=0)&&ro!==rd&&Math.abs(rd-ro)/(td-1)<=Math.max(ro,rd)*ec/1e4*2,[tB,ec,td,ro,rd]),rm=parseFloat(tg)||0,rf=parseFloat(tw)||0,rx=""===tu||!isNaN(ev=parseInt(tu))&&ev>=U.MIN_DCA_LEGS&&ev<=U.MAX_DCA_LEGS,rg=!!c&&!(c<=0)&&!(ro<=0)&&!(rd<=0)&&(ro>rd?Math.min(ro,rd)>c:Math.max(ro,rd)<c),rb=t0>0&&ro>0&&rd>0&&ro!==rd&&!rg&&td>=U.MIN_DCA_LEGS&&td<=U.MAX_DCA_LEGS&&rx&&!rh&&!rp,rv=(0,i.useMemo)(()=>{if(!tB||"time"!==tf||!eH||W(eH))return null;let e=1e3*tv*td,t=q($(eH));return t>0&&e>t?eI("dcaScheduleOutsideHours"):null},[tB,tf,eH,tv,td,eI]),ry=t0>0&&t1>0&&td>=U.MIN_DCA_LEGS&&td<=U.MAX_DCA_LEGS&&rx&&!rh&&("duration"!==tS||tE>=U.MIN_DCA_LEGS&&tE<=U.MAX_DCA_LEGS),rw=t0>0&&t1>0&&rm>0&&rf>0&&td>=U.MIN_DCA_LEGS&&td<=U.MAX_DCA_LEGS&&rx&&!rh,rj="price"===tf?rb:"time"===tf?ry:rw,rS=(0,i.useMemo)(()=>{if(!tB||"price"!==tf||ro<=0||rd<=0||ro===rd)return null;let e=ro>rd;return{longWarn:!e,shortWarn:e}},[tB,tf,ro,rd]),rk=tB?rj:tO?ru:rc,rN=tB?eb([[!t8,ex?eI("setSize"):eI("setCollateral")],..."price"===tf?[[ro<=0,eI("setStartPrice")],[rd<=0,eI("setEndPrice")],[rg,eI("fixPriceRange")]]:[..."ratchet"===tf?[[rm<=0,eI("setPriceLimit")],[rf<=0,eI("setTrailSize")]]:[]]]):tO?eb([[!t8,ex?eI("setSize"):eI("setCollateral")],[ra<=0||ra>100,eI("setThreshold")],[tt&&rl<=0,eI("setTrailSize")]]):eb([[!t8,ex?eI("setSize"):eI("setCollateral")],[rs<=0,eI("setWorstPrice")],[rn<=0,eI("setTrailSize")]]),rP=e=>{let t=(0,el.sanitizeDecimalInput)(e,ez);eY(t);let r=(parseFloat(t)||0)*em;eK(r>0?r.toFixed(2):"")},rT=e=>{if(v||null==p||p<=0)return;let t=Math.floor(p*e+1e-7)/100;rP(t>0?t.toFixed(2):"")},rC=async e=>{try{await rM(e)}catch(e){a.toast.error(e instanceof Error?e.message:String(e))}},rM=async e=>{if(!eV)return void(0,D.promptConnectWallet)();if(!rk||!c)return;let t=ex?t4:parseFloat(eG)||0,r=(!eu&&null!=p&&p>0?es(t,p):t)+(ex?t3-t5:0),i=eu||void 0,s=h>0?Math.min(em,h):em,n=Math.min(t1,ex||r<=0||!(h>0)||!isFinite(h)?1/0:r*h);n<t1&&a.toast.info(eI("sizeCappedToLeverage"));let l=!1;if(tB){let t=parseFloat(tg)||0,a=parseFloat(tw)||0;l="time"===tf?await g({marketMint:ee,side:e?"long":"short",sizeUsd:n,collateralAmount:r,leverage:s,priceLimit:t,intervalSeconds:tv,numLegs:td,weightingType:tp,currentPrice:c,deferFunding:i,startDelaySeconds:tI}):"ratchet"===tf?await b({marketMint:ee,side:e?"long":"short",sizeUsd:n,collateralAmount:r,leverage:s,priceLimit:t,intervalSeconds:0,numLegs:td,weightingType:tp,ratchetSize:a,currentPrice:c,deferFunding:i,startDelaySeconds:tI}):await x({marketMint:ee,side:e?"long":"short",sizeUsd:n,collateralAmount:r,leverage:s,startPrice:ro,endPrice:rd,numLegs:td,weightingType:tp,currentPrice:c,deferFunding:i})}else l=tO?await f({marketMint:ee,side:e?"long":"short",sizeUsd:n,collateralAmount:r,leverage:s,indicatorType:0,timeframeCode:e4,period:14,indicatorCondition:e8,thresholdValue:ra,...tt&&rl>0?{ratchetSize:rl}:{},deferFunding:i}):await m({marketMint:ee,side:e?"long":"short",sizeUsd:n,collateralAmount:r,leverage:s,currentPrice:c,worstPrice:rs,ratchetSize:rn,deferFunding:i});l&&(eY(""),eK(""))},r_=`${eB.fixed(em,+!Number.isInteger(em))}x`,rA=`$${eB.number(t4)} \xb7 ${r_}`,rE=tU&&rn>0&&c&&c>0?eB.percent(rn/c*100,2):null,rL=tU&&rn>0?rE?`$${eB.number(rn)} \xb7 ${rE}`:`$${eB.number(rn)}`:null,rF=(0,i.useMemo)(()=>
2{if(!tB||td<1||t0<=0)return null;let e=Math.floor(1e6*t0),t=I.PassthroughClient.calculateDcaLegCollateral(e,td,tp,0)/1e6,r=I.PassthroughClient.calculateDcaLegCollateral(e,td,tp,td-1)/1e6,i=Math.min(t,r),s=Math.max(t,r),n=.005>Math.abs(s-i)?`$${eB.number(s)}`:`$${eB.number(i)}–$${eB.number(s)}`;return`${n} \xd7 ${td}`},[tB,td,tp,t0,eB]),rR=(0,i.useMemo)(()=>{if(!tB||"price"!==tf||td<2||ro<=0||rd<=0||ro===rd)return null;let e=(rd-ro)/(td-1),t=Math.floor(1e6*t0),r=0,i=0;for(let s=0;s<td;s++){let n=ro+s*e,a=t>0?I.PassthroughClient.calculateDcaLegCollateral(t,td,tp,s):1;r+=n*a,i+=a}let s=(eB.number(rd).split(".")[1]??"").length;return{step:Math.abs(e),stepText:eB.fixed(Math.abs(e),s),avgEntry:i>0?r/i:0}},[tB,tf,td,ro,rd,tp,t0,eB]),rD=parseFloat(e0)||0,rI=parseFloat(e2)||0,rU="long"===J,rO=!v&&!(re&&!eu)&&!ri&&rk&&!(tB&&ef)&&!(rU?j:S)&&!(rU?rS?.longWarn:rS?.shortWarn)&&(tB||(eT=rU?e0:e2,eC=rU?rD:rI,!eT||eC>0&&(rU?eC<rs:eC>rs))),rB=e=>{if(w)return w;let r=ex?t1:t4,i=e?eI(rU?"confirmLong":"confirmShort"):eI(rU?"openLong":"openShort");return r>0?(0,t.jsxs)(t.Fragment,{children:[i,(0,t.jsx)("span",{className:e?"tabular-nums":"font-mono tabular-nums",children:e?` - ${eB.number(r)}`:` — $${eB.number(r)}`})]}):i},rz=eV?rr?(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:eo,variant:"outline",className:eN,children:e$?eI("getDepositAddress"):eI("depositToTrade")}):(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:()=>rC(rU),disabled:!rO,"aria-busy":v,variant:"outline",className:`h-[45px] w-full rounded-[5px] border-0 text-[14px] font-semibold ${rO||v?"bg-[var(--confirm-pad)] text-primary hover:brightness-110":"cursor-not-allowed bg-surface-interactive text-muted-foreground"}`,children:v?y??eI("submitting"):rN??rB(!0)}):(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:D.promptConnectWallet,variant:"outline",className:eN,children:eO("connectWallet")}),r$=(0,t.jsx)(t.Fragment,{children:(eM=[],e_=(e,t,r)=>eM.push({k:e,label:t,value:r}),(ex||e_("margin",eI("margin"),t4>0?rA:"—"),tU&&(e_("worst",eI("worstPrice"),rs>0?`$${eB.number(rs)}`:"—"),e_("trail",eI("trailSize"),rL??"—")),tB&&(e_("perLeg",eI("perLeg"),rF??"—"),"price"===tf&&(e_("step",eI("ladderStep"),rR?`$${rR.stepText}`:"—"),e_("entry",eI("estEntryPrice"),rR?`$${eB.number(rR.avgEntry)}`:"—"))),G&&e_("slippage",eI("maxSlippage"),G),0===eM.length)?null:N?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-x-[9px] gap-y-[10px] text-[10.66px] font-medium [&_.font-mono]:font-sans [&_.text-secondary-foreground]:text-[#D9DBE0]",children:eM.map((e,r)=>(0,t.jsxs)("div",{className:(0,T.cn)("flex items-center justify-between gap-2",r===eM.length-1&&eM.length%2==1&&"col-span-2"),children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:e.label}),(0,t.jsx)("span",{className:"font-sans font-semibold tabular-nums text-secondary-foreground",children:e.value})]},e.k))}):(0,t.jsx)("div",{"data-pro-summary":!0,className:"flex flex-col pt-0.5 text-xs",children:eM.map(e=>(0,t.jsx)(ey,{label:e.label,children:(0,t.jsx)("span",{className:"font-mono font-semibold tabular-nums text-secondary-foreground",children:e.value})},e.k))}))}),rV=(0,t.jsxs)(t.Fragment,{children:[ri&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:eI("minimumCollateralIs",{amount:`$${u}`})}),re&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:eI("insufficientSubaccountBalance")})]}),rH=(0,t.jsxs)(t.Fragment,{children:[rt&&(0,t.jsxs)("label",{className:"flex items-center gap-2 justify-center cursor-pointer",children:[(0,t.jsx)("input",{type:"checkbox",checked:eu,onChange:e=>eh(e.target.checked),className:"rounded border-border-strong bg-surface text-primary focus:ring-primary/50"}),(0,t.jsx)("span",{className:"text-xs text-amber-400",children:eI("deferFundingNote")})]}),rh&&(0,t.jsx)("div",{className:"text-xs text-destructive text-center",children:eI("dcaLegCollateralTooSmall",{minSize:`$${eB.grouped(U.MIN_DCA_LEG_SIZE_USD/1e6)}`})}),rp&&"price"===tf&&(0,t.jsx)("div",{className:"text-xs text-destructive text-center",children:eI("dcaLegsOverlap")}),rv&&(0,t.jsx)("div",{className:"text-xs text-amber-400 text-center",children:rv}),tB&&ef&&(0,t.jsx)("div",{className:"text-xs text-destructive text-center",children:eI("phoenixDcaLeverageBlocked",{symbol:ef.symbol,cap:eB.fixed(ef.capX,2),implied:eB.fixed(ef.impliedX,2)})}),H]}),rW=k?Q?(0,s.createPortal)(rz,Q):null:eV?rr?(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:eo,variant:"outline",className:eP,children:e$?eI("getDepositAddress"):eI("depositToTrade")}):(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:()=>rC(rU),disabled:!rO,"aria-busy":v,variant:"ghost",className:`h-12 w-full rounded-control font-semibold transition-colors duration-150 ${rO||v?rU?"bg-[var(--side-pad-long)] text-[var(--side-ink-long)] hover:brightness-110":"bg-[var(--side-pad-short)] text-side-short hover:brightness-110":"cursor-not-allowed bg-surface-interactive text-muted-foreground"}`,children:v?y??eI("submitting"):rN??rB(!1)}):(0,t.jsx)(o.Button,{"data-ticket-submit":!0,onClick:D.promptConnectWallet,variant:"outline",className:eP,children:eO("connectWallet")}),rq=(0,t.jsxs)(t.Fragment,{children:[r$,rH,rW]});return(0,t.jsxs)("div",{ref:eD,className:(0,T.cn)("space-y-[11px]",eR&&ej.default.form),children:[tO&&(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("rsiTimeframe")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("rsiTimeframeHelp")})})]})]}),(0,t.jsx)("div",{className:"flex gap-1",children:ek.map(e=>(0,t.jsx)("button",{onClick:()=>e6(e),disabled:v,className:`flex-1 text-xs min-h-11 rounded-[7px] transition-colors ${e4===e?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:M[e]},e))})]}),(0,t.jsxs)("div",{"data-pro-parameter-stack":!0,className:"grid grid-cols-2 items-end gap-3",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("condition")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("conditionHelp")})})]})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-1",children:_.map(e=>(0,t.jsx)("button",{onClick:()=>e9(e),disabled:v,className:`text-2xs min-h-11 rounded-[7px] transition-colors ${e8===e?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:eI(A[e])},e))})]}),(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 whitespace-nowrap text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("rsiThreshold")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("rsiThresholdHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:e7,onChange:e=>te(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),placeholder:"30",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none w-full [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v})]})]}),(0,t.jsx)(X,{market:ee,timeframe:e4,underwriter:et,threshold:e7,condition:e8,trailing:tt,deferred:eu}),(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2.5 rounded-[11.4px] border-[0.85px] border-[var(--phone-card-border)] bg-[var(--phone-chip)] pl-[14px] pr-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:"shrink-0 text-[14px] font-semibold text-foreground",children:eI("rsiTrailing")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[260px]",children:(0,t.jsx)("p",{children:eI("rsiTrailingHelp")})})]})]}),(0,t.jsx)("label",{className:"flex h-11 w-11 shrink-0 cursor-pointer items-center justify-end",children:(0,t.jsx)(C,{"aria-label":eI("rsiTrailing"),checked:tt,onCheckedChange:tr,disabled:v})})]}),tt&&(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1.5 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:[eI("trailSize"),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"h-3 w-3 cursor-help text-label-muted"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[260px]",children:(0,t.jsx)("p",{children:eI("rsiTrailingHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal",value:ti,onChange:e=>ts((0,el.sanitizeDecimalInput)(e.target.value,ez)),onWheel:e=>e.currentTarget.blur(),placeholder:"0.5",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 w-full min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("rsiPoints")})]})]})]}),tB&&(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)("div",{className:"flex flex-1 items-center gap-1 rounded-[9px] bg-black/40 p-1",children:["price","time","ratchet"].map(e=>(0,t.jsx)("button",{onClick:()=>tx(e),disabled:v,className:(0,T.cn)("flex-1 h-9 rounded-[7px] text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",tf===e?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-foreground"),children:"price"===e?eI("price"):"time"===e?eI("time"):eI("trailing")},e))})}),"price"===tf&&(0,t.jsxs)("div",{"data-pro-parameter-stack":!0,className:"grid grid-cols-2 gap-3",children:[(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("startPrice")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("startPriceHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:tn,onChange:e=>ta((0,el.sanitizeDecimalInput)(e.target.value,ez)),onWheel:e=>e.currentTarget.blur(),placeholder:c?eB.number(c):"0.00",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none w-full [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v})]}),(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("endPrice")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("endPriceHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:tl,onChange:e=>to((0,el.sanitizeDecimalInput)(e.target.value,ez)),onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none w-full [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v})]})]}),("time"===tf||"ratchet"===tf)&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:"time"===tf?eI("priceLimitOptional"):eI("priceLimit")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:"ratchet"===tf?(0,t.jsx)("p",{children:eI("priceLimitRatchetHelp")}):(0,t.jsx)("p",{children:eI("priceLimitTimeHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:tg,onChange:e=>tb((0,el.sanitizeDecimalInput)(e.target.value,ez)),onWheel:e=>e.currentTarget.blur(),placeholder:"time"===tf?eI("noLimit"):c?eB.number(c):"0.00",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none w-full [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v})]}),"time"===tf&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"flex items-center justify-end",children:(0,t.jsx)("div",{className:"flex items-center gap-1 rounded-[9px] bg-black/40 p-1 text-2xs",children:["duration","interval"].map(e=>(0,t.jsx)("button",{onClick:()=>tk(e),disabled:v,className:(0,T.cn)("h-8 px-3 rounded-[6px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",tS===e?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-foreground"),title:"duration"===e?eI("durationStyleTitle"):eI("intervalStyleTitle"),children:"duration"===e?eI("duration"):eI("interval")},e))})}),"duration"===tS?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("duration")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[240px]",children:(
20,t.jsx)("p",{children:eI("durationHelp")})})]})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:tN,onChange:e=>tP(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:"h"})]}),(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:tT,onChange:e=>tC(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:"m"})]})]})]}),(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("frequency")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("frequencyHelp")})})]})]}),(0,t.jsx)("div",{className:"flex gap-1",children:U.DCA_INTERVAL_OPTIONS.map(e=>(0,t.jsx)("button",{onClick:()=>t_(e.value),disabled:v,className:`flex-1 text-xs min-h-11 rounded-[7px] transition-colors ${tM===e.value?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:e.label},e.value))}),tA>0&&tM>
20&&(0,t.jsx)("div",{className:`text-2xs ${tE<U.MIN_DCA_LEGS||tE>U.MAX_DCA_LEGS?"text-destructive":"text-label-muted"}`,children:tE<U.MIN_DCA_LEGS?eI("durationTooShort",{min:U.MIN_DCA_LEGS}):tE>U.MAX_DCA_LEGS?eI("tooManyLegs",{count:tE,max:U.MAX_DCA_LEGS}):eI("legsCountPlain",{count:tE})})]})]}):(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("interval")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("intervalHelp")})})]})]}),(0,t.jsx)("div",{className:"flex gap-1",children:U.DCA_INTERVAL_OPTIONS.map(e=>(0,t.jsx)("button",{onClick:()=>ty(e.value),disabled:v,className:`flex-1 text-xs min-h-11 rounded-[7px] transition-colors ${tv===e.value?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:e.label},e.value))})]})]}),"ratchet"===tf&&(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("trailSize")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("trailSizeHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:tw,onChange:e=>tj((0,el.sanitizeDecimalInput)(e.target.value,ez)),onWheel:e=>e.currentTarget.blur(),placeholder:eW,className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 w-full min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"shrink-0 text-2xs font-semibold text-label-muted",children:"USD"})]}),("time"===tf||"ratchet"===tf)&&(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("delayedStart")}),(0,t.jsx)("span",{className:"text-2xs text-label-muted",children:eI("optionalSuffix")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[240px]",children:(0,t.jsx)("p",{children:eI("delayedStartHelp")})})]})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:tL,onChange:e=>tF(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:"h"})]}),(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:tR,onChange:e=>tD(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:"m"})]})]}),tI>0&&(0,t.jsx)("div",{className:"text-2xs text-label-muted",children:eI("startsAfterCreation",{delay:[tL&&parseInt(tL)>0?`${parseInt(tL)}h`:"",parseInt(tR)>0?`${parseInt(tR)}
2m`:""].filter(Boolean).join(" ")})})]})]}),("time"!==tf||"duration"!==tS)&&(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("entries")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("entriesHelp",{min:U.MIN_DCA_LEGS,max:U.MAX_DCA_LEGS})})})]})]}),(0,t.jsxs)("div",{className:"flex gap-1",children:[[2,3,5,10].map(e=>(0,t.jsx)("button",{onClick:()=>{tc(e),th("")},disabled:v,className:`flex-1 text-xs min-h-11 rounded-[7px] transition-colors ${td===e&&""===tu?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:e},e)),(0,t.jsx)("input",{"data-ticket-field":!0,"aria-invalid":""!==tu&&!rx||void 0,type:"text",inputMode:"numeric",value:tu,placeholder:"#",onChange:e=>{let t=e.target.value.replace(/[^0-9]/g,"");th(t);let r=parseInt(t);!isNaN(r)&&r>=U.MIN_DCA_LEGS&&r<=U.MAX_DCA_LEGS&&tc(r)},onBlur:()=>{if(""===tu)return;let e=parseInt(tu);isNaN(e)||e<U.MIN_DCA_LEGS?(tc(U.MIN_DCA_LEGS),th(String(U.MIN_DCA_LEGS))):e>U.MAX_DCA_LEGS&&(tc(U.MAX_DCA_LEGS),th(String(U.MAX_DCA_LEGS)))},disabled:v,className:`w-14 text-xs text-center min-h-11 rounded-[7px] transition-colors [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none ${""!==tu&&!rx?"bg-destructive/10 text-destructive border border-destructive/50":""!==tu?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"} focus:outline-none focus:border-primary/60`})]})]}),(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"shrink-0 text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:eI("cashWeighting")}),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"w-3 h-3 text-label-muted cursor-help"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[260px]",children:(0,t.jsx)("p",{children:eI("cashWeightingHelp")})})]})]}),(0,t.jsx)("div",{className:"grid grid-cols-3 gap-1",children:E.map(e=>(0,t.jsx)("button",{onClick:()=>tm(e),disabled:v,className:`text-xs min-h-11 rounded-[7px] transition-colors ${tp===e?"border border-border-strong text-foreground":"bg-[var(--phone-chip)] text-muted-foreground border border-[var(--phone-card-border)] hover:border-border-strong hover:text-foreground"}`,children:eI(L[e])},e))}),t6&&(0,t.jsx)("p",{className:"text-2xs text-label-muted leading-snug",children:eI("dcaWeightingEvenSplit")})]})]}),tU&&!eR&&(0,t.jsx)("div",{className:"space-y-[11px]"}),tU&&(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsxs)("div",{"data-pro-money":!0,"data-keypad-reveal":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-[73px] px-[15px] pb-3 pt-[13px] flex flex-col justify-between focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-[12px] font-medium text-foreground/50",children:[eI("worstPrice"),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"h-3 w-3 cursor-help text-label-muted"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("minPriceHelp")})})]})]}),(0,t.jsx)("span",{className:"shrink-0 text-[12px] font-medium text-foreground/50",children:rU?eI("worstPriceMostYouPay"):eI("worstPriceLeastYouGet")})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:eX,onChange:e=>{let t=(0,el.sanitizeDecimalInput)(e.target.value,ez);eQ(t),e3.current="worstPrice";let r=parseFloat(t),i=parseFloat(e0),s=parseFloat(e2);r>0&&i>0?eZ(parseFloat(Math.abs(r-i).toPrecision(12)).toString()):r>0&&s>0&&eZ(parseFloat(Math.abs(s-r).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),placeholder:c?eB.number(c):"0.00",className:"font-sans text-[22px] font-bold tabular-nums text-foreground
2/70 bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"flex h-[26px] shrink-0 items-center rounded-chip border border-foreground/10 bg-foreground/8 px-2 text-[14px] font-bold text-foreground",children:"USD"})]})]}),(0,t.jsxs)("div",{"data-pro-money":!0,"data-keypad-reveal":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-[73px] px-[15px] pb-3 pt-[13px] flex flex-col justify-between focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-[12px] font-medium text-foreground/50",children:[eI("trailSize"),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"h-3 w-3 cursor-help text-label-muted"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[220px]",children:(0,t.jsx)("p",{children:eI("trailSizeHelp")})})]})]}),rE&&(0,t.jsx)("span",{className:"shrink-0 text-[12px] font-medium text-foreground/50",children:eI("pctOfMark",{pct:rE})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:eJ,onChange:e=>{eZ((0,el.sanitizeDecimalInput)(e.target.value,ez)),e3.current="ratchetSize"},onWheel:e=>e.currentTarget.blur(),placeholder:eW,className:"font-sans text-[22px] font-bold tabular-nums text-foreground/70 bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"flex h-[26px] shrink-0 items-center rounded-chip border border-foreground
2/10 bg-foreground/8 px-2 text-[14px] font-bold text-foreground",children:"USD"})]})]})]}),(0,t.jsx)("div",{className:"space-y-[11px]",children:(0,t.jsxs)("div",{"data-pro-field":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-11 px-3 flex items-center gap-2.5 focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1.5 whitespace-nowrap text-3xs font-semibold uppercase tracking-[0.09em] text-label-muted",children:[rU?eI("longActivation"):eI("shortActivation"),(0,t.jsxs)(d.Tooltip,{children:[(0,t.jsx)(d.TooltipTrigger,{asChild:!0,children:(0,t.jsx)(n.Info,{className:"h-3 w-3 cursor-help text-label-muted"})}),(0,t.jsx)(d.TooltipContent,{className:"max-w-[240px]",children:(0,t.jsx)("p",{children:eI("activationHelp")})})]})]}),(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:rU?e0:e2,onChange:e=>{let t=(0,el.sanitizeDecimalInput)(e.target.value,ez);rU?(e1(t),e5("")):(e5(t),e1("")),e3.current=rU?"longDrag":"shortDrag";let r=parseFloat(t),i=parseFloat(eX);r>0&&i>0&&eZ(parseFloat(Math.abs(i-r).toPrecision(12)).toString())},onWheel:e=>e.currentTarget.blur(),placeholder:(eA=parseFloat(eX)||c||0,eE=parseFloat(eJ)||parseFloat(eW),eA>0&&eE>0?eB.number(rU?eA-eE:eA+eE):"0.00"),className:"text-base font-mono tabular-nums text-foreground text-right bg-transparent border-none focus:outline-none flex-1 w-full min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v})]})})]}),!ex&&(0,t.jsxs)("div",{className:"space-y-[11px]",children:[(0,t.jsxs)("div",{"data-pro-money":!0,"data-keypad-reveal":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-[73px] px-[15px] pb-3 pt-[13px] flex flex-col justify-between focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-[12px] font-medium text-foreground/50",children:eI("collateral")}),(0,t.jsx)(Z,{balance:p,onDepositClick:eo,onUseBalance:null!=p&&p>0?()=>rT(100):void 0,disabled:v})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:eG,onChange:e=>rP(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"font-sans text-[22px] font-bold tabular-nums text-foreground/70 bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"flex h-[26px] shrink-0 items-center rounded-chip border border-foreground
2/10 bg-foreground/8 px-2 text-[14px] font-bold text-foreground",children:"USDC"})]})]}),(0,t.jsx)(er,{compact:N,maxUsd:p??0,valueUsd:parseFloat(eG)||0,onSelect:rT,disabled:v})]}),ex&&(0,t.jsx)("div",{className:"space-y-[11px]",children:(0,t.jsxs)("div",{"data-pro-money":!0,"data-keypad-reveal":!0,className:"bg-[var(--phone-chip)] border border-border-strong rounded-field h-[73px] px-[15px] pb-3 pt-[13px] flex flex-col justify-between focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/40",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-[12px] font-medium text-foreground/50",children:eU("size.full")}),ex&&(0,t.jsx)(Z,{balance:p,onDepositClick:eo})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:eq,onChange:e=>(e=>{let t=(0,el.sanitizeDecimalInput)(e,ez);eK(t);let r=parseFloat(t)||0;if(em>0){let e=r/em;eY(e>0?e.toFixed(2):"")}})(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"font-sans text-[22px] font-bold tabular-nums text-foreground/70 bg-transparent border-none focus:outline-none flex-1 min-w-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",disabled:v}),(0,t.jsx)("span",{className:"flex h-[26px] shrink-0 items-center rounded-chip border border-foreground
2/10 bg-foreground/8 px-2 text-[14px] font-bold text-foreground",children:"USDC"})]})]})}),!eR&&rV,V,tB&&"price"===tf&&ro>0&&rd>0&&ro!==rd&&!ex&&t0>0&&(0,t.jsxs)("div",{className:"text-xs space-y-0.5 bg-[var(--phone-chip)] border border-border-strong rounded-float px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex justify-between text-3xs mb-0.5",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:eI("entryPrice")}),(0,t.jsx)("span",{className:"text-muted-foreground",children:eI("collateral")})]}),(eL=Math.floor(1e6*t0),eF=rd>ro,Array.from({length:td},(e,r)=>{let i=1===td?ro:ro+r*(rd-ro)/(td-1),s=I.PassthroughClient.calculateDcaLegCollateral(eL,td,tp,r)/1e6;return(0,t.jsxs)("div",{className:"flex justify-between font-mono text-3xs leading-4",children:[(0,t.jsxs)("span",{className:eF?"text-side-short":"text-side-long",children:["$",eB.number(i)]}),(0,t.jsxs)("span",{className:"text-secondary-foreground",children:["$",eB.number(s)]})]},r)}))]}),eR?(0,t.jsxs)(t.Fragment,{children:[B&&(0,s.createPortal)((0,t.jsx)("div",{className:ej.default.footer,children:r$}),B),z&&(0,s.createPortal)((0,t.jsx)(ew.TerminalActionSection,{before:(0,t.jsxs)(t.Fragment,{children:[rV,rH]}),children:rW}),z)]}):N?rq:(0,t.jsx)("div",{className:"-mx-4 -mb-4 border-t border-border bg-surface px-4 pb-4 pt-2.5",children:rq})]})}],784010);let eT={collateralUsd:0,leverage:3},eC=(0,i.createContext)({...eT,publish:()=>{}});e.s(["PairTicketProvider",0,function({children:e}){let[r,s]=(0,i.useState)(eT),n=(0,i.useMemo)(()=>({...r,publish:e=>s(t=>t.collateralUsd===e.collateralUsd&&t.leverage===e.leverage?t:e)}),[r]);return(0,t.jsx)(eC.Provider,{value:n,children:e})},"usePairTicket",0,function(){return(0,i.useContext)(eC)}],937626)},87602,360042,e=>{"use strict";let t,r;var i,s,n,a,l,o=e.i(394390),d=e.i(183023),c=e.i(942553),u=Object.defineProperty,h=Object.getOwnPropertySymbols,p=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,f=(e,t,r)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,x=(e,t)=>{for(var r in t||(t={}))p.call(t,r)&&f(e,r,t[r]);if(h)for(var r of h(t))m.call(t,r)&&f(e,r,t[r]);return e},g=(e,t)=>{var r={};for(var i in e)p.call(e,i)&&0>t.indexOf(i)&&(r[i]=e[i]);if(null!=e&&h)for(var i of h(e))0>t.indexOf(i)&&m.call(e,i)&&(r[i]=e[i]);return r};(e=>{let t=class t{constructor(e,r,i,n){if(this.version=e,this.errorCorrectionLevel=r,this.modules=[],this.isFunction=[],e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError("Version value out of range");if(n<-1||n>7)throw RangeError("Mask value out of range");this.size=4*e+17;let a=[];for(let e=0;e<this.size;e++)a.push(!1);for(let e=0;e<this.size;e++)this.modules.push(a.slice()),this.isFunction.push(a.slice());this.drawFunctionPatterns();const l=this.addEccAndInterleave(i);if(this.drawCodewords(l),-1==n){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);const r=this.getPenaltyScore();r<e&&(n=t,e=r),this.applyMask(t)}}s(0<=n&&n<=7),this.mask=n,this.applyMask(n),this.drawFormatBits(n),this.isFunction=[]}static encodeText(r,i){let s=e.QrSegment.makeSegments(r);return t.encodeSegments(s,i)}static encodeBinary(r,i){let s=e.QrSegment.makeBytes(r);return t.encodeSegments([s],i)}static encodeSegments(e,i,n=1,l=40,o=-1,d=!0){let c,u;if(!(t.MIN_VERSION<=n&&n<=l&&l<=t.MAX_VERSION)||o<-1||o>7)throw RangeError("Invalid value");for(c=n;;c++){let r=8*t.getNumDataCodewords(c,i),s=a.getTotalBits(e,c);if(s<=r){u=s;break}if(c>=l)throw RangeError("Data too long")}for(let e of[t.Ecc.MEDIUM,t.Ecc.QUARTILE,t.Ecc.HIGH])d&&u<=8*t.getNumDataCodewords(c,e)&&(i=e);let h=[];for(let t of e)for(let e of(r(t.mode.modeBits,4,h),r(t.numChars,t.mode.numCharCountBits(c),h),t.getData()))h.push(e);s(h.length==u);let p=8*t.getNumDataCodewords(c,i);s(h.length<=p),r(0,Math.min(4,p-h.length),h),r(0,(8-h.length%8)%8,h),s(h.length%8==0);for(let e=236;h.length<p;e^=253)r(e,8,h);let m=[];for(;8*m.length<h.length;)m.push(0);return h.forEach((e,t)=>m[t>>>3]|=e<<7-(7&t)),new t(c,i,m,o)}getModule(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]}getModules(){return this.modules}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let r=0;r<t;r++)for(let i=0;i<t;i++)(0!=r||0!=i)&&(0!=r||i!=t-1)&&(r!=t-1||0!=i)&&this.drawAlignmentPattern(e[r],e[i]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.errorCorrectionLevel.formatBits<<3|e,r=t;for(let e=0;e<10;e++)r=r<<1^(r>>>9)*1335;let n=(t<<10|r)^21522;s(n>>>15==0);for(let e=0;e<=5;e++)this.setFunctionModule(8,e,i(n,e));this.setFunctionModule(8,7,i(n,6)),this.setFunctionModule(8,8,i(n,7)),this.setFunctionModule(7,8,i(n,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,i(n,e));for(let e=0;e<8;
vendor: 9,503 bytes, line 2
2e++)this.setFunctionModule(this.size-1-e,8,i(n,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,i(n,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;s(t>>>18==0);for(let e=0;e<18;e++){let r=i(t,e),s=this.size-11+e%3,n=Math.floor(e/3);this.setFunctionModule(s,n,r),this.setFunctionModule(n,s,r)}}drawFinderPattern(e,t){for(let r=-4;r<=4;r++)for(let i=-4;i<=4;i++){let s=Math.max(Math.abs(i),Math.abs(r)),n=e+i,a=t+r;0<=n&&n<this.size&&0<=a&&a<this.size&&this.setFunctionModule(n,a,2!=s&&4!=s)}}drawAlignmentPattern(e,t){for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++)this.setFunctionModule(e+i,t+r,1!=Math.max(Math.abs(i),Math.abs(r)))}setFunctionModule(e,t,r){this.modules[t][e]=r,this.isFunction[t][e]=!0}addEccAndInterleave(e){let r=this.version,i=this.errorCorrectionLevel;if(e.length!=t.getNumDataCodewords(r,i))throw RangeError("Invalid argument");let n=t.NUM_ERROR_CORRECTION_BLOCKS[i.ordinal][r],a=t.ECC_CODEWORDS_PER_BLOCK[i.ordinal][r],l=Math.floor(t.getNumRawDataModules(r)/8),o=n-l%n,d=Math.floor(l/n),c=[],u=t.reedSolomonComputeDivisor(a);for(let r=0,i=0;r<n;r++){let s=e.slice(i,i+d-a+(r<o?0:1));i+=s.length;let n=t.reedSolomonComputeRemainder(s,u);r<o&&s.push(0),c.push(s.concat(n))}let h=[];for(let e=0;e<c[0].length;e++)c.forEach((t,r)=>{(e!=d-a||r>=o)&&h.push(t[e])});return s(h.length==l),h}drawCodewords(e){if(e.length!=Math.floor(t.getNumRawDataModules(this.version)/8))throw RangeError("Invalid argument");let r=0;for(let t=this.size-1;t>=1;t-=2){6==t&&(t=5);for(let s=0;s<this.size;s++)for(let n=0;n<2;n++){let a=t-n,l=(t+1&2)==0?this.size-1-s:s;!this.isFunction[l][a]&&r<8*e.length&&(this.modules[l][a]=i(e[r>>>3],7-(7&r)),r++)}}s(r==8*e.length)}applyMask(e){if(e<0||e>7)throw RangeError("Mask value out of range");for(let t=0;t<this.size;t++)for(let r=0;r<this.size;r++){let i;switch(e){case 0:i=(r+t)%2==0;break;case 1:i=t%2==0;break;case 2:i=r%3==0;break;case 3:i=(r+t)%3==0;break;case 4:i=(Math.floor(r/3)+Math.floor(t/2))%2==0;break;case 5:i=r*t%2+r*t%3==0;break;case 6:i=(r*t%2+r*t%3)%2==0;break;case 7:i=((r+t)%2+r*t%3)%2==0;break;default:throw Error("Unreachable")}!this.isFunction[t][r]&&i&&(this.modules[t][r]=!this.modules[t][r])}}getPenaltyScore(){let e=0;for(let r=0;r<this.size;r++){let i=!1,s=0,n=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[r][a]==i?5==++s?e+=t.PENALTY_N1:s>5&&e++:(this.finderPenaltyAddHistory(s,n),i||(e+=this.finderPenaltyCountPatterns(n)*t.PENALTY_N3),i=this.modules[r][a],s=1);e+=this.finderPenaltyTerminateAndCount(i,s,n)*t.PENALTY_N3}for(let r=0;r<this.size;r++){let i=!1,s=0,n=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][r]==i?5==++s?e+=t.PENALTY_N1:s>5&&e++:(this.finderPenaltyAddHistory(s,n),i||(e+=this.finderPenaltyCountPatterns(n)*t.PENALTY_N3),i=this.modules[a][r],s=1);e+=this.finderPenaltyTerminateAndCount(i,s,n)*t.PENALTY_N3}for(let r=0;r<this.size-1;r++)for(let i=0;i<this.size-1;i++){let s=this.modules[r][i];s==this.modules[r][i+1]&&s==this.modules[r+1][i]&&s==this.modules[r+1][i+1]&&(e+=t.PENALTY_N2)}let r=0;for(let e of this.modules)r=e.reduce((e,t)=>e+ +!!t,r);let i=this.size*this.size,n=Math.ceil(Math.abs(20*r-10*i)/i)-1;return s(0<=n&&n<=9),s(0<=(e+=n*t.PENALTY_N4)&&e<=2568888),e}getAlignmentPatternPositions(){if(1==this.version)return[];{let e=Math.floor(this.version/7)+2,t=32==this.version?26:2*Math.ceil((4*this.version+4)/(2*e-2)),r=[6];for(let i=this.size-7;r.length<e;i-=t)r.splice(1,0,i);return r}}static getNumRawDataModules(e){if(e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError("Version number out of range");let r=(16*e+128)*e+64;if(e>=2){let t=Math.floor(e/7)+2;r-=(25*t-10)*t-55,e>=7&&(r-=36)}return s(208<=r&&r<=29648),r}static getNumDataCodewords(e,r){return Math.floor(t.getNumRawDataModules(e)/8)-t.ECC_CODEWORDS_PER_BLOCK[r.ordinal][e]*t.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][e]}static reedSolomonComputeDivisor(e){if(e<1||e>255)throw RangeError("Degree out of range");let r=[];for(let t=0;t<e-1;t++)r.push(0);r.push(1);let i=1;for(let s=0;s<e;s++){for(let e=0;e<r.length;e++)r[e]=t.reedSolomonMultiply(r[e],i),e+1<r.length&&(r[e]^=r[e+1]);i=t.reedSolomonMultiply(i,2)}return r}static reedSolomonComputeRemainder(e,r){let i=r.map(e=>0);for(let s of e){let e=s^i.shift();i.push(0),r.forEach((r,s)=>i[s]^=t.reedSolomonMultiply(r,e))}return i}static reedSolomonMultiply(e,t){if(e>>>8!=0||t>>>8!=0)throw RangeError("Byte out of range");let r=0;for(let i=7;i>=0;i--)r=r<<1^(r>>>7)*285^(t>>>i&1)*e;return s(r>>>8==0),r}finderPenaltyCountPatterns(e){let t=e[1];s(t<=3*this.size);let r=t>0&&e[2]==t&&e[3]==3*t&&e[4]==t&&e[5]==t;return(r&&e[0]>=4*t&&e[6]>=t?1:0)+(r&&e[6]>=4*t&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,r){return e&&(this.finderPenaltyAddHistory(t,r),t=0),t+=this.size,this.finderPenaltyAddHistory(t,r),this.finderPenaltyCountPatterns(r)}finderPenaltyAddHistory(e,t){0==t[0]&&(e+=this.size),t.pop(),t.unshift(e)}};function r(e,t,r){if(t<0||t>31||e>>>t!=0)throw RangeError("Value out of range");for(let i=t-1;i>=0;i--)r.push(e>>>i&1)}function i(e,t){return(e>>>t&1)!=0}function s(e){if(!e)throw Error("Assertion error")}t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;let n=class e{constructor(e,t,r){if(this.mode=e,this.numChars=t,this.bitData=r,t<0)throw RangeError("Invalid argument");this.bitData=r.slice()}static makeBytes(t){let i=[];for(let e of t)r(e,8,i);return new e(e.Mode.BYTE,t.length,i)}static makeNumeric(t){if(!e.isNumeric(t))throw RangeError("String contains non-numeric characters");let i=[];for(let e=0;e<t.length;){let s=Math.min(t.length-e,3);r(parseInt(t.substring(e,e+s),10),3*s+1,i),e+=s}return new e(e.Mode.NUMERIC,t.length,i)}static makeAlphanumeric(t){let i;if(!e.isAlphanumeric(t))throw RangeError("String contains unencodable characters in alphanumeric mode");let s=[];for(i=0;i+2<=t.length;i+=2){let n=45*e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i));r(n+=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i+1)),11,s)}return i<t.length&&r(e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i)),6,s),new e(e.Mode.ALPHANUMERIC,t.length,s)}static makeSegments(t){return""==t?[]:e.isNumeric(t)?[e.makeNumeric(t)]:e.isAlphanumeric(t)?[e.makeAlphanumeric(t)]:[e.makeBytes(e.toUtf8ByteArray(t))]}static makeEci(t){let i=[];if(t<0)throw RangeError("ECI assignment value out of range");if(t<128)r(t,8,i);else if(t<16384)r(2,2,i),r(t,14,i);else if(t<1e6)r(6,3,i),r(t,21,i);else throw RangeError("ECI assignment value out of range");return new e(e.Mode.ECI,0,i)}static isNumeric(t){return e.NUMERIC_REGEX.test(t)}static isAlphanumeric(t){return e.ALPHANUMERIC_REGEX.test(t)}getData(){return this.bitData.slice()}static getTotalBits(e,t){let r=0;for(let i of e){let e=i.mode.numCharCountBits(t);if(i.numChars>=1<<e)return 1/0;r+=4+e+i.bitData.length}return r}static toUtf8ByteArray(e){e=encodeURI(e);let t=[];for(let r=0;r<e.length;r++)"%"!=e.charAt(r)?t.push(e.charCodeAt(r)):(t.push(parseInt(e.substring(r+1,r+3),16)),r+=2);return t}};n.NUMERIC_REGEX=/^[0-9]*$/,n.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,n.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let a=n;e.QrSegment=n})(l||(l={})),s=(i=l||(l={})).QrCode||(i.QrCode={}),(t=class{constructor(e,t){this.ordinal=e,this.formatBits=t}}).LOW=new t(0,1),t.MEDIUM=new t(1,0),t.QUARTILE=new t(2,3),t.HIGH=new t(3,2),s.Ecc=t,a=(n=l||(l={})).QrSegment||(n.QrSegment={}),(r=class{constructor(e,t){this.modeBits=e,this.numBitsCharCount=t}numCharCountBits(e){return this.numBitsCharCount[Math.floor((e+7)/17)]}}).NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),a.Mode=r;var b=l,v={L:b.QrCode.Ecc.LOW,M:b.QrCode.Ecc.MEDIUM,Q:b.QrCode.Ecc.QUARTILE,H:b.QrCode.Ecc.HIGH},y="#FFFFFF",w="#000000";function j(e,t=0){let r=[];return e.forEach(function(e,i){let s=null;e.forEach(function(n,a){if(!n&&null!==s){r.push(`M${s+t} ${i+t}h${a-s}v1H${s+t}z`),s=null;return}if(a===e.length-1){if(!n)return;null===s?r.push(`M${a+t},${i+t} h1v1H${a+t}z`):r.push(`M${s+t},${i+t} h${a+1-s}v1H${s+t}z`);return}n&&null===s&&(s=a)})}),r.join("")}function S(e,t){return e.slice().map((e,r)=>r<t.y||r>=t.y+t.h?e:e.map((e,r)=>(r<t.x||r>=t.x+t.w)&&e))}function k({value:e,level:t,minVersion:r,includeMargin:i,marginSize:s,imageSettings:n,size:a,boostLevel:l}){let o=d.default.useMemo(()=>{let i=(Array.isArray(e)?e:[e]).reduce((e,t)=>
2(e.push(...b.QrSegment.makeSegments(t)),e),[]);return b.QrCode.encodeSegments(i,v[t],r,void 0,void 0,l)},[e,t,r,l]),{cells:c,margin:u,numCells:h,calculatedImageSettings:p}=d.default.useMemo(()=>{let e=o.getModules(),t=null!=s?Math.max(Math.floor(s),0):4*!!i,r=e.length+2*t,l=function(e,t,r,i){if(null==i)return null;let s=e.length+2*r,n=Math.floor(.1*t),a=s/t,l=(i.width||n)*a,o=(i.height||n)*a,d=null==i.x?e.length/2-l/2:i.x*a,c=null==i.y?e.length/2-o/2:i.y*a,u=null==i.opacity?1:i.opacity,h=null;if(i.excavate){let e=Math.floor(d),t=Math.floor(c),r=Math.ceil(l+d-e),i=Math.ceil(o+c-t);h={x:e,y:t,w:r,h:i}}return{x:d,y:c,h:o,w:l,excavation:h,opacity:u,crossOrigin:i.crossOrigin}}(e,a,t,n);return{cells:e,margin:t,numCells:r,calculatedImageSettings:l}},[o,a,n,i,s]);return{qrcode:o,margin:u,cells:c,numCells:h,calculatedImageSettings:p}}var N=function(){try{new Path2D().addPath(new Path2D)}catch(e){return!1}return!0}(),P=d.default.forwardRef(function(e,t){let{value:r,size:i=128,level:s="L",bgColor:n=y,fgColor:a=w,includeMargin:l=!1,minVersion:o=1,boostLevel:c,marginSize:u,imageSettings:h}=e,p=g(e,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:m}=p,f=g(p,["style"]),b=null==h?void 0:h.src,v=d.default.useRef(null),P=d.default.useRef(null),T=d.default.useCallback(e=>{v.current=e,"function"==typeof t?t(e):t&&(t.current=e)},[t]),[C,M]=d.default.useState(!1),{margin:_,cells:A,numCells:E,calculatedImageSettings:L}=k({value:r,level:s,minVersion:o,boostLevel:c,includeMargin:l,marginSize:u,imageSettings:h,size:i});d.default.useEffect(()=>{if(null!=v.current){let e=v.current,t=e.getContext("2d");if(!t)return;let r=A,s=P.current,l=null!=L&&null!==s&&s.complete&&0!==s.naturalHeight&&0!==s.naturalWidth;l&&null!=L.excavation&&(r=S(A,L.excavation));let o=window.devicePixelRatio||1;e.height=e.width=i*o;let d=i/E*o;t.scale(d,d),t.fillStyle=n,t.fillRect(0,0,E,E),t.fillStyle=a,N?t.fill(new Path2D(j(r,_))):A.forEach(function(e,r){e.forEach(function(e,i){e&&t.fillRect(i+_,r+_,1,1)})}),L&&(t.globalAlpha=L.opacity),l&&t.drawImage(s,L.x+_,L.y+_,L.w,L.h)}}),d.default.useEffect(()=>{M(!1)},[b]);let F=x({height:i,width:i},m),R=null;return null!=b&&(R=d.default.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{M(!0)},ref:P,crossOrigin:null==L?void 0:L.crossOrigin})),d.default.createElement(d.default.Fragment,null,d.default.createElement("canvas",x({style:F,height:i,width:i,ref:T,role:"img"},f)),R)});P.displayName="QRCodeCanvas";var T=d.default.forwardRef(function(e,t){let{value:r,size:i=128,level:s="L",bgColor:n=y,fgColor:a=w,includeMargin:l=!1,minVersion:o=1,boostLevel:c,title:u,marginSize:h,imageSettings:p}=e,m=g(e,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:f,cells:b,numCells:v,calculatedImageSettings:N}=k({value:r,level:s,minVersion:o,boostLevel:c,includeMargin:l,marginSize:h,imageSettings:p,size:i}),P=b,T=null;null!=p&&null!=N&&(null!=N.excavation&&(P=S(b,N.excavation)),T=d.default.createElement("image",{href:p.src,height:N.h,width:N.w,x:N.x+f,y:N.y+f,preserveAspectRatio:"none",opacity:N.opacity,crossOrigin:N.crossOrigin}));let C=j(P,f);return d.default.createElement("svg",x({height:i,width:i,viewBox:`0 0 ${v} ${v}`,ref:t,role:"img"},m),!!u&&d.default.createElement("title",null,u),d.default.createElement("path",{fill:n,d:`M0,0 h${v}v${v}H0z`,shapeRendering:"crispEdges"}),d.default.createElement("path",{fill:a,d:C,shapeRendering:"crispEdges"}),T)});T.displayName="QRCodeSVG",e.s(["QRCodeCanvas",0,P,"QRCodeSVG",0,T],360042);var C=e.i(457395),M=e.i(202647),_=e.i(394802),A=e.i(1169);let E={default:{root:"space-y-2",card:"rounded-lg border border-border bg-surface overflow-hidden",head:"w-full flex items-center justify-between px-3 py-2.5 hover:bg-surface-interactive transition-colors",label:"text-xs font-medium text-muted-foreground",chipWrap:"flex items-center gap-2",chip:"flex items-center gap-1.5 px-2 py-1 rounded-md bg-canvas border border-border hover:border-border-strong transition-colors cursor-pointer",chipText:"font-mono text-xs text-secondary-foreground",glyph:"w-3.5 h-3.5",chevron:"w-4 h-4",body:"px-3 pb-3 pt-1 space-y-3",hint:"text-[11px] text-muted-foreground leading-relaxed",warn:"flex items-start gap-2 rounded-md border border-amber-500/20 bg-amber-500/5 px-2.5 py-2",warnGlyph:"w-3.5 h-3.5 text-amber-400 shrink-0 mt-0.5",warnText:"text-[11px] text-amber-200/90 leading-relaxed"},phone:{root:"space-y-[8px]",card:"rounded-[6.27px] bg-[var(--phone-address-row)] overflow-hidden",head:"w-full flex h-[30px] items-center justify-between pl-[10.7px] pr-[5px] transition-colors",label:"text-[8.5px] leading-none text-label-muted",chipWrap:"flex items-center gap-[9px]",chip:"flex h-[18.8px] items-center gap-[5px] rounded-[4.48px] border-[0.67px] border-[var(--phone-address-chip-edge)] bg-[var(--phone-address-chip)] px-[8px] transition-colors cursor-pointer",chipText:"text-[7.61px] font-medium leading-none text-foreground",glyph:"h-[5px] w-[5px]",chevron:"h-[7px] w-[7px]",body:"px-[10px] pb-[10px] pt-[4px] space-y-[8px]",hint:"text-[8.5px] leading-[13px] text-label-muted",warn:"ml-[2px] flex min-h-[26px] items-center gap-[6px] rounded-[5.37px] border-[0.67px] border-[var(--phone-warn-edge)] bg-[var(--phone-warn-p
2ad)] px-[9px] py-[4px]",warnGlyph:"h-[8px] w-[8px] shrink-0 text-[var(--phone-warn-ink)]",warnText:"text-[7.61px] font-medium leading-[10px] text-[var(--phone-warn-ink)]"}};e.s(["ProfileAddressCard",0,function({address:e,defaultExpanded:t=!1,size:r="default"}){let i=(0,c.useTranslations)("wallet"),s=E[r],[n,a]=(0,d.useState)(t),[l,u]=(0,d.useState)(!1),h=e.toBase58(),p=`${h.slice(0,4)}…${h.slice(-4)}`,m=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(h),u(!0),setTimeout(()=>u(!1),1500)}catch{}};return(0,o.jsxs)("div",{className:s.root,children:[(0,o.jsxs)("div",{className:s.card,children:[(0,o.jsxs)("button",{onClick:()=>a(e=>!e),className:s.head,children:[(0,o.jsx)("span",{className:s.label,children:i("depositAddress")}),(0,o.jsxs)("div",{className:s.chipWrap,children:[(0,o.jsxs)("span",{onClick:m,className:s.chip,children:[(0,o.jsx)("span",{className:s.chipText,children:p}),l?(0,o.jsx)(M.Check,{className:`${s.glyph} text-green-400`}):(0,o.jsx)(C.Copy,{className:`${s.glyph} text-muted-foreground`})]}),(0,o.jsx)(A.ChevronDown,{className:`${s.chevron} text-muted-foreground transition-transform ${n?"rotate-180":""}`})]})]}),n&&(0,o.jsxs)("div",{className:s.body,children:[(0,o.jsx)("div",{className:"flex justify-center",children:(0,o.jsx)("div",{className:"rounded-md bg-white p-2",children:(0,o.jsx)(T,{value:h,size:136,level:"M"})})}),(0,o.jsx)("p",{className:s.hint,children:i("depositAddressHint")})]})]}),(0,o.jsxs)("div",{className:s.warn,children:[(0,o.jsx)(_.AlertTriangle,{className:s.warnGlyph}),(0,o.jsx)("p",{className:s.warnText,children:i("solanaNetworkOnly")})]})]})}],87602)},987363,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(860991),s=e.i(942553),n=e.i(799227);e.i(943353);var a=e.i(356534),l=e.i(568801),o=e.i(21859),d=e.i(1169),c=e.i(943494),u=e.i(116082);e.i(875574);var h=e.i(142298),p=e.i(985604),m=e.i(586569),f=e.i(984241),x=e.i(653982);let g={[x.SOL_MINT.toBase58()]:"WSOL",[x.BTC_MINT.toBase58()]:"BTC",[x.ETH_MINT.toBase58()]:"ETH"},b=new Map;async function v(e){let t=b.get(e);if(t)return t;let r=g[e];if(r){let t={symbol:r,logoURI:null};return b.set(e,t),t}try{let t=new AbortController,r=setTimeout(()=>t.abort(),2e3),i=await fetch(`https://datapi.jup.ag/v2/search?query=${e}&tokenExactCaseInsensitive=false`,{signal:t.signal});if(clearTimeout(r),!i.ok)throw Error("search failed");let s=await i.json(),n=Array.isArray(s)?s[0]:null,a=n?.token??n,l={symbol:a?.symbol??null,logoURI:a?.icon??a?.logoURI??null};return b.set(e,l),l}catch{let t={symbol:null,logoURI:null};return b.set(e,t),t}}var y=e.i(596331),w=e.i(689384),j=e.i(797699),S=e.i(936548),k=e.i(719367),N=e.i(299959);e.s(["ProfileTokenRescueList",0,function({profilePda:e,profileIndex:b,walletPubkey:P,isActive:T,onRescueDone:C}){let M=(0,s.useTranslations)("wallet"),_=(0,N.useFormatters)(),{connection:A,sendTransaction:E,signTransaction:L}=(0,h.useUnifiedWallet)(),[F,R]=(0,r.useState)(!1),[D,I]=(0,r.useState)({}),{tokens:U,loading:O,error:B,refetch:z}=function(e,t){let{connection:i}=(0,h.useUnifiedWallet)(),[s,a]=(0,r.useState)([]),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(null),[u,b]=(0,r.useState)(0),y=(0,r.useRef)(!1),w=(0,r.useCallback)(()=>b(e=>e+1),[]);return(0,r.useEffect)(()=>t&&e&&i?(y.current=!1,o(!0),c(null),(async()=>{try{let[t,r]=await Promise.all([i.getParsedTokenAccountsByOwner(e,{programId:p.TOKEN_PROGRAM_ID}),i.getParsedTokenAccountsByOwner(e,{programId:p.TOKEN_2022_PROGRAM_ID})]);if(y.current)return;let s=x.USDC_MINT.toBase58(),l=[],d=(e,t)=>{for(let{account:r}of e){let e=r.data.parsed?.info;if(!e?.mint||!e.tokenAmount||e.mint===s)continue;let i=e.tokenAmount.amount??"0";if("0"===i||""===i)continue;let a=BigInt(i);l.push({mint:new n.PublicKey(e.mint),rawAmount:a,uiAmount:e.tokenAmount.uiAmount??Number(a)/10**(e.tokenAmount.decimals??0),decimals:e.tokenAmount.decimals??0,symbol:g[e.mint]??null,logoURI:null,tokenProgram:t})}};d(t.value,p.TOKEN_PROGRAM_ID),d(r.value,p.TOKEN_2022_PROGRAM_ID),a(l),o(!1),l.forEach(e=>
2{e.symbol||v(e.mint.toBase58()).then(t=>{y.current||a(r=>r.map(r=>r.mint.equals(e.mint)?{...r,symbol:t.symbol,logoURI:t.logoURI}:r))})})}catch(e){if(y.current)return;(0,f.reportWalletError)("profile token load",e),c((0,f.walletActionError)(e,(0,m.message)("wallet","tokensLoadFailed"))),o(!1)}})(),()=>{y.current=!0}):void a([]),[e?.toBase58(),t,i,u]),{tokens:s,loading:l,error:d,refetch:w}}(e,T&&F),$=async(e,t,r,s)=>{if(!A||!L||!E)return void u.toast.error(M("walletNotConnected"));let d=e.toBase58(),c=r??`${d.slice(0,4)}…${d.slice(-4)}`;I(e=>({...e,[d]:!0}));try{let r=!1,h=await (0,w.buildRescueTx)({wallet:P.toBase58(),profileIndex:b,mint:d,amount:t.toString(),tokenProgram:s.toBase58()});if("user_error"===h.kind)return void u.toast.error((0,S.errorFromPayload)({error:h.message}).message);if("ok"===h.kind){let e=Uint8Array.from(atob(h.transaction),e=>e.charCodeAt(0)),t=n.Transaction.from(e),s=await L(t),a=await A.sendRawTransaction(s.serialize());await (0,i.confirmSignatureOrVerifyLanded)(A,a),r=!0}if(!r){let r=new n.Transaction,d=(0,o.getAssociatedTokenAddressSync)(e,P,!1,s);r.add((0,l.createAssociatedTokenAccountIdempotentInstruction)(P,d,P,e,s));let c=new y.PassthroughClient(A);r.add(c.withdrawFromProfileIx({wallet:P,profileIndex:b,mint:e,amount:new a.BN(t.toString()),tokenProgram:s}));let{blockhash:u,lastValidBlockHeight:h}=await A.getLatestBlockhash();r.recentBlockhash=u,r.feePayer=P;let p=await E(r);await (0,i.confirmOrVerifyLanded)(A,{signature:p,blockhash:u,lastValidBlockHeight:h})}(0,j.gtagEvent)("profile_rescue",{mint:d,sponsored:r}),u.toast.success(M("recoveredToken",{label:c})),z(),C?.()}catch(t){let e=t instanceof Error?t.message:"";e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||u.toast.error((0,S.displayClientError)(t))}finally{I(e=>{let t={...e};return delete t[d],t})}};return(0,t.jsxs)("div",{className:"px-6 pb-4",children:[(0,t.jsxs)("button",{onClick:()=>R(e=>!e),className:"w-full flex items-center justify-between py-2 text-xs font-medium text-muted-foreground hover:text-secondary-foreground transition-colors",children:[(0,t.jsx)("span",{children:F&&U.length>0?M("recoverOtherTokensWithCount",{count:String(U.length)}):M("recoverOtherTokens")}),(0,t.jsx)(d.ChevronDown,{className:`w-4 h-4 transition-transform ${F?"rotate-180":""}`})]}),F&&(0,t.jsxs)("div",{className:"mt-2 space-y-1.5",children:[O&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"h-12 rounded-lg bg-surface animate-pulse"}),(0,t.jsx)("div",{className:"h-12 rounded-lg bg-surface animate-pulse"})]}),!O&&B&&(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2",children:[(0,t.jsx)("span",{className:"text-xs text-red-300",children:B}),(0,t.jsx)("button",{onClick:z,className:"text-xs text-red-200 hover:text-red-100 underline",children:M("retry")})]}),!O&&!B&&0===U.length&&(0,t.jsx)("p",{className:"text-xs text-label-muted py-2",children:M("noExtraTokens")}),!O&&!B&&U.map(e=>{var r,i;let s=e.mint.toBase58(),n=D[s],a=e.symbol??`${s.slice(0,4)}…${s.slice(-4)}`;return(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-border bg-surface px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("div",{className:"text-sm text-foreground truncate",children:a}),(0,t.jsx)("div",{className:"text-[11px] font-mono tabular-nums text-label-muted truncate",children:(r=e.uiAmount,i=_.intlTag,0===r?"0":r<1e-4?r.toExponential(2):r<1?(0,k.formatGrouped)(r,i,{maximumFractionDigits:6}):(0,k.formatGrouped)(r,i,{maximumFractionDigits:4}))})]}),(0,t.jsx)("button",{onClick:()=>void $(e.mint,e.rawAmount,e.symbol,e.tokenProgram),disabled:n,className:"h-8 px-3 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:n?(0,t.jsx)(c.Loader2,{className:"w-3.5 h-3.5 animate-spin"}):M("withdraw")})]},s)})]})]})}],987363)},767041,944475,263424,85161,e=>{"use strict";e.s(["ReduceOnlyTicket",()=>I],767041),e.s(["useClosePosition",()=>D],263424);var t=e.i(394390),r=e.i(183023),i=e.i(679278),s=e.i(942553),n=e.i(494286),a=e.i(875574),l=e.i(142298),o=e.i(430232),d=e.i(299959),c=e.i(259048),u=e.i(153517),h=e.i(213076),p=e.i(984457),m=e.i(59392),f=e.i(752717),x=e.i(546642),g=e.i(172581),b=e.i(91525),v=e.i(116082),y=e.i(514049),w=e.i(689384),j=e.i(567978),S=e.i(473344),k=e.i(936548),N=e.i(190459),P=e.i(727322),T=e.i(631193),C=e.i(799227),M=e.i(43690),_=e.i(326702);let A=e=>["sunrise-payouts",e];async function E(e,t){let r=_.SUNRISE_PROGRAM_ID;if(!r)throw Error("Armada is not configured");let i=await (0,_.getSunriseConnection)().getProgramAccounts(r,{commitment:"confirmed",withContext:!0,minContextSlot:t,filters:(0,_.marginAccountFilters)(e)});if(void 0!==t&&i.context.slot<t)throw Error("Payout status precedes the last confirmed read");let s=i.value.map(({pubkey:t,account:i})=>{let s=(0,_.decodeMargin)(i.data);if(!s||s.user!==e||!i.owner.equals(r))throw Error("Invalid Armada margin account");if(!(0,_.getMarginPdaForSeatText)(new C.PublicKey(s.profile),s.seatAsset).equals(t))throw Error("Invalid Armada margin address");return{...s,address:t.toBase58()}});return{wallet:e,slot:i.context.slot,accounts:s}}e.s(["sunrisePayoutsQueryKey",0,A,"useSunrisePayouts",0,function(e){let t=(0,y.useQueryClient)(),r=A(e);return(0,M.useQuery)({queryKey:r,queryFn:()=>E(e,t.getQueryData(r)?.slot),enabled:!!e&&!!_.SUNRISE_PROGRAM_ID,staleTime:1e4,refetchInterval:15e3})}],944475);var L=e.i(722732),F=e.i(670374),R=e.i(26826);
2function D({marketMint:e,livePrices:t,liveMarkPrice:i,onPositionChange:l}){let o=(0,s.useTranslations)("positions"),{publicKey:d}=(0,a.useUnifiedWalletContext)(),c=(0,y.useQueryClient)(),{closePosition:u}=(0,P.useTradeActions)(),{slippageBps:h}=(0,T.useSlippageBps)(),{addPendingPosition:p}=(0,j.usePendingPositions)(),m=d?.toBase58()??null;return(0,r.useCallback)(async(r,s,a)=>{try{let f;if("venue_direct"===r.ownership&&"phoenix"===r.underwriter){let e=await u({ownership:r.ownership,underwriter:r.underwriter,directVenue:r.directVenue,asset:r.asset,entirePosition:100===s,closeBps:Math.round(100*s),slippageBps:h});if(e){v.toast.success(100===s?o("toastPhoenixPositionClosed"):o("toastPhoenixPositionReduced"));let e=["phoenix-direct-positions",m],t=["phoenix-direct-history",m];for(let i of(100===s&&m?(await c.cancelQueries({queryKey:e}),c.setQueryData(e,e=>e?.filter(e=>e.id!==r.id)),(async()=>{for(let i of[1e3,2e3,4e3]){await new Promise(e=>window.setTimeout(e,i));let s=await (0,w.fetchPhoenixDirectPositions)(m,!0);if(c.invalidateQueries({queryKey:t}),!s.some(e=>e.id===r.id))return void c.setQueryData(e,s)}})().catch(e=>{console.warn("Phoenix close reconciliation failed:",e)})):await c.invalidateQueries({queryKey:e}),await c.invalidateQueries({queryKey:t}),[2e3,6e3]))window.setTimeout(()=>{c.invalidateQueries({queryKey:t})},i)}return!!e}try{f=(0,F.getCloseOrderTargetFromLifecycle)(r,{marketMintFallback:e})}catch(e){return v.toast.error((0,k.displayClientError)(e)),!1}let x=(0,R.parseRawValue)(r.sizeUsd),g=(0,R.parseRawValue)(r.collateralUsd),b=(0,R.parseRawValue)(r.markPrice),y=f.marketMint;if("gmtrade"===r.underwriter){let e=(0,L.getGlobalGmTradeRegistry)(),t=e?.getMarketBySymbol(r.asset);
2t&&(y=t.indexTokenMint.toBase58())}let j=t?.[y],P=await u({...f,positionPubkey:r.positionPda,marketMint:y,currentPrice:a??j??(b>0?b:i??0),sizeUsd:x*s/100,collateralUsd:g*s/100,entirePosition:100===s,closeBps:Math.round(100*s),slippageBps:h});return P&&d&&(c.invalidateQueries({queryKey:A(m)}),m&&c.invalidateQueries({queryKey:(0,n.sunriseMarginWalletKey)(m)}),p({id:P,market:(0,S.pendingMarketKey)(y),marketId:y,owner:d,type:100===s?"closing":"reducing",isLong:"long"===r.side,timestamp:Date.now(),status:"pending",positionPda:r.positionPda,asset:r.asset,profileIndex:r.profileIndex??void 0,venue:r.underwriter,sizeUsdAtIntent:x,settledAtSubmit:(0,N.settlesSynchronously)(r.underwriter)}),l?.()),!!P}catch(e){return console.error("Error closing position:",e),v.toast.error((0,k.displayClientError)(e)),!1}},[e,t,i,u,l,d,p,c,h,m,o])}function I({lifecycle:e,symbol:a,orderType:v,marketMint:y,markPrice:w,compact:j,ctaHost:S,actionHost:k,summaryHost:N,onPositionChange:P}){let T=(0,s.useTranslations)("trading"),C=(0,s.useTranslations)("wallet"),M=(0,s.useTranslations)("positions"),_=(0,d.useFormatters)(),{publicKey:A}=(0,l.useUnifiedWallet)(),E="sunrise"===e.underwriter||"7"===e.underwriter,{data:L}=(0,n.useSunriseMargin)(e.wallet,e.profileIndex??0,e.sunriseMarginSeat??null,E&&void 0!==e.sunriseMarginSeat),F=L?.primeBound===!0,U=(0,g.useCloseAmount)(e,0),{sizePercent:O}=U,B=(0,b.useLimitClose)(e,w),z=D({marketMint:y,liveMarkPrice:w,onPositionChange:P}),[$,V]=(0,r.useState)(!1),H="limit"===v,W=H&&!(0,b.canPlaceLimitClose)(e),q="long"===e.side,K=(0,R.parseRawValue)(e.sizeUsd),G=O/100,Y=(0,R.parseRawValue)(e.collateralUsd)*G,X=(0,R.netCapitalForDisplay)(e),Q=(0,R.estimateClosePnl)(e,{execPrice:H&&B.isValidPrice?B.price:w,closeFraction:G}),J=Q?(0,R.getDisplayPnl)(Q,Y,null!==X?X*G:null):null,Z=W?T("reduceOnlyLimitUnavailable"):H?B.missingLabel(O):(0,x.pickMissingLabel)([[O<=0,M("setSize")]]),ee=H?B.submitting:$,et=!!A&&null===Z&&!ee,er=async()=>{if(!A)return void(0,o.promptConnectWallet)();if(et){if(H){await B.submit(O)&&(U.handleSizePercent(0),P?.());return}V(!0);try{await z(e,O,w)&&U.handleSizePercent(0)}finally{V(!1)}}},ei=T(q?"reduceLong":"reduceShort"),es=K*G,en=(0,t.jsx)(h.Button,{"data-ticket-submit":!0,onClick:er,disabled:!!A&&!et,"aria-busy":ee,variant:"outline",className:(0,u.cn)("w-full border-0",j?"h-[45px] rounded-[5px] text-[14px] font-semibold":"h-14 rounded-control text-base font-bold",et||ee||!A?"bg-[var(--confirm-pad)] text-primary hover:brightness-110":"bg-surface-interactive text-muted-foreground cursor-not-allowed"),children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[ee&&(0,t.jsx)(p.Spinner,{className:"size-3.5"}),A?ee?T("submitting"):Z??(0,t.jsxs)(t.Fragment,{children:[ei,(0,t.jsx)("span",{className:j?"tabular-nums":"font-mono tabular-nums",children:j?` - ${_.number(es)}`:` — $${_.number(es)}`})]}):C("connectWallet")]})}),ea=(0,t.jsxs)(t.Fragment,{children:[F&&O<100&&(0,t.jsx)("p",{className:"text-[11px] text-muted-foreground",children:T("reduceOnlyPrimePartialLocked")}),H&&B.isValidPrice&&(0,t.jsx)("p",{className:"text-[11px] text-muted-foreground",children:M(B.movesUp?"limitCloseRisesTo":"limitCloseFallsTo",{percent:O,asset:a,price:_.number(B.price)})})]}),el=(0,t.jsxs)("div",{"data-reduce-summary":!0,className:"flex flex-col pb-2 pt-0.5 text-xs",children:[(0,t.jsx)(x.SummaryRow,{label:T("reduceOnlyEstPnl"),children:(0,t.jsx)("span",{className:(0,u.cn)("font-mono tabular-nums",null!==J&&O>0?(0,c.pnlColor)(J):"text-muted-foreground"),children:null!==J&&O>0?`${J>=0?"+":""}$${_.number(J)}`:"—"})}),O>0&&(0,t.jsx)(f.CloseFeeBreakdown,{lifecycle:e,sizePercent:O,compact:!0})]});return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-md border border-border bg-surface-raised px-3 py-2 text-xs",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:T("reduceOnlyTarget")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:[(0,t.jsx)("span",{className:q?"text-side-long":"text-side-short",children:M(q?"long":"short")})," ","$",_.number(K)]})]}),H&&!W&&(0,t.jsxs)("div",{"data-ticket-field":!0,className:(0,u.cn)("flex h-10 items-center gap-2 rounded-md border bg-surface-raised px-3",B.hasPrice&&!B.isValidPrice?"border-destructive/60":"border-border"),children:[(0,t.jsx)("span",{className:"text-3xs font-semibold uppercase tracking-wider text-muted-foreground",children:T("orderTypeLimit")}),(0,t.jsx)("input",{type:"text",inputMode:"decimal",value:B.priceInput,onChange:e=>B.handlePriceTyped(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:w?_.number(w):"0.00","aria-label":M("limitClosePriceLabel"),"aria-invalid":B.hasPrice&&!B.isValidPrice||void 0,className:"min-w-0 flex-1 bg-transparent font-mono text-[15px] tabular-nums text-foreground focus:outline-none"}),(0,t.jsx)("button",{type:"button",onClick:()=>B.handlePriceTyped(String(w)),className:"rounded bg-surface-interactive px-2 py-0.5 text-3xs font-semibold text-muted-foreground transition-colors hover:text-foreground",children:M("priceRefMark")})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)("div",{"data-ticket-field":!0,className:"flex h-10 items-center rounded-md border border-border bg-surface-raised px-3",children:[(0,t.jsx)("input",{type:"text",inputMode:"decimal",value:U.amountInput,onChange:e=>U.handleAmountTyped(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0","aria-label":M("amountLabel"),className:"min-w-0 flex-1 bg-transparent font-mono text-[15px] tabular-nums text-foreground focus:outline-none"}),U.canToggleUnit?(0,t.jsx)("button",{type:"button",onClick:U.toggleAmountUnit,className:"ml-2 roun
2ded border border-border-strong bg-surface px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground",title:M("switchUnit",{unit:"usd"===U.amountUnit?e.asset:"USDC"}),children:"usd"===U.amountUnit?"USDC":e.asset}):(0,t.jsx)("span",{className:"ml-2 text-xs text-muted-foreground",children:"USDC"})]}),(0,t.jsx)("div",{className:"grid grid-cols-4 gap-1.5",children:[25,50,75,100].map(e=>(0,t.jsxs)("button",{type:"button",onClick:()=>U.handleSizePercent(e),className:(0,u.cn)("h-8 rounded-md border font-mono text-xs tabular-nums transition-colors disabled:opacity-40",O===e?"border-border-strong text-foreground":"border-border text-muted-foreground hover:border-border-strong hover:text-foreground"),children:[e,"%"]},e))})]}),j?ea:k?(0,i.createPortal)((0,t.jsx)(m.TerminalActionSection,{before:ea,children:en}),k):null,j?el:N?(0,i.createPortal)(el,N):null,j&&S?(0,i.createPortal)(en,S):null]})}var U=e.i(440094),O=e.i(1169),B=e.i(943494),z=e.i(268680),$=e.i(924416),V=e.i(554580);class H extends Error{status;code;constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="StrengthApiError"}get needsMoreTrades(){return"StrengthNeedsMoreTrades"===this.code}get rangeNeedsMoreTrades(){return"StrengthRangeNeedsMoreTrades"===this.code}}async function W(e,t){let r=await fetch("https://api.imperial.space/api/v1/trade-strength",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});if(!r.ok){let e=await r.json().catch(()=>null);throw new H(e?.error??`Strength check failed (${r.status})`,r.status,e?.errorCode)}return r.json()}var q=e.i(764324),K=e.i(303404),G=e.i(575146);let Y={1:"tradeStrengthScore1",2:"tradeStrengthScore2",3:"tradeStrengthScore3",4:"tradeStrengthScore4",5:"tradeStrengthScore5"};e.s(["TradeStrength",0,function({asset:e,side:i,action:n,collateralUsd:a,leverage:l,orderType:o,limitPrice:d,className:c,floatingDetails:h=!1}){var p;let m=(0,U.useLocale)(),f=(0,s.useTranslations)("trading"),x=(0,$.useSessionJwt)(),{range:g}=(0,V.useTradeStrengthRange)(),b=(0,V.useStrengthRangeLabel)(g),[v,y]=(0,r.useState)(null),[w,j]=(0,r.useState)(!1),[S,k]=(0,r.useState)(null),[N,P]=(0,r.useState)(!1);if((0,r.useEffect)(()=>{y(null),k(null),P(!1)},[e,i,n,a,l,o,d,g]),!x||!(a>0))return null;let T=async()=>{j(!0),k(null);try{let t=await W({asset:e,side:i,action:n,collateralUsd:a,leverage:l,orderType:o,limitPrice:d,...(0,K.resolveStrengthRange)(g)},x);y(t)}catch(e){e instanceof H&&e.needsMoreTrades?k(f("tradeStrengthNeedsHistory")):e instanceof H&&e.rangeNeedsMoreTrades?k(f("tradeStrengthRangeNeedsHistory")):(console.error("[strength] derive",e),k(e instanceof Error?e.message:f("tradeStrengthFailed")))}finally{j(!1)}};if(!v)return(0,t.jsxs)("div",{className:(0,u.cn)("flex flex-col items-center gap-1",c),children:[(0,t.jsxs)("button",{type:"button",onClick:T,disabled:w,className:"flex items-center gap-1.5 text-2xs text-muted-foreground transition-colors hover:text-foreground disabled:opacity-60",children:[w&&(0,t.jsx)(B.Lo
2ader2,{className:"h-3 w-3 animate-spin"}),(0,t.jsx)("span",{className:"underline decoration-dotted decoration-leader-strong underline-offset-[3px]",children:w?f("tradeStrengthReading"):f("tradeStrengthAction")})]}),S&&(0,t.jsx)("div",{className:"text-center text-2xs text-side-short",children:S})]});let C=(0,q.resolveTokens)(v.tooltip,v.tokens,m),M=(0,q.resolveAll)(v.detail,v.tokens,m),_=!v.basis.emphasisedAsset||0===v.basis.priceBars,A=(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-surface p-3",children:[(0,t.jsx)("div",{className:"flex flex-col gap-2",children:M.map((e,r)=>(0,t.jsx)("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:e},r))}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 border-t border-border-subtle pt-2 text-[10px] text-muted-foreground/70",children:[(0,t.jsxs)("span",{children:[v.basis.tradesOverall," closed trades"]}),"all"!==g.preset&&(0,t.jsx)("span",{children:b}),(0,t.jsxs)("span",{children:[v.basis.tradesThisAsset," on ",e]}),v.basis.priceBars>0&&(0,t.jsxs)("span",{children:[v.basis.priceBars," hourly bars"]})]}),_&&(0,t.jsx)("p",{className:"text-[10px] leading-relaxed text-amber-400/80",children:"Based on limited data — treat this as a weak signal."}),(0,t.jsx)("p",{className:"text-[10px] text-muted-foreground/60",children:"An analysis of fit against your own history. Not financial advice."})]}),E=(0,t.jsxs)("button",{type:"button",onClick:h?void 0:()=>P(e=>!e),className:"flex w-full items-center gap-2 text-left","aria-expanded":N,children:[(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:"Strength"}),(0,t.jsx)("span",{className:"flex flex-1 gap-0.5",role:"img","aria-label":`${v.score} out of 5`,children:Array.from({length:5},(e,r)=>{var i;return(0,t.jsx)("span",{className:(0,u.cn)("h-1.5 flex-1 rounded-sm transition-colors",r<v.score?(i=v.score)>=4?"bg-emerald-400":3===i?"bg-amber-400":"bg-red-400":"bg-surface-interactive")},r)})}),(0,t.jsx)("span",{className:(0,u.cn)("text-[11px] tabular-nums",(p=v.score)>=4?"text-emerald-400":3===p?"text-amber-400":"text-red-400"),children:v.score in Y?f(Y[v.score]):v.score}),(0,t.jsx)(O.ChevronDown,{className:(0,u.cn)("h-3 w-3 text-muted-foreground transition-transform",N&&"rotate-180")})]}),L=(0,t.jsxs)("div",{className:(0,u.cn)("flex flex-col gap-2",c),children:[(0,t.jsx)(z.TooltipProvider,{delayDuration:100,children:(0,t.jsxs)(z.Tooltip,{children:[(0,t.jsx)(z.TooltipTrigger,{asChild:!0,children:h?(0,t.jsx)(G.PopoverTrigger,{asChild:!0,children:E}):E}),(0,t.jsx)(z.TooltipContent,{side:"top",className:"max-w-[16rem]",children:C})]})}),h?(0,t.jsx)(G.PopoverContent,{side:"top",align:"end",className:"max-h-[min(360px,60vh)] overflow-y-auto p-0",children:A}):N?A:null]});return h?(0,t.jsx)(G.Popover,{open:N,onOpenChange:P,children:L}):L}],85161)},711104,e=>{e.v({after:"terminal-action-section-module__OmDQ9W__after",before:"terminal-action-section-module__OmDQ9W__before",button:"terminal-action-section-module__OmDQ9W__button",content:"terminal-action-section-module__OmDQ9W__content",section:"terminal-action-section-module__OmDQ9W__section"})},831519,71917,591872,588018,492728,114787,682331,271434,59392,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(457058),s=e.i(1169),n=e.i(92065),a=e.i(931524),l=e.i(884629),o=e.i(942553),d=e.i(623075),c=e.i(213076),u=e.i(575146),h=e.i(685576),p=e.i(619966),m=e.i(894771);e.i(654249);var f=e.i(972015),x=e.i(190459);function g(e){return x.VENUE_UNDERWRITER_BYTE[e]}function b(e,t){return e.minLoanBpsVenue?.[g(t)]||(e.minLoanBps??0)}function v(e){return"phoenix"===e?50:null}function y(e,t,r){return e&&r&&Number.isInteger(r.fee1e6)&&!(r.fee1e6<0)&&!(r.fee1e6>1e6)&&Number.isInteger(r.gminBps)&&!(r.gminBps<=0)&&!(r.gminBps>=1e4)&&Number.isFinite(r.maxLoanUsd)&&!(r.maxLoanUsd<=0)&&Number.isSafeInteger(r.maxMultiplierMicro)&&!(r.maxMultiplierMicro<=1e6)&&e.perMarket.some(e=>e.symbol===t&&e.enabled&&e.mint===r.lendingMarketMint)?{...e,vaultBalanceUsd:Math.min(e.vaultBalanceUsd,r.maxLoanUsd),maxMultiplierMicro:Math.min(e.maxMultiplierMicro,r.maxMultiplierMicro)}:null}function w(e,t,r){var i,s,n,a,l;let o,d,c=(i=e.utilizationBps,s=e.baseRateBps,n=e.kinkUtilBps,a=e.slope1Bps,l=e.slope2Bps,o=Math.min(Math.max(Math.floor(i),0),1e4),0===(d=Math.min(Math.max(Math.floor(n),0),1e4))?s+a+Math.floor(o*l/1e4):o<=d?s+Math.floor(o*a/d):s+a+Math.floor((o-d)*l/(1e4-d))),u="long"===r?t.skewLongBps:t.skewShortBps;return Math.max(0,Math.floor(c*t.riskMultBps/1e4)+u)}function j(e,t,r,i=0){let s=e.maxMultiplierMicro/1e6,n=e.poolValueUsd*e.maxPositionLoanBps/1e4,a=Math.max(0,i);return Math.min(Math.max(0,(s>1?r*(s-1):0)-a),Math.max(0,n-a),Math.max(0,t.debtCeilingUsd-t.borrowedUsd),e.vaultBalanceUsd)}function S(e){let t,r,{venue:i,venueCap:s,gMinBps:n,collateralUsd:a,targetEffectiveLeverage:l,poolState:o,market:d,side:c}=e;if(!(a>0)||!isFinite(a)||!(l>1)||!isFinite(l)||!(s>=1)||!isFinite(s))return null;let u=o.perMarket.find(e=>e.symbol===d);
2if(!u||!u.enabled||"phoenix"===i&&!u.phoenixMarketMint)return null;let h=u.maxLeverageMicro??0;if(h>0&&l>h/1e6*.9980009979999999)return null;let p=Math.min(s,1/(n/1e4+1/l));if(l>s)t=s,r="reach";else{r="safer-liq";let e=o.maxMultiplierMicro/1e6,i=Math.min(Math.max(2,e>0?l/e:l),p);t=i+(p-i)*(o.kinkUtilBps>0?Math.min(Math.max(o.utilizationBps/o.kinkUtilBps,0),1):1)}if(!(t>=1)||t>=l)return null;let m=l/t,f=o.maxMultiplierMicro/1e6;if(f>0&&m>f*(1+1e-9))return null;let x=a*(m-1);if(!(x>0))return null;let g=a*l*b(u,i)/1e4;if(x<g){let e=1+g/a;if(f>0&&e>f*(1+1e-9))return null;let r=l/e;if(!(r>=1))return null;x=g,t=r}if("safer-liq"===r&&x>200*o.poolValueUsd/1e4||x>o.poolValueUsd*o.maxPositionLoanBps/1e4||u.borrowedUsd+x>u.debtCeilingUsd||x>o.vaultBalanceUsd)return null;let v=w(o,u,c),y=x*v/1e4;return{venueLeverage:t,loanAmountUsd:x,ourRateBps:v,loanCostUsdPerYear:y,mode:r}}function k(e,t,r){let i=r.loanCostUsdPerYear*t/8760;return{...e,loanCost:i,total:e.total+i}}e.s(["armadaPrimePool",0,y,"computeLoanSplit",0,S,"foldLoanIntoCost",0,k,"liveBucketRateBps",0,w,"loanAwareMaxLeverage",0,function(e,t,r,i,s){if(!t||!(e>=1)||!isFinite(e))return null;let n=t.perMarket.find(e=>e.symbol===r);if(!n||!n.enabled)return null;let a=n.maxLeverageMicro??0,l=t.maxMultiplierMicro/1e6,o=Math.min(a>0?a/1e6*.998:1/0,l>0?e*l:1/0);if(null!=i&&i>0&&isFinite(i)){let r=j(t,n,i);null!=s&&isFinite(s)&&(r=Math.min(r,Math.max(0,s))),o=Math.min(o,(1+r/i)*e)}return isFinite(o)&&o>e?o:null},"loanSlTriggerPriceUsd",0,function(e){let{isLong:t,entryPrice:r,ownedCollateralUsd:i,notionalUsd:s,premiumBps:n}=e;if(!(r>0)||!isFinite(r)||!(s>0)||!isFinite(s)||!(i>0)||!isFinite(i))return null;let a=Math.min(i/s,1),l=n/1e4;return t?r*(1-a)*(1+l):r*(1+a)*(1-l)},"loanVenueGminBps",0,v,"maxLoanForMarket",0,j,"minLoanBpsFor",0,b,"premiumBpsFor",0,function(e,t){return e.premiumBpsVenue?.[g(t)]||e.premiumBps}],71917);var N=e.i(599059);function P(e){return N.VENUE_LABELS[e]}let T=[];function C(e){return T.includes(e)}let M="Excluded by your profile";function _(e,t){let r=isFinite(e),i=isFinite(t);return r&&i?e-t:r?-1:+!!i}function A(e){let{asset:t,side:r,notional:i,desiredLeverage:s,holdHours:n,subaccountDefaultVenue:a,stickyVenue:l,currentVenue:o,capabilities:d,liquidity:c}=e,u=new Set(e.excludedVenues??[]),h=e.venueLock&&e.venueLock.length>0?new Set(e.venueLock):null,p=h?null:e.poolState??null,m=(n,a)=>{if(!p)return null;if("armada"===n.venue){if(e.stickyVenue||!n.armadaPrime)return null;let t=Math.round(i/s*1e6),r=Math.round(1e6*i);if(t<=Math.ceil(r*n.armadaPrime.gminBps/1e4)+Math.floor(r*n.armadaPrime.fee1e6/1e6))return null}let l="armada"===n.venue?y(p,t,n.armadaPrime):p;if(!l)return null;let o="armada"===n.venue?n.armadaPrime?.gminBps??null:v(n.venue);return null===o?null:S({venue:n.venue,venueCap:n.maxLeverage,gMinBps:o,collateralUsd:i/s,targetEffectiveLeverage:a,poolState:l,market:t,side:r})},x=(e,t)=>{let s=(0,f.computeCost)(e,c?.[e.venue],r,i,n),a=m(e,t);if(!a)return{breakdown:s};let l=e.borrowHourlyPctBySide?"long"===r?e.borrowHourlyPctBySide.long:e.borrowHourlyPctBySide.short:e.borrowHourlyPct??0;return{breakdown:k(s,n,a),loanSplit:{loanAmountUsd:a.loanAmountUsd,venueLeverage:a.venueLeverage,ourRateBps:a.ourRateBps,mode:a.mode,venueBorrowHourlyPct:Math.max(0,l)}}},g=e=>e.maxLeverage>=s||m(e,s)?.mode==="reach",b=d.filter(e=>e.asset===t&&e.supported).map(e=>{let{breakdown:t,loanSplit:r}=x(e,s),n=u.has(e.venue)?M:e.maxLeverage<s&&r?.mode!=="reach"?`Leverage cap ${e.maxLeverage}x < ${s}x`:t.total===1/0?`Insufficient liquidity at $${i.toFixed(0)}`:void 0;return{venue:e.venue,expectedCostUsd:t.total,costBreakdown:t,maxLeverage:e.maxLeverage,filteredReason:n,loanSplit:r}}).sort((e,t)=>_(e.expectedCostUsd,t.expectedCostUsd));if(l){let r=d.find(e=>e.asset===t&&e.venue===l);if(r?.supported){let i=s>r.maxLeverage&&!g(r),{breakdown:n,loanSplit:a}=x(r,i?r.maxLeverage:s),o="orders"===e.stickySource?"Resting orders":"Open position",d=u.has(l)?`${o} on ${t} routes to ${P(l)}. (overrides exclusion)`:`${o} on ${t} routes to ${P(l)}.`;return{venue:l,reason:d,maxLeverage:r.maxLeverage,expectedCostUsd:n.total,costBreakdown:n,clamped:i,clampedMaxLeverage:i?r.maxLeverage:void 0,candidates:b,loanSplit:a}}}if(h){let r=d.filter(e=>e.asset===t&&e.supported&&h.has(e.venue));if(0===r.length)return null;let i=b.filter(e=>h.has(e.venue)).map(e=>e.filteredReason===M?{...e,filteredReason:void 0}:e),n=r.map(e=>({cap:e,...x(e,s)})).sort((e,t)=>
2_(e.breakdown.total,t.breakdown.total)),a=n.find(e=>g(e.cap)),l=n.find(t=>t.cap.venue===e.manualVenue&&g(t.cap)&&Number.isFinite(t.breakdown.total)),o=l??a??n[0],c=!l&&!a,{breakdown:u,loanSplit:p}=c?x(o.cap,o.cap.maxLeverage):o;return{venue:o.cap.venue,reason:l?`You picked ${P(l.cap.venue)}.`:c?`Unified margin routes to ${P(o.cap.venue)} — clamped to its ${o.cap.maxLeverage}x cap.`:`Unified margin routes to ${P(o.cap.venue)}.`,maxLeverage:o.cap.maxLeverage,expectedCostUsd:u.total,costBreakdown:u,clamped:c,clampedMaxLeverage:c?o.cap.maxLeverage:void 0,venueLocked:!0,candidates:i,loanSplit:p}}if(e.manualVenue){let t=b.find(t=>t.venue===e.manualVenue&&!t.filteredReason&&isFinite(t.expectedCostUsd));if(t)return{venue:t.venue,reason:`You picked ${P(t.venue)}.`,maxLeverage:t.maxLeverage,expectedCostUsd:t.expectedCostUsd,costBreakdown:t.costBreakdown,clamped:!1,candidates:b,loanSplit:t.loanSplit}}if(a&&C(a)){let e=b.find(e=>e.venue===a&&!e.filteredReason&&isFinite(e.expectedCostUsd));if(e)return{venue:e.venue,reason:"Your default venue for this subaccount.",maxLeverage:e.maxLeverage,expectedCostUsd:e.expectedCostUsd,costBreakdown:e.costBreakdown,clamped:!1,candidates:b,loanSplit:e.loanSplit}}let w=d.filter(e=>e.asset===t&&e.supported),j=w.filter(e=>!u.has(e.venue)&&!C(e.venue));if(0===w.length)return null;if(0===j.length){let e=w.filter(e=>!u.has(e.venue)),r=(e.length>0?e:w).map(e=>({cap:e,...x(e,s)})).sort((e,t)=>_(e.breakdown.total,t.breakdown.total))[0],{cap:i}=r,n=s>i.maxLeverage&&!g(i),{breakdown:a,loanSplit:l}=n?x(i,i.maxLeverage):r,o=C(i.venue)?"(beta)":"(exclusion overridden)";return{venue:i.venue,reason:`${P(i.venue)}: only venue supporting ${t} ${o}.`,maxLeverage:i.maxLeverage,expectedCostUsd:a.total,costBreakdown:a,clamped:n,clampedMaxLeverage:n?i.maxLeverage:void 0,exclusionOverridden:u.has(i.venue),candidates:b,loanSplit:l}}let N=j.filter(e=>g(e));if(0===N.length){let e=w.filter(e=>g(e)&&(C(e.venue)||u.has(e.venue))).map(e=>({cap:e,...x(e,s)}));if(e.length>0){let r=e.filter(e=>!u.has(e.cap.venue)),i=r.length>0?r:e;i.sort((e,t)=>_(e.breakdown.total,t.breakdown.total));let{cap:n,breakdown:a,loanSplit:l}=i[0],o=b.find(e=>e.venue===n.venue);o&&(o.filteredReason=void 0);let d=u.has(n.venue)?"(exclusion overridden)":"(beta)",c=u.has(n.venue)?j.reduce((e,t)=>Math.max(e,t.maxLeverage),0):0;return{venue:n.venue,reason:`${P(n.venue)}: only venue supporting ${s}x for ${t} ${d}.`,maxLeverage:n.maxLeverage,expectedCostUsd:a.total,costBreakdown:a,clamped:!1,exclusionOverridden:u.has(n.venue),leverDownToLeverage:c>0?c:void 0,candidates:b,loanSplit:l}}let r=j.reduce((e,t)=>t.maxLeverage>e.maxLeverage?t:e),{breakdown:i,loanSplit:n}=x(r,r.maxLeverage);return{venue:r.venue,reason:`Clamped to ${r.maxLeverage}x — highest available for ${t}.`,maxLeverage:r.maxLeverage,expectedCostUsd:i.total,costBreakdown:i,clamped:!0,clampedMaxLeverage:r.maxLeverage,candidates:b,loanSplit:n}}if(a){let e=N.find(e=>e.venue===a);if(e){let{breakdown:t,loanSplit:r}=x(e,s);return{venue:e.venue,reason:"Your default venue for this subaccount.",maxLeverage:e.maxLeverage,expectedCostUsd:t.total,costBreakdown:t,clamped:!1,candidates:b,loanSplit:r}}}let T=N.map(e=>({cap:e,...x(e,s)})).sort((e,t)=>_(e.breakdown.total,t.breakdown.total)),A=T[0],E=!1;if(o&&A.cap.venue!==o){let e=T.find(e=>e.cap.venue===o);e&&A.breakdown.total>=.9*e.breakdown.total&&(A=e,E=!0)}let L=T.find(e=>e.cap.venue!==A.cap.venue),F=E?`Holding ${P(A.cap.venue)} — no venue is decisively cheaper right now.`:function(e){let{asset:t,desiredLeverage:r,subaccountDefaultVenue:i,defaultVenueAvailableForAsset:s,winner:n,runnerup:a}=e;if(i)return s?`Auto-routed — your default venue ${P(i)} doesn't support ${t} at ${r}x.`:`Auto-routed — your default venue ${P(i)} doesn't support ${t}.`;if(!a)return`${P(n.cap.venue)}: only venue supporting ${r}x for ${t}.`;let l=n.breakdown.openFee+n.breakdown.closeFee,o=a.breakdown.openFee+a.breakdown.closeFee,d=n.breakdown.openSlip+n.breakdown.closeSlip;return Math.abs(o-l)>=Math.abs(a.breakdown.openSlip+a.breakdown.closeSlip-d)?`${P(n.cap.venue)} has the lowest round-trip fees for your size.`:`${P(n.cap.venue)} offers tighter pricing — less slippage at this size.`}({asset:t,desiredLeverage:s,subaccountDefaultVenue:a??null,defaultVenueAvailableForAsset:null!=a&&j.some(e=>e.venue===a),winner:A,runnerup:L,notional:i});return{venue:A.cap.venue,reason:F,maxLeverage:A.cap.maxLeverage,expectedCostUsd:A.breakdown.total,costBreakdown:A.breakdown,clamped:!1,candidates:b,loanSplit:A.loanSplit}}e.s(["computeRoute",0,function(e){let t=A(e);if(!e.lighterOpenBlocked||t?.venue!=="armada"||e.stickyVenue||e.excludedVenues?.includes("phoenix")||e.venueLock?.length&&!e.venueLock.includes("phoenix"))return t;let r=A({...e,capabilities:e.capabilities.filter(e=>"phoenix"===e.venue),manualVenue:"phoenix",subaccountDefaultVenue:null,currentVenue:null});if(!r||r.clamped||!Number.isFinite(r.expectedCostUsd))return t;let i="account_data_unavailable"===e.lighterOpenBlockedReason?"Armada is temporarily unavailable":"risk_limit"===e.lighterOpenBlockedReason?"Trade exceeds Armada’s market r
2isk limit":"Insufficient available capacity on Armada";return{...r,reason:`Auto-routed to Phoenix — ${i}.`,availabilityNotice:`${i}. This order will use Phoenix.`,candidates:t.candidates.map(e=>"armada"===e.venue?{...e,filteredReason:i}:e)}},"isBetaVenue",0,C],591872);var E=e.i(406470),L=e.i(299959);e.s(["VenueInlineSelector",0,function({activeUnderwriter:e,resolvedVenue:f,routedVenue:x,supportedVenues:g,excludedVenues:b,manualVenue:v,hasStickyPosition:y,lockedReason:w=null,allowedVenues:j=null,referenceHoldHours:S,routingNotional:k,sizeNum:P,perVenueMaxLeverage:T,onManualVenue:M,onManageVenues:_,compact:A=!1,desktopOrderSettings:F}){let R=(0,o.useTranslations)("trading"),D=(0,o.useTranslations)("common"),I=(0,L.useFormatters)(),U=(0,p.useIsMobile)(),O=!U&&!A,[B,z]=(0,r.useState)(!1),$=(0,r.useRef)(null),V=(0,r.useRef)(!0),[H,W]=(0,r.useState)(null),[q,K]=(0,r.useState)(v),[G,Y]=(0,r.useState)("manual"),X=null!==j||(0,m.isAutoUnderwriter)(e),Q=y||null!==j&&j.length<=1,J=e=>null===j&&b.includes(e),Z=e=>Q||null!==j&&!j.includes(e),ee=e=>x?.candidates.find(t=>t.venue===e)??null,et=(x?.candidates??[]).filter(e=>!e.filteredReason&&Number.isFinite(e.expectedCostUsd)),er=et.find(e=>!C(e.venue))?.venue,ei=N.VENUE_ICON_MAP[f],es=g.includes("armada"),en=!Q&&X&&(null===q||g.includes(q)&&!Z(q)&&!J(q)),ea=q===v||en,el=()=>{V.current=!1,z(!1),_()},eo=e=>{if(O&&!g.includes(e)||Z(e))return;let t=J(e);!X||t?el():O?K(e):(M(e===f?null:e),z(!1))},ed=(0,t.jsxs)("span",{"data-venue-badge":O?f:void 0,className:`flex min-w-0 items-center transition-colors group-hover:border-border-strong ${A?"h-[26px] gap-[3px] rounded-control border border-foreground
2/10 bg-foreground/8 px-[11px]":"h-7 gap-1.5 rounded-control border border-border bg-surface-raised px-2.5"}`,children:[Q?(0,t.jsx)(n.Lock,{className:"w-3 h-3 text-label-muted shrink-0"}):ei&&(0,t.jsx)(i.default,{src:ei.src,alt:ei.alt,width:A?12:14,height:A?12:14,className:"rounded-full shrink-0"}),(0,t.jsx)("span",{className:`truncate font-medium text-foreground ${A?"text-[14px]":"text-xs"}`,children:N.VENUE_LABELS[f]}),(0,t.jsx)(s.ChevronDown,{"data-venue-badge-chevron":O||void 0,className:`shrink-0 text-label-muted ${A?"h-2 w-2":"h-3 w-3"}`})]}),ec=`group flex min-w-0 items-center ${A?"h-11":"h-9"}`,eu="armada"===f,eh=`${R("venue")}: ${N.VENUE_LABELS[f]}`,ep=eu?(0,t.jsx)(i.default,{src:"/armada-wordmark.svg",alt:N.VENUE_LABELS.armada,width:235,height:26,unoptimized:O,"data-venue-wordmark":O?"desktop":void 0,className:`h-auto shrink-0 drop-shadow-[0_0_10px_rgba(255,165,82,0.45)] transition-[filter] group-hover:brightness-110 ${O?"w-[74px]":"w-[100px]"}`}):ed,em=(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"mb-1.5 text-[10px] text-muted-foreground",children:R("venue")}),(Q||null!==w)&&(0,t.jsx)("div",{className:"mb-2 text-[11px] text-label-muted",children:y?R("venueLockedByPosition",{venue:N.VENUE_LABELS[f]}):w}),(0,t.jsxs)("div",{className:"space-y-0.5",children:[X&&!Q&&(0,t.jsxs)("button",{type:"button","aria-pressed":O?null===q:void 0,onClick:()=>{O?K(null):(M(null),z(!1))},className:`w-full flex items-center justify-between gap-3 rounded-chip px-2 py-1.5 text-left transition-colors ${(O?q:v)===null?"bg-surface-raised text-secondary-foreground":"text-muted-foreground hover:bg-surface-interactive"}`,children:[(0,t.jsx)("span",{className:"text-[11px] font-medium",children:R("autoRoute")}),(O?q:v)===null&&(0,t.jsx)("span",{className:"text-[9px] text-emerald-400 shrink-0",children:R("stateOn")})]}),g.filter(e=>!O||!es||"manual"===G||"armada"===e).map(e=>{var r,n,a;let l,o,d,c,u,h,p=J(e),m=e===f,x=O?e===q:m,g=!p&&er===e,b=C(e),v=N.VENUE_LABELS[e],y=N.VENUE_ICON_MAP[e],w=H===e,j=(l=ee(e))&&!l.filteredReason&&Number.isFinite(l.expectedCostUsd)?l.expectedCostUsd:null,M=(r=T(e),n=I.intlTag,null===r||!Number.isFinite(r)||r<=0?null:`${(0,E.formatFixed)(r,+!Number.isInteger(r),n)}x`),_=ee(e),A=_?.costBreakdown;return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:`flex items-center gap-1 rounded-chip transition-colors ${x?"bg-surface-raised":"hover:bg-surface-interactive"}`,children:[(0,t.jsxs)("button",{type:"button",onClick:()=>eo(e),disabled:Z(e),"aria-pressed":O?x:void 0,title:m?R("routingHere"):p?R("venueExcluded"):R("routeViaVenue",{venue:v}),className:`min-w-0 flex-1 flex items-center justify-between gap-3 rounded-chip px-1 py-1.5 text-left disabled:cursor-default ${x?"text-secondary-foreground":"text-muted-foreground"}`,children:[(0,t.jsxs)("div",{className:"min-w-0 flex items-center gap-1.5",children:["armada"===e?(0,t.jsx)("span",{className:`relative shrink-0 ${p?"opacity-50 after:absolute after:inset-x-0 after:top-1/2 after:h-px after:bg-current":""}`,children:(0,t.jsx)(i.default,{src:"/armada-wordmark.svg",alt:v,width:235,height:26,className:"h-auto w-[84px] drop-shadow-[0_0_10px_rgba(255,165,82,0.45)]"})}):(0,t.jsxs)(t.Fragment,{children:[y&&(0,t.jsx)(i.default,{src:y.src,alt:y.alt,width:12,height:12,className:`rounded-full shrink-0 ${p?"opacity-50":""}`}),(0,t.jsx)("span",{className:`text-[11px] font-medium truncate ${p?"line-through":""}`,children:v})]}),M&&(0,t.jsx)("span",{className:"text-[10px] text-label-muted font-mono tabular-nums shrink-0",children:M}),g&&(0,t.jsx)("span",{className:"text-[9px] text-emerald-400 shrink-0",children:R("badgeBest")}),b&&(0,t.jsx)("span",{className:"text-[9px] text-amber-400 border border-amber-500/40 rounded-chip px-1 shrink-0",children:R("badgeBeta")})]}),(0,t.jsx)("span",{className:`text-[11px] font-mono tabular-nums ${x?"text-foreground":"text-muted-foreground"}`,children:P>0?(a=I.intlTag,null!==j&&Number.isFinite(j)?`$${(0,E.formatFixed)(j,2,a)}`:"-"):""})]}),A&&(0,t.jsx)("button",{type:"button",onClick:()=>W(w?null:e),"aria-label":w?R("hideFeeBreakdown"):R("showFeeBreakdown"),className:"shrink-0 px-1.5 py-1.5 rounded-control hover:bg-surface-interactive transition-colors",children:(0,t.jsx)(s.ChevronDown,{className:`w-3 h-3 text-muted-foreground transition-transform ${w?"rotate-180":""}`})})]}),_?.filteredReason&&(0,t.jsx)("div",{className:"px-1 pb-1.5 text-[10px] text-label-muted",children:_.filteredReason}),w&&A&&(o=e=>k>0?e/k*1e4:0,d=e=>`$${I.fixed(e,4)}`,c=e=>`${I.fixed(e,2)} bps`,h=[{key:"openFee",label:R("breakdownOpenFee"),rate:c(o(A.openFee)),usd:A.openFee},{key:"closeFee",label:R("closeFee"),rate:c(o(A.closeFee)),usd:A.closeFee},{key:"entrySlip",label:R("entrySlip"),rate:c(o(A.openSlip)),usd:A.openSlip},{key:"exitSlip",label:R("exitSlip"),rate:c(o(A.closeSlip)),usd:A.closeSlip},{key:"borrow",label:R("borrowOverHold",{hours:`${S}h`}),rate:k>0&&S>0?(u=100*A.borrow/(k*S),`${I.fixed(u,4)}%/hr`):"",usd:A.borrow},...void 0!==A.loanCost&&A.loanCost>0?[{key:"imperialLoan",label:R("imperialLoanOverHold",{hours:`${S}h`}),rate:"",usd:A.loanCost}]:[]],(0,t.jsxs)("div",{className:"ml-5 mr-1 mb-1 mt-0.5 border-l border-border pl-2.5 space-y-0.5",children:[h.map(e=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 text-[10px] tabular-nums",children:[(0,t.jsx)("span",{className:"text-label-muted truncate",children:e.label}),(0,t.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[e.rate&&(0,t.jsx)("span",{className:"text-muted-foreground",children:e.rate}),(0,t.jsx)("span",{className:"font-mono tabular-nums text-secondary-foreground w-14 text-right",children:d(e.usd)})]})]},e.key)),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 text-[10px] tabular-nums pt-1 mt-0.5 border-t border-border",children:[(0,t.jsx)("span",{className:"text-muted-foreground font-medium",children:R("total")}),(0,t.jsx)("span",{className:"font-mono tabular-nums text-foreground w-14 text-right",children:d(A.total)})]})]}))]},e)})]}),(0,t.jsxs)("button",{type:"button",onClick:el,className:"mt-2 w-full flex items-center gap-1.5 px-2 py-1.5 rounded-chip text-[11px] text-muted-foreground hover:text-foreground hover:bg-surface-interactive transition-colors border-t border-border pt-2",children:[(0,t.jsx)(a.Settings,{className:"w-3 h-3 shrink-0"}),R("manageAllowedVenues")]})]});return U?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button","aria-label":eh,className:ec,onClick:()=>z(!0),children:ep}),(0,t.jsx)(h.Sheet,{open:B,onOpenChange:z,children:(0,t.jsxs)(h.SheetContent,{side:"bottom",className:"bg-canvas border-t border-border rounded-t-xl px-4 pb-8 pt-4 text-foreground",children:[(0,t.jsx)(h.SheetTitle,{className:"text-sm font-medium text-secondary-foreground mb-3",children:R("venue")}),em]})})]}):A?(0,t.jsxs)(u.Popover,{open:B,onOpenChange:z,children:[(0,t.jsx)(u.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button","aria-label":eh,className:ec,children:ep})}),(0,t.jsx)(u.PopoverContent,{align:"end",sideOffset:4,className:"w-[340px] p-3 text-xs",children:em})]}):(0,t.jsxs)(d.Dialog,{open:B,onOpenChange:e=>{e&&(V.current=!0,K(v),Y("armada"===f&&es?"armada":"manual"),W(null)),z(e)},children:[(0,t.jsx)(d.DialogTrigger,{asChild:!0,children:(0,t.jsxs)("button",{ref:$,type:"button","aria-label":eh,"data-venue-trigger":"desktop",className:"group flex h-7 shrink-0 items-center gap-1.5 rounded-[5px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[ep,(0,t.jsx)("span",{"data-venue-settings-icon":!0,className:"flex size-7 shrink-0 items-center justify-center",children:(0,t.jsx)(l.SlidersHorizontal,{"aria-hidden":"true",className:"size-4 shrink-0 text-secondary-foreground"})})]})}),(0,t.jsxs)(d.DialogContent,{onCloseAutoFocus:e=>{e.preventDefault();let t=$.current;
2V.current&&t?.isConnected&&t.focus({preventScroll:!0})},className:"gap-0 overflow-x-hidden border-border-strong bg-canvas sm:max-w-[400px]",children:[es&&(0,t.jsxs)("div",{className:"relative h-[148px] overflow-hidden","aria-hidden":"true",children:[(0,t.jsx)(i.default,{src:"/armada-routing-hero.png",alt:"",fill:!0,sizes:"400px",className:"object-cover object-[45%_65%]"}),(0,t.jsx)("div",{className:"absolute inset-0 bg-gradient-to-t from-canvas via-transparent to-transparent"})]}),(0,t.jsxs)("div",{className:"px-5 pb-5 pt-5",children:[es&&(0,t.jsx)(i.default,{src:"/armada-wordmark.svg",alt:N.VENUE_LABELS.armada,width:235,height:26,className:"mb-4 h-auto w-[150px]"}),(0,t.jsx)(d.DialogTitle,{className:"pr-6 text-xl leading-tight",children:R("routingDialogTitle")}),(0,t.jsx)(d.DialogDescription,{className:"mt-2 text-xs leading-5",children:R("routingDialogDescription")}),es&&(0,t.jsxs)("div",{role:"group","aria-label":R("routingMode"),className:"mt-4 grid grid-cols-2 gap-1 rounded-control border border-border bg-surface p-1",children:[(0,t.jsx)("button",{type:"button","aria-pressed":"armada"===G,disabled:Z("armada"),onClick:()=>{Z("armada")||(Y("armada"),eo("armada"))},className:`min-h-10 rounded-control px-3 text-xs font-semibold transition-colors disabled:cursor-default disabled:opacity-50 ${"armada"===G?"bg-primary/15 text-primary":"text-label-muted hover:bg-surface-interactive"}`,children:N.VENUE_LABELS.armada}),(0,t.jsx)("button",{type:"button","aria-pressed":"manual"===G,onClick:()=>Y("manual"),className:`min-h-10 rounded-control px-3 text-xs font-medium transition-colors ${"manual"===G?"bg-surface-interactive text-foreground":"text-label-muted hover:bg-surface-interactive"}`,children:R("routingManual")})]}),(0,t.jsx)("div",{className:"mt-4",children:em}),F&&(0,t.jsxs)("details",{className:"mt-4 border-t border-border pt-3",children:[(0,t.jsx)("summary",{className:"cursor-pointer text-xs font-medium text-secondary-foreground focus-visible:outline-2 focus-visible:outline-ring",children:R("orderSettings")}),(0,t.jsx)("div",{className:"mt-3",children:F})]}),(0,t.jsx)("p",{className:"mt-4 text-[11px] leading-4 text-label-muted",children:R("routingNewOrdersOnly")}),(0,t.jsxs)("div",{className:"mt-4 flex gap-2",children:[(0,t.jsx)(c.Button,{type:"button",variant:"outline",onClick:()=>z(!1),className:"min-h-10 flex-1",children:D("cancel")}),(0,t.jsx)(c.Button,{type:"button",disabled:!ea,onClick:()=>{ea&&(q!==v&&M(q),z(!1))},className:"min-h-10 flex-1",children:R("routingApply")})]})]})]})]})}],831519);var F=e.i(873029),R=e.i(467290),D=e.i(43690),I=e.i(153517);let U=(e,t)=>Number.isFinite(e)&&Number.isFinite(t)&&Math.abs(e-t)<=Math.max(1,e,t)*Number.EPSILON*16,O=e=>Number.isFinite(e)&&e>=0,B=e=>Number.isSafeInteger(e)&&e>=0;function z(e,t=Date.now()){let r=e?.benchmark;if(!r||"equal_weight_phoenix_jupiter_base_v1"!==r.method||!Array.isArray(r.venues)||2!==r.venues.length||"phoenix"!==r.venues[0]||"jupiter"!==r.venues[1]||!Number.isSafeInteger(r.computedAtUnixMs)||r.computedAtUnixMs<=0||!Number.isFinite(t))return!1;let i=t-r.computedAtUnixMs;return!(i<-6e4||!B(r.phoenixRateAgeMs)||!B(r.jupiterRateAgeMs)||r.phoenixRateAgeMs+Math.max(0,i)>3e5||r.jupiterRateAgeMs+Math.max(0,i)>9e4)&&!![r.estimatedFeesUsd,r.phoenixFeesUsd,r.jupiterFeesUsd,r.armadaFeesUsd,r.comparedVolumeUsd].every(O)&&!!B(r.comparedFillCount)&&!!B(r.excludedFillCount)&&!!U(r.estimatedFeesUsd,(r.phoenixFeesUsd+r.jupiterFeesUsd)/2)&&(0===r.comparedFillCount?0===r.estimatedFeesUsd&&0===r.armadaFeesUsd&&0===r.comparedVolumeUsd&&r.savingsUsd===(0===r.excludedFillCount?0:null):r.comparedVolumeUsd>0&&r.phoenixFeesUsd>0&&r.jupiterFeesUsd>0&&null!==r.savingsUsd&&O(r.savingsUsd)&&U(r.savingsUsd,Math.max(0,r.estimatedFeesUsd-r.armadaFeesUsd)))}function $(e,t=Date.now()){return z(e,t)&&null!==e.benchmark.savingsUsd&&Math.round(100*e.benchmark.savingsUsd)>0&&e.benchmark.comparedFillCount>0}function V(e,t){if(!Number.isFinite(new Date(t).getTime())||!$(e,t)||!e?.benchmark)return null;let r=e.benchmark,i=r.savingsUsd;if(null===i)return null;let s=i/r.estimatedFeesUsd*100;return Number.isFinite(s)?Object.freeze({...r,venues:Object.freeze([...r.venues]),savingsUsd:i,benchmarkFeesUsd:r.estimatedFeesUsd,capturedAt:t,percentSaved:s}):null}e.s(["canShareArmadaFeeSavings",0,$,"captureArmadaFeeSavings",0,V,"validArmadaFeeSavings",0,z],588018);var H=e.i(457395),W=e.i(988462),q=e.i(107481);let K="@ImperialPerps";e.s(["X_HANDLE",0,K],492728);var G=e.i(831979);async function Y(e,t,r){let i=new URL(t);if("https://x.com"!==i.origin||"/intent/tweet"!==i.pathname||i.username||i.password||"image/png"!==e.type)throw Error("Invalid image share destination");if(!r())return"retired";if(!navigator.clipboard?.write||"u"<typeof ClipboardItem)throw Error("Image clipboard is unavailable");if(await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),!r())return"retired";let s=null;try{if(!(s=window.open("about:blank","_blank")))return"popup-blocked";s.opener=null;let e=s.document.createElement("meta");return e.name="referrer",e.content="no-referrer",s.document.head.appendChild(e),s.location.replace(i.href),"opened"}
2catch{try{s?.close()}catch{}return"popup-blocked"}}e.s(["copyImageToX",0,Y],114787);let X=["hero.png","mask.svg","wordmark.svg","imperial.svg"];function Q(e){return new Promise((t,r)=>{let i=new Image,s=setTimeout(()=>r(Error("Fee share asset timed out")),15e3);i.onload=()=>{clearTimeout(s),t(i)},i.onerror=()=>{clearTimeout(s),r(Error("Fee share asset unavailable"))},i.src=`/share/armada-fees-${e}`})}async function J(e,t){let r,i=(e,r)=>`${e} ${r}px ${t}`,s=Promise.race([Promise.all([400,600,700].map(e=>document.fonts.load(i(e,16)))),new Promise((e,t)=>{r=setTimeout(()=>t(Error("Fee share font timed out")),15e3)})]).finally(()=>clearTimeout(r)),[n]=await Promise.all([Promise.all(X.map(Q)),s]),[a,l,o,d]=n,c=document.createElement("canvas"),u=c.getContext("2d");if(!u)throw Error("Canvas is unavailable");u.font=i(400,11);let h=[e.scope,e.coverage,e.exclusions,e.captured].flatMap(e=>(function(e,t){let r=[],i="";for(let s of t){let t=i+s;if(i&&e.measureText(t).width>532){let e=i.lastIndexOf(" ");e>0?(r.push(i.slice(0,e)),i=i.slice(e+1)+s):(r.push(i),i=s)}else i=t}return i&&r.push(i),r})(u,e)),p=339+16*h.length+20;c.width=2368,c.height=4*p,u.scale(4,4),u.fillStyle="#131315",u.fillRect(0,0,592,p);let m=document.createElement("canvas");m.width=2368,m.height=1356;let f=m.getContext("2d");if(!f)throw Error("Canvas is unavailable");f.scale(4,4),f.save(),f.translate(599,-108.718),f.scale(-1,1),f.drawImage(a,0,0,728,409.718),f.restore(),f.globalCompositeOperation="destination-in",f.translate(0,339),f.rotate(-Math.PI/2),f.drawImage(l,0,0,339,592),u.drawImage(m,0,0,592,339),u.drawImage(o,373.4,163.97,213.2,66.1967),u.drawImage(d,511.7,171,42.2944,6.68964);let x=[139,136,128,128],g=30,b=(e,t,r,s,n)=>{u.font=i(s,r);let a=u.measureText(e).width;a>n&&(u.font=i(s,r*n/a)),u.fillText(e,g+10,t)};for(let t=0;t<x.length;t++)u.fillStyle=3===t?"#e5c05b":2===t?"#2b2c2e":"#131315",u.fillRect(g,230,x[t],81),u.strokeStyle="#2b2c2e",u.strokeRect(g+.5,230.5,x[t]-1,80),u.fillStyle=3===t?"#191919":"#ffffff",b(e.labels[t].toLocaleUpperCase(),249,9.4,600,x[t]-20),u.fillStyle=3===t?"#191919":2===t?"#ffffff":"rgba(255,255,255,.7)",b(e.values[t],291,32.9,700,x[t]-20),g+=x[t];return u.font=i(400,11),u.fillStyle="#b7b7bb",h.forEach((e,t)=>u.fillText(e,30,345+16*t)),c.toDataURL("image/png")}let Z="focus-ring flex min-h-10 items-center justify-center gap-2 rounded-md border border-border bg-surface px-3 py-2 text-xs text-foreground hover:bg-accent disabled:opacity-40",ee="imperial-armada-fee-savings.png";function et({snapshot:e,onClose:i,returnFocusRef:s}){let n=(0,o.useTranslations)("trading"),a=(0,L.useFormatters)(),[l,c]=(0,r.useState)(0),[u,h]=(0,r.useState)(null),[p,m]=(0,r.useState)(null),[f,x]=(0,r.useState)(null),g=(0,r.useRef)(0),b=(0,r.useRef)(!1),[v]=(0,r.useState)(()=>({copy:"u">typeof navigator&&!!navigator.clipboard?.write&&"u">typeof ClipboardItem,share:"u">typeof navigator&&!!navigator.share})),y=(0,r.useMemo)(()=>{let t=new Intl.DateTimeFormat(a.intlTag,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e.capturedAt);return{labels:[n("feesSavedArmada"),n("feesSavedBenchmark"),n("feesSavedEstimated"),n("feesSavedPercent")],values:[`$${a.fixed(e.armadaFeesUsd,2)}`,`$${a.fixed(e.benchmarkFeesUsd,2)}`,`$${a.fixed(e.savingsUsd,2)}`,`${e.percentSaved<.1?"<":""}${a.fixed(Math.max(.1,e.percentSaved),1)}%`],scope:n("feesSavedShareScope"),coverage:n("feesSavedCoverage",{count:e.comparedFillCount})+(e.excludedFillCount>0?` \xb7 ${n("feesSavedExcluded",{count:e.excludedFillCount})}`:""),exclusions:n("feesSavedShareExclusions"),captured:n("feesSavedSnapshot",{time:t})}},[a,e,n]),w=n("feesSavedShareText",{amount:y.values[2],handle:K}),j=u?.attempt===l&&u.text===y?u.url:void 0,S=u?.attempt===l&&u.text===y&&u.failed,[k,N]=(0,r.useState)(j);k!==j&&(N(j),m(null),x(null)),(0,r.useLayoutEffect)(()=>(g.current+=1,b.current=!1,()=>{g.current+=1}),[j]),(0,r.useEffect)(()=>{let e=!1;return J(y,getComputedStyle(document.body).getPropertyValue("--font-bai-jamjuree").trim()||getComputedStyle(document.body).fontFamily).then(t=>{e||h({attempt:l,text:y,url:t})},()=>{e||h({attempt:l,text:y,failed:!0})}),()=>{e=!0}},[l,y]);let P=()=>new File([(0,q.dataUrlToPngBlob)(j)],ee,{type:"image/png"}),T=(e,t)=>
2{t!==g.current||e instanceof Error&&"AbortError"===e.name||m("error")};return(0,t.jsx)(d.Dialog,{open:!0,onOpenChange:e=>{e||(g.current+=1,i())},children:(0,t.jsxs)(d.DialogContent,{onCloseAutoFocus:e=>{e.preventDefault();let t=s.current;t?.isConnected&&!t.disabled&&t.focus({preventScroll:!0})},className:"gap-0 overflow-hidden border-2 border-[#26282a] bg-[#131315] sm:max-w-[596px]",children:[(0,t.jsx)(d.DialogTitle,{className:"sr-only",children:n("feesSavedShareTitle")}),(0,t.jsx)(d.DialogDescription,{className:"sr-only",children:n("feesSavedExplanation")}),(0,t.jsxs)("div",{className:"max-h-[calc(90dvh-3rem)] overflow-y-auto",children:[j?(0,t.jsx)("img",{src:j,className:"block h-auto w-full",alt:n("feesSavedShareAlt",{armada:y.values[0],benchmark:y.values[1],savings:y.values[2],percent:y.values[3]})}):(0,t.jsxs)("div",{className:"flex min-h-80 flex-col items-center justify-center gap-4 px-6 text-center text-sm",role:"status",children:[(0,t.jsx)("p",{children:n(S?"feesSavedShareRenderError":"feesSavedShareRendering")}),S&&(0,t.jsx)("button",{className:Z,type:"button",onClick:()=>c(e=>e+1),children:n("feesSavedShareRetry")})]}),(0,t.jsxs)("div",{className:"space-y-3 border-t border-border px-5 py-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,t.jsxs)("button",{type:"button",className:Z,disabled:!j||"copying"===p,onClick:()=>{if(!j||b.current)return;let e=g.current;m(null),x(null);try{if((0,q.isWalletInAppBrowser)()){let t=P();navigator.canShare?.({files:[t]})?navigator.share({files:[t]}
2).catch(t=>T(t,e)):m("longPress");return}let t=document.createElement("a");t.href=j,t.download=ee,t.click()}catch{m("error")}},children:[(0,t.jsx)(W.Download,{className:"size-4","aria-hidden":"true"}),n("feesSavedShareDownload")]}),v.copy&&(0,t.jsxs)("button",{type:"button",className:Z,disabled:!j||"copying"===p,onClick:()=>{if(!j||b.current)return;let e=g.current;b.current=!0,m("copying"),x(null);try{navigator.clipboard.write([new ClipboardItem({"image/png":(0,q.dataUrlToPngBlob)(j)})]).then(()=>{e===g.current&&m("copied")},()=>{e===g.current&&m("error")}).finally(()=>{e===g.current&&(b.current=!1)})}catch{b.current=!1,m("error")}},children:[(0,t.jsx)(H.Copy,{className:"size-4","aria-hidden":"true"}),n("feesSavedShareCopy")]}),v.share&&(0,t.jsxs)("button",{type:"button",className:Z,disabled:!j||"copying"===p,onClick:()=>{if(!j||b.current)return;let e=g.current;m(null),x(null);try{let t=P();if(!navigator.canShare?.({files:[t]}))return void m("longPress");navigator.share({files:[t],text:w}).catch(t=>T(t,e))}catch{m("error")}},children:[(0,t.jsx)(R.Share2,{className:"size-4","aria-hidden":"true"}),n("feesSavedShareNative")]}),(0,t.jsxs)("button",{type:"button",className:Z,disabled:!j||"copying"===p,"aria-busy":"copying"===p,onClick:()=>{if(!j||b.current)return;let e=g.current,t=`https://x.com/intent/tweet?${new URLSearchParams({text:w})}`;b.current=!0,m("copying"),x(null);try{Y((0,q.dataUrlToPngBlob)(j),t,()=>e===g.current).then(r=>{e===g.current&&"retired"!==r&&(m(r),"popup-blocked"===r&&x(t))}).catch(()=>{e===g.current&&(m("error"),x(t))}).finally(()=>{e===g.current&&(b.current=!1)})}catch{b.current=!1,m("error"),x(t)}},children:[(0,t.jsx)(G.XIcon,{className:"size-4"}),n("shareCopyOpenX")]})]}),(0,t.jsx)("div",{className:"h-[54px] overflow-y-auto text-xs leading-[18px] text-muted-foreground",children:(0,t.jsxs)("p",{role:"error"===p?"alert":"status",children:[n("copying"===p?"shareCopyingImage":"opened"===p?"shareXCopied":"popup-blocked"===p?"shareXPopupBlocked":"copied"===p?"feesSavedShareCopied":"longPress"===p?"feesSavedShareLongPress":"error"===p?"feesSavedShareActionError":"feesSavedShareHint"),f&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{className:"underline underline-offset-2",href:f,target:"_blank",rel:"noopener noreferrer",children:n("shareOpenX")})]})]})})]})]})]})})}function er({wallet:e,className:i}){let s=(0,o.useTranslations)("trading"),n=(0,L.useFormatters)(),{data:a,isError:l}=(0,D.useQuery)({queryKey:["armada-fee-savings",e],queryFn:async({signal:t})=>{let r=await fetch(`https://api.imperial.space/api/v1/profile/${e}/armada-fee-savings`,{signal:t});if(!r.ok)throw Error(`Armada fee savings: ${r.status}`);return r.json()},enabled:!!e,staleTime:3e4,refetchInterval:3e4}),d=(0,r.useRef)(null),[c,h]=(0,r.useState)(null),p=z(a),m=p?a.benchmark:null,f=m?.savingsUsd,x=l||void 0!==a&&!p,g=e&&!x&&p&&null!=f?`$${n.fixed(f,2)}`:"—",b=!!e&&!x&&$(a),v="flex w-9 shrink-0 items-center justify-center self-stretch border-l border-border hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary";return(0,t.jsxs)("div",{className:(0,I.cn)("flex min-h-9 items-center border-y border-border bg-surface text-xs text-[#e5c05b]",i),children:[(0,t.jsxs)("span",{className:"min-w-0 flex-1 px-3 py-1.5",children:[s("feesSaved"),": ",(0,t.jsx)("span",{className:"tabular-nums",children:g})]}),(0,t.jsxs)(u.Popover,{children:[(0,t.jsx)(u.PopoverTrigger,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:v,"aria-label":s("feesSavedInfo"),children:(0,t.jsx)(F.Info,{className:"size-3.5","aria-hidden":"true"})})}),(0,t.jsxs)(u.PopoverContent,{side:"top",align:"end",className:"space-y-2 text-xs",children:[(0,t.jsx)("p",{className:"font-medium",children:s("feesSavedInfo")}),(0,t.jsx)("p",{className:"text-muted-foreground",children:s("feesSavedExplanation")}),e?x?(0,t.jsx)("p",{children:s("feesSavedUnavailable")}):m&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("dl",{className:"space-y-1 tabular-nums",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("dt",{children:s("feesSavedBenchmark")}),(0,t.jsxs)("dd",{children:["$",n.fixed(m.estimatedFeesUsd,2)]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("dt",{children:s("feesSavedArmada")}),(0,t.jsxs)("dd",{children:["$",n.fixed(m.armadaFeesUsd,2)]})]})]}),(0,t.jsx)("p",{className:"text-muted-foreground",children:s("feesSavedCoverage",{count:m.comparedFillC
2ount})}),m.excludedFillCount>0&&(0,t.jsx)("p",{className:"text-muted-foreground",children:s("feesSavedExcluded",{count:m.excludedFillCount})}),0===m.comparedFillCount&&(0,t.jsx)("p",{className:"text-muted-foreground",children:s("feesSavedNoComparison")})]}):(0,t.jsx)("p",{children:s("feesSavedConnect")})]})]}),(0,t.jsx)("button",{ref:d,type:"button",disabled:!b,className:(0,I.cn)(v,"disabled:opacity-40"),"aria-label":s("feesSavedShareTitle"),"aria-haspopup":"dialog",onClick:()=>{b&&h(V(a,Date.now()))},children:(0,t.jsx)(R.Share2,{className:"size-3.5","aria-hidden":"true"})}),c&&(0,t.jsx)(et,{snapshot:c,onClose:()=>h(null),returnFocusRef:d})]})}e.s(["ArmadaFeeShareDialog",0,et],682331),e.s(["ArmadaFeesSaved",0,function({wallet:e,className:r}){return(0,t.jsx)(er,{wallet:e,className:r},e??"disconnected")}],271434);var ei=e.i(711104);function es({kind:e,label:i,children:s}){let n=(0,r.useRef)(null),a=(0,r.useRef)(null),[l,o]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=n.current,t=a.current;if(!e||!t||"u"<typeof ResizeObserver)return;let r=new ResizeObserver(()=>{o(e.scrollHeight>e.clientHeight+1)});return r.observe(e),r.observe(t),()=>r.disconnect()},[]),(0,t.jsx)("div",{ref:n,"data-terminal-action-before":"before"===e||void 0,"data-terminal-action-after":"after"===e||void 0,className:ei.default[e],tabIndex:l?0:void 0,role:l?"region":void 0,"aria-label":l?i:void 0,children:(0,t.jsx)("div",{ref:a,className:ei.default.content,children:s})})}e.s(["TerminalActionSection",0,function({before:e,after:r,children:i}){let s=(0,o.useTranslations)("trading");return(0,t.jsxs)("div",{"data-terminal-action":!0,className:ei.default.section,children:[(0,t.jsx)(es,{kind:"before",label:s("terminalOrderNotices"),children:e}),(0,t.jsx)("div",{"data-terminal-action-button":!0,className:ei.default.button,children:i}),(0,t.jsx)(es,{kind:"after",label:s("terminalTradeStrength"),children:r})]})}],59392)},673028,373447,578152,e=>{"use strict";var t=e.i(394390),r=e.i(873029),i=e.i(942553);e.i(875574);var s=e.i(142298),n=e.i(183023),a=e.i(21859),l=e.i(214732),o=e.i(653982);function d(e){let t=(0,n.useMemo)(()=>{if(!e)return null;try{return(0,a.getAssociatedTokenAddressSync)(o.USDT_MINT,e)}catch{return null}},[e?.toBase58()]),{data:r,isLoading:i}=(0,l.useAccountSubscription)({account:t,decoder:e=>(function(e){try{if(e.length<72)return null;return{amount:e.readBigUInt64LE(64)}}catch{return null}})(e.data),commitment:"processed",enabled:!!t}),s=r?.amount??BigInt(0),d=Number(s)/1e6;return{rawBalance:s,uiBalance:d,ata:t,isLoading:i}}e.s(["useUsdtWalletBalance",0,d],373447);var c=e.i(860991),u=e.i(799227),h=e.i(116082);class p{async getQuote(e){if(!e.userPublicKey)throw Error("Titan requires userPublicKey for quotes");let t=new URL("/api/titan/quote",window.location.origin);t.searchParams.set("inputMint",e.inputMint),t.searchParams.set("outputMint",e.outputMint),t.searchParams.set("amount",e.amount),t.searchParams.set("slippageBps",e.slippageBps.toString()),t.searchParams.set("userPublicKey",e.userPublicKey),e.maxSwapBytes&&t.searchParams.set("maxSwapBytes",e.maxSwapBytes.toString());let r=await fetch(t.toString());if(!r.ok)throw Error((await r.json()).error||"Titan quote failed");return r.json()}async getSwapTransaction(e){let t=await fetch("/api/titan/swap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quoteResponse:e.quote,userPublicKey:e.userPublicKey,wrapAndUnwrapSol:e.wrapAndUnwrapSol??!0})});if(!t.ok)throw Error((await t.json()).error||"Titan swap failed");return t.json()}}class m{async getQuote(e){let t=new URL("/api/dflow/quote",window.location.origin);t.searchParams.set("inputMint",e.inputMint),t.searchParams.set("outputMint",e.outputMint),t.searchParams.set("amount",e.amount),t.searchParams.set("slippageBps",e.slippageBps.toString());let r=await fetch(t.toString());if(!r.ok)throw Error((await r.json()).error||"DFlow quote failed");return r.json()}async getSwapTransaction(e){let t=await fetch("/api/dflow/swap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quoteResponse:e.quote,userPublicKey:e.userPublicKey,wrapAndUnwrapSol:e.wrapAndUnwrapSol??!0,dynamicComputeUnitLimit:!0})});if(!t.ok)throw Error((await t.json()).error||"DFlow swap failed");return t.json()}}class f{client;constructor(){this.client=new m}async getQuote(e){return await this.client.getQuote(e)}async getSwapTransaction(e){return await this.client.getSwapTransaction({quote:e.quote,userPublicKey:e.userPublicKey,wrapAndUnwrapSol:e.wrapAndUnwrapSol})}}class x{titan;dflow;constructor(){this.titan=new p,this.dflow=new f}async getQuote(e){let[t,r]=await Promise.allSettled([this.titan.getQuote(e),this.dflow.getQuote(e)]);if("fulfilled"===t.status)return"fulfilled"===r.status&&(t.value._fallbackQuote=r.value),t.value;if(console.warn("Titan quote failed, falling back to DFlow:",t.reason),"fulfilled"===r.status)return r.value;throw Error(`Both swap providers failed. Titan: ${t.reason}. DFlow: ${r.reason}`)}async getSwapTransaction(e){if(e.quote._titanQuote)try{return await this.titan.getSwapTransaction(e)}catch(i){console.warn("Titan swap failed, retrying with DFlow quote:",i);let t=e.quote._fallbackQuote;if(t)return this.dflow.getSwapTransaction({...e,quote:t});let r=await this.dflow.getQuote({inputMint:e.quote.inputMint,outputMint:e.quote.outputMint,amount:e.quote.inAmount,slippageBps:e.quote.slippageBps});return this.dflow.getSwapTransaction({...e,quote:r})}return this.dflow.getSwapTransaction(e)}}var g=e.i(936548),b=e.i(739835),v=e.i(586569);function y({rawUsdtBalance:e,enabled:t,onSuccess:r}){let{publicKey:i,connection:a,sendTransaction:l}
2=(0,s.useUnifiedWallet)(),[d,p]=(0,n.useState)(!1),m=i?.toBase58()??null,f=e.toString(),w=t&&!!m&&e>BigInt(0),{quote:j,error:S,isLoading:k}=function({inputMint:e,outputMint:t,amount:r,slippageBps:i,userPublicKey:s,enabled:a=!0}){let[l,o]=(0,n.useState)(null),[d,c]=(0,n.useState)(!1),[u,h]=(0,n.useState)(!1),[p,m]=(0,n.useState)(null),[f,x]=(0,n.useState)(null),g=(0,n.useRef)(null),b=(0,n.useRef)(null),v=(0,n.useRef)(null),y=(0,n.useRef)(""),w=(0,n.useRef)(0),j=(0,n.useCallback)(()=>{if(!s||!a)return;let n=parseInt(r,10);if(isNaN(n)||n<1e3)return void o(null);let l=new URLSearchParams({inputMint:e,outputMint:t,amount:r,slippageBps:i.toString(),userPublicKey:s}).toString();if(l===y.current&&g.current)return;g.current&&(g.current.close(),g.current=null),v.current&&(clearTimeout(v.current),v.current=null),y.current=l,h(!0),m(null);let d=new EventSource(`https://api.imperial.space/api/v1/titan/quote-stream?${l}`);g.current=d,d.addEventListener("connected",()=>{c(!0),m(null),w.current=0}),d.addEventListener("quote",e=>{try{let t=JSON.parse(e.data);o(t),x(Date.now()),h(!1),m(null)}catch(e){console.error("Failed to parse quote:",e)}}),d.addEventListener("heartbeat",()=>{}),d.addEventListener("error",e=>{if(e instanceof MessageEvent)try{let t=JSON.parse(e.data);m(t.message||"Stream error")}catch{m("Stream error")}h(!1)}),d.addEventListener("disconnected",e=>{c(!1);try{JSON.parse(e.data).reconnecting||m("Disconnected from quote stream")}catch{}}),d.onerror=()=>{c(!1),h(!1),g.current&&(g.current.close(),g.current=null),y.current="";let e=Math.min(1e3*Math.pow(2,Math.min(w.current,6)),6e4)*(.5+.5*Math.random());w.current+=1,v.current=setTimeout(()=>{j()},e)}},[e,t,r,i,s,a]);return(0,n.useEffect)(()=>(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{j()},300),()=>{b.current&&clearTimeout(b.current)}),[j]),(0,n.useEffect)(()=>()=>{g.current&&(g.current.close(),g.current=null),v.current&&(clearTimeout(v.current),v.current=null)},[]),(0,n.useEffect)(()=>{!a&&g.current&&(g.current.close(),g.current=null,c(!1),y.current="")},[a]),(0,n.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&a&&s&&(!g.current||g.current.readyState===EventSource.CLOSED)&&(w.current=0,v.current&&(clearTimeout(v.current),v.current=null),y.current="",j())};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[j,a,s]),{quote:l,isConnected:d,isLoading:u,error:p,lastUpdated:f}}({inputMint:o.USDT_MINT.toBase58(),outputMint:o.USDC_MINT.toBase58(),amount:f,slippageBps:50,userPublicKey:m,enabled:w}),N=(0,n.useCallback)(async()=>{if(!i||!a||!l)return void h.toast.error((0,v.message)("wallet","walletNotConnected"));if(!j)return void h.toast.error((0,v.message)("wallet","swapQuoteUnavailable"));p(!0);try{let e=new x,t=await e.getSwapTransaction({quote:j,userPublicKey:i.toBase58(),wrapAndUnwrapSol:!1}),s=Uint8Array.from(atob(t.swapTransaction),e=>e.charCodeAt(0)),n=u.VersionedTransaction.deserialize(s),o=await l(n);await (0,c.confirmOrVerifyLanded)(a,{signature:o,blockhash:n.message.recentBlockhash,lastValidBlockHeight:t.lastValidBlockHeight},"confirmed"),h.toast.success((0,v.message)("wallet","swappedUsdtToUsdc")),r?.()}catch(e){(0,b.isUserRejection)(e)||h.toast.error((0,g.displayClientError)(e))}finally{p(!1)}},[i,a,l,j,r]);return{quote:j,quoteError:S,quoteLoading:k,swap:N,pending:d}}e.s(["useSwapUsdtToUsdc",0,y],578152);var w=e.i(299959);let j=BigInt(1e6);e.s(["UsdtHintRow",0,function({onSwapSuccess:e}={}){let n=(0,i.useTranslations)("trading"),a=(0,w.useFormatters)(),{publicKey:l,isJWTMode:o}=(0,s.useUnifiedWallet)(),{rawBalance:c,uiBalance:u}=d(o?null:l),h=c>=j&&!o,{quote:p,swap:m,pending:f}=y({rawUsdtBalance:c,enabled:h,onSuccess:e});return h?(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-sky-500/20 bg-sky-500/5 px-3 py-2 text-xs text-sky-200 min-w-0",children:[(0,t.jsx)(r.Info,{className:"h-3.5 w-3.5 text-sky-400 flex-shrink-0"}),(0,t.jsx)("span",{className:"flex-1 min-w-0 truncate",children:n.rich("usdtInWallet",{amount:`${a.fixed(u,2)} USDT`,strong:e=>(0,t.jsx)("span",{className:"font-semibold font-mono tabular-nums text-foreground",children:e})})}),(0,t.jsx)("button",{onClick:()=>void m(),disabled:f||!p,className:"px-2 py-0.5 rounded bg-sky-500/20 hover:bg-sky-500/30 border border-sky-500/40 text-sky-100 text-[11px] font-medium disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0",children:n(f?"swapping":"swap")})]}):null}],673028)},626074,e=>{"use strict";var t=e.i(394390),r=e.i(234792),i=e.i(402392),s=e.i(478081),s=s;let n=(0,e.i(504458).default)("circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);var a=e.i(153517);e.s(["DropdownMenu",0,function({...e}){return(0,t.jsx)(r.Root,{"data-slot":"dropdown-menu",...e})},"DropdownMenuCheckboxItem",0,function({className:e,children:s,checked:n,...l}){return(0,t.jsxs)(r.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:(0,a.cn)("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-chip py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:n,...l,children:[(0,t.jsx)("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:(0,t.jsx)(r.ItemIndicator,{children:(0,t.jsx)(i.CheckIcon,{className:"size-4"})})}),s]})},"DropdownMenuContent",0,function({className:e,sideOffset:i=4,...s}){return(0,t.jsx)(r.Portal,{children:(0,t.jsx)(r.Content,{"data-slot":"dropdown-menu-content",sideOffset:i,className:(0,a.cn)("bg-popover text-popover-foreground border-border-strong data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
2de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-float border p-1 shadow-md",e),...s})})},"DropdownMenuItem",0,function({className:e,inset:i,variant:s="default",...n}){return(0,t.jsx)(r.Item,{"data-slot":"dropdown-menu-item","data-inset":i,"data-variant":s,className:(0,a.cn)("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-chip px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})},"DropdownMenuLabel",0,function({className:e,inset:i,...s}){return(0,t.jsx)(r.Label,{"data-slot":"dropdown-menu-label","data-inset":i,className:(0,a.cn)("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...s})},"DropdownMenuRadioGroup",0,function({...e}){return(0,t.jsx)(r.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})},"DropdownMenuRadioItem",0,function({className:e,children:i,...s}){return(0,t.jsxs)(r.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:(0,a.cn)("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-chip py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...s,children:[(0,t.jsx)("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:(0,t.jsx)(r.ItemIndicator,{children:(0,t.jsx)(n,{className:"size-2 fill-current"})})}),i]})},"DropdownMenuSeparator",0,function({className:e,...i}){return(0,t.jsx)(r.Separator,{"data-slot":"dropdown-menu-separator",className:(0,a.cn)("bg-border -mx-1 my-1 h-px",e),...i})},"DropdownMenuSub",0,function({...e}){return(0,t.jsx)(r.Sub,{"data-slot":"dropdown-menu-sub",...e})},"DropdownMenuSubContent",0,function({className:e,...i}){return(0,t.jsx)(r.SubContent,{"data-slot":"dropdown-menu-sub-content",className:(0,a.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-float border border-border-strong p-1 shadow-lg",e),...i})},"DropdownMenuSubTrigger",0,function({className:e,inset:i,children:n,...l}){return(0,t.jsxs)(r.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":i,className:(0,a.cn)("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-chip px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",e),...l,children:[n,(0,t.jsx)(s.default,{className:"ml-auto size-4"})]})},"DropdownMenuTrigger",0,function({...e}){return(0,t.jsx)(r.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}],626074)},685576,928993,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(207867),s=e.i(942553),n=e.i(876699),a=e.i(827751);function l({onDismiss:e,extended:t=!1,onExpand:i,onCollapse:s}){let n=(0,r.useRef)(null),a=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(null),h=(0,r.useCallback)(()=>{let e=n.current;e&&(e.style.transition="",e.style.removeProperty("transform"))},[]),p=(0,r.useCallback)(()=>{for(let e of[a,o])null!==e.current&&(window.clearTimeout(e.current),e.current=null)},[]),m=(0,r.useCallback)((t=e)=>{let r=n.current;if(!r||window.matchMedia("(prefers-reduced-motion: reduce)").matches){h(),t();return}
2p(),r.style.transition="transform 250ms ease-in",r.style.transform=`translateY(${r.offsetHeight+40}px)`,a.current=window.setTimeout(()=>{a.current=null;let e=`translateY(${r.offsetHeight+40}px)`;r.style.transition="none",r.style.setProperty("transform",e,"important"),t(),o.current=window.setTimeout(()=>{o.current=null,h()},350)},250)},[e,h,p]),f=(0,r.useCallback)(e=>{if(d.current){if(e.currentTarget.hasPointerCapture(d.current.id))return;d.current=null}("mouse"!==e.pointerType||0===e.button)&&(p(),h(),d.current={id:e.pointerId,y:e.clientY,armed:!1,ty:0,up:0,h:n.current?.offsetHeight??0},c.current={y:e.clientY,t:e.timeStamp},u.current=null,e.currentTarget.setPointerCapture(e.pointerId))},[p,h]),x=(0,r.useCallback)(e=>{let t=d.current,r=n.current;if(!t||t.id!==e.pointerId||!r)return;let i=e.clientY-t.y;if(u.current=c.current,c.current={y:e.clientY,t:e.timeStamp},t.up=Math.max(t.up,-i),!t.armed){if(i<10)return;t.armed=!0}t.ty=Math.max(0,i-10),r.style.transition="none",r.style.transform=`translateY(${t.ty}px)`},[]),g=(0,r.useCallback)(()=>{let e=n.current;if(e){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void h();e.style.transition="transform 200ms ease-out",e.style.transform="translateY(0)",a.current=window.setTimeout(()=>{a.current=null,h()},200)}},[h]),b=(0,r.useCallback)(e=>{let r=d.current;if(!r||r.id!==e.pointerId||(d.current=null,!n.current))return;let a=u.current,l=c.current,o=a&&l&&l.t>a.t?(l.y-a.y)/(l.t-a.t):0;if(!r.armed){i&&!t&&(r.up>=60||o<=-.5)&&i();return}r.ty>=Math.min(120,.4*r.h)||o>=.5?t&&s?(s(),g()):m():g()},[m,t,s,i,g]),v=(0,r.useCallback)(e=>{let t=d.current;t&&t.id===e.pointerId&&(d.current=null,g())},[g]);return{contentRef:n,animateOut:m,resetForOpen:(0,r.useCallback)(()=>{p(),h()},[p,h]),grabProps:{onPointerDown:f,onPointerMove:x,onPointerUp:b,onPointerCancel:v}}}e.s(["useSheetDrag",0,l],928993);var o=e.i(153517);function d({...e}){return(0,t.jsx)(i.Portal,{"data-slot":"sheet-portal",...e})}let c="mx-auto h-1 w-10 shrink-0",u=`${c} rounded-full bg-border-strong`;function h(e,t){if("function"==typeof e)return e(t);e&&(e.current=t)}function p({className:e,...r}){return(0,t.jsx)("div",{className:(0,o.cn)(c,"relative cursor-grab touch-none active:cursor-grabbing [[data-scrolled]>&]:pointer-events-none","before:absolute before:-inset-x-8 before:-inset-y-5 before:content-['']","after:absolute after:inset-0 after:rounded-full after:bg-border-strong after:content-['']",e),...r})}function m({className:e,...r}){return(0,t.jsx)(i.Overlay,{"data-slot":"sheet-overlay",className:(0,o.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...r})}let f={"--tw-enter-translate-y":"0","--tw-enter-opacity":"0","--tw-animation-duration":"150ms"},x="data-[state=closed]:duration-[240ms] data-[state=open]:duration-[240ms] motion-reduce:animate-none! motion-reduce:transition-none",g=`flex h-full w-[86%] max-w-none flex-col border-l border-border-strong bg-surface focus:outline-none focus-visible:outline-none sm:max-w-none ${x}`;e.s(["SHEET_MOTION",0,x,"SHEET_PHONE_DRAWER",0,g,"Sheet",0,function({...e}){return(0,t.jsx)(i.Root,{"data-slot":"sheet",...e})},"SheetCloseChip",0,function({className:e,onClick:r,...i}){let a=(0,s.useTranslations)("common");return(0,t.jsx)("button",{type:"button",onClick:r,"aria-label":a("close"),className:(0,o.cn)("absolute z-10 flex h-9 w-9 items-center justify-center rounded-control border border-border bg-surface-raised text-secondary-foreground transition-colors hover:text-foreground before:absolute before:-inset-1 before:content-[''] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",e),...i,children:(0,t.jsx)(n.XIcon,{className:"size-4","aria-hidden":!0})})},"SheetContent",0,function({className:e,children:c,side:u="right",forceMount:x,hideClose:g,hideHandle:b,enterInPlace:v,style:y,ref:w,onPointerDownOutside:j,onFocusOutside:S,onOpenAutoFocus:k,...N}){let P=(0,s.useTranslations)("common"),{closeRef:T,grabProps:C,attachContent:M}=function(e){let t=r.useRef(null),{contentRef:i,grabProps:s}=l({onDismiss:r.useCallback(()=>t.current?.click(),[])});return{closeRef:t,grabProps:s,attachContent:r.useCallback(t=>{i.current=t;let r=h(e,t),s=()=>t.toggleAttribute("data-scrolled",t.scrollTop>0);return t.addEventListener("scroll",s,{passive:!0}),()=>{t.removeEventListener("scroll",s),i.current=null,"function"==typeof r?r():h(e,null)}},[i,e])}}(w),_="bottom"===u&&!b;return(0,t.jsxs)(d,{forceMount:x,children:[(0,t.jsx)(m,{forceMount:x,className:x?"data-[state=closed]:invisible data-[state=closed]:transition-[visibility] data-[state=closed]:[transition-duration:0s] data-[state=closed]:[transition-delay:300ms]":void 0}),(0,t.jsxs)(i.Content,{"data-slot":"sheet-content","data-sheet-swi
2pe":_?"":void 0,ref:M,forceMount:x,className:(0,o.cn)("bg-surface text-foreground border-border data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500","right"===u&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm","left"===u&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm","top"===u&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b","bottom"===u&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto max-h-[85dvh] rounded-t-lg border-t pb-[max(env(safe-area-inset-bottom),1rem)]",x&&"data-[state=closed]:invisible data-[state=closed]:transition-[visibility] data-[state=closed]:[transition-duration:0s] data-[state=closed]:[transition-delay:300ms]",e),style:v?{...f,...y}:y,...(0,a.keypadLayerProps)({onPointerDownOutside:j,onFocusOutside:S,onOpenAutoFocus:k}),...N,children:[_&&(0,t.jsx)(p,{...C,className:"z-20 mt-2 -mb-2"}),c,(!g||_)&&(0,t.jsxs)(i.Close,{ref:T,tabIndex:g?-1:void 0,className:(0,o.cn)("ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-2 right-2 z-30 rounded-md p-2 opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",g&&"sr-only p-0"),children:[(0,t.jsx)(n.XIcon,{className:"size-4"}),(0,t.jsx)("span",{className:"sr-only",children:P("close")})]})]})]})},"SheetDescription",0,function({className:e,...r}){return(0,t.jsx)(i.Description,{"data-slot":"sheet-description",className:(0,o.cn)("text-muted-foreground text-sm",e),...r})},"SheetHandle",0,function({className:e,...r}){return(0,t.jsx)("div",{"aria-hidden":!0,"data-slot":"sheet-handle",className:(0,o.cn)(u,e),...r})},"SheetHeader",0,function({className:e,...r}){return(0,t.jsx)("div",{"data-slot":"sheet-header",className:(0,o.cn)("flex flex-col gap-1.5 p-4",e),...r})},"SheetTitle",0,function({className:e,...r}){return(0,t.jsx)(i.Title,{"data-slot":"sheet-title",className:(0,o.cn)("text-foreground font-semibold",e),...r})},"SheetTrigger",0,function({...e}){return(0,t.jsx)(i.Trigger,{"data-slot":"sheet-trigger",...e})}],685576)},679555,e=>{"use strict";var t=e.i(394390),r=e.i(153517);e.s(["Skeleton",0,function({className:e,...i}){return(0,t.jsx)("div",{"data-slot":"skeleton",className:(0,r.cn)("animate-pulse rounded-md bg-surface-raised motion-reduce:animate-none",e),style:{boxShadow:"0px 8px 33px rgba(0,0,0,0.6), inset 0px 1px 2px rgba(255,255,255,0.05)"},...i})}])},103887,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(750815),s=e.i(489980),n=e.i(375039),a=e.i(541078),l=e.i(204095),o=e.i(936456),d=e.i(327494),c=e.i(575856),u=e.i(671454),h=e.i(750045),p=["PageUp","PageDown"],m=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],f={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},x="Slider",[g,b,v]=(0,h.createCollection)(x),[y,w]=(0,a.createContextScope)(x,[v]),[j,S]=y(x),k=r.forwardRef((e,n)=>{let{name:a,min:o=0,max:d=100,step:c=1,orientation:u="horizontal",disabled:h=!1,minStepsBetweenThumbs:f=0,defaultValue:x=[o],value:b,onValueChange:v=()=>{},onValueCommit:y=()=>{},inverted:w=!1,form:S,...k}=e,N=r.useRef(new Set),P=r.useRef(0),M="horizontal"===u,[_=[],A]=(0,l.useControllableState)({prop:b,defaultProp:x,onChange:e=>{let t=[...N.current];t[P.current]?.focus(),v(e)}}),E=r.useRef(_);function L(e,t,{commit:r}={commit:!1}){let s,n=(String(c).split(".")[1]||"").length,a=Math.round((Math.round((e-o)/c)*c+o)*(s=Math.pow(10,n)))/s,l=(0,i.clamp)(a,[o,d]);A((e=[])=>{let i=function(e=[],t,r){let i=[...e];return i[r]=t,i.sort((e,t)=>e-t)}(e,l,t);if(!function(e,t){if(t>0)return Math.min(...e.slice(0,-1).map((t,r)=>e[r+1]-t))>=t;return!0}(i,f*c))return e;{P.current=i.indexOf(l);let t=String(i)!==String(e);return t&&r&&y(i),t?i:e}})}return(0,t.jsx)(j,{scope:e.__scopeSlider,name:a,disabled:h,min:o,max:d,valueIndexToChangeRef:P,thumbs:N.current,values:_,orientation:u,form:S,children:(0,t.jsx)(g.Provider,{scope:e.__scopeSlider,children:(0,t.jsx)(g.Slot,{scope:e.__scopeSlider,children:(0,t.jsx)(M?T:C,{"aria-disabled":h,"data-disabled":h?"":void 0,...k,ref:n,onPointerDown:(0,s.composeEventHandlers)(k.onPointerDown,()=>{h||(E.current=_)}),min:o,max:d,inverted:w,onSlideStart:h?void 0:function(e){let t=function(e,t){if(1===e.length)return 0;let r=e.map(e=>Math.abs(e-t)),i=Math.min(...r);return r.indexOf(i)}(_,e);L(e,t)},onSlideMove:h?void 0:function(e){L(e,P.current)},onSlideEnd:h?void 0:function(){let e=E.current[P.current];_[P.current]!==e&&y(_)},onHomeKeyDown:()=>!h&&L(o,0,{commit:!0}),onEndKeyDown:()=>!h&&L(d,_.length-1,{commit:!0}),onStepKeyDown:({event:e,direction:t})=>
2{if(!h){let r=p.includes(e.key)||e.shiftKey&&m.includes(e.key),i=P.current;L(_[i]+c*(r?10:1)*t,i,{commit:!0})}}})})})})});k.displayName=x;var[N,P]=y(x,{startEdge:"left",endEdge:"right",size:"width",direction:1}),T=r.forwardRef((e,i)=>{let{min:s,max:a,dir:l,inverted:d,onSlideStart:c,onSlideMove:u,onSlideEnd:h,onStepKeyDown:p,...m}=e,[x,g]=r.useState(null),b=(0,n.useComposedRefs)(i,e=>g(e)),v=r.useRef(void 0),y=(0,o.useDirection)(l),w="ltr"===y,j=w&&!d||!w&&d;function S(e){let t=v.current||x.getBoundingClientRect(),r=O([0,t.width],j?[s,a]:[a,s]);return v.current=t,r(e-t.left)}return(0,t.jsx)(N,{scope:e.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:(0,t.jsx)(M,{dir:y,"data-orientation":"horizontal",...m,ref:b,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:e=>{let t=S(e.clientX);c?.(t)},onSlideMove:e=>{let t=S(e.clientX);u?.(t)},onSlideEnd:()=>{v.current=void 0,h?.()},onStepKeyDown:e=>{let t=f[j?"from-left":"from-right"].includes(e.key);p?.({event:e,direction:t?-1:1})}})})}),C=r.forwardRef((e,i)=>{let{min:s,max:a,inverted:l,onSlideStart:o,onSlideMove:d,onSlideEnd:c,onStepKeyDown:u,...h}=e,p=r.useRef(null),m=(0,n.useComposedRefs)(i,p),x=r.useRef(void 0),g=!l;function b(e){let t=x.current||p.current.getBoundingClientRect(),r=O([0,t.height],g?[a,s]:[s,a]);return x.current=t,r(e-t.top)}return(0,t.jsx)(N,{scope:e.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:(0,t.jsx)(M,{"data-orientation":"vertical",...h,ref:m,style:{...h.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:e=>{let t=b(e.clientY);o?.(t)},onSlideMove:e=>{let t=b(e.clientY);d?.(t)},onSlideEnd:()=>{x.current=void 0,c?.()},onStepKeyDown:e=>{let t=f[g?"from-bottom":"from-top"].includes(e.key);u?.({event:e,direction:t?-1:1})}})})}),M=r.forwardRef((e,r)=>{let{__scopeSlider:i,onSlideStart:n,onSlideMove:a,onSlideEnd:l,onHomeKeyDown:o,onEndKeyDown:d,onStepKeyDown:c,...h}=e,f=S(x,i);return(0,t.jsx)(u.Primitive.span,{...h,ref:r,onKeyDown:(0,s.composeEventHandlers)(e.onKeyDown,e=>{"Home"===e.key?(o(e),e.preventDefault()):"End"===e.key?(d(e),e.preventDefault()):p.concat(m).includes(e.key)&&(c(e),e.preventDefault())}),onPointerDown:(0,s.composeEventHandlers)(e.onPointerDown,e=>{let t=e.target;t.setPointerCapture(e.pointerId),e.preventDefault(),f.thumbs.has(t)?t.focus():n(e)}
2),onPointerMove:(0,s.composeEventHandlers)(e.onPointerMove,e=>{e.target.hasPointerCapture(e.pointerId)&&a(e)}),onPointerUp:(0,s.composeEventHandlers)(e.onPointerUp,e=>{let t=e.target;t.hasPointerCapture(e.pointerId)&&(t.releasePointerCapture(e.pointerId),l(e))})})}),_="SliderTrack",A=r.forwardRef((e,r)=>{let{__scopeSlider:i,...s}=e,n=S(_,i);return(0,t.jsx)(u.Primitive.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...s,ref:r})});A.displayName=_;var E="SliderRange",L=r.forwardRef((e,i)=>{let{__scopeSlider:s,...a}=e,l=S(E,s),o=P(E,s),d=r.useRef(null),c=(0,n.useComposedRefs)(i,d),h=l.values.length,p=l.values.map(e=>U(e,l.min,l.max)),m=h>1?Math.min(...p):0,f=100-Math.max(...p);return(0,t.jsx)(u.Primitive.span,{"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,...a,ref:c,style:{...e.style,[o.startEdge]:m+"%",[o.endEdge]:f+"%"}})});L.displayName=E;var F="SliderThumb",R=r.forwardRef((e,i)=>{let s=b(e.__scopeSlider),[a,l]=r.useState(null),o=(0,n.useComposedRefs)(i,e=>l(e)),d=r.useMemo(()=>a?s().findIndex(e=>e.ref.current===a):-1,[s,a]);return(0,t.jsx)(D,{...e,ref:o,index:d})}),D=r.forwardRef((e,i)=>{var a,l,o,d,h;let p,m,{__scopeSlider:f,index:x,name:b,...v}=e,y=S(F,f),w=P(F,f),[j,k]=r.useState(null),N=(0,n.useComposedRefs)(i,e=>k(e)),T=!j||y.form||!!j.closest("form"),C=(0,c.useSize)(j),M=y.values[x],_=void 0===M?0:U(M,y.min,y.max),A=(a=x,(l=y.values.length)>2?`Value ${a+1} of ${l}`:2===l?["Minimum","Maximum"][a]:void 0),E=C?.[w.size],L=E?(o=E,d=_,h=w.direction,m=O([0,50],[0,p=o/2]),(p-m(d)*h)*h):0;return r.useEffect(()=>{if(j)return y.thumbs.add(j),()=>{y.thumbs.delete(j)}},[j,y.thumbs]),(0,t.jsxs)("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[w.startEdge]:`calc(${_}% + ${L}px)`},children:[(0,t.jsx)(g.ItemSlot,{scope:e.__scopeSlider,children:(0,t.jsx)(u.Primitive.span,{role:"slider","aria-label":e["aria-label"]||A,"aria-valuemin":y.min,"aria-valuenow":M,"aria-valuemax":y.max,"aria-orientation":y.orientation,"data-orientation":y.orientation,"data-disabled":y.disabled?"":void 0,tabIndex:y.disabled?void 0:0,...v,ref:N,style:void 0===M?{display:"none"}:e.style,onFocus:(0,s.composeEventHandlers)(e.onFocus,()=>{y.valueIndexToChangeRef.current=x})})}),T&&(0,t.jsx)(I,{name:b??(y.name?y.name+(y.values.length>1?"[]":""):void 0),form:y.form,value:M},x)]})});R.displayName=F;var I=r.forwardRef(({__scopeSlider:e,value:i,...s},a)=>{let l=r.useRef(null),o=(0,n.useComposedRefs)(l,a),c=(0,d.usePrevious)(i);return r.useEffect(()=>{let e=l.current;if(!e)return;let t=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set;if(c!==i&&t){let r=new Event("input",{bubbles:!0});t.call(e,i),e.dispatchEvent(r)}},[c,i]),(0,t.jsx)(u.Primitive.input,{style:{display:"none"},...s,ref:o,defaultValue:i})});function U(e,t,r){return(0,i.clamp)(100/(r-t)*(e-t),[0,100])}function O(e,t){return r=>{if(e[0]===e[1]||t[0]===t[1])return t[0];let i=(t[1]-t[0])/(e[1]-e[0]);return t[0]+i*(r-e[0])}}I.displayName="RadioBubbleInput";var B=e.i(153517);e.s(["Slider",0,function({className:e,defaultValue:i,value:s,min:n=0,max:a=100,thumbProps:l,trackJump:o=!1,orientation:d="horizontal",onValueChange:c,onPointerDown:u,onPointerMove:h,onPointerUp:p,onPointerCancel:m,...f}){let x=r.useMemo(()=>Array.isArray(s)?s:Array.isArray(i)?i:[n,a],[s,i,n,a]),g=r.useRef(null),b=r.useRef(null),v=r.useRef(new Set),y="vertical"===d,w=r.useCallback(e=>{let t=e.target;if(t?.closest?.('[data-slot="slider-thumb"]')==null&&!o){e.preventDefault(),v.current.add(e.pointerId),t?.hasPointerCapture?.(e.pointerId)&&t.releasePointerCapture(e.pointerId);return}"touch"===e.pointerType&&(g.current={x:e.clientX,y:e.clientY,id:e.pointerId},b.current=Array.isArray(s)?[...s]:null)},[o,s]),j=r.useCallback(e=>{if(v.current.has(e.pointerId)){e.preventDefault();let t=e.target;t?.hasPointerCapture?.(e.pointerId)&&t.releasePointerCapture(e.pointerId);return}let t=g.current;if(!t||t.id!==e.pointerId)return;let r=Math.abs(y?e.clientY-t.y:e.clientX-t.x),i=Math.abs(y?e.clientX-t.x:e.clientY-t.y);if(i>6&&i>r){g.current=null;let t=e.target;t?.hasPointerCapture?.(e.pointerId)&&t.releasePointerCapture(e.pointerId);let r=b.current;b.current=null,r&&Array.isArray(s)&&r.some((e,t)=>e!==s[t])&&c?.(r);return}r>6&&(g.current=null)},[y,s,c]),S=r.useCallback(e=>{e&&v.current.delete(e.pointerId),g.current=null,b.current=null},[]),N=r.useCallback(e=>{e&&v.current.delete(e.pointerId),g.current=null;let t=b.current;b.current=null,t&&Array.isArray(s)&&t.some((e,t)=>e!==s[t])&&c?.(t)},[s,c]);return(0,t.jsxs)(k,{"data-slot":"slider",defaultValue:i,value:s,min:n,max:a,orientation:d,onValueChange:c,onPointerDown:e=>{u?.(e),w(e)},onPointerMove:e=>{h?.(e),j(e)},onPointerUp:e=>{p?.(e),S(e)},onPointerCancel:e=>{m?.(e),N(e)},className:(0,B.cn)("relative flex w-full items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",y?"touch-pan-x":"touch-p
2an-y",e),...f,children:[(0,t.jsx)(A,{"data-slot":"slider-track",className:(0,B.cn)("bg-muted border-border-strong relative grow overflow-hidden rounded-full border shadow-xs data-[orientation=horizontal]:h-2.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-2.5"),children:(0,t.jsx)(L,{"data-slot":"slider-range",className:(0,B.cn)("bg-primary absolute rounded-full data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:x.length},(e,r)=>(0,t.jsx)(R,{"data-slot":"slider-thumb",...l,className:(0,B.cn)("border-primary bg-background ring-ring/50 relative block size-5 shrink-0 rounded-full border-2 shadow-md transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50")},r))]})}],103887)},291953,275813,298913,524536,7658,711451,379966,725747,416627,296228,134138,870020,756880,e=>{"use strict";e.s(["InlineTpSlForm",()=>e3],870020),e.s(["InlineCloseForm",()=>ef],725747),e.s(["useChainPositionHistory",()=>E],275813),e.s(["TpSlModalShell",()=>ec],379966);var t=e.i(394390),r=e.i(183023),i=e.i(489980),s=e.i(541078),n=e.i(181276),a=e.i(837299),l=e.i(671454),o=e.i(936456),d=e.i(204095),c=e.i(729418),u="Tabs",[h,p]=(0,s.createContextScope)(u,[n.createRovingFocusGroupScope]),m=(0,n.createRovingFocusGroupScope)(),[f,x]=h(u),g=r.forwardRef((e,r)=>{let{__scopeTabs:i,value:s,onValueChange:n,defaultValue:a,orientation:h="horizontal",dir:p,activationMode:m="automatic",...x}=e,g=(0,o.useDirection)(p),[b,v]=(0,d.useControllableState)({prop:s,onChange:n,defaultProp:a??"",caller:u});return(0,t.jsx)(f,{scope:i,baseId:(0,c.useId)(),value:b,onValueChange:v,orientation:h,dir:g,activationMode:m,children:(0,t.jsx)(l.Primitive.div,{dir:g,"data-orientation":h,...x,ref:r})})});g.displayName=u;var b="TabsList",v=r.forwardRef((e,r)=>{let{__scopeTabs:i,loop:s=!0,...a}=e,o=x(b,i),d=m(i);return(0,t.jsx)(n.Root,{asChild:!0,...d,orientation:o.orientation,dir:o.dir,loop:s,children:(0,t.jsx)(l.Primitive.div,{role:"tablist","aria-orientation":o.orientation,...a,ref:r})})});v.displayName=b;var y="TabsTrigger",w=r.forwardRef((e,r)=>{let{__scopeTabs:s,value:a,disabled:o=!1,...d}=e,c=x(y,s),u=m(s),h=k(c.baseId,a),p=N(c.baseId,a),f=a===c.value;return(0,t.jsx)(n.Item,{asChild:!0,...u,focusable:!o,active:f,children:(0,t.jsx)(l.Primitive.button,{type:"button",role:"tab","aria-selected":f,"aria-controls":p,"data-state":f?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:h,...d,ref:r,onMouseDown:(0,i.composeEventHandlers)(e.onMouseDown,e=>{o||0!==e.button||!1!==e.ctrlKey?e.preventDefault():c.onValueChange(a)}),onKeyDown:(0,i.composeEventHandlers)(e.onKeyDown,e=>{[" ","Enter"].includes(e.key)&&c.onValueChange(a)}),onFocus:(0,i.composeEventHandlers)(e.onFocus,()=>{let e="manual"!==c.activationMode;f||o||!e||c.onValueChange(a)})})})});w.displayName=y;var j="TabsContent",S=r.forwardRef((e,i)=>{let{__scopeTabs:s,value:n,forceMount:o,children:d,...c}=e,u=x(j,s),h=k(u.baseId,n),p=N(u.baseId,n),m=n===u.value,f=r.useRef(m);return r.useEffect(()=>{let e=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(e)},[]),(0,t.jsx)(a.Presence,{present:o||m,children:({present:r})=>(0,t.jsx)(l.Primitive.div,{"data-state":m?"active":"inactive","data-orientation":u.orientation,role:"tabpanel","aria-labelledby":h,hidden:!r,id:p,tabIndex:0,...c,ref:i,style:{...e.style,animationDuration:f.current?"0s":void 0},children:r&&d})})});function k(e,t){return`${e}-trigger-${t}`}function N(e,t){return`${e}-content-${t}`}S.displayName=j;var P=e.i(153517);e.s(["Tabs",0,function({className:e,...r}){return(0,t.jsx)(g,{"data-slot":"tabs",className:(0,P.cn)("flex flex-col gap-2",e),...r})},"TabsContent",0,function({className:e,...r}){return(0,t.jsx)(S,{"data-slot":"tabs-content",className:(0,P.cn)("flex-1 outline-none data-[state=active]:animate-in data-[state=active]:fade-in-0 data-[state=active]:duration-150 motion-reduce:animate-none",e),...r})},"TabsList",0,function({className:e,...r}){return(0,t.jsx)(v,{"data-slot":"tabs-list",className:(0,P.cn)("bg-surface-raised text-muted-foreground inline-flex h-[var(--control-h)] w-fit items-center justify-center rounded-control border border-border p-[3px]",e),...r})},"TabsTrigger",0,function({className:e,...r}){return(0,t.jsx)(w,{"data-slot":"tabs-trigger",className:(0,P.cn)("text-muted-foreground data-[state=active]:bg-surface-interactive data-[state=active]:text-foreground data-[state=active]:border-border-strong focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-chip border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focu
2s-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:text-disabled disabled:opacity-100 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r})}],291953);var T=e.i(799227),C=e.i(689384),M=e.i(938425);e.i(889723);var _=e.i(49332),A=e.i(643459);function E(e,t=!0){let i=e?.toBase58()??null,s=(0,r.useMemo)(()=>({walletAddress:i}),[i]),[n,a]=(0,r.useState)(null),[l,o]=(0,r.useState)(null);return(0,r.useEffect)(()=>{let e,r;if(!i||!t)return;let n=new T.PublicKey(i),l=!1;async function d(){if(!l&&"visible"===document.visibilityState){e=new AbortController,o(s);try{let t=[],r=new Map;for(let e=0;e<6;e++){let[i]=(0,M.getProfilePda)(n,e),s=i.toBase58();t.push(s),r.set(s,e)}let{trades:o,partial:d}=await (0,C.fetchJupiterTradesDirect)(i,t,e.signal);if(l)return;let c=o.map((e,t)=>{let s,n,a,l,o=function(e,t,r){let i=e._queriedAddress;if(i===t)return"Direct";let s=r.get(i);return void 0!==s?`Profile ${s+1}`:"Direct"}(e,i,r);return s=e.action.toLowerCase(),n="decrease"===s,a=e.txHash??"",l=e.createdTime??0,{id:`jup-${a||t}`,actionType:s,status:"completed",sequenceNumber:0,failureReason:null,tx1Signature:a,tx1Timestamp:l,collateralDeposited:n?null:e.collateralUsdDelta??null,platformFee:null,hadSwap:!1,swapSlippage:null,tx2Signature:a,tx2Timestamp:l,sizeDelta:e.size??null,sizeDeltaTokens:null,collateralDelta:e.collateralUsdDelta??null,jupiterFee:e.fee??null,interest:e.borrowFee??null,entryPrice:e.price??null,tx3Signature:n?a:null,tx3Timestamp:n?l:null,pnlRealized:e.pnl??null,hasProfit:e.pnl?parseFloat(e.pnl)>=0:null,userReceived:n?e.collateralUsdDelta??null:null,tx3PlatformFee:null,tx3SwapFee:null,tx3SweepSlippage:null,proOrderFee:null,collateralAfter:null,positionSizeAfter:null,postLiquidationPriceUsd:null,orderType:null,triggerPrice:null,triggerCondition:null,orderSizeUsd:null,orderSlippageBps:null,orderCreatedAt:null,orderWaitPrice:null,orderWaitDurationSecs:null,orderWorstPrice:null,orderRatchetSize:null,orderExecutionTriggerPrice:null,orderIndicatorConfig:null,orderThresholdValue:null,orderTriggerDelaySecs:null,orderDcaNumLegs:null,orderDcaLegNumber:null,orderDcaLegTrigger:null,orderDcaStartPrice:null,orderDcaEndPrice:null,orderDcaPriceLimit:null,orderDcaIntervalSeconds:null,positionKey:e.positionPubkey,owner:e.owner??"",side:e.side?"long"===e.side.toLowerCase()?"long":"short":null,asset:function(e){if(!e)return"SOL";let t=_.JUPITER_MARKETS[e];return t?t.symbol:(0,A.resolveMintSymbol)(e)??"SOL"}(e.mint),source:o}});c.sort((e,t)=>(t.tx1Timestamp??0)-(e.tx1Timestamp??0)),a({owner:s,actions:c,unverified:d})}catch{l||a(e=>({owner:s,actions:e?.owner===s?e.actions:[],unverified:!0}))}finally{l||(o(null),r=setTimeout(d,6e4))}}}return d(),()=>{l=!0,clearTimeout(r),e?.abort()}},[i,s,t]),{actions:n?.owner===s?n.actions:[],isLoading:t&&l===s,unverified:n?.owner!==s||n.unverified}}var L=e.i(710729);function F(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function R(){return"visible"===document.visibilityState}e.s(["useHistoryPaneDemand",0,function(e){let t=(0,L.useDesktopWorkspacePanelVisible)(),i=(0,r.useSyncExternalStore)(F,R,()=>!1);return e&&t&&i}],298913);var D=e.i(13734),I=e.i(175701),U=e.i(514049),O=e.i(989714);e.s(["usePhoenixDirectHistory",0,function(e,t=!0){let i=(0,U.useQueryClient)(),s=t&&!!e,n=["phoenix-direct-history",e],a=(0,I.useInfiniteQuery)({queryKey:n,queryFn:({pageParam:t,signal:r})=>(0,C.fetchPhoenixDirectHistory)(e,t,100,r),initialPageParam:void 0,getNextPageParam:e=>e.hasMore?e.nextCursor??void 0:void 0,enabled:e=>s&&!(e.state.error instanceof C.PhoenixDirectHistoryReadError&&(e.state.error.retryAt>Date.now()||!D.focusManager.isFocused())),staleTime:3e4,refetchInterval:C.PHOENIX_DIRECT_HISTORY_RETRY_MS,refetchOnWindowFocus:!0,retry:!1}),l=a.error instanceof C.PhoenixDirectHistoryReadError?a.error.retryAt:0,o=(0,O.useTickingNowSecs)(s&&0!==l);(0,r.useEffect)(()=>{let t=i.getQueryCache(),r=["phoenix-direct-history",e],s=t.find({queryKey:r,exact:!0});if(!s)return;let n=()=>
2{if("idle"===s.state.fetchStatus||s.isActive())return;let e=s.promise;queueMicrotask(()=>{t.find({queryKey:r,exact:!0})!==s||s.promise!==e||"idle"===s.state.fetchStatus||s.isActive()||s.cancel({revert:!0})})},a=t.subscribe(e=>{e.query===s&&("observerRemoved"===e.type||"observerOptionsUpdated"===e.type)&&n()});return n(),()=>{a(),n()}},[i,s,e]),(0,r.useEffect)(()=>{if(!s||!l||l>Date.now()||!D.focusManager.isFocused())return;let t=i.getQueryState(["phoenix-direct-history",e]);t?.fetchStatus==="idle"&&t.error instanceof C.PhoenixDirectHistoryReadError&&t.error.retryAt<=Date.now()&&a.refetch({cancelRefetch:!1})},[i,s,e,l,o,a.refetch]);let d=()=>{let e=i.getQueryState(n);return s&&D.focusManager.isFocused()&&e?.fetchStatus!=="fetching"&&!(e?.error instanceof C.PhoenixDirectHistoryReadError&&e.error.retryAt>Date.now())},c=(0,r.useMemo)(()=>a.data?.pages.flatMap(e=>e.data)??[],[a.data]),u=(0,r.useMemo)(()=>a.data?.pages.flatMap(e=>e.collateralEvents??[])??[],[a.data]);return{...a,requestBlocked:!s||a.isFetching||Math.ceil(l/1e3)>o,refresh:()=>{d()&&a.refetch()},loadMore:()=>{d()&&a.hasNextPage&&a.fetchNextPage({cancelRefetch:!1})},actions:c,collateralEvents:u}}],524536);var B=e.i(43690),z=e.i(242132);async function $(){let e=await fetch("https://api.imperial.space/api/v1/status",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`Status fetch failed: ${e.status}`);return e.json()}let V=(0,r.createContext)({status:null,overallHealth:"down",isLoading:!0,isError:!1});e.s(["ApiHealthProvider",0,function({children:e}){let{data:r,isLoading:i,isError:s}=(0,B.useQuery)({queryKey:["api-status"],queryFn:$,staleTime:3e4,refetchInterval:3e4,retry:1,retryDelay:3e3,placeholderData:z.keepPreviousData}),n=function(e){if(!e||"healthy"!==e.db)return"down";let t=!e.indexer||"healthy"===e.indexer.status,r=!e.orderBot||"healthy"===e.orderBot.status;return t&&r?"healthy":"degraded"}(r);return(0,t.jsx)(V.Provider,{value:{status:r??null,overallHealth:n,isLoading:i,isError:s},children:e})},"useApiHealth",0,function(){return(0,r.useContext)(V)}],7658);var H=e.i(942553),W=e.i(116082),q=e.i(142298),K=e.i(944475),G=e.i(122097),Y=e.i(299959);function X(e,t=Date.now()/1e3){return Math.max(0,e.collateralUsd-function(e,t=Date.now()/1e3){return Math.min((e.heldProfit??[]).filter(e=>t<e.until&&e.amountUsd>0).reduce((e,t)=>e+t.amountUsd,0),Math.max(0,e.collateralUsd-(e.depositBasisUsd??e.collateralUsd)))}(e,t))}function Q(e,t=Date.now()/1e3){return!1===e.primeBound&&(null!==e.seatAsset||!1===e.retainsCollateral)&&0===e.openPositions&&0===e.grossNotionalUsd&&Number.isFinite(e.collateralUsd)&&X(e,t)>0}e.s(["SunrisePayoutSync",0,function(){let e=(0,H.useTranslations)("positions"),i=(0,Y.useFormatters)(),{publicKey:s}=(0,q.useUnifiedWallet)(),n=s?.toBase58()??null,{data:a,isError:l}=(0,K.useSunrisePayouts)(n),o=(0,r.useRef)(void 0);(0,r.useEffect)(()=>{if(!a||a.wallet!==n){o.current=void 0;return}(function(e,t,r=Date.now()/1e3){return!!e&&e.wallet===t.wallet&&!(t.slot<e.slot)&&e.accounts.some(e=>Q(e,r)&&t.accounts.some(t=>t.address===e.address&&t.collateralUsd<e.collateralUsd&&0===X(t,r)&&0===t.openPositions&&0===t.grossNotionalUsd))})(o.current,a)&&((0,G.requestProfileBalancesBurstRefresh)(),W.toast.success(e("payoutReceived"))),o.current=a},[a,n,e]);let d=a?.wallet===n?a.accounts.filter(e=>Q(e)):[];if(!n||0===d.length)return null;let c=d.reduce((e,t)=>e+X(t),0);return(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"shrink-0 border-b border-border bg-muted/40 px-4 py-3 text-sm",children:[(0,t.jsx)("p",{className:"font-medium",children:e("payoutPendingTitle")}),(0,t.jsx)("p",{className:"text-muted-foreground",children:e("payoutPendingBody",{amount:i.number(c)})}),l&&(0,t.jsx)("p",{className:"mt-1 text-muted-foreground",children:e("payoutStatusUnavailable")})]})}],711451);var J=e.i(494286),Z=e.i(259048),ee=e.i(670374),et=e.i(26826),er=e.i(752717),ei=e.i(546642),es=e.i(665757),en=e.i(984457),ea=e.i(457058),el=e.i(623075);function eo({title:e,lifecycle:r,symbol:i,iconSrc:s,leverage:n,livePrices:a,subtitle:l}){let o=(0,H.useTranslations)("positions"),d=(0,Y.useFormatters)(),c="long"===r.side,u=(0,et.parseRawValue)(r.entryPrice),h=(0,ee.getMarketMintFromAsset)(r.asset,r.underwriter),p=h?a?.[h]:void 0,m=p??((0,et.parseRawValue)(r.markPrice)||u),f=p??m,x=(0,et.parseRawValue)((0,ee.displayLiquidationPriceForLifecycle)(r)),g=(0,et.phoenixCashBasisBreakeven)(r)??(0,et.parseRawValue)(r.breakevenPriceUsd),b=(0,et.parseRawValue)(r.liqTriggerPriceUsd),v=(0,et.parseRawValue)(r.liqBandPriceUsd),y=null!=n?Math.round(parseFloat(String(n))):0;return(0,t.jsxs)("div",{className:"flex flex-col w-full",children:[(0,t.jsx)(el.DialogTitle,{className:"text-lg font-semibold text-foreground",children:e}),(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-2.5",children:[s&&(0,t.jsx)(ea.default,{src:s,alt:i,width:22,height:22,className:"rounded-full",unoptimized:!0}),(0,t.jsxs)("span",{className:"text-base font-semibold text-foreground",children:[i," PERP"]}),(0,t.jsxs)("span",{className:(0,P.cn)("text-[11px] font-medium px-2 py-0.5 rounded",c?"bg-side-long/15 text-side-long":"bg-side-short/15 text-side-short"),children:[o(c?"long":"short"),y>0?` ${y}X`:""]})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 pt-3 text-[13px]",children:[(0,t.jsx)(ed,{label:o("avgPriceUsd"),value:d.number(u)}),(0,t.jsx)(ed,{label:o("lastPriceUsd"),value:d.number(f)}),(0,t.jsx)(ed,{label:o("markPriceUsd"),value:d.number(m)}
2),(0,t.jsx)(ed,{label:o("estLiqPriceUsd"),value:x>0?d.number(x):"—"}),b>0&&(0,t.jsx)(ed,{label:o("liqEstFillUsd"),value:d.number(b)}),v>0&&(0,t.jsx)(ed,{label:o("liqWorstFillUsd"),value:d.number(v)}),g>0&&(0,t.jsx)(ed,{label:o("breakevenUsd"),value:d.number(g)})]}),l&&(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug pt-2",children:l})]})}function ed({label:e,value:r}){return(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-label-muted",children:e}),(0,t.jsx)("span",{className:"text-foreground font-medium font-mono tabular-nums",children:r})]})}function ec({title:e,lifecycle:r,symbol:i,iconSrc:s,leverage:n,livePrices:a,subtitle:l,tab:o,onTabChange:d,children:c,confirmLabel:u,onCancel:h,onConfirm:p,submitting:m,disabled:f,tabsDisabled:x,footerExtra:g}){let b=(0,H.useTranslations)("positions"),v=(0,H.useTranslations)("common");return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsx)("div",{className:"px-4 pt-4 pb-3 border-b border-border",children:(0,t.jsx)(eo,{title:e,lifecycle:r,symbol:i,iconSrc:s,leverage:n,livePrices:a,subtitle:l})}),d&&(0,t.jsx)("div",{className:"flex items-center gap-6 px-4 pt-3 border-b border-border",children:["entire","partial"].map(e=>(0,t.jsxs)("button",{disabled:m||x,onClick:()=>d(e),className:(0,P.cn)("relative pb-2.5 text-sm font-semibold transition-colors",o===e?"text-foreground":"text-label-muted hover:text-secondary-foreground"),children:["entire"===e?b("entirePosition"):b("partialPosition"),o===e&&(0,t.jsx)("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full"})]},e))}),(0,t.jsx)("div",{className:"px-4 py-4 flex flex-col gap-4 max-h-[55vh] overflow-y-auto",children:c}),(0,t.jsxs)("div",{className:"px-4 py-3 border-t border-border flex flex-col gap-2",children:[g,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-3",children:[(0,t.jsx)("button",{onClick:h,disabled:m,className:"h-8 px-6 text-[13px] font-medium rounded-md border border-border text-secondary-foreground hover:bg-surface-interactive hover:text-foreground disabled:opacity-50",children:v("cancel")}),(0,t.jsxs)("button",{onClick:p,disabled:m||f,className:"h-8 px-6 text-[13px] font-semibold rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center min-w-[130px]",children:[m&&(0,t.jsx)(en.Spinner,{}),u]})]})]})]})}var eu=e.i(172581),eh=e.i(91525),ep=e.i(275683),em=e.i(227456);function ef({lifecycle:e,symbol:r,iconSrc:i,leverage:s,livePrices:n,isClosing:a,onClose:l,onSubmit:o,otherOpenLegs:d=0,onPositionChange:c,onOrderSubmitted:u}){let h=(0,H.useTranslations)("positions"),p=(0,H.useTranslations)("terms"),m=(0,Y.useFormatters)(),f="sunrise"===e.underwriter||"7"===e.underwriter,{data:x}=(0,J.useSunriseMargin)(e.wallet,e.profileIndex??0,e.sunriseMarginSeat??null,f&&void 0!==e.sunriseMarginSeat),g=x?.primeBound===!0,b=(0,et.parseRawValue)(e.collateralUsd),v=(0,et.parseRawValue)(e.entryPrice),y=(0,ee.getMarketMintFromAsset)(e.asset,e.underwriter),w=(y?n?.[y]:void 0)??((0,et.parseRawValue)(e.markPrice)||v),j=g?null:(0,et.calculateLockInitialsPercent)(e,w),{sizePercent:S,amountInput:k,amountUnit:N,canToggleUnit:T,handleSizePercent:C,handleAmountTyped:M,toggleAmountUnit:_}=(0,eu.useCloseAmount)(e),A=(0,eh.useLimitClose)(e,w),E=(0,eh.canPlaceLimitClose)(e),L=E&&"limit"===A.mode,F=S/100,R=b*F,D=(0,et.netCapitalForDisplay)(e),I=(0,et.estimateClosePnl)(e,{execPrice:L?A.execPrice:w,closeFraction:F}),U=I?(0,et.getEstimatedReturn)(R,I):R,O=I?(0,et.getDisplayPnl)(I,R,null!==D?D*F:null):0,B=I?I.total:null,z=null!==B&&Math.abs((0,et.sumRealizedPnlFromActions)(e))>=1&&Math.abs(O-B)>=.01,$=(0,ep.closeProceedsDestination)({marginMode:e.directVenue?.marginMode,sizePercent:S,otherOpenLegs:d}),V=L?A.missingLabel(S):(0,ei.pickMissingLabel)([[S<=0,h("setSize")]]),W=async()=>{if(!L)return void o(S);let t=e.tpslOrders?.length??0;await A.submit(S)&&(u?.(t),l(),c?.())};return(0,t.jsxs)(ec,{title:h("closePositionTitle"),lifecycle:e,symbol:r,iconSrc:i,leverage:s,livePrice
2s:n,confirmLabel:V??(L?h("limitCloseAction"):h("closeAction")),onCancel:l,onConfirm:W,submitting:L?A.submitting:a,disabled:null!==V,children:[g&&(0,t.jsx)("p",{className:"text-xs text-label-muted",children:"Proceeds from a partial close stay in this position until it is fully closed and Prime is repaid."}),E&&(0,t.jsx)("div",{className:"flex items-center gap-0.5 self-start rounded-md border border-border-strong bg-surface-raised p-0.5",children:["market","limit"].map(e=>(0,t.jsx)("button",{onClick:()=>A.setMode(e),className:(0,P.cn)("px-3 py-1 text-xs font-medium rounded transition-colors",A.mode===e?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-foreground"),children:"market"===e?h("closeTypeMarket"):h("closeTypeLimit")},e))}),(0,t.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted w-7",children:p("size.abbrev")}),(0,t.jsx)("input",{type:"range",...em.THUMB_ONLY_SLIDER,min:1,max:100,value:S,onChange:e=>C(parseInt(e.target.value)),className:(0,P.cn)(em.RANGE_SLIDER_CLASSES,"flex-1 [&::-webkit-slider-thumb]:bg-primary")}),(0,t.jsxs)("span",{className:"text-xs text-foreground w-10 font-mono tabular-nums",children:[S,"%"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[[25,50,75,100].map(e=>(0,t.jsxs)("button",{onClick:()=>C(e),className:(0,P.cn)("px-2 py-0.5 text-xs rounded font-mono tabular-nums",S===e?"bg-surface-interactive text-foreground":"text-muted-foreground hover:text-muted-foreground"),children:[e,"%"]},e)),j&&(0,t.jsx)("button",{onClick:()=>C(j.percent),className:(0,P.cn)("px-2 py-0.5 text-xs rounded",S===j.percent?"bg-cyan-500/20 text-cyan-400 border border-cyan-500/30":"text-cyan-600 hover:text-cyan-400 border border-transparent"),children:h("initialCapitalPercent",{percent:j.percent})})]}),j&&S===j.percent&&(0,t.jsx)("div",{className:"text-[10px] text-cyan-400/70",children:h("initialCapitalSplit",{initial:m.number(j.receiving),profit:m.number(j.remaining)})})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:h("amountLabel")}),(0,t.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2",children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",value:k,onChange:e=>M(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),T?(0,t.jsx)("button",{type:"button",onClick:_,className:"text-xs text-muted-foreground ml-2 px-2 py-0.5 rounded border border-border-strong bg-surface hover:text-foreground hover:border-border-strong transition-colors",title:h("switchUnit",{unit:"usd"===N?e.asset:"USDC"}),children:"usd"===N?"USDC":e.asset}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USDC"})]})]}),L&&(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:h("limitClosePriceLabel")}),(0,t.jsxs)("button",{type:"button",onClick:()=>A.handlePriceTyped(String(w)),className:"text-[11px] text-label-muted hover:text-foreground transition-colors",children:[h("priceRefMark")," ",(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",m.number(w)]})]})]}),(0,t.jsxs)("div",{className:(0,P.cn)("flex items-center bg-surface-raised border rounded-lg px-3 py-2",A.hasPrice&&!A.isValidPrice?"border-destructive/60":"border-border-strong"),children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",value:A.priceInput,onChange:e=>A.handlePriceTyped(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:"0.00",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USD"})]}),A.isValidPrice&&(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:(0,P.cn)("text-[10px] font-medium px-1.5 py-0.5 rounded","tp"===A.leg?"bg-side-long/15 text-side-long":"bg-side-short/15 text-side-short"),children:"tp"===A.leg?h("takeProfit"):h("stopLoss")}),(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:h(A.movesUp?"limitCloseRisesTo":"limitCloseFallsTo",{percent:S,asset:r,price:m.number(A.price)})})]})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs",children:[(0,t.jsx)("span",{className:"text-label-muted",children:$?.kind==="account"?h("settles"):h("receiving")}),(0,t.jsxs)("span",{className:(0,P.cn)("font-mono tabular-nums",U>=0?"text-cyan-400":"text-destructive"),children:["$",m.number(Math.max(0,U))," USDC"]})]}),$&&(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:$.note})]}),(0,t.jsx)(er.CloseFeeBreakdown,{lifecycle:e,sizePercent:S,compact:!0}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs",children:[(0,t.jsx)("span",{className:"text-label-muted",children:h("netPnl")}),(0,t.jsxs)("span",{className:(0,P.cn)("font-mono tabular-nums",(0,Z.pnlColor)(O)),children:[O>=0?"+":"",m.number(O)," USD"]})]}),z&&null!==B&&(0,t.jsxs)("div",{className:"flex items-center justify-between text-[11px] ml-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:h("legPnl")}),(0,t.jsxs)("span",{className:(0,P.cn)("font-mono tabular-nums",(0,Z.pnlColorDim)(B)),children:[B>=0?"+":"",m.number(B)," USD"]})]}),L&&A.isValidPrice&&(0,t.jsx)("span",{className:"text-[11px] text-label-muted",children:h("limitCloseEstimateNote")})]})]})}e.i(875574);let ex=new Map,eg=new Set,eb=new Set;function ev(e){return eb.add(e),()=>{eb.delete(e)}}let ey=()=>{for(let e of eb)e()},ew=(e,t)=>`imperial:tpsl-attempt:v1:${JSON.stringify([e,t])}`;function ej(){try{return"u"<typeof sessionStorage?void 0:sessionStorage}catch{return}}function eS(e,t){let r={...t,persistence:"memory"};try{let t=eg.has(e)?void 0:ej();t&&(t.setItem(e,JSON.stringify({...r,persistence:"session"})),r.persistence="session")}catch{}return ex.set(e,r),ey(),r}function ek(e,t){let r,i=ew(e,t),s=ex.get(i);if(s)return s;let n=ej();if(!n)return eg.add(i),null;if(eg.has(i))return null;try{r=n.getItem(i)}catch{return eg.add(i),null}if(null===r)return null;try{let s=JSON.parse(r);if(1!==s.version||s.scope!==e||s.leg!==t||"string"!=typeof s.attemptId||!["sending","submitted","uncertain"].includes(s.status)||!s.intent||!Number.isFinite(s.intent.triggerPrice)||!Number.isFinite(s.intent.closeBps)||!Number.isFinite(s.intent.sizeUsd)||!Array.isArray(s.intent.baselineOrderPdas))throw Error("Invalid attempt");return s.persistence="session","sending"===s.status&&(s.status="uncertain"),ex.set(i,s),s}catch{let r={version:1,attemptId:"unreadable",scope:e,leg:t,status:"uncertain",intent:null,persistence:"session"};return ex.set(i,r),r}}function eN(e,t,r){if(ek(e,t))return null;let i="u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return eS(ew(e,t),{version:1,attemptId:i,scope:e,leg:t,status:"sending",intent:r,persistence:"memory",startedAt:new Date().toISOString()})}function eP(e,t,r,i,s){let n=ek(e,t);n?.attemptId===r&&eS(ew(e,t),{...n,status:i,...s?{signature:s}:{}})}function eT(e,t,r){if(ek(e,t)?.attemptId!==r)return!1;let i=ew(e,t);try{eg.has(i)||ej()?.removeItem(i)}catch{return!1}return ex.delete(i),ey(),!0}let eC=e=>Math.floor(1e9*Number(e)),eM=e=>Math.floor(1e6*Number(e)),e_=new Map,eA=new Map;function eE(e,t,r){return eA.get(`${ew(e,t)}:reviewed:${r}`)}function eL(e,t,r){let i=ek(e,t);if(!i||i.attemptId!==r||"sending"===i.status||i.ownerReviewedAt)return!1;let s=ew(e,t),n=`${s}:reviewed:${r}`,a=JSON.stringify({...i,recovery:"owner_review",recoveredAt:new Date().toISOString()});e_.set(n,a);let l=eg.has(s)?void 0:ej(),o=!1;if(l)try{l.setItem(n,a),o=!0}catch{}if(i.intent?.kind==="cancel"){let e=eS(s,{...i,ownerReviewedAt:new Date().toISOString()});return eA.set(n,o&&"session"===e.persistence?"session":"memory"),!0}if(l)try{l.removeItem(s)}catch{return!1}else if("session"===i.persistence)return!1;return eA.set(n,o?"session":"memory"),ex.delete(s),ey(),!0}e.s(["beginTpSlAttempt",0,eN,"getTpSlAttempt",0,ek,"getTpSlRecoveryPersistence",0,eE,"reconcileTpSlAttempt",0,function(e,t,r){let i=ek(e,t);if(!i?.intent||"sending"===i.status)return!1;let s=i.intent;if("cancel"===s.kind){let n=r.some(e=>e.orderPda===s.targetOrderPda),a="submitted"===i.status&&r.some(e=>e.orderPda===s.targetOrderPda&&"cancelled"===e.status),l=!!i.ownerReviewedAt&&!n;return(a||l)&&eT(e,t,i.attemptId)}return(!!s.targetOrderPda||!!i.signature)&&1===r.filter(e=>!(!e.orderPda||![t,`private_${t}`].includes(e.orderType)||e.status&&!["pending","open","active"].includes(e.status)||s.parentOrderPda&&e.parentOrderPda!==s.parentOrderPda||(s.targetOrderPda?e.orderPda!==s.targetOrderPda:s.baselineOrderPdas.includes(e.orderPda)))&&
2(!!s.targetOrderPda||i.signature===e.creationSignature)&&eC(e.triggerPriceUsd)===eC(s.triggerPrice)&&("number"!=typeof e.closeBps||!(e.closeBps>0)||e.closeBps===s.closeBps)&&eM(e.sizeUsd)===eM(s.sizeUsd)).length&&eT(e,t,i.attemptId)},"recoverTpSlAttempt",0,eL,"rejectTpSlAttempt",0,eT,"settleTpSlAttempt",0,eP,"subscribeTpSlAttempts",0,ev],416627);let eF=new WeakMap;function eR(e){let t=ek(e,"sl");if(!t)return null;let r=t.intent?.advanced;if(r?.version===1&&["create","update"].includes(r.operation)&&"string"==typeof r.orderType&&r.parameters&&"object"==typeof r.parameters&&Object.values(r.parameters).every(e=>void 0===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)))return t;let i=eF.get(t);return i||(i={...t,intent:null},eF.set(t,i)),i}async function eD({scope:e,intent:t,send:r,wasRejected:i,isCurrent:s}){if(!s())return null;let n=eN(e,"sl",t);if(!n)return null;try{let t=await r();return t?eP(e,"sl",n.attemptId,"submitted",t):!0===i()?eT(e,"sl",n.attemptId):eP(e,"sl",n.attemptId,"uncertain"),s()?t:null}catch(t){throw eP(e,"sl",n.attemptId,"uncertain"),t}}let eI=e=>Math.floor(1e6*Number(e)),eU=e=>Math.floor(1e9*Number(e));function eO(e){let{publicKey:r}=(0,q.useUnifiedWallet)(),i=r?.toBase58()??"";return(0,t.jsx)(eB,{...e,activeWallet:i},i)}function eB({scope:e,leg:i,attempt:s,wallet:n,market:a,onRecovered:l,activeWallet:o,label:d=i.toUpperCase(),intentDetails:c}){let u=(0,H.useTranslations)("positions"),h=(0,A.resolveMintSymbol)(a)??a,[p,m]=(0,r.useState)(!1),[f,x]=(0,r.useState)(!1),[g,b]=(0,r.useState)(!1);return s.ownerReviewedAt?(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:u("tpslCancelReviewed")}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button",className:"text-xs text-primary underline underline-offset-2",disabled:"sending"===s.status||o!==n,onClick:()=>{x(!1),b(!1),m(!0)},children:u("tpslReviewAttempt",{leg:d})}),(0,t.jsx)(el.Dialog,{open:p,onOpenChange:m,children:(0,t.jsxs)(el.DialogContent,{className:"max-w-md",children:[(0,t.jsx)(el.DialogHeader,{children:(0,t.jsx)(el.DialogTitle,{children:u("tpslRecoveryTitle",{leg:d})})}),(0,t.jsx)("p",{className:"text-sm",children:u("tpslRecoveryWarning")}),(0,t.jsxs)("div",{className:"rounded border border-border p-3 text-xs space-y-2",children:[(0,t.jsxs)("p",{className:"break-all",children:[h," · ",d]}),h!==a&&(0,t.jsx)("p",{className:"break-all text-muted-foreground",children:a}),(0,t.jsx)("p",{className:"break-all",children:n}),c??(s.intent?(0,t.jsx)("p",{children:u("tpslRecoveryIntent",{price:String(s.intent.triggerPrice),amount:String(s.intent.sizeUsd),percent:String(s.intent.closeBps/100)})}):(0,t.jsx)("p",{children:u("tpslRecoveryDetailsUnavailable")})),s.startedAt&&(0,t.jsx)("p",{children:s.startedAt}),s.signature&&(0,t.jsx)("a",{className:"block break-all text-primary underline",href:`https://solscan.io/tx/${encodeURIComponent(s.signature)}`,target:"_blank",rel:"noopener noreferrer",children:s.signature})]}),(0,t.jsxs)("label",{className:"flex items-start gap-2 text-xs",children:[(0,t.jsx)("input",{type:"checkbox",checked:f,onChange:e=>x(e.target.checked),className:"mt-0.5"}),(0,t.jsx)("span",{children:u("tpslRecoveryAcknowledge")})]}),g&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:u("tpslRecoveryFailed")}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-end gap-3",children:[(0,t.jsx)("button",{type:"button",className:"rounded border border-border px-3 py-2 text-xs",onClick:()=>m(!1),children:u("tpslKeepPaused")}),(0,t.jsx)("button",{type:"button",className:"rounded bg-primary px-3 py-2 text-xs text-primary-foreground disabled:opacity-50",disabled:!f||o!==n,onClick:()=>{let t=ek(e,i);if(f&&o===n&&t?.attemptId===s.attemptId&&t.scope===e&&t.leg===i&&"sending"!==t.status){if(!eL(e,i,s.attemptId))return void b(!0);"memory"===eE(e,i,s.attemptId)&&W.toast.info(u("tpslRecoveryMemoryOnly")),m(!1),x(!1),l()}},children:u("tpslClearHold")})]})]})})]})}e.s(["TpSlAttemptRecovery",0,eO],296228);var ez=e.i(1169),e$=e.i(873029),eV=e.i(475274),eH=e.i(734195),eW=e.i(936548),eq=e.i(858007),eK=e.i(821043),eG=e.i(626074),eY=e.i(268680),eX=e.i(637740),eQ=e.i(727322),eJ=e.i(905843),eZ=e.i(459),e0=e.i(596331);function e1(e,t,r,i){if(i)return e>t&&e<t+r;let s=t-r;return s>=BigInt(0)&&e<t&&e>s}function e2(e){return BigInt(Math.floor(1e9*e))}function e5(e){return"ratchet"===e||"fib_ratchet"===e?"ratchet":e.startsWith("dca_")?"dca_close":"rsi"===e||e.startsWith("indicator")?"rsi":null}function e3(e){let{publicKey:r}=(0,q.useUnifiedWallet)(),i=r?.toBase58()??"",s=e.lifecycle,n=JSON.stringify([i,s.wallet,s.positionPda,s.asset,s.profileIndex,s.underwriter,s.side,s.sunriseMarginSeat,e.editOrder?.orderPda,e.defaultOrderType]);return(0,t.jsx)(e4,{...e,activeWallet:i},n)}
2function e4({lifecycle:e,activeWallet:i,livePrices:s,orderbookMidPrice:n,editOrder:a,defaultOrderType:l,title:o,subtitle:d,onClose:c,onPositionChange:u,onOrderSubmitted:h,onOrderTypeChange:p,onCancelPassthroughOrder:m,onCancelJupiterOrder:f}){var x,g;let b,v,y,w,j,S,k,N,T,C,M,_,A,E,L,F,R,D,I,U,O,B=(0,H.useTranslations)("positions"),z=(0,H.useTranslations)("common"),$=(0,H.useTranslations)("trading"),V=(0,Y.useFormatters)(),q=(0,Y.useDecimalSeparator)(),[K,G]=(0,r.useState)(a?e5(a.orderType)??("tp"===a.orderType?"tp":"sl"):l??"tp"),[X,Q]=(0,r.useState)(""),[J,er]=(0,r.useState)("price"),ea=t=>{if(a||"tp"!==t&&"sl"!==t)return 100;let r=(0,et.parseRawValue)(e.sizeUsd);if(r<=0)return 100;let i="tp"===t?["tp","private_tp"]:["sl","private_sl"],s=(e.tpslOrders??[]).filter(e=>i.includes(e.orderType));return s.some(e=>(e.closeBps??0)>=1e4)?0:Math.max(0,Math.min(100,Math.round(100-s.reduce((e,t)=>e+parseFloat(t.sizeUsd||"0"),0)/r*100)))},el=e=>Math.max(1,Math.min(1e4,Math.round(100*e))),[eo,ed]=(0,r.useState)(()=>ea(a?.orderType==="sl"?"sl":a?.orderType==="ratchet"?"ratchet":l??"tp")),[eu,eh]=(0,r.useState)(!1),[ep,ef]=(0,r.useState)(!1),ex=(0,r.useRef)(!1),[eg,eb]=(0,r.useState)(!1),[ey,ew]=(0,r.useState)("entire"),[ej,eS]=(0,r.useState)(""),[ek,eN]=(0,r.useState)(""),[eP,eC]=(0,r.useState)(""),[eM,e_]=(0,r.useState)(""),[eA,eE]=(0,r.useState)(!1),[eL,eF]=(0,r.useState)(""),eB=(0,r.useRef)(null),[e3,e8]=(0,r.useState)(3),[e9,e7]=(0,r.useState)(0),[te,tt]=(0,r.useState)("30"),[tr,ti]=(0,r.useState)(!1),[ts,tn]=(0,r.useState)(""),[ta,tl]=(0,r.useState)(""),[to,td]=(0,r.useState)(""),[tc,tu]=(0,r.useState)(5),[th,tp]=(0,r.useState)(""),[tm,tf]=(0,r.useState)(0),[tx,tg]=(0,r.useState)("price"),[tb,tv]=(0,r.useState)(""),[ty,tw]=(0,r.useState)(3600),[tj,tS]=(0,r.useState)(""),[tk,tN]=(0,r.useState)("0"),[tP,tT]=(0,r.useState)("0"),tC=(0,r.useMemo)(()=>Math.max(0,3600*(parseInt(tk)||0)+60*(parseInt(tP)||0)),[tk,tP]),{createTriggerOrder:tM,createPassthroughOrder:t_,updateTriggerOrder:tA,updatePassthroughOrder:tE,createRatchetOrder:tL,createIndicatorCloseOrder:tF,createDcaCloseOrder:tR,createDcaTimeCloseOrder:tD,createDcaRatchetCloseOrder:tI,wasLastErrorRejection:tU}=(0,eQ.useTradeActions)(),tO=!!e.wallet&&i===e.wallet,tB=(0,r.useRef)(null);(0,r.useLayoutEffect)(()=>(tB.current={},()=>{tB.current=null}),[]);let tz=(0,r.useRef)(!1),[t$,tV]=(0,r.useState)(!1),tH=e5(a?.orderType??K),tW=!!a&&!!e5(a.orderType)&&!(a.orderPda&&"ratchet"===a.orderType&&"imperial_passthrough"===a.source),tq=tH?(x=(0,eQ.underwriterToNum)(e.underwriter),g=a?.orderPda,JSON.stringify(["advanced-position-close",e.wallet,e.positionPda,e.asset,e.profileIndex,x,e.side,e.sunriseMarginSeat??null,tH,g??"create"])):"",tK=(0,r.useSyncExternalStore)(ev,()=>tq?eR(tq):null,()=>null);(0,r.useEffect)(()=>{tq&&function(e,t){let r=eR(e),i=r?.intent;if(!r||"submitted"!==r.status||!r.signature||!i?.advanced)return!1;let{advanced:s}=i;return 1===s.version&&!!s.parameters&&!!Array.isArray(i.baselineOrderPdas)&&1===t.filter(e=>{if(!e.orderPda||e.orderType!==s.orderType||eI(e.sizeUsd)!==eI(i.sizeUsd)||i.closeBps>0&&e.closeBps!==i.closeBps)return!1;if("create"===s.operation)return!i.baselineOrderPdas.includes(e.orderPda)&&e.creationSignature===r.signature;if(e.orderPda!==i.targetOrderPda||"ratchet"!==s.orderType)return!1;let t=s.parameters;return e.closeBps===i.closeBps&&eU(e.worstPriceUsd??0)===eU(Number(t.worstPrice))&&eU(e.ratchetSizeUsd??0)===eU(Number(t.ratchetSize))&&(void 0===t.stopTriggerPrice||eU(e.stopTriggerPriceUsd??0)===eU(Number(t.stopTriggerPrice)))}).length&&eT(e,"sl",r.attemptId)}(tq,e.tpslOrders??[])&&tV(!0)},[tq,e.tpslOrders,tK]);let tG=async(t,r,i)=>{if(!tq||!tO||!tB.current||tW)return null;let s=tB.current,n=()=>tB.current===s,l={};for(let[e,t]of Object.entries({...r,...r.proOrderUpdate})){if("number"==typeof t&&!Number.isFinite(t))return W.toast.error(B("advancedCloseInvalidValues")),null;("string"==typeof t||"boolean"==typeof t||"number"==typeof t)&&(l[e]=t)}let o=await eD({scope:tq,intent:{triggerPrice:r.triggerPrice??0,sizeUsd:r.sizeUsd??0,closeBps:r.closeBps??0,targetOrderPda:a?.orderPda,baselineOrderPdas:(e.tpslOrders??[]).flatMap(e=>e.orderPda?[e.orderPda]:[]),advanced:{version:1,orderType:t,operation:a?"update":"create",parameters:l}},send:i,wasRejected:tU,isCurrent:n});return o&&n()&&tV(!0),o},tY=e=>e.proOrderUpdate?.type==="ratchet"?tG("ratchet",e,()=>tE(e)):tE(e),tX=!!a,tQ="long"===e.side,tJ=(0,r.useMemo)(()=>ea(K),[K,e.tpslOrders,e.sizeUsd,tX]),tZ=!tX&&("tp"===K||"sl"===K)&&tJ<=0,t0=!!a?.orderPda&&("jupiter_native"===a.source&&!!f||"jupiter_native"!==a.source&&void 0!==a.profileIndex&&!!m),t1=async()=>
2{if(!tO||!tB.current||!a?.orderPda||ex.current||tz.current)return;ex.current=!0;let e=tB.current;ef(!0);try{if(!("jupiter_native"===a.source?await f?.(a.orderPda):void 0!==a.profileIndex&&await m?.(a.orderPda,a.profileIndex))||tB.current!==e)return;c(),u?.()}finally{ex.current=!1,ef(!1)}};(0,r.useEffect)(()=>{tX||("tp"===K||"sl"===K)&&ed(e=>e>tJ?tJ:e)},[tJ,K,tX]);let t2=(0,et.parseRawValue)(e.sizeUsd),t5=(0,et.parseRawValue)(e.entryPrice),t3="phoenix"===e.underwriter||"2"===e.underwriter,t4=(0,ee.getMarketMintFromAsset)(e.asset,e.underwriter),t6=(t4?s?.[t4]:void 0)??s?.[e.asset],t8=t3?(0,et.parseRawValue)(e.markPrice)||t5:t6??((0,et.parseRawValue)(e.markPrice)||t5),t9=(0,et.parseRawValue)(e.collateralUsd),t7=t3?(0,et.phoenixCashBasisBreakeven)(e)??(0,et.parseRawValue)(e.breakevenPriceUsd):0,re=e.asset,rt=(0,ee.getTokenInfo)(e.asset)?.image,rr=e.maxLeverageX??e.leverageX;(0,r.useEffect)(()=>{"entire"===ey?ed(100):""===ej&&t2>0&&eS((0,eK.toDecimalInputValue)(t2*eo/100))},[ey]);let ri=t2*eo/100,rs=(0,et.netCapitalForDisplay)(e),rn=(0,et.sumRealizedPnlFromActions)(e),ra=Math.abs(rn)>=1,rl=(0,et.feesPaidForRemainingSize)(e),ro=(0,et.parseRawValue)(e.feesOwed),rd=parseFloat(X)||0,rc=t5>0?t5:t8,ru=(()=>{if(rd<=0)return rd;if("pct"===J&&rc>0)return"tp"===K?tQ?rc*(1+rd/100):rc*(1-rd/100):tQ?rc*(1-rd/100):rc*(1+rd/100);if("pnl"===J&&t5>0&&t2>0){let e="tp"===K?rd:-rd;return(0,et.priceForTargetPnlPct)({sizeUsd:t2,collateralUsd:t9,netCapital:rs,realizedPnl:rn,entryPrice:t5,feesPaid:rl,feesOwed:ro,isLong:tQ,targetPnlPct:e})??0}return rd})(),rh=ru>0&&(tQ?ru>t8:ru<t8),rp="sl"===K?(0,eV.stopLossLiquidationError)(tQ,ru,e.liquidationPrice):null,rm=!rp&&ru>0&&(tQ?ru<t8:ru>t8),rf="rsi"===K||"dca_close"===K||("tp"===K?rh:rm),rx=t8>0&&ru>0?Math.abs(ru-t8)/t8*100:0,rg="sl"===K?40:75,rb="sl"===K?80:150,rv=("tp"===K||"sl"===K)&&rx>=rb?"strong":("tp"===K||"sl"===K)&&rx>=rg?"warn":"none";(0,r.useEffect)(()=>{p?.(K)},[K,p]),(0,r.useEffect)(()=>{if("ratchet"===l&&!a&&!eP&&t8>0){let e=t8>=1e4?"500":t8>=1e3?"5":t8>=100?"0.5":"0.05";eC(e);let t=parseFloat(e),r=parseFloat(ek);if(t>0&&r>0){let e=parseFloat((tQ?r+t:r-t).toPrecision(12));e_(e>0?e.toString():"")}}},[]);let ry=eo/100,rw=(0,r.useMemo)(()=>(0,et.estimateClosePnl)(e,{execPrice:ru,closeFraction:ry}),[e,ru,ry]);rw?.total;let rj=(0,r.useMemo)(()=>{let t=parseFloat(ek)||0;return(0,et.estimateClosePnl)(e,{execPrice:t,closeFraction:ry})},[e,ek,ry]),rS=rj?.total??null,rk=(0,r.useMemo)(()=>(0,et.estimateClosePnl)(e,{execPrice:ru,closeFraction:1}),[e,ru]),rN=(0,r.useMemo)(()=>{let t=parseFloat(ek)||0;return(0,et.estimateClosePnl)(e,{execPrice:t,closeFraction:1})},[e,ek]),rP=rw?.total??null;(0,r.useEffect)(()=>{if(a){let t=parseFloat(a.triggerPriceUsd||"0");if(Q(t>0?t.toString():""),"ratchet"===a.orderType){G("ratchet");let e=parseFloat(a.worstPriceUsd||"0"),t=parseFloat(a.ratchetSizeUsd||"0");if(eN(e>0?e.toString():""),eC(t>0?t.toString():""),e>0&&t>0){let r=tQ?e+t:e-t;e_(r>0?r.toString():"")}let r=parseFloat(a.stopTriggerPriceUsd||"0");eF(r>0?r.toString():""),eE(r>0)}else G(e5(a.orderType)??("tp"===a.orderType?"tp":"sl")),eN(""),eC(""),e_(""),eF("");let r=100;if("number"==typeof a.closeBps&&a.closeBps>0)r=Math.min(100,Math.round(a.closeBps/100));else{let t=parseFloat(a.sizeUsd||"0"),i=(0,et.parseRawValue)(e.sizeUsd);t>0&&i>0&&(r=Math.min(100,Math.round(t/i*100)))}if(ed(r),r<100){ew("partial");let t=(0,et.parseRawValue)(e.sizeUsd)*r/100;eS(t>0?V.number(t):"")}}},[a,e.sizeUsd,e.entryPrice]);let rT=async()=>{if(!(tz.current||ex.current||!tO||!tB.current||tW||t$||tq&&eR(tq))){tz.current=!0;try{await rC()}finally{tz.current=!1}}},rC=async()=>{let t=tX&&a?.source==="jupiter_native"&&("tp"===K||"sl"===K),r=null;if(!t)try{r=(0,ee.getCloseOrderTargetFromLifecycle)(e)}catch(t){console.error("[position-exit] Could not resolve close target",{buildId:"a99c7ad",asset:e.asset,underwriter:e.underwriter,profileIndex:e.profileIndex},t),(0,eq.reportTradeError)(t,{stage:"close_target",action:K,wallet:e.wallet,positionPda:e.positionPda,asset:e.asset,underwriter:e.underwriter,profileIndex:e.profileIndex}),W.toast.error((0,eW.displayClientError)(t));return}let i=r?.marketMint??(0,ee.getMarketMintFromAsset)(e.asset,e.underwriter);if(!i)return void W.toast.error(B("errorMarketDataUnavailable"));if(r&&"dca_close"===K){if("price"===tx){let t=parseFloat(ta)||0,i=parseFloat(to)||0;if(t<=0||i<=0)return void W.toast.error(B("errorInvalidStartEndPrices"));if(t===i)return void W.toast.error((0,eH.tradingValidationError)("identicalDcaPrices"));try{let s;eh(!0);let n=e.tpslOrders?.length??0;
2await (s={...r,sizeUsd:ri,startPrice:t,endPrice:i,numLegs:tc,weightingType:tm},tG("dca_close",s,()=>tR(s)))&&(W.toast.success(B("toastDcaCloseOrderCreated")),h?.(n),c(),u?.())}catch(e){console.error("Error creating DCA close order:",e),W.toast.error(B("toastDcaCloseOrderFailed"))}finally{eh(!1)}}else if("time"===tx){let t=parseFloat(tb)||0;if(""!==tb.trim()&&t<=0)return void W.toast.error(B("errorInvalidPriceLimit"));try{let i;eh(!0);let s=e.tpslOrders?.length??0;await (i={...r,sizeUsd:ri,priceLimit:t,intervalSeconds:ty,numLegs:tc,weightingType:tm,startDelaySeconds:tC},tG("dca_time_close",i,()=>tD(i)))&&(W.toast.success(B("toastDcaTimeCloseOrderCreated")),h?.(s),c(),u?.())}catch(e){console.error("Error creating DCA time close order:",e),W.toast.error(B("toastDcaTimeCloseOrderFailed"))}finally{eh(!1)}}else{let t=parseFloat(tb)||0,i=parseFloat(tj)||0;if(t<=0)return void W.toast.error(B("errorInvalidPriceLimit"));if(i<=0)return void W.toast.error(B("errorInvalidTrailSize"));if(!tQ&&i>=t)return void W.toast.error((0,eH.tradingValidationError)("shortTrailExceedsLimit"));try{let s;eh(!0);let n=e.tpslOrders?.length??0;await (s={...r,sizeUsd:ri,priceLimit:t,intervalSeconds:0,numLegs:tc,weightingType:tm,ratchetSize:i,startDelaySeconds:tC},tG("dca_ratchet_close",s,()=>tI(s)))&&(W.toast.success(B("toastDcaTrailingCloseOrderCreated")),h?.(n),c(),u?.())}catch(e){console.error("Error creating DCA ratchet close order:",e),W.toast.error(B("toastDcaTrailingCloseOrderFailed"))}finally{eh(!1)}}return}if(r&&"rsi"===K){let t=parseFloat(te)||0;if(t<=0||t>=100)return void W.toast.error((0,eH.tradingValidationError)("invalidIndicatorThreshold"));if(tr&&0>=(parseFloat(ts)||0))return void W.toast.error(B("errorInvalidRsiTrailSize"));try{let i;eh(!0);let s=e.tpslOrders?.length??0;await (i={...r,sizeUsd:ri,indicatorType:0,timeframeCode:e3,period:14,indicatorCondition:e9,thresholdValue:t,ratchetSize:tr?parseFloat(ts):void 0,closeBps:el(eo)},tG(i.ratchetSize?"indicator_ratchet":"indicator",i,()=>tF(i)))&&(W.toast.success(B("toastRsiCloseOrderCreated")),h?.(s),c(),u?.())}catch(e){console.error("Error creating RSI close order:",e),W.toast.error(B("toastRsiCloseOrderFailed"))}finally{eh(!1)}return}if(r&&"ratchet"===K){let t=parseFloat(ek)||0,i=parseFloat(eP)||0;if(t<=0)return void W.toast.error(B("errorInvalidWorstPrice"));if(i<=0)return void W.toast.error(B("errorInvalidTrailSize"));let s=parseFloat(eL)||0;if(s>0&&!e1(e2(s),e2(t),e2(i),tQ))return void W.toast.error(B("stopTriggerOutOfRange",{extreme:tQ?"min":"max"}));try{if(eh(!0),tX&&a?.orderPda&&"ratchet"===a.orderType){if("imperial_passthrough"!==a.source)return void W.toast.error(B("errorTrailingSlPassthroughOnly"));await tY({orderPda:a.orderPda,profileIndex:a.profileIndex??r.profileIndex,sizeUsd:ri,underwriter:r.underwriter,closeBps:el(eo),proOrderUpdate:{type:"ratchet",worstPrice:t,ratchetSize:i,stopTriggerPrice:s>0?s:a.stopTriggerPriceUsd?0:void 0}})&&(W.toast.success(B("toastTrailingSlOrderUpdated")),c(),u?.())}else{let n,a=e.tpslOrders?.length??0;await (n={...r,sizeUsd:ri,currentPrice:t8,worstPrice:t,ratchetSize:i,stopTriggerPrice:s>0?s:void 0,closeBps:el(eo)},tG("ratchet",n,()=>tL(n)))&&(W.toast.success(B("toastTrailingSlOrderCreated")),h?.(a),c(),u?.())}}catch(e){console.error("Error handling ratchet order:",e),W.toast.error(tX?B("toastTrailingSlUpdateFailed"):B("toastTrailingSlOrderFailed"))}finally{eh(!1)}return}if(rp)return void W.toast.error((0,eH.tradingValidationError)(rp));if(!ru||ru<=0)return void W.toast.error((0,eH.tradingValidationError)("invalidTriggerPrice"));try{eh(!0);let t="tp"===K,s="imperial",n=el(eo),l=(0,et.buildQuoteSnapshot)(e,{leg:t?"tp":"sl",execPrice:ru,closeFraction:n/1e4,closeBps:n,priceRef:"mark",inputMode:J,markPrice:t8,lastPrice:t8,identity:{side:+("long"!==e.side),orderType:eJ.PassthroughOrderType.StopLimit,underwriter:(0,eQ.underwriterToNum)(r.underwriter),marketMint:i}});if(tX&&a?.orderPda)("jupiter_native"===a.source?await tA({positionPubkey:e.positionPda,positionRequestPubkey:a.orderPda,marketMint:i,sizeUsd:ri,triggerPrice:ru,positionSource:s,profileIndex:e.profileIndex,underwriter:e.underwriter,quote:l}):await tY({orderPda:a.orderPda,profileIndex:a.profileIndex??r.profileIndex,triggerPrice:ru,sizeUsd:ri,underwriter:r.underwriter,closeBps:n,quote:l}))&&(W.toast.success(B("toastCloseOrderUpdated",{type:t?"tp":"sl"})),c(),u?.());else if(r){let i=e.tpslOrders?.length??0;await tM({positionPubkey:e.positionPda,...r,sizeUsd:ri,triggerPrice:ru,isTakeProfit:t,positionSource:s,closeBps:n,quote:l})&&(W.toast.success(B("toastCloseOrderCreated",{type:t?"tp":"sl"})),h?.(i),c(),u?.())}}catch(t){console.error("Error handling order:",t),(0,eq.reportTradeError)(t,{stage:"submission",action:K,wallet:e.wallet,positionPda:e.positionPda,asset:e.asset,marketMint:i,underwriter:e.underwriter,profileIndex:e.profileIndex,sunriseSeat:r?.sunriseSeat}),W.toast.error(tX?B("toastUpdateOrderFailed"):B("toastCreateOrderFailed"))}finally{eh(!1)}},rM=parseFloat(ek)||0,r_=parseFloat(eP)||0,rA=parseFloat(eL)||0,rE=rA>0&&rM>0&&r_>0&&!e1(e2(rA),e2(rM),e2(r_),tQ),rL=rM>0&&r_>0&&eo>0&&!rE,rF=parseFloat(te)||0,rR=rF>
20&&rF<100&&eo>0&&(!tr||(parseFloat(ts)||0)>0),rD=parseFloat(ta)||0,rI=parseFloat(to)||0,rU=(0,r.useMemo)(()=>{if("dca_close"!==K||ri<=0||tc<2)return 1===tc;let e=Math.floor(1e6*ri);return(1===tm&&tc>=3?Math.min(e0.PassthroughClient.calculateDcaLegSize(e,tc,tm,tc-1),e0.PassthroughClient.calculateDcaLegSize(e,tc,tm,tc-2)):e0.PassthroughClient.calculateDcaLegSize(e,tc,tm,1===tm?tc-1:0))<eJ.MIN_DCA_CLOSE_LEG_SIZE_USD},[K,ri,tc,tm]),rO=parseFloat(tb)||0,rB=parseFloat(tj)||0,rz=!tQ&&rB>0&&rB>=rO,r$=""===th||!isNaN(b=parseInt(th))&&b>=eJ.MIN_DCA_LEGS&&b<=eJ.MAX_DCA_LEGS,rV=("price"===tx?rD>0&&rI>0&&rD!==rI&&eo>0&&!rU:"time"===tx?(""===tb.trim()||rO>0)&&eo>0&&!rU:rO>0&&rB>0&&eo>0&&!rU&&!rz)&&r$;e.underwriter&&e.underwriter;let rH="dca_close"===K?(0,ei.pickMissingLabel)([[eo<=0,B("setSize")],..."price"===tx?[[rD<=0,B("setStartPrice")],[rI<=0,B("setEndPrice")]]:"ratchet"===tx?[[rO<=0,tQ?B("setFloorPrice"):B("setCeilingPrice")],[rB<=0,B("setTrailSize")]]:[]]):"rsi"===K?(0,ei.pickMissingLabel)([[eo<=0,B("setSize")],[rF<=0||rF>=100,B("setRsiThreshold")],[tr&&0>=(parseFloat(ts)||0),B("setTrailSize")]]):"ratchet"===K?(0,ei.pickMissingLabel)([[eo<=0,B("setSize")],[rM<=0,tQ?B("setMinPrice"):B("setMaxPrice")],[r_<=0,B("setTrailSize")],[rE,B("stopTriggerOutOfRange",{extreme:tQ?"min":"max"})]]):(0,ei.pickMissingLabel)([[!tZ&&eo<=0,B("setSize")],[!X,B("setTriggerPrice")]]),rW=null!==rH||("dca_close"===K?!rV:"rsi"===K?!rR:"ratchet"===K?!rL:!rf||tZ),rq=rH??(tX?B("updateAction"):z("confirm")),rK=o??("ratchet"===K?B("trailingStopLossTitle"):"rsi"===K?B("indicatorCloseTitle"):"dca_close"===K?B("orderTypeDcaClose"):"TP/SL"),rG=d??("ratchet"===K?B("trailingSubtitle"):"rsi"===K?B("indicatorCloseSubtitle"):"dca_close"===K?B("dcaCloseSubtitle"):void 0);return(0,t.jsx)(ec,{title:rK,lifecycle:e,symbol:re,iconSrc:rt,leverage:rr,livePrices:s,subtitle:rG,tab:ey,onTabChange:ew,confirmLabel:rq,onCancel:c,onConfirm:rT,submitting:eu,disabled:rW||!tO||tW||!!tK||t$,tabsDisabled:tW||!!tK||t$,footerExtra:(0,t.jsxs)(t.Fragment,{children:[t$&&!tK&&(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:B("advancedCloseConfirmed")}),tW&&(0,t.jsx)("p",{role:"status",className:"text-xs text-muted-foreground",children:B("advancedCloseEditUnsupported")}),tK&&(0,t.jsxs)("div",{role:"status",className:"space-y-2 text-xs text-muted-foreground",children:[(0,t.jsx)("p",{children:B("advancedClosePending")}),"memory"===tK.persistence&&(0,t.jsx)("p",{children:B("tpslGuardMemoryOnly")}),(0,t.jsx)(eO,{scope:tq,leg:"sl",label:"ratchet"===tH?B("columnTrailing"):"rsi"===tH?B("mobileIndicator"):B("orderTypeDcaClose"),intentDetails:tK.intent?.advanced?(0,t.jsx)(e6,{intent:tK.intent}):void 0,attempt:tK,wallet:e.wallet,market:e.asset,onRecovered:()=>{tV(!1),u?.()}},tK.attemptId)]}),tX&&t0?(0,t.jsx)("button",{onClick:t1,disabled:ep||eu||!tO,className:"w-full px-3 py-1.5 text-xs rounded border-0 bg-destructive/10 text-destructive hover:bg-destructive/20 disabled:opacity-50 flex items-center justify-center",children:ep?(0,t.jsx)(en.Spinner,{className:"size-3"}):B("cancelOrderAction")}):null]}),children:!tW&&(0,t.jsxs)("fieldset",{disabled:eu||!!tK||t$||!tO,className:"flex min-w-0 flex-col gap-4 border-0 p-0",children:["dca_close"===K&&(0,t.jsx)("div",{className:"flex items-center gap-0",children:["price","time","ratchet"].map((e,r)=>(0,t.jsx)("button",{onClick:()=>tg(e),className:(0,P.cn)("px-3 py-1.5 text-xs font-medium border transition-colors",0===r&&"rounded-l",2===r&&"rounded-r",r>0&&"border-l-0",tx===e?"bg-cyan-500/20 text-cyan-400 border-cyan-500/40":"bg-surface-raised text-muted-foreground border-border-strong hover:border-border-strong"),children:"price"===e?B("inputModePrice"):"time"===e?B("dcaModeTime"):B("columnTrailing")},e))}),"rsi"===K?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ei.LabeledField,{label:B("labelTimeframe"),children:(0,t.jsx)("select",{value:e3,onChange:e=>e8(Number(e.target.value)),className:"w-full bg-surface-raised border border-border-strong rounded-lg px-3 py-2 text-sm text-foreground",children:Object.entries(eZ.TIMEFRAME_LABELS).map(([e,r])=>(0,t.jsx)("option",{value:e,children:r},e))})}),(0,t.jsx)(ei.LabeledField,{label:B("conditionLabel"),children:(0,t.jsx)("select",{value:e9,onChange:e=>e7(Number(e.target.value)),className:"w-full bg-surface-raised border border-border-strong rounded-lg px-3 py-2 text-sm text-foreground",children:eZ.CONDITION_OPTIONS.map(e=>(0,t.jsx)("option",{value:e,children:$(eZ.CONDITION_LABEL_KEYS[e])},e))})}),(0,t.jsx)(ei.LabeledField,{label:B("thresholdLabel"),children:(0,t.jsx)(ei.OrderFormInput,{value:te,filter:/-/g,inputMode:"numeric",placeholder:"30",unit:"",onChange:tt})}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between min-h-[18px]",children:[(0,t.jsx)(eY.TooltipProvider,{delayDuration:0,
2children:(0,t.jsxs)(eY.Tooltip,{children:[(0,t.jsx)(eY.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("span",{className:"text-xs text-muted-foreground cursor-help flex items-center gap-1",children:[B("rsiTrailing"),(0,t.jsx)(e$.Info,{className:"w-3 h-3 text-muted-foreground"})]})}),(0,t.jsx)(eY.TooltipContent,{side:"top",className:"max-w-[240px]",showArrow:!1,children:(0,t.jsx)("p",{className:"text-xs text-foreground",children:B("rsiTrailingExplainer")})})]})}),(0,t.jsx)(eX.Switch,{checked:tr,onCheckedChange:ti,className:"data-[state=checked]:bg-amber-500 data-[state=unchecked]:bg-surface-interactive"})]}),tr&&(0,t.jsx)(ei.OrderFormInput,{value:ts,placeholder:"0.5",unit:"",onChange:tn})]})]}):"ratchet"===K?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ei.LabeledField,{label:(0,t.jsx)(eY.TooltipProvider,{delayDuration:0,children:(0,t.jsxs)(eY.Tooltip,{children:[(0,t.jsx)(eY.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("span",{className:"flex items-center gap-1 cursor-help",children:[tQ?B("minPrice"):B("maxPrice"),(0,t.jsx)(e$.Info,{className:"w-3 h-3 text-muted-foreground"})]})}),(0,t.jsx)(eY.TooltipContent,{side:"top",className:"max-w-[220px]",showArrow:!1,children:(0,t.jsx)("p",{className:"text-xs text-foreground",children:B("ratchetActivationExplainer",{extreme:tQ?"min":"max"})})})]})}),children:(0,t.jsx)(ei.OrderFormInput,{value:ek,placeholder:V.number(t5),unit:"USD",onChange:e=>{eN(e),eB.current="worstPrice";let t=parseFloat(e),r=parseFloat(eP),i=parseFloat(eM);if(t>0&&r>0){let e=parseFloat((tQ?t+r:t-r).toPrecision(12));e_(e>0?e.toString():"")}else t>0&&i>0&&eC(parseFloat(Math.abs(i-t).toPrecision(12)).toString())}})}),(0,t.jsx)(ei.LabeledField,{label:B("trailSize"),children:(0,t.jsx)(ei.OrderFormInput,{value:eP,placeholder:t8>=1e4?"500":t8>=1e3?"5":t8>=100?"0.5":"0.05",unit:"USD",onChange:e=>{eC(e),eB.current="ratchetSize";let t=parseFloat(e),r=parseFloat(ek);if(t>0&&r>0){let e=parseFloat((tQ?r+t:r-t).toPrecision(12));e_(e>0?e.toString():"")}}})}),(0,t.jsx)(ei.LabeledField,{label:B("activationPrice"),children:(0,t.jsx)(ei.OrderFormInput,{value:eM,placeholder:V.number(t8),unit:"USD",onChange:e=>{e_(e),eB.current="dragPrice";let t=parseFloat(e),r=parseFloat(ek);t>0&&r>0&&eC(parseFloat(Math.abs(t-r).toPrecision(12)).toString())}})}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:()=>eE(e=>!e),"aria-expanded":eA,className:"flex items-center justify-between min-h-[18px] text-xs text-muted-foreground hover:text-foreground transition-colors",children:[(0,t.jsxs)("span",{children:[B("ratchetAdvanced"),!eA&&rA>0&&` \xb7 ${B("ratchetEarlyStop")} ${V.number(rA)}`]}),(0,t.jsx)(ez.ChevronDown,{className:(0,P.cn)("w-3 h-3 transition-transform",eA&&"rotate-180")})]}),eA&&(0,t.jsxs)(ei.LabeledField,{label:(0,t.jsx)(eY.TooltipProvider,{delayDuration:0,children:(0,t.jsxs)(eY.Tooltip,{children:[(0,t.jsx)(eY.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("span",{className:"flex items-center gap-1 cursor-help",children:[B("stopTrigger"),(0,t.jsx)(e$.Info,{className:"w-3 h-3 text-muted-foreground"})]})}),(0,t.jsxs)(eY.TooltipContent,{side:"top",className:"max-w-[240px]",showArrow:!1,children:[(0,t.jsx)("p",{className:"text-xs text-foreground",children:B("ratchetEarlyStopExplainer",{extreme:tQ?"min":"max"})}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:B("stopTriggerMarketNote")})]})]})}),children:[(0,t.jsx)(ei.OrderFormInput,{value:eL,placeholder:B("ratchetEarlyStop"),unit:"USD",onChange:eF}),(0,t.jsx)("p",{className:"text-3xs text-muted-foreground",children:B("stopTriggerMarketNote")})]})]})]}):"dca_close"===K?(0,t.jsxs)(t.Fragment,{children:["price"===tx?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:B("startPrice")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-40",children:(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",placeholder:V.number(t8),value:ta,onChange:e=>tl((0,eK.sanitizeDecimalInput)(e.target.value,q)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:B("endPrice")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-40",children:(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",placeholder:V.number(tQ?1.05*t8:.95*t8),value:to,onChange:e=>td((0,eK.sanitizeDecimalInput)(e.target.value,q)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("span",{className:"text-xs text-label-muted",children:[tQ?B("floorPrice"):B("ceilingPrice"),"time"===tx&&(0,t.jsxs)("span",{className:"text-[10px] text-muted-foreground",children:[" ",B("optionalSuffix")]})]}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-40",children:(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",placeholder:"time"===tx?B("placeholderNoLimit"):V.number(t8),value:tb,onChange:e=>tv((0,eK.sanitizeDecimalInput)(e.target.value,q)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),"time"===tx&&(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:B("labelInterval")}),(0,t.jsx)("div",{className:"flex gap-1",children:eJ.DCA_INTERVAL_OPTIONS.map(e=>(0,t.jsx)("button",{onClick:()=>tw(e.value),className:(0,P.cn)("px-1.5 py-1 text-[10px] rounded transition-colors",ty===e.value?"bg-cyan-500/20 text-cyan-400 border border-cyan-500/40":"bg-canvas text-muted-foreground border border-border hover:border-border-strong"),children:e.label},e.value))})]}),"ratchet"===tx&&(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:B("trailSize")}),(0,t.jsx)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5 w-40",children:(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",placeholder:t8>=1e4?"500":t8>=1e3?"5":t8>=100?"0.5":"0.05",value:tj,onChange:e=>tS((0,eK.sanitizeDecimalInput)(e.target.value,q)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("span",{className:"text-xs text-label-muted",children:[B("delayedStart")," ",(0,t.jsx)("span",{className:"text-[10px] text-muted-foreground",children:B("optionalSuffix")})]}),(0,t.jsxs)("div",{className:"flex gap-1",children:[(0,t.jsxs)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-2 py-1.5 w-16 flex items-center gap-1",children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"numeric",placeholder:"0",value:tk,onChange:e=>tN(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:"h"})]}),(0,t.jsxs)("div",{className:"bg-surface-raised border border-border-strong rounded-lg px-2 py-1.5 w-16 flex items-center gap-1",children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"numeric",placeholder:"0",value:tP,onCh
2ange:e=>tT(e.target.value.replace(/[^0-9]/g,"")),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:"m"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-xs text-label-muted",children:B("legsRange",{min:eJ.MIN_DCA_LEGS,max:eJ.MAX_DCA_LEGS})}),(0,t.jsxs)("div",{className:"flex gap-1",children:[[2,3,5,10].map(e=>(0,t.jsx)("button",{onClick:()=>{tu(e),tp("")},className:(0,P.cn)("px-2 py-1 text-[10px] rounded transition-colors",tc===e&&""===th?"bg-cyan-500/20 text-cyan-400 border border-cyan-500/40":"bg-canvas text-muted-foreground border border-border hover:border-border-strong"),children:e},e)),(0,t.jsx)("input",{type:"text",inputMode:"numeric",value:th,placeholder:"#",onChange:e=>{let t=e.target.value.replace(/[^0-9]/g,"");tp(t);let r=parseInt(t);!isNaN(r)&&r>=eJ.MIN_DCA_LEGS&&r<=eJ.MAX_DCA_LEGS&&tu(r)},onBlur:()=>{if(""===th)return;let e=parseInt(th);isNaN(e)||e<eJ.MIN_DCA_LEGS?(tu(eJ.MIN_DCA_LEGS),tp(String(eJ.MIN_DCA_LEGS))):e>eJ.MAX_DCA_LEGS&&(tu(eJ.MAX_DCA_LEGS),tp(String(eJ.MAX_DCA_LEGS)))},className:(0,P.cn)("w-10 px-1 py-1 text-[10px] text-center rounded transition-colors bg-transparent focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",""===th||r$?""!==th?"border border-cyan-500/40 bg-cyan-500/20 text-cyan-400":"border border-border text-muted-foreground hover:border-border-strong":"border border-destructive/50 bg-destructive/10 text-destructive")}
2)]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(eY.TooltipProvider,{delayDuration:0,children:(0,t.jsxs)(eY.Tooltip,{children:[(0,t.jsx)(eY.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("span",{className:"text-xs text-label-muted cursor-help flex items-center gap-1",children:[B("weightingLabel"),(0,t.jsx)(e$.Info,{className:"w-3 h-3 text-muted-foreground"})]})}),(0,t.jsx)(eY.TooltipContent,{side:"left",className:"max-w-[240px]",showArrow:!1,children:(0,t.jsx)("p",{className:"text-xs text-foreground",children:B("weightingExplainer")})})]})}),(0,t.jsx)("div",{className:"flex gap-1",children:eZ.WEIGHTING_OPTIONS.map(e=>(0,t.jsx)("button",{onClick:()=>tf(e),className:(0,P.cn)("px-2 py-1 text-[10px] rounded transition-colors",tm===e?"bg-cyan-500/20 text-cyan-400 border border-cyan-500/40":"bg-canvas text-muted-foreground border border-border hover:border-border-strong"),children:$(eZ.WEIGHTING_LABEL_KEYS[e])},e))})]}),rU&&(0,t.jsx)("span",{className:"text-3xs text-destructive",children:B("dcaLegTooSmall",{minSize:V.grouped(eJ.MIN_DCA_CLOSE_LEG_SIZE_USD/1e6)})})]}):(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:"tp"===K?B("takeProfit"):B("stopLoss")}),(0,t.jsxs)(eG.DropdownMenu,{children:[(0,t.jsx)(eG.DropdownMenuTrigger,{asChild:!0,children:(0,t.jsxs)("button",{className:"flex items-center gap-0.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:["price"===J?B("inputModePrice"):"pct"===J?B("inputModePctPrice"):B("inputModePctPnl"),(0,t.jsx)(ez.ChevronDown,{className:"w-3 h-3"})]})}),(0,t.jsxs)(eG.DropdownMenuContent,{align:"start",className:"min-w-[100px]",children:[(0,t.jsx)(eG.DropdownMenuItem,{onClick:()=>{er("price"),Q("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:B("inputModePrice")}),(0,t.jsx)(eG.DropdownMenuItem,{onClick:()=>{er("pct"),Q("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:B("inputModePctPrice")}),(0,t.jsx)(eG.DropdownMenuItem,{onClick:()=>{er("pnl"),Q("")},className:"text-xs text-foreground hover:bg-surface-interactive",children:B("inputModePctPnl")})]})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[void 0!==n&&n>0&&(0,t.jsx)("button",{onClick:()=>{"price"===J&&Q((0,eK.toDecimalInputValue)(n))},className:"text-xs text-label-muted hover:text-foreground transition-colors",children:B("midPriceShortcut")}),(0,t.jsx)("button",{onClick:()=>{"price"===J&&Q((0,eK.toDecimalInputValue)(t8))},className:"text-xs text-label-muted hover:text-foreground transition-colors",children:B("lastPriceShortcut")})]})]}),(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsxs)("div",{className:"flex-1 flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-1.5",children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal",placeholder:"pnl"===J?"tp"===K?B("placeholderPctGain"):B("placeholderPctLoss"):"pct"===J?"tp"===K?B("placeholderIncrease"):B("placeholderDecrease"):"tp"===K?tQ?`>${V.number(t8)}`:`<${V.number(t8)}`:tQ?`<${V.number(t8)}`:`>${V.number(t8)}`,value:X,onChange:e=>Q((0,eK.sanitizeDecimalInput)(e.target.value,q)),onWheel:e=>e.currentTarget.blur(),className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,t.jsx)("span",{className:"text-xs text-label-muted ml-2",children:"price"===J?"USD":"%"})]})}),"pnl"===J&&(0,t.jsx)(ei.PnlPctPresets,{value:X,onChange:Q,orderType:"tp"===K?"tp":"sl"}),"price"===J&&void 0!==n&&n>0&&(0,t.jsx)("div",{className:"text-[10px] text-label-muted",children:B("midPriceValue",{price:V.number(n)})}),("pct"===J||"pnl"===J)&&ru>0&&(0,t.jsxs)("div",{className:"text-[10px] text-label-muted font-mono tabular-nums",children:["≈ $",V.number(ru)]}),X&&!rf&&(0,t.jsx)("span",{className:"text-3xs text-destructive",children:rp?(0,eH.tradingValidationError)(rp):"pct"===J?"tp"===K?B("resolvedPriceInvalidForTp",{price:V.number(ru)}):B("resolvedPriceInvalidForSl",{price:V.number(ru)}):"tp"===K===tQ?B("mustBeAboveMark",{price:V.number(t8)}):B("mustBeBelowMark",{price:V.number(t8)})}),X&&"none"!==rv&&(0,t.jsxs)("span",{className:(0,P.cn)("text-3xs","strong"===rv?"text-destructive":"text-amber-400"),children:["strong"===rv?B("checkDecimalsPrefix"):"",ru>t8?B("triggerDeviationAbove",{deviation:V.percent(rx,0),mark:V.number(t8)}):B("triggerDeviationBelow",{deviation:V.percent(rx,0),mark:V.number(t8)})]}),t3&&t7>0&&("tp"===K||"sl"===K)&&(v=ru>t7,y=tQ?v:!v,w="tp"===K&&ru>0&&rf&&!y,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-[10px] text-label-muted",children:B("breakevenValue",{price:V.number(t7)})}),w&&(0,t.jsx)("span",{className:"text-[10px] text-amber-400",children:B("takeProfitLossSideOfBreakeven",{price:V.number(t7)})})]}))]}),"partial"===ey&&(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:B("amountLabel")}),(0,t.jsxs)("div",{className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2",children:[(0,t.jsx)(es.Input,{type:"text",inputMode:"decimal","data-keypad-unit":"money",value:ej,onChange:e=>{var t;let r,i;return t=e.target.value,eS(r=(0,eK.sanitizeDecimalInput)(t,q)),i=parseFloat(r)||0,void(t2>0&&ed(Math.max(0,Math.min(100,Math.round(i/t2*100)))))},onWheel:e=>e.currentTarget.blur(),placeholder:"0",className:"bg-transparent border-none text-foreground text-sm p-0 h-auto flex-1 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground ml-2",children:"USDC"})]}),(0,t.jsx)("input",{type:"range",...em.THUMB_ONLY_SLIDER,min:1,max:100,value:eo,onChange:e=>{var t;ed(t=parseInt(e.target.value)),eS(t2>0?V.number(t2*t/100):"")},className:(0,P.cn)(em.RANGE_SLIDER_CLASSES,"w-full [&::-webkit-slider-thumb]:bg-white")}),(0,t.jsxs)("div",{className:"flex items-center justify-between text-xs text-label-muted",children:[(0,t.jsx)("span",{className:"text-foreground font-medium",children:B("closingPercent",{percent:eo})}),(0,t.jsx)("span",{children:B("ofAmountUsdc",{amount:V.number(t2)})})]})]}),(()=>{if("ratchet"===K)return(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:B.rich("triggerExplainer",{ref:tQ?B("extremeMin"):B("extremeMax"),price:rM>0?`$${V.number(rM)} USD`:"-- USD",pnl:null!==rS&&rM>0?`${rS>=0?"+":""}${V.number(rS)} USD`:"-- USD",strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e}),pnlStyle:e=>(0,t.jsx)("span",{className:(0,P.cn)("font-medium",(0,Z.pnlColor)(rS)),children:e})})});if("rsi"===K)return(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:B.rich("rsiCloseExplainer",{percent:eo,condition:`RSI ${$(eZ.CONDITION_LABEL_KEYS[e9])} ${te||"--"}`,timeframe:eZ.TIMEFRAME_LABELS[e3],strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e})})});if("dca_close"===K){if("price"===tx)return(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:B.rich("dcaPriceExplainer",{legs:tc,start:rD>0?`$${V.number(rD)}`:"--",end:rI>0?`$${V.number(rI)}`:"--",strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e})})});let e=eJ.DCA_INTERVAL_OPTIONS.find(e=>e.value===ty)?.label??"";return"time"===tx?(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:rO>0?B.rich(tQ?"dcaTimeExplainerAbove":"dcaTimeExplainerBelow",{legs:tc,interval:e,limit:`$${V.number(rO)}`,strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e})}):B.rich("dcaTimeExplainerAnyPrice",{legs:tc,interval:e,strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e})})}):(0,t.jsx)("p",{className:"text-[11px] text-label-muted leading-snug",children:B.rich("dcaTrailingExplainer",{legs:tc,from:rO>0?`$${V.number(rO)}`:"--",trail:rB>0?V.number(rB):"--",strong:e=>(0,t.jsx)("span",{className:"font-medium text-foreground",children:e})})})}return null})(),(0,t.jsx)("div",{className:"flex flex-col gap-3",children:"rsi"!==K&&"dca_close"!==K&&(S=(j="ratchet"===K)?rj:rw,k=j?rN:rk,N=j?rS:rP,T=k?(0,et.wholeTradeNetPnl)(e,k,rs):N,C=ry<1,M=(ra||C)&&null!==T&&null!==N&&Math.abs(T-N)>=.01,_=rs??t9,A=!j&&("tp"===K||"sl"===K)&&ru>0&&!rf,E=null!==T&&S&&!A,L=eo/100,F=(0,et.parseRawValue)(e.borrowFeeOwed)*L,R=(0,et.parseRawValue)(e.closeFeeOwed)*L,D=(0,et.parseRawValue)(e.swapFeeOwed)*L,U=F+R+D+(I=rl*L),(0,t.jsxs)("div",{className:"bg-surface-raised border border-border-strong rounded-lg overflow-hidden",children:[(0,t.jsxs)("div",{role:"button",tabIndex:0,onClick:e=>{e.stopPropagation(),E&&eb(!eg)},className:(0,P.cn)("flex items-center justify-between text-xs px-3 py-1.5",E&&"cursor-pointer select-none touch-manipulation"),children:[(0,t.jsxs)("span",{className:"flex items-center gap-1 text-label-muted",children:[j?B("netPnlAtExtreme",{extreme:tQ?"min":"max"}):B("netPnl"),E&&(0,t.jsx)(ez.ChevronDown,{className:(0,P.cn)("w-3 h-3 transition-transform",eg&&"rotate-180")}
2)]}),E?(0,t.jsxs)("div",{className:"flex flex-col items-end",children:[(0,t.jsxs)("span",{className:(0,P.cn)("font-mono tabular-nums",(0,Z.pnlColor)(T)),children:[T>=0?"+":"",V.number(T)," USD"]}),(0,t.jsxs)("span",{className:(0,P.cn)("text-[10px] font-mono tabular-nums",(0,Z.pnlColorDim)(T)),children:["(",T>=0?"+":"",_>0?V.fixed(T/_*100,2):V.fixed(0,2),"%)"]}),M&&null!==N&&(0,t.jsx)("span",{className:(0,P.cn)("text-[10px] mt-0.5 font-mono tabular-nums",(0,Z.pnlColorDim)(N)),children:B("legPnlAmount",{amount:`${N>=0?"+":""}${V.number(N)}`})})]}):(0,t.jsx)("span",{className:"text-label-muted",children:"—"})]}),eg&&E&&(0,t.jsxs)("div",{className:"px-3 pb-2 space-y-1 text-xs font-mono border-t border-border-strong",children:[(0,t.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1",children:B("pnlBreakdownLabel")}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("pricePnlLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:[S.pricePnl>=0?"+":"",V.number(S.pricePnl)]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("afterFeesPaidLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:[S.afterFeesPaid>=0?"+":"",V.number(S.afterFeesPaid)]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("afterFeesOwedLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:[S.afterFeesOwed>=0?"+":"",V.number(S.afterFeesOwed)]})]}),!j&&ra&&k&&(.01>Math.abs(O=null!==rs?(0,et.getEstimatedReturn)(t9,k)-k.total-rs:rn)?null:(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border-strong pt-1",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("realizedPnlLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:[O>=0?"+":"",V.number(O)]})]})),!j&&null!==rs&&k&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1 border-t border-border-strong",children:B("costBasisLabel")}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("netDepositedLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",V.number(rs)]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("valueAtTriggerLabel")}),(0,t.jsxs)("span",{className:"font-mono tabular-nums",children:["$",V.number((0,et.getEstimatedReturn)(t9,k))]})]})]}),U>=.01&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"font-semibold text-foreground pt-2 pb-1 border-t border-border-strong",children:B("feeBreakdownLabel")}),I>=.005&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("entryFeesLabel")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",V.number(I)]})]}),F>=.005&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("borrowFeeLabel")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",V.number(F)]})]}),R>=.005&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("closeFeeLabel")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",V.number(R)]})]}),D>=.005&&(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("platformFeeLabel")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",V.number(D)]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border-strong pt-1",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:B("totalFeesLabel")}),(0,t.jsxs)("span",{className:"text-amber-400 font-mono tabular-nums",children:["$",V.number(U)]})]})]})]})]}))})]})})}function e6({intent:e}){let r=(0,H.useTranslations)("positions"),i=(0,H.useTranslations)("trading"),s=e.advanced.parameters,n=[["worstPrice",r("worstPrice")],["ratchetSize",r("trailSize")],["stopTriggerPrice",r("stopTrigger")],["startPrice",r("startPrice")],["endPrice",r("endPrice")],["priceLimit",r("priceLimitLabel")],["numLegs",r("advancedClose
2Legs")],["intervalSeconds",r("advancedCloseIntervalSeconds")],["startDelaySeconds",r("advancedCloseDelaySeconds")],["thresholdValue",r("rsiThresholdLabel")]];return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("p",{children:r("advancedCloseRequestDetails",{amount:String(e.sizeUsd)})}),e.closeBps>0&&(0,t.jsx)("p",{children:r("advancedClosePercent",{percent:String(e.closeBps/100)})}),n.map(([e,r])=>void 0!==s[e]&&(0,t.jsxs)("p",{children:[r," ",String(s[e])]},e)),"number"==typeof s.timeframeCode&&(0,t.jsxs)("p",{children:[r("timeframeLabel")," ",eZ.TIMEFRAME_LABELS[s.timeframeCode]??String(s.timeframeCode)]}),"number"==typeof s.indicatorCondition&&(0,t.jsxs)("p",{children:[r("conditionLabel")," ",eZ.CONDITION_LABEL_KEYS[s.indicatorCondition]?i(eZ.CONDITION_LABEL_KEYS[s.indicatorCondition]):String(s.indicatorCondition)]}),"number"==typeof s.weightingType&&(0,t.jsxs)("p",{children:[r("weightingLabel")," ",eZ.WEIGHTING_LABEL_KEYS[s.weightingType]?i(eZ.WEIGHTING_LABEL_KEYS[s.weightingType]):String(s.weightingType)]}),e.targetOrderPda&&(0,t.jsxs)("p",{className:"break-all",children:[r("advancedCloseTarget")," ",e.targetOrderPda]})]})}e.s(["isRatchetStopTripped",0,function(e,t,r){return e>0&&t>0&&(r?t>=e:t<=e)},"isValidRatchetStopTrigger",0,e1,"toOraclePrice",0,e2],134138);var e8=e.i(227824);e.s(["ChartCandlestick",()=>e8.default],756880)},831979,e=>{"use strict";var t=e.i(394390);e.s(["XIcon",0,function({className:e}
2){return(0,t.jsx)("svg",{viewBox:"0 0 24 24",className:e,fill:"currentColor","aria-hidden":"true",focusable:"false",children:(0,t.jsx)("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})})}])},432533,744030,265172,937505,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(43690),s=e.i(514049),n=e.i(483007);function a(e){return e.lifecycleId??e.id}function l(e){return e?`${e.totalCount}|${e.dataList.map(a).sort().join(",")}`:""}e.s(["HISTORY_PAGE_SIZE",0,50,"headHasMore",0,function(e){return!!e&&e.totalCount>e.dataList.length},"headSignature",0,l,"mergeHistoryPages",0,function(e,t){let r=new Set(e.map(a)),i=[...e];for(let e of t.flat()){let t=a(e);r.has(t)||(r.add(t),i.push(e))}return i}],744030);let o=["indexed_positions","wallet_orders","executed_orders","dca_indices","action_orders","sunrise_order_seats","fee_policy","loan_index","jupiter_wallet_direct"],d=["missing_indexed_value","invalid_source_value","context_unavailable","identity_unresolved"],c=["indexed_lifecycle","indexed_actions","jupiter_live","phoenix_live","indexed_loan","live_loan"];function u(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function h(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function p(e){return h(e)&&new Set(e).size===e.length}function m(e,t=!1){return"string"==typeof e&&e.length<=256&&/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))&&(!t||Number(e)>0)}function f(e,t){return"string"==typeof e&&t.includes(e)}function x(e,t){return h(e)&&new Set(e).size===e.length&&e.every(e=>t.includes(e))}function g(e){return"string"==typeof e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function b(e){return"string"==typeof e&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(e)&&Number.isFinite(Date.parse(e))}function v(e,t){return b(e)&&b(t)&&Date.parse(e)<=Date.parse(t)}function y(e,t){if(!u(e)||1!==e.version||e.resource!==t.resource||e.walletAddress!==t.wallet||e.underwriter!==(t.underwriter??null)||!f(e.visibility,["public","owner"])||!f(e.status,["available","partial"])||"required_account_reads"!==e.coverage||"best_effort"!==e.liveEnrichment||!g(e.readId)||!v(e.startedAt,e.completedAt)||!x(e.missingSources,o)||!x(e.unavailableEnrichments,["jupiter_profile_positions","phoenix_position_state","phoenix_cross_margin","loan_live_overlay"])||!p(e.indexedLoanOnlyLifecycleIds)||!e.indexedLoanOnlyLifecycleIds.every(g)||!p(e.unindexedJupiterRowIds))throw Error("Invalid account-read metadata");if("positions"===t.resource?null!==e.page:!u(e.page)||e.page.limit!==String(t.page?.limit??50)||e.page.offset!==String(t.page?.offset??0))throw Error("Account-read page mismatch");if("available"===e.status!=(0===e.missingSources.length)||"trades"===t.resource&&"available"!==e.status)throw Error("Invalid account-read coverage");let r=e.lifetimeNetPnlRead;if("positions"===t.resource?null!==r:null===r)throw Error("Account totals evidence mismatch");if(null!==r&&(!u(r)||!g(r.calculationId)||"single_statement"!==r.source||"terminal_lifecycle_action_statement_snapshot"!==r.assurance||"boolean"!=typeof r.sharedInFlight||!v(r.startedAt,r.completedAt)))throw Error("Invalid totals metadata");return e}function w(e){return"unavailable"===e.status&&"string"==typeof e.reason&&d.includes(e.reason)}function j(e){return u(e)&&(w(e)||"known"===e.status&&m(e.value)&&Array.isArray(e.origins)&&e.origins.length>0&&x(e.origins,c))}function S(e,t){if(!u(e)||!Array.isArray(e.dataList)||!e.dataList.every(e=>u(e)&&e.wallet===t.wallet&&"string"==typeof e.id&&"string"==typeof e.positionPda&&"string"==typeof e.asset&&void 0===e.kind)||!Number.isSafeInteger(e.count)||0>Number(e.count)||!Number.isSafeInteger(e.totalCount)||0>Number(e.totalCount))throw Error("Invalid account rows");let r=void 0===e.accountRead?void 0:y(e.accountRead,t),i=e.unavailablePositionDetails;if(r&&"positions"===t.resource&&!Array.isArray(i))throw Error("Missing negotiated position details");if(void 0!==i&&(!r||"positions"!==t.resource||!Array.isArray(i)))throw Error("Invalid partial account response");let s=i?.map(e=>(function(e,t){if(!u(e)||"indexed_position_exit_v1"!==e.kind||!g(e.lifecycleId)||e.wallet!==t||!["positionPda","source","underwriter","asset"].every(t=>"string"==typeof e[t])||!f(e.ownership,["imperial","venue_direct","unavailable"])||null!==e.marketMint&&"string"!=typeof e.marketMint||![null,"long","short"].includes(e.side)||!(null===e.profileIndex||Number.isSafeInteger(e.profileIndex)&&Number(e.profileIndex)>=0&&255>=Number(e.profileIndex))||!x(e.missingSources,o))throw Error("Invalid indexed exit identity");let r=e.openingSlot;if(!u(r)||!("unavailable"===r.status&&f(r.reason,["missing_indexed_value","invali
2d_source_value"])||"known"===r.status&&"string"==typeof r.value&&/^[1-9][0-9]*$/.test(r.value)&&r.value.length<=19&&0x7fffffffffffffffn>=BigInt(r.value)))throw Error("Invalid indexed opening slot");let i=e.sunriseMarginSeat;if(!u(i)||!("not_applicable"===i.status||w(i)||"known"===i.status&&(null===i.value||"string"==typeof i.value)))throw Error("Invalid indexed exit seat");let s=e.closeBasis;if(!u(s)||!j(s.sizeUsd)||!j(s.collateralUsd))throw Error("Invalid indexed close amounts");let n=s.markPrice;if(!u(n)||!(w(n)||"known"===n.status&&m(n.value,!0)&&"string"==typeof n.marketMint&&n.marketMint.length>0&&f(n.origin,["jupiter_live","market_price","indexed_mark","entry_fallback"])))throw Error("Invalid indexed close mark");return e})(e,t.wallet))??[];if(r?.status==="available"&&s.length>0||new Set(s.map(e=>e.lifecycleId)).size!==s.length||s.some(t=>e.dataList.some(e=>(e.lifecycleId??e.id)===t.lifecycleId)))throw Error("Conflicting account rows");if(r){let t=new Set([...e.dataList.map(e=>e.lifecycleId??e.id),...s.map(e=>e.lifecycleId)]),i=new Set(e.dataList.filter(e=>"jupiter_direct"===e.source).map(e=>e.id));if(r.indexedLoanOnlyLifecycleIds.some(e=>!t.has(e))||r.unindexedJupiterRowIds.some(e=>!i.has(e)))throw Error("Account evidence references absent rows")}if("trades"===t.resource&&(!["lifetimeCollateralUsd","lifetimePnlUsd","lifetimeFeesUsd"].every(t=>"string"==typeof e[t])||!u(e.lifetimeFeeBreakdown)))throw Error("Invalid account totals");if(r&&"trades"===t.resource&&!["lifetimeCollateralUsd","lifetimePnlUsd","lifetimeFeesUsd","lifetimeNetPnlUsd"].every(t=>m(e[t])))throw Error("Invalid negotiated account totals");return{...e,accountRead:r,unavailablePositionDetails:s}}class k extends Error{retryAfterMs;status;constructor(e,t=3e4,r){super(e),this.retryAfterMs=t,this.status=r}}async function N(e,t,r){let i=new URLSearchParams({walletAddress:e.wallet,accountReadVersion:"1"});e.underwriter&&i.set("underwriter",e.underwriter),"trades"===e.resource&&(i.set("limit",String(e.page?.limit??50)),i.set("offset",String(e.page?.offset??0)));let s=await fetch(`https://api.imperial.space/api/v1/${e.resource}?${i}`,{cache:"no-store",headers:t?{Authorization:`Bearer ${t}`}:{},signal:r});if(!s.ok){let e=s.headers.get("Retry-After"),t=e&&/^\d+$/.test(e)?1e3*Number(e):e?Date.parse(e)-Date.now():3e4;throw new k("Account data is temporarily unavailable.",Number.isFinite(t)?Math.max(3e4,t):3e4,s.status)}return S(await s.json(),e)}e.s(["AccountReadError",0,k,"READ_STALE_MS",0,3e4,"decodeAccountRead",0,y,"decodeAccountResponse",0,S,"fetchAccountRead",0,N,"object",0,u,"utcTime",0,b,"uuid",0,g],265172);let P=Object.freeze({status:"unknown",lastSuccessAt:null,lastReadAt:null,lastTransportSuccessAt:null,error:null,retryAt:0,metadata:null,exits:[]}),T=e=>["jupiter-positions",e],C=(e,t=0)=>0===t?["jupiter-lifecycles",e]:["jupiter-lifecycle-pages",e,t],M=()=>new DOMException("Account view changed","AbortError");function _(e){return JSON.stringify([e.lifecycleId??e.id,e.wallet,e.positionPda,e.underwriter,e.ownership,e.profileIndex,e.asset,e.side,e.sunriseMarginSeat,e.directVenue])}class A{client;now;entries;audiences;listeners;serial;revision;currentAuth;constructor(e,t=Date.now){this.client=e,this.now=t,this.entries=new WeakMap,this.audiences=new Map,this.listeners=new Set,this.serial=0,this.revision=0,this.currentAuth=null,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.snapshot=()=>this.revision}connect(){let e=this.client;return e.getQueryCache().subscribe(t=>{if("removed"===t.type){this.entries.get(t.query)?.flight?.controller.abort(),this.entries.delete(t.query);let r=t.query.queryKey[1];"string"!=typeof r||e.getQueryCache().getAll().some(e=>e.queryKey[1]===r&&this.entries.has(e))||this.audiences.delete(r)}if("updated"===t.type&&"invalidate"===t.action.type){let e=this.entries.get(t.query);e&&(e.invalidated=!0)}("removed"===t.type||"updated"===t.type||"added"===t.type)&&this.emit()})}subscribe;snapshot;emit(){this.revision+=1,n.notifyManager.batch(()=>{for(let e of this.listeners)n.notifyManager.schedule(e)})}
2tick(){this.emit()}pageMatches(e,t,r){let i=this.query(e),s=i&&this.entries.get(i);return s?.auth===t&&s.pageHead===r}isCurrent(e){return this.currentAuth===e}commit(e){if(this.currentAuth!==e){for(let t of(this.currentAuth=e,this.audiences.clear(),this.client.getQueryCache().getAll())){let r=this.entries.get(t);["jupiter-positions","jupiter-lifecycles","jupiter-lifecycle-pages","jupiter-orders","passthrough-orders","phoenix-direct-positions"].includes(String(t.queryKey[0]))&&r?.auth!==e&&(r?.flight?.controller.abort(),this.entries.delete(t),t.reset())}this.emit()}}retire(e){if(this.currentAuth===e){for(let e of(this.currentAuth=null,this.client.getQueryCache().getAll()))this.entries.get(e)?.flight?.controller.abort();this.emit()}}query(e){return this.client.getQueryCache().find({queryKey:e,exact:!0})}entry(e,t){let r=this.query(e);if(!r||!this.isCurrent(t))throw M();let i=this.entries.get(r);return i&&i.auth===t||(i={access:"account",auth:t,availability:P,httpFailure:0,httpSuccess:0,versionedObserved:!1,wsFailure:0,accepted:0,baseId:null,invalidated:!1},this.entries.set(r,i)),i}available(e,t){let r=this.query(e),i=r&&this.entries.get(r);return this.isCurrent(t)&&i?.auth===t?this.audiences.get(String(e[1]))?.publicOnly&&"account"===i.access&&i.availability.metadata?.visibility!=="public"?"unavailable"===i.availability.status?{...P,status:"unavailable",error:i.availability.error,retryAt:i.availability.retryAt}:P:i.availability:P}data(e,t){let r=this.query(e),i=r&&this.entries.get(r);return this.isCurrent(t)&&i?.auth===t&&!(this.audiences.get(String(e[1]))?.publicOnly&&"account"===i.access&&i.availability.metadata?.visibility!=="public")?r?.state.data:void 0}stale(e,t){let r=this.query(e),i=r&&this.entries.get(r);return!i||i.auth!==t||i.invalidated||!i.availability.lastReadAt||this.now()-i.availability.lastReadAt>=3e4||"available"!==i.availability.status}audience(e,t){let r=this.audiences.get(e);return r?.auth===t?r.generation:0}setVisibility(e,t,r,i){let s=this.audiences.get(e),n="public"===r;if((s?.auth!==t||s.publicOnly!==n)&&(this.audiences.set(e,{auth:t,generation:(s?.generation??0)+(s||n?1:0),publicOnly:n}),n))for(let r of this.client.getQueryCache().getAll()){let s=this.entries.get(r);r.queryKey[1]===e&&r!==this.query(i)&&s?.auth===t&&"account"===s.access&&s.availability.metadata?.visibility!=="public"&&(s.baseId=null,s.availability={...P,status:s.httpFailure||s.wsFailure?"unavailable":"unknown",error:s.httpFailure||s.wsFailure?"Account data is temporarily unavailable.":null,retryAt:s.availability.retryAt},r.setState({data:void 0,dataUpdatedAt:0,error:null,status:"pending"}))}}accept(e,t,r,i,s=!0){let n=t.accountRead;n&&(e.versionedObserved=!0),i&&(e.httpSuccess=r);let a=i&&r>e.httpFailure&&!!n&&"available"===n.status,l=r>e.wsFailure&&!!n&&"available"===n.status;a&&(e.httpFailure=0),l&&(e.wsFailure=0);let o=!!e.httpFailure&&(e.versionedObserved||e.httpSuccess<=e.httpFailure)||!!e.wsFailure,d=n?.status==="available"&&!o;e.availability={status:o?"unavailable":n?.status??"unknown",lastSuccessAt:d?this.now():e.availability.lastSuccessAt,lastReadAt:n?this.now():e.availability.lastReadAt,lastTransportSuccessAt:i?this.now():e.availability.lastTransportSuccessAt,error:o?"Account data is temporarily unavailable.":null,retryAt:n?.status==="partial"?this.now()+3e4:d||i&&!n&&!o?0:e.availability.retryAt,metadata:n??null,exits:t.unavailablePositionDetails??[]},e.baseId=n?.readId??null,e.accepted=r,e.invalidated=!1,s&&this.emit()}async read(e,t,r,i,s,n){let a=this.entry(e,r);if(a.flight)return a.flight.promise;if(a.availability.retryAt>this.now())throw new k(a.availability.error??"Account data is temporarily unavailable.",a.availability.retryAt-this.now());let o=++this.serial,d=this.audience(t.wallet,r),c=new AbortController,u=Promise.resolve().then(async()=>{try{let u=await i(c.signal);if(void 0!==n&&l(this.data(C(t.wallet),r))!==n||c.signal.aborted||!this.isCurrent(r)||this.audience(t.wallet,r)!==d&&!(this.audiences.get(t.wallet)?.publicOnly&&u.accountRead?.visibility==="public")||o<a.accepted)throw M();if(!u.accountRead&&this.audiences.get(t.wallet)?.publicOnly)throw new k("Account data is temporarily unavailable.");u.accountRead&&this.setVisibility(t.wallet,r,u.accountRead.visibility,e),this.accept(a,u,o,!0,!1),a.pageHead=n;let h=s(u);
2return this.client.setQueryData(e,h),this.emit(),h}catch(e){if(c.signal.aborted||!this.isCurrent(r)||e instanceof DOMException&&"AbortError"===e.name)throw e;throw a.httpFailure=++this.serial,a.availability={...a.availability,status:"unavailable",error:"Account data is temporarily unavailable.",retryAt:this.now()+(e instanceof k?e.retryAfterMs:3e4)},this.emit(),e}finally{a.flight?.controller===c&&(a.flight=void 0)}});return a.flight={controller:c,promise:u},u}async independent(e,t,r,i="complete",s){let n=this.entry(e,t);if(n.access="independent_public",s?.aborted)throw s.reason??M();if(n.flight&&!n.flight.controller.signal.aborted)return n.flight.promise;if(n.availability.retryAt>this.now())throw new k("Account data is temporarily unavailable.",n.availability.retryAt-this.now());let a=new AbortController,l=()=>a.abort(s?.reason);s?.addEventListener("abort",l,{once:!0});let o=Promise.resolve().then(async()=>{try{let e=await r(a.signal);if(a.signal.aborted||!this.isCurrent(t))throw M();return n.availability="complete"===i?{...P,status:"available",lastReadAt:this.now(),lastSuccessAt:this.now(),lastTransportSuccessAt:this.now()}:{...P,lastTransportSuccessAt:this.now()},this.emit(),e}catch(e){throw!a.signal.aborted&&this.isCurrent(t)&&(n.availability={...n.availability,status:"unavailable",error:"Account data is temporarily unavailable.",retryAt:this.now()+3e4},this.emit()),e}finally{s?.removeEventListener("abort",l),n.flight?.controller===a&&(n.flight=void 0)}});return n.flight={controller:a,promise:o},o}socket(e,t){let r=this.audience(e,t),i=!0,s=-1,n=!1,a=T(e),l=()=>i&&this.isCurrent(t)&&this.audience(e,t)===r;return{current:l,retire:()=>{i=!1},receive:r=>{if(!l()||!u(r)||r.wallet!==e||!Number.isSafeInteger(r.seq)||Number(r.seq)<=s)return"ignored";let i=()=>{s=Number(r.seq)};if(!this.query(a))return"ignored";let o=this.entry(a,t),d=o.availability.metadata?.visibility;if("position_state_unavailable"===r.type)return 1!==r.version||"positions"!==r.resource||!("string"==typeof r.visibility&&["owner","public"].includes(r.visibility))||!g(r.readId)||!b(r.startedAt)||!b(r.failedAt)||"owner"===r.visibility&&this.audiences.get(e)?.publicOnly?"ignored":("public"===r.visibility&&this.setVisibility(e,t,"public",a),"public"===r.visibility&&"public"!==d&&(this.client.setQueryData(a,[]),o.availability=P),o.versionedObserved=!0,o.wsFailure=++this.serial,o.availability={...o.availability,status:"unavailable",error:"Account data is temporarily unavailable.",retryAt:this.now()+3e4},this.emit(),i(),"accepted");if("position_state"!==r.type||!Array.isArray(r.positions))return"ignored";if("snapshot"===r.updateKind){let s,n;try{if(s=y(r.accountRead,{wallet:e,resource:"positions"}),this.audiences.get(e)?.publicOnly&&"owner"===s.visibility)return"ignored";n=S({dataList:r.positions,count:r.positions.length,totalCount:r.positions.length,accountRead:s,unavailablePositionDetails:r.unavailablePositionDetails},{wallet:e,resource:"positions"})}catch{return"ignored"}return this.setVisibility(e,t,s.visibility,a),this.accept(o,n,++this.serial,!1,!1),this.client.setQueryData(a,n.dataList),i(),"accepted"}let c=void 0===r.updateKind&&void 0===r.accountRead;if(!c&&("price"!==r.updateKind||!("string"==typeof r.visibility&&["public","owner"].includes(r.visibility))||!g(r.snapshotReadId)||!b(r.accountReadCompletedAt)||!b(r.priceUpdatedAt)))return"ignored";if(!c&&("price"!==r.updateKind||r.visibility!==d||r.snapshotReadId!==o.baseId||r.accountReadCompletedAt!==o.availability.metadata?.completedAt||!b(r.priceUpdatedAt)))return o.baseId||n?"ignored":(n=!0,i(),"refresh");let h=this.data(a,t);if(!h)return"ignored";let p=new Map;for(let t of r.positions)u(t)&&t.wallet===e&&"string"==typeof t.id&&p.set(_(t),t);return this.client.setQueryData(a,h.map(e=>{let t=p.get(_(e));if(!t)return e;let r="string"==typeof t.markPrice&&Number.isFinite(Number(t.markPrice))&&Number(t.markPrice)>0?t.markPrice:e.markPrice;return c?{...e,markPrice:r}:{...e,markPrice:r,pnlUsd:"string"==typeof t.pnlUsd&&Number.isFinite(Number(t.pnlUsd))?t.pnlUsd:e.pnlUsd,pnlPercent:"string"==typeof t.pnlPercent&&Number.isFinite(Number(t.pnlPercent))?t.pnlPercent:e.pnlPercent}})),i(),"accepted"}}}}e.s(["AccountReadCache",0,A,"historyKey",0,C,"positionsKey",0,T],937505);let E=(0,r.createContext)(null);function L(){let e=(0,r.useContext)(E);
2if(!e)throw Error("AccountReadProvider is required");return(0,r.useSyncExternalStore)(e.cache.subscribe,e.cache.snapshot,e.cache.snapshot),{...e,ready:e.cache.isCurrent(e.auth)}}e.s(["AccountReadProvider",0,function({wallet:e,jwt:i,children:n}){let a=(0,s.useQueryClient)(),[l]=(0,r.useState)(()=>new A(a)),o=(0,r.useMemo)(()=>({wallet:e,authenticated:null!==i}),[e,i]),d=(0,r.useMemo)(()=>({cache:l,auth:o,jwt:i}),[l,o,i]);return(0,r.useLayoutEffect)(()=>{let e=l.connect();return l.commit(o),()=>{l.retire(o),e()}},[l,o]),(0,r.useEffect)(()=>{let e=setInterval(()=>l.tick(),15e3);return()=>clearInterval(e)},[l]),(0,t.jsx)(E.Provider,{value:d,children:n})},"useAccountQuery",0,function({request:e,select:t,interval:r,enabled:s=!0}){let{cache:n,auth:a,jwt:l,ready:o}=L(),d=e?.resource==="positions"?T(e.wallet):C(e?.wallet??"",e?.page?.offset??0);return{...(0,i.useQuery)({queryKey:d,queryFn:()=>{if(!e)throw Error("No account selected");return n.read(d,e,a,t=>N(e,l,t),t)},enabled:o&&s&&!!e,retry:!1,staleTime:e?.resource==="positions"?1e4:3e4,refetchInterval:r??!1,refetchOnWindowFocus:e?.resource==="positions"||e?.page?.offset===0}),data:n.data(d,a),availability:n.available(d,a),stale:n.stale(d,a),key:d}},"useAccountReadSession",0,L,"useIndependentAccountQuery",0,function({key:e,fetcher:t,enabled:r,interval:s,staleTime:n=1e4,coverage:a="complete",refetchOnWindowFocus:l}){let{cache:o,auth:d,ready:c}=L();return{...(0,i.useQuery)({queryKey:e,queryFn:({signal:r})=>o.independent(e,d,t,a,r),enabled:c&&r,retry:!1,staleTime:n,refetchInterval:s,...void 0===l?{}:{refetchOnWindowFocus:l}}),data:o.data(e,d),availability:o.available(e,d)}}],432533)},684446,296234,717997,475274,734195,756950,92065,931524,575146,e=>{"use strict";let t,r,i;e.s(["DesktopChartLinkBadge",()=>d],296234);var s=e.i(394390),n=e.i(183023);let a=(0,n.createContext)(null);e.s(["DesktopTicketDraftProvider",0,function({store:e,owner:t,children:r}){let[i]=(0,n.useState)(()=>Symbol("ticket-draft")),l=(0,n.useMemo)(()=>({store:e,owner:t,lease:i,pending:new Map}),[e,t,i]);return(0,n.useLayoutEffect)(()=>{for(let[r,s]of(e.acquire(t,i),l.pending))e.write(t,i,r,s);l.pending.clear()},[e,t,i,l]),(0,s.jsx)(a.Provider,{value:l,children:r})},"useClearDesktopTicketDraftPrefix",0,function(){let e=(0,n.useContext)(a);return(0,n.useCallback)(t=>{e&&e.store.clearPrefix(e.owner,e.lease,t)},[e])},"useDesktopTicketDraftHas",0,function(e){let t=(0,n.useContext)(a);return t?.store.has(t.owner,e)??!1},"useDesktopTicketDraftState",0,function(e,t){let r=(0,n.useContext)(a),[i,s]=(0,n.useState)(()=>{if(r?.store.has(r.owner,e))return r.store.read(r.owner,e);let i="function"==typeof t?t():t;return r?.pending.set(e,i),i});(0,n.useLayoutEffect)(()=>{r?.pending.has(e)&&r.store.write(r.owner,r.lease,e,r.pending.get(e))&&r.pending.delete(e)},[r,e]);let l=(0,n.useRef)(i),o=(0,n.useRef)(!0);return(0,n.useLayoutEffect)(()=>(o.current=!0,()=>{o.current=!1}),[]),[i,(0,n.useCallback)(t=>{let i="function"==typeof t?t(l.current):t;if(r&&!r.store.write(r.owner,r.lease,e,i)){if(!o.current)return;r.pending.set(e,i)}l.current=i,o.current&&s(i)},[r,e])]}],684446);var l=e.i(942553),o=e.i(585457);function d(){let e=(0,l.useTranslations)("trading"),{desktopCharts:t,marketInfo:r}=(0,o.useMarketContext)();return t.enabled&&!(t.state.slots.length<2)&&r?(0,s.jsx)("span",{"data-linked-chart":t.state.activeId,"aria-label":e("chartDeskTrading",{symbol:r.symbol}),className:"inline-flex max-w-16 shrink-0 items-center truncate px-1 text-[11px] font-medium text-foreground",children:r.symbol}):null}e.s(["useLeverageCapSync",0,function({leverageKey:e,leverage:t,maxLeverage:r,capKnown:i,onClamp:s}
2){let[a,l]=(0,n.useState)(e);(0,n.useEffect)(()=>{a!==e?l(e):i&&Number.isFinite(r)&&r>0&&t>r&&s(r)},[e,a,t,r,i,s])}],717997),e.s(["stopLossLiquidationError",0,function(e,t,r){if(!Number.isFinite(t)||t<=0)return null;let i=Number(r);return!Number.isFinite(i)||i<=0?null:(e?t<=i:t>=i)?"stopLossBeyondLiquidation":null}],475274);var c=e.i(586569);e.s(["tradingValidationError",0,function(e){return(0,c.validationText)(e)}],734195),e.s(["useExecutionGeneration",0,function(e){let[t,r]=(0,n.useState)(()=>({identity:e,token:Symbol(e)}));t.identity!==e&&r({identity:e,token:Symbol(e)});let i=(0,n.useRef)(null);return(0,n.useLayoutEffect)(()=>(i.current=t.token,()=>{i.current=null}),[t.token]),(0,n.useCallback)(()=>i.current===t.token,[t.token])}],756950);var u=e.i(504458);let h=(0,u.default)("lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);e.s(["Lock",0,h],92065);let p=(0,u.default)("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["Settings",0,p],931524);var m=e.i(489980),f=e.i(375039),x=e.i(541078),g=e.i(310526),b=e.i(507767),v=e.i(151067),y=e.i(729418),w=e.i(839209),j=e.i(406277),S=e.i(837299),k=e.i(671454),N=Symbol("radix.slottable");function P(e){return n.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===N}var T=e.i(204095),C=e.i(370030),M=e.i(710460),_="Popover",[A,E]=(0,x.createContextScope)(_,[w.createPopperScope]),L=(0,w.createPopperScope)(),[F,R]=A(_),D=e=>{let{__scopePopover:t,children:r,open:i,defaultOpen:a,onOpenChange:l,modal:o=!1}=e,d=L(t),c=n.useRef(null),[u,h]=n.useState(!1),[p,m]=(0,T.useControllableState)({prop:i,defaultProp:a??!1,onChange:l,caller:_});return(0,s.jsx)(w.Root,{...d,children:(0,s.jsx)(F,{scope:t,contentId:(0,y.useId)(),triggerRef:c,open:p,onOpenChange:m,onOpenToggle:n.useCallback(()=>m(e=>!e),[m]),hasCustomAnchor:u,onCustomAnchorAdd:n.useCallback(()=>h(!0),[]),onCustomAnchorRemove:n.useCallback(()=>h(!1),[]),modal:o,children:r})})};D.displayName=_;var I="PopoverAnchor",U=n.forwardRef((e,t)=>{let{__scopePopover:r,...i}=e,a=R(I,r),l=L(r),{onCustomAnchorAdd:o,onCustomAnchorRemove:d}=a;return n.useEffect(()=>(o(),()=>d()),[o,d]),(0,s.jsx)(w.Anchor,{...l,...i,ref:t})});U.displayName=I;var O="PopoverTrigger",B=n.forwardRef((e,t)=>{let{__scopePopover:r,...i}=e,n=R(O,r),a=L(r),l=(0,f.useComposedRefs)(t,n.triggerRef),o=(0,s.jsx)(k.Primitive.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":J(n.open),...i,ref:l,onClick:(0,m.composeEventHandlers)(e.onClick,n.onOpenToggle)});return n.hasCustomAnchor?o:(0,s.jsx)(w.Anchor,{asChild:!0,...a,children:o})});B.displayName=O;var z="PopoverPortal",[$,V]=A(z,{forceMount:void 0}),H=e=>{let{__scopePopover:t,forceMount:r,children:i,container:n}=e,a=R(z,t);return(0,s.jsx)($,{scope:t,forceMount:r,children:(0,s.jsx)(S.Presence,{present:r||a.open,children:(0,s.jsx)(j.Portal,{asChild:!0,container:n,children:i})})})};H.displayName=z;var W="PopoverContent",q=n.forwardRef((e,t)=>{let r=V(W,e.__scopePopover),{forceMount:i=r.forceMount,...n}=e,a=R(W,e.__scopePopover);return(0,s.jsx)(S.Presence,{present:i||a.open,children:a.modal?(0,s.jsx)(G,{...n,ref:t}):(0,s.jsx)(Y,{...n,ref:t})})});q.displayName=W;var K=((i=n.forwardRef((e,t)=>{let{children:r,...i}=e;if(n.isValidElement(r)){var s;let e,a,l=(s=r,(a=(e=Object.getOwnPropertyDescriptor(s.props,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?s.ref:(a=(e=Object.getOwnPropertyDescriptor(s,"ref")?.get)&&"isReactWarning"in e&&e.isReactWarning)?s.props.ref:s.props.ref||s.ref),o=function(e,t){let r={...t};for(let i in t){let s=e[i],n=t[i];/^on[A-Z]/.test(i)?s&&n?r[i]=(...e)=>{let t=n(...e);return s(...e),t}:s&&(r[i]=s):"style"===i?r[i]={...s,...n}
2:"className"===i&&(r[i]=[s,n].filter(Boolean).join(" "))}return{...e,...r}}(i,r.props);return r.type!==n.Fragment&&(o.ref=t?(0,f.composeRefs)(t,l):l),n.cloneElement(r,o)}return n.Children.count(r)>1?n.Children.only(null):null})).displayName="PopoverContent.RemoveScroll.SlotClone",t=i,(r=n.forwardRef((e,r)=>{let{children:i,...a}=e,l=n.Children.toArray(i),o=l.find(P);if(o){let e=o.props.children,i=l.map(t=>t!==o?t:n.Children.count(e)>1?n.Children.only(null):n.isValidElement(e)?e.props.children:null);return(0,s.jsx)(t,{...a,ref:r,children:n.isValidElement(e)?n.cloneElement(e,void 0,i):null})}return(0,s.jsx)(t,{...a,ref:r,children:i})})).displayName="PopoverContent.RemoveScroll.Slot",r),G=n.forwardRef((e,t)=>{let r=R(W,e.__scopePopover),i=n.useRef(null),a=(0,f.useComposedRefs)(t,i),l=n.useRef(!1);return n.useEffect(()=>{let e=i.current;if(e)return(0,C.hideOthers)(e)},[]),(0,s.jsx)(M.RemoveScroll,{as:K,allowPinchZoom:!0,children:(0,s.jsx)(X,{...e,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:(0,m.composeEventHandlers)(e.onCloseAutoFocus,e=>{e.preventDefault(),l.current||r.triggerRef.current?.focus()}),onPointerDownOutside:(0,m.composeEventHandlers)(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey;l.current=2===t.button||r},{checkForDefaultPrevented:!1}),onFocusOutside:(0,m.composeEventHandlers)(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),Y=n.forwardRef((e,t)=>{let r=R(W,e.__scopePopover),i=n.useRef(!1),a=n.useRef(!1);return(0,s.jsx)(X,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(i.current||r.triggerRef.current?.focus(),t.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(i.current=!0,"pointerdown"===t.detail.originalEvent.type&&(a.current=!0));let s=t.target;r.triggerRef.current?.contains(s)&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&a.current&&t.preventDefault()}})}),X=n.forwardRef((e,t)=>{let{__scopePopover:r,trapFocus:i,onOpenAutoFocus:n,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:d,onFocusOutside:c,onInteractOutside:u,...h}=e,p=R(W,r),m=L(r);return(0,b.useFocusGuards)(),(0,s.jsx)(v.FocusScope,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:n,onUnmountAutoFocus:a,children:(0,s.jsx)(g.DismissableLayer,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:d,onFocusOutside:c,onDismiss:()=>p.onOpenChange(!1),children:(0,s.jsx)(w.Content,{"data-state":J(p.open),role:"dialog",id:p.contentId,...m,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Q="PopoverClose";function J(e){return e?"open":"closed"}n.forwardRef((e,t)=>{let{__scopePopover:r,...i}=e,n=R(Q,r);return(0,s.jsx)(k.Primitive.button,{type:"button",...i,ref:t,onClick:(0,m.composeEventHandlers)(e.onClick,()=>n.onOpenChange(!1))})}).displayName=Q,n.forwardRef((e,t)=>{let{__scopePopover:r,...i}=e,n=L(r);return(0,s.jsx)(w.Arrow,{...n,...i,ref:t})}).displayName="PopoverArrow";var Z=e.i(827751),ee=e.i(153517);e.s(["Popover",0,function({...e}){return(0,s.jsx)(D,{"data-slot":"popover",...e})},"PopoverAnchor",0,function({...e}){return(0,s.jsx)(U,{"data-slot":"popover-anchor",...e})},"PopoverContent",0,function({className:e,align:t="center",sideOffset:r=4,onPointerDownOutside:i,onFocusOutside:n,onOpenAutoFocus:a,onCloseAutoFocus:l,...o}){return(0,s.jsx)(H,{children:(0,s.jsx)(q,{"data-slot":"popover-content",align:t,sideOffset:r,...(0,Z.keypadLayerProps)({onPointerDownOutside:i,onFocusOutside:n,onOpenAutoFocus:a}),onCloseAutoFocus:(0,Z.keepMovedFocusOnClose)(l),className:(0,ee.cn)("bg-popover text-popover-foreground border-border-strong data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
2de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-float border p-4 shadow-md outline-hidden",e),...o})})},"PopoverTrigger",0,function({...e}){return(0,s.jsx)(B,{"data-slot":"popover-trigger",...e})}],575146)},585457,e=>{"use strict";e.s(["MarketProvider",()=>w,"resolveMarketInfo",()=>b,"useMarketContext",()=>j]);var t=e.i(394390),r=e.i(183023);e.i(889723);var i=e.i(49332),s=e.i(465217),n=e.i(622463),a=e.i(722732),l=e.i(643459),o=e.i(828047),d=e.i(51314),c=e.i(781355),u=e.i(979804),h=e.i(619966),p=e.i(106476);let m={version:2,slots:[],activeId:"",layout:1,nextId:2},f="So11111111111111111111111111111111111111112",x=[{isLoaded:()=>null!==(0,n.getGlobalPhoenixRegistry)(),subscribe:n.subscribePhoenixRegistry},{isLoaded:()=>null!==(0,a.getGlobalGmTradeRegistry)(),subscribe:a.subscribeGmTradeRegistry}],g=(0,r.createContext)({marketMint:f,setMarketMint:()=>{},marketInfo:null,desktopCharts:{enabled:!1,ready:!1,loading:!1,error:!1,retry:()=>{},state:m,focusRevision:0,isCurrentFocus:()=>!1,visibleIds:[],cells:[],capacity:1,targetKey:"",present:()=>{},selectTarget:()=>!1,isTargetCurrent:()=>!1,focus:()=>{},selectMarket:()=>{},close:()=>{},setLayout:()=>{},setResolution:()=>{},reset:()=>{}}});function b(e){let t=i.JUPITER_MARKETS[e];if(t)return t;let r=(0,l.resolveMintSymbol)(e);
2if(r)return{symbol:r,name:r,image:(0,s.getFlashTokenImage)(r)};let d=(0,n.resolvePhoenixSymbol)(e);if(d)return{symbol:d,name:d,image:(0,s.getFlashTokenImage)(d)};let c=(0,a.resolveGmTradeMarket)(e);if(c)return{symbol:c.symbol,name:c.symbol,image:(0,s.getFlashTokenImage)(c.symbol)};if((0,o.sunriseListsSymbol)(e)){let t=e.toUpperCase();return{symbol:t,name:t,image:(0,s.getFlashTokenImage)(t)}}return null}function v(){let e=window.location.pathname.match(/^(?:\/[a-z]{2})?\/perps\/([a-zA-Z0-9-]+)$/);return e?e[1]:null}function y(e){let t=new URLSearchParams(window.location.search).toString();return`/perps/${(0,d.toUrlSlug)(e)}${t?`?${t}`:""}`}function w({initialMint:i,children:s}){(0,u.useTokenIconsVersion)();let n=(0,h.useIsDesktop)(),{multiChartEnabled:a,preferenceRevision:l}=(0,p.useMultiChartPreference)(),[j,S]=(0,r.useState)(()=>({marketMint:i,workspace:null,focusRevision:0,targetRevision:0})),k=(0,r.useRef)(j),N=(0,r.useRef)(null),P=(0,r.useRef)(null),[T,C]=(0,r.useState)(null),[M,_]=(0,r.useState)({capacity:1,expanded:!1}),A=(0,r.useRef)(M),E=(0,r.useRef)(void 0),L=(0,r.useRef)(0),[F,R]=(0,r.useState)(0),[D,I]=(0,r.useState)(0),[U,O]=(0,r.useState)(null),B=!0===n&&a,z=j.marketMint,$=(0,r.useCallback)((e,t)=>(0,d.toUrlSlug)(e)===(0,d.toUrlSlug)(t),[]),V=(0,r.useCallback)(()=>{let e=P.current;return e&&(0,p.getMultiChartPreference)()&&(0,p.getMultiChartPreferenceRevision)()===e.preferenceRevision&&L.current===e.viewportRevision&&window.matchMedia(h.DESKTOP_QUERY).matches?e:null},[]),H=B&&T&&P.current===T&&T.preferenceRevision===l&&T.viewportRevision===F?T:null,W=B&&U?.preferenceRevision===l&&U.viewportRevision===F&&U.loadAttempt===D,q=(0,r.useCallback)((e,t,r=!1)=>{let i=k.current,s=r||i.marketMint!==e||i.workspace?.activeId!==t?.activeId;if(!s&&i.workspace===t)return i;let n=N.current,a=r||t!==i.workspace&&!!n&&!!t&&(!i.workspace||n.desktopChartTargetKey(t)!==n.desktopChartTargetKey(i.workspace)),l={marketMint:e,workspace:t,focusRevision:i.focusRevision+Number(s),targetRevision:i.targetRevision+Number(a)};return k.current=l,S(l),l},[]),K=(0,r.useCallback)((e,t,r)=>{window.history["replace"===t?"replaceState":"pushState"](r?{imperialDesktopChart:r}:null,"",y(e))},[]);(0,r.useEffect)(()=>{if(!a)return;let e=window.matchMedia(h.DESKTOP_QUERY),t=()=>{P.current=null,L.current+=1,R(L.current)};return e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[a]),(0,r.useEffect)(()=>{if(P.current=null,!B)return;let t=!1,r=null,i=()=>!t&&(0,p.getMultiChartPreference)()&&(0,p.getMultiChartPreferenceRevision)()===l&&L.current===F&&window.matchMedia(h.DESKTOP_QUERY).matches,s=e=>{if(N.current=e,!i())return;let t=k.current,s=t.workspace;if(!s){try{let t=localStorage.getItem(e.DESKTOP_CHART_STORAGE_KEY);s=e.parseDesktopChartWorkspace(t),null===t&&(s=e.parseDesktopChartWorkspace(localStorage.getItem(e.LEGACY_DESKTOP_CHART_STORAGE_KEY)))}catch{}s??=e.createDesktopChartWorkspace(t.marketMint)}s=e.selectDesktopChartMarket(s,t.marketMint,void 0,$),P.current=r={model:e,preferenceRevision:l,viewportRevision:F},q(t.marketMint,s,!0),C(r)};return N.current?s(N.current):e.A(692218).then(s).catch(()=>{i()&&O({preferenceRevision:l,viewportRevision:F,loadAttempt:D})}),()=>{t=!0,P.current===r&&(P.current=null)}},[B,l,F,D,q,$]),(0,r.useEffect)(()=>{if(H&&V()===H&&j.workspace)try{localStorage.setItem(H.model.DESKTOP_CHART_STORAGE_KEY,H.model.serializeDesktopChartWorkspace(j.workspace))}catch{}},[H,V,j.workspace]);let[G,Y]=(0,r.useState)(0),[X,Q]=(0,r.useState)(0);(0,r.useEffect)(()=>{let e=()=>{Y(x.filter(e=>e.isLoaded()).length)},t=x.map(t=>t.subscribe(e));return e(),()=>t.forEach(e=>e())},[]),(0,r.useEffect)(()=>{let e=()=>Q(e=>e+1),t=(0,o.subscribeSunriseMarkets)(e);return e(),t},[]);let J=G===x.length&&null!==(0,o.getGlobalSunriseMarkets)(),Z=(0,r.useCallback)((e,t="push")=>{let r=k.current,i=V(),s=i&&r.workspace?i.model.selectDesktopChartMarket(r.workspace,e,void 0,$):r.workspace,n=i&&s?i.model.activeDesktopChart(s).marketMint:e;(r.marketMint!==n||r.workspace!==s)&&(q(n,s),K(n,t,i?s?.activeId:void 0))},[V,$,q,K]),ee=(0,r.useCallback)(e=>
2{if(!H||V()!==H)return!1;let t=k.current;if(!t.workspace)return!1;let r=e(t.workspace,H.model);if(r===t.workspace)return!1;let i=H.model.activeDesktopChart(r).marketMint;return q(i,r),(i!==t.marketMint||r.activeId!==t.workspace.activeId)&&K(i,"push",r.activeId),!0},[H,V,q,K]),et=(0,r.useCallback)((e,t,r)=>{if(!V())return;E.current=r;let i={capacity:Number.isFinite(e)?Math.max(1,Math.min(4,Math.floor(e))):1,expanded:t};A.current=i,_(e=>e.capacity===i.capacity&&e.expanded===i.expanded?e:i)},[V]),er=(0,r.useCallback)(()=>{let e=E.current?.()??A.current.capacity;return Number.isFinite(e)?Math.max(1,Math.min(4,Math.floor(e))):1},[]),ei=(0,r.useCallback)(()=>{let e=V();return e?`${e.preferenceRevision}:${e.viewportRevision}:${k.current.targetRevision}`:""},[V]),es=(0,r.useCallback)(e=>{if(!H||V()!==H||e.expectedKey!==ei())return!1;let t=k.current.workspace;if(!t)return!1;let r=er();if("add"===e.kind)return!A.current.expanded&&t.slots.length<r;let i=H.model.presentedDesktopChartCells(t,r,A.current.expanded);return"replace"===e.kind?i.some(t=>t.slot?.id===e.chartId):!A.current.expanded&&i.some(t=>t.position===e.position&&!t.slot)},[H,V,ei,er]),en=(0,r.useCallback)((e,t)=>!!es(e)&&ee((r,i)=>{if("replace"===e.kind)return i.selectDesktopChartMarket(r,t,e.chartId,$);if("fill"===e.kind)return i.fillDesktopChartCell(r,e.position,t,er(),i.desktopChartTargetKey(r));let s=i.addDesktopChart(r,t,er());return s===r?r:{...s,activeId:r.activeId}}),[es,ee,$,er]),ea=(0,r.useMemo)(()=>({retry:()=>I(e=>e+1),isCurrentFocus:e=>!!H&&V()===H&&k.current.focusRevision===e,focus:e=>ee((t,r)=>r.focusDesktopChart(t,e)),selectMarket:(e,t)=>ee((r,i)=>i.selectDesktopChartMarket(r,t,e,$)),close:e=>ee((t,r)=>r.closeDesktopChart(t,e)),setLayout:e=>ee((t,r)=>e<=er()?r.setDesktopChartLayout(t,e):t),setResolution:(e,t)=>ee((r,i)=>i.setDesktopChartResolution(r,e,t)),reset:()=>ee((e,t)=>({...e,slots:[{...t.activeDesktopChart(e),position:0}],layout:1}))}),[H,V,ee,$,er]),el=(0,r.useMemo)(()=>{let e=H&&j.workspace?H.model.presentedDesktopChartCells(j.workspace,M.capacity,M.expanded):[];return{...ea,enabled:!!H,ready:!!H,loading:B&&!H&&!W,error:!!W,state:H&&j.workspace?j.workspace:m,focusRevision:j.focusRevision,targetKey:H?`${H.preferenceRevision}:${H.viewportRevision}:${j.targetRevision}`:"",visibleIds:e.flatMap(e=>e.slot?[e.slot.id]:[]),cells:e,capacity:M.capacity,present:et,selectTarget:en,isTargetCurrent:es}},[H,B,W,j.workspace,j.focusRevision,j.targetRevision,ea,M,et,en,es]);(0,r.useEffect)(()=>{let e=e=>{let t=v();if(!t)return;let r=(0,d.fromUrlSlug)(t),i=k.current,s=V(),n=s&&"string"==typeof e.state?.imperialDesktopChart?i.workspace?.slots.find(t=>t.id===e.state.imperialDesktopChart&&$(t.marketMint,r)):void 0,a=s&&i.workspace?s.model.selectDesktopChartMarket(i.workspace,r,n?.id,$):i.workspace;q(s&&a?s.model.activeDesktopChart(a).marketMint:r,a)};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[V,$,q]),(0,r.useEffect)(()=>{b(z)&&(0,c.writeLastMarketSlug)((0,d.toUrlSlug)(z))},[z,G]),(0,r.useEffect)(()=>{!J||b(z)||Z(f,"replace")},[z,J,X,Z]),(0,r.useEffect)(()=>{let e=v();e&&d.MINT_TO_SLUG[e]&&window.history.replaceState(null,"",y(e))},[]);let eo=b(z);return(0,t.jsx)(g.Provider,{value:{marketMint:z,setMarketMint:Z,marketInfo:eo,desktopCharts:el},children:s})}function j(){return(0,r.useContext)(g)}},567978,562955,255094,473344,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(116082),s=e.i(942553),n=e.i(599059);async function a(e,t){let{value:r}=await e.getSignatureStatuses([t],{searchTransactionHistory:!0}),i=r[0];return i?i.err?"failed":"confirmed"===i.confirmationStatus||"finalized"===i.confirmationStatus?i.slot:null:null}e.s(["SUNRISE_SETTLEMENT_GIVE_UP_MS",0,6e4,"confirmedSunriseSlot",0,a,"createSunriseSettlementRefresh",0,function(e,t,r=(e,t)=>{let r=setTimeout(e,t);return()=>clearTimeout(r)},i=()=>{}){let s=!1,n=new Set,a=new Map,l=new Map,o=(e,t)=>{l.set(e,t),i(e,t)},d=new Set;return{enqueue(i){if(s||n.has(i.signature))return;n.add(i.signature),a.set(i.signature,i);let l=null,c=0,u=0,h=async()=>{if(s)return;if(null===l&&u>=6e4)return void a.delete(i.signature);try{if(null===l){let t=await e(i.signature);if(s)return;if("failed"===t){a.delete(i.signature),o(i.signature,"failed");return}l=t,null!==l&&o(i.signature,"confirmed")}if(null!==l){if(await t({minContextSlot:l,profileIndex:i.profileIndex,symbol:i.symbol}))return void a.delete(i.signature)}else u>=8e3&&await t()}catch{}if(s)return;let n=c++<20?250:1e3;u+=n;let p=r(()=>{d.delete(p),h()},n);d.add(p)};h()},outcome:e=>l.get(e),isPending:e=>[...a.values()].some(t=>t.symbol===e),dispose(){for(let e of(s=!0,a.clear(),l.clear(),d))e();d.clear()}}},"indexedSunriseSettlements",0,function(e,t){return t?e.flatMap(e=>e.wallet===t&&"sunrise"===e.underwriter&&"open"===e.status&&e.asset&&e.openingSignature?[{signature:e.openingSignature,profileIndex:e.profileIndex??0,symbol:e.asset}]:[]):[]},"onSunriseRpcOpen",0,function(e,t){let r=e._rpcWebSocket;return r?(r.on("open",t),()=>r.off("open",t)):()=>{}}],562955);var l=e.i(190459);function o(e){return!!e.settledAtSubmit&&(!(0,l.confirmsAfterResponse)(e.venue)||!!e.signatureConfirmed)}function d(e,t){return(0,l.confirmsAfterResponse)(e.venue)&&!e.signatureConfirmed?6e4:t}e.s(["closeConfirmSignal",0,function(e,t){var r,i;let s;if(t.disappeared.has(e.key))return"disappearance";if(e.firstSight&&t.hasSeenLive&&!t.liveKeys.has(e.key))return"first-sight-missing";let n=(r=e.venue,i=t.venues,(s=(0,l.underwriterLiteralFrom)(r))?i[s]:void 0);if("closing"===e.type&&void 0!==n&&n.observedProfiles.has(e.profileIndex)&&!n.keys.has(e.key))return"venue-authoritative-absence";if("reducing"===e.type&&void 0!==e.sizeUsdAtIntent&&t.liveKeys.has(e.key)){let r=t.sizeByKey.get(e.key);if(void 0!==r&&r<e.sizeUsdAtIntent-.01)return"size-decrease"}return null},"intentTimeoutMs",0,d,"settledIntentAwaitingView",0,function(e,t){return"pending"===e.status&&!!o(e)&&!!["opening","increasing","closing","reducing"].includes(e.type)&&t-e.timestamp>=8e3},"settlementProven",0,o],255094);var c=e.i(799227);e.s(["pendingMarketIdentifier",0,function(e){return e.market?.toBase58()??e.marketId},"pendingMarketKey",0,function(e){try{return new c.PublicKey(e)}catch{return}}],473344);let u=(0,r.createContext)(void 0);e.s(["PendingPositionsProvider",0,function({children:e}){let a=(0,s.useTranslations)("trading"),[l,c]=(0,r.useState)([]),h=(0,r.useRef)(new Set),p=(0,r.useCallback)(e=>{c(t=>[...t,e])},[]);(0,r.useEffect)(()=>
2{if(0===l.length)return;let e=setInterval(()=>{let e=Date.now();c(t=>{let r=t.filter(t=>"pending"===t.status&&e-t.timestamp>d(t,3e4));for(let e of r){if(h.current.has(e.id)||(h.current.add(e.id),o(e)))continue;let t="opening"===e.type?"open":"increasing"===e.type?"increase":"close",r=e.venue?(0,n.getVenueLabel)(e.venue):null;i.toast.error(r?a("pendingIntentTimeoutVenue",{verb:t,venue:r}):a("pendingIntentTimeout",{verb:t}))}return t.filter(e=>!r.some(t=>t.id===e.id))})},2e3);return()=>clearInterval(e)},[l.length,a]);let m=(0,r.useCallback)((e,t)=>{c(r=>r.map(r=>r.id===e?{...r,status:t}:r)),("confirmed"===t||"failed"===t)&&c(t=>t.filter(t=>t.id!==e))},[]),f=(0,r.useCallback)(e=>{c(t=>t.some(t=>t.id===e&&!t.signatureConfirmed)?t.map(t=>t.id===e?{...t,signatureConfirmed:!0}:t):t)},[]),x=(0,r.useCallback)(e=>{c(t=>t.filter(t=>t.id!==e))},[]),g=(0,r.useCallback)((e,t)=>e&&t?l.filter(r=>{try{return r.market&&r.owner&&r.market.equals(e)&&r.owner.equals(t)&&"pending"===r.status}catch(e){return console.error("Error comparing PublicKeys:",e),!1}}):[],[l]),b=(0,r.useCallback)(()=>{let e=Date.now()-3e5;c(t=>t.filter(t=>t.timestamp>e||"pending"!==t.status))},[]),v=(0,r.useCallback)((e,t,r)=>l.some(i=>{try{return"closing"===i.type&&"pending"===i.status&&i.market&&i.owner&&i.market.equals(e)&&i.owner.equals(t)&&i.closingPosition?.openTime===r}catch(e){return console.error("Error checking if position is being closed:",e),!1}}),[l]),y=(0,r.useCallback)((e,t,r)=>l.find(i=>{try{return"pending"===i.status&&i.market&&i.owner&&i.market.equals(e)&&i.owner.equals(t)&&i.closingPosition?.openTime===r}catch(e){return console.error("Error getting pending operation for position:",e),!1}})||null,[l]),w=(0,r.useCallback)((e,t)=>l.find(r=>{try{return"opening"===r.type&&"pending"===r.status&&(r.market?.toBase58()===e||r.marketId===e)&&r.isLong===t}catch(e){return console.error("Error getting pending opening for market side:",e),!1}})||null,[l]),j=(0,r.useCallback)(e=>{c(t=>{let r=t.find(t=>"pending"===t.status&&("opening"===t.type||"increasing"===t.type)&&t.positionPda===e);return r?t.filter(e=>e.id!==r.id):t})},[]),S=(0,r.useCallback)(e=>{c(t=>t.filter(t=>"pending"!==t.status||"closing"!==t.type&&"reducing"!==t.type||t.positionPda!==e))},[]),k=(0,r.useCallback)((e,t)=>l.some(r=>("closing"===r.type||"reducing"===r.type)&&"pending"===r.status&&r.positionPda===e&&(!t||!r.asset||r.asset===t)),[l]);return(0,t.jsx)(u.Provider,{value:{pendingPositions:l,addPendingPosition:p,updatePositionStatus:m,markSignatureConfirmed:f,removePendingPosition:x,getPendingPositionsForMarket:g,clearOldPendingPositions:b,isPositionBeingClosed:v,getPendingOperationForPosition:y,getPendingOpeningForMarketSide:w,confirmPendingByPositionPda:j,confirmPendingCloseByPositionPda:S,hasPendingCloseForPda:k},children:e})},"usePendingPositions",0,function(){let e=(0,r.useContext)(u);if(!e)throw Error("usePendingPositions must be used within a PendingPositionsProvider");return e}],567978)},731926,e=>{"use strict";var t=e.i(394390),r=e.i(183023),i=e.i(43690);async function s(){let e=await fetch("/api/price/sol");if(!e.ok)throw Error("Failed to fetch SOL price");let t=await e.json(),r=t?.usdPrice;if("number"!=typeof r||!(r>0))throw Error("SOL price not found in response");return r}var n=e.i(299959);let a=(0,r.createContext)(void 0);e.s(["PriceDisplayProvider",0,function({children:e}){let[l]=(0,r.useState)("USD"),{data:o=250}=(0,i.useQuery)({queryKey:["sol-price"],queryFn:s,staleTime:3e4,refetchInterval:6e4,refetchOnWindowFocus:!0,placeholderData:250}),d=(0,n.useIntlTag)();return(0,t.jsx)(a.Provider,{value:{priceMode:l,togglePriceMode:()=>{},formatPrice:(e,t)=>{let r="number"==typeof e?{usd:e,sol:e/o,denomination:"SOL"}:e;if("USD"===l){let e=r.usd,i=t;void 0===i&&(i=e>=100?2:e>=1?5:e>=.01?4:e>=1e-4?6:8);let s=e.toLocaleString(d,{minimumFractionDigits:i,maximumFractionDigits:i});return`$${s}`}{let e=r.sol,i=t;void 0===i&&(i=e>=1?4:e>=.01?6:e>=1e-4?8:10);let s=e.toLocaleString(d,{minimumFractionDigits:i,maximumFractionDigits:i});return`${s} SOL`}},solPrice:o},children:e})},"usePriceDisplay",0,function(){let e=(0,r.useContext)(a);if(void 0===e)throw Error("usePriceDisplay must be used within a PriceDisplayProvider");return e}],731926)},124593,e=>{"use strict";var t=e.i(394390),r=e.i(183023);let i=(0,r.createContext)({isPro:!0,isLoading:!1});e.s(["ProWhitelistProvider",0,function({children:e}){return(0,t.jsx)(i.Provider,{value:{isPro:!0,isLoading:!1},children:e})},"useProWhitelist",0,function(){return(0,r.useContext)(i)}])},711915,e=>{"use strict";var t=e.i(394390),r=e.i(183023);e.i(875574);var i=e.i(142298),s=e.i(214732);let n=(0,r.createContext)(void 0);e.s(["SolBalanceProvider",0,function({children:e}){let{publicKey:a}=(0,i.useUnifiedWallet)(),{balance:l,isLoading:o,known:d,refetch:c}
2=(0,s.useSolBalanceSubscription)({publicKey:a,commitment:"processed",enabled:!!a}),u=(0,r.useMemo)(()=>({balanceLamports:l,balanceSol:l/1e9,balanceKnown:d,isLoading:o,refetch:c}),[l,d,o,c]);return(0,t.jsx)(n.Provider,{value:u,children:e})},"useSolBalance",0,function(){let e=(0,r.useContext)(n);if(void 0===e)throw Error("useSolBalance must be used within a SolBalanceProvider");return e}])},687229,e=>{"use strict";e.s(["UnifiedPositionProvider",()=>eh,"mintToMatchingKey",()=>en,"useUnifiedPositions",()=>em]);var t=e.i(394390),r=e.i(183023),i=e.i(432533),s=e.i(365221),n=e.i(37086),a=e.i(799227),l=e.i(718516),o=e.i(43690),d=e.i(514049),c=e.i(942553),u=e.i(116082);e.i(875574);var h=e.i(142298),p=e.i(894771),m=e.i(567978),f=e.i(473344),x=e.i(224996),g=e.i(86306),b=e.i(737707),v=e.i(520639),y=e.i(717421),w=e.i(703206),j=e.i(29265),S=e.i(810638),k=e.i(924416),N=e.i(670374),P=e.i(689384),T=e.i(68409),C=e.i(828047),M=e.i(777670),_=e.i(326702),A=e.i(562955),E=e.i(275683),L=e.i(938425),F=e.i(156777),R=e.i(190459),D=e.i(599059),I=e.i(255094),U=e.i(795974),O=e.i(439507),B=e.i(622463),z=e.i(265724);e.i(965155);var $=e.i(22156),V=e.i(762745),H=e.i(122097),W=e.i(653982),q=e.i(905843),K=e.i(13294),G=e.i(362221),Y=e.i(555381),X=e.i(722732),Q=e.i(51314),J=e.i(477303),Z=e.i(976125),ee=e.i(341833),et=e.i(728570),er=e.i(613448),ei=e.i(643459);function es(e,t){let r=W.ASSET_TO_MINT[e];if(r)return r;let i=(0,er.pairsMintForPosition)(e,t);if(i)return i;let s=(0,ei.mintForSymbol)(e);if(s)return s;let n=(0,B.getGlobalPhoenixRegistry)();if(n){let t=n.getMarketBySymbol(e);if(t)return t.orderbook.toBase58()}let a=(0,X.getGlobalGmTradeRegistry)();if(a){let t=a.getMarketBySymbol(e)??a.getMarketBySymbol(e.toUpperCase());if(t)return t.indexTokenMint.toBase58()}if((0,C.sunriseListsSymbol)(e))return e.toUpperCase()}function en(e){let t=Q.MINT_TO_SLUG[e];if(t)return t;let r=(0,ei.resolveMintSymbol)(e);if(r)return r.toLowerCase();let i=(0,B.getGlobalPhoenixRegistry)();if(i){let t=i.getSymbolByOrderbook(e);if(t)return t.toLowerCase();if(i.getMarketBySymbol(e))return e.toLowerCase()}let s=(0,X.getGlobalGmTradeRegistry)();if(s){let t=s.getSymbolByIndexMint(e);if(t)return t.toLowerCase();if(s.getMarketBySymbol(e))return e.toLowerCase()}if((0,C.sunriseListsSymbol)(e))return e.toLowerCase();let n=(0,C.sunriseSymbolFromAssetMint)(e);return n?n.toLowerCase():e}let ea=(0,r.createContext)(void 0),el="imperial:loan-overlays:";function eo(e,t,r){return`phoenix:imperial:${e}:${t}:${r??0}`}function ed(e,t){try{let r={};for(let[e,i]of t)(i.borrowedUsd??0)>0&&(r[e]=i);let i=el+e;0===Object.keys(r).length?window.localStorage.removeItem(i):window.localStorage.setItem(i,JSON.stringify(r))}catch{}}let ec=W.USDC_MINT.toBase58(),eu=W.SOL_MINT.toBase58();function eh({children:e}){let{publicKey:r}=(0,h.useUnifiedWallet)(),s=(0,k.useSessionJwt)();return(0,t.jsx)(i.AccountReadProvider,{wallet:r?.toBase58()??null,jwt:s,children:(0,t.jsx)(ep,{children:e})})}function ep({children:e}){let k=(0,c.useTranslations)("trading"),{publicKey:C,isLoading:W}=(0,h.useUnifiedWallet)(),{activeProfileIndex:Q}=(0,p.useProfile)(),er=(0,d.useQueryClient)(),[ei,eh]=(0,r.useState)(0);(0,r.useEffect)(()=>(0,X.subscribeGmTradeRegistry)(()=>eh(e=>e+1)),[]);let{pendingPositions:em,addPendingPosition:ef,updatePositionStatus:ex,markSignatureConfirmed:eg,confirmPendingCloseByPositionPda:eb}=(0,m.usePendingPositions)(),{isConnected:ev}=(0,y.useAccountSubscriptionContext)(),{isConnected:ey}=(0,j.useApiWebSocket)(C?.toBase58()??null),{prices:ew,sourceTimestamps:ej}=(0,$.useAllMarketsPricesThrottled)(),eS=(0,r.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(ew))void 0!==r&&(e[t]=r);return e},[ew]),[ek,eN]=(0,r.useState)([]),[eP,eT]=(0,r.useState)(new Map),[eC,eM]=(0,r.useState)(new Map),e_=(0,r.useRef)(null),eA=(0,r.useRef)(null),eE=(0,r.useRef)(new Map),eL=C?.toBase58()??null;(0,r.useEffect)(()=>{eE.current=eL?function(e){let t=new Map;try{let r=window.localStorage.getItem(el+e);if(!r)return t;let i=Date.now();for(let[e,s]of Object.entries(JSON.parse(r)))s&&"number"==typeof s.borrowedUsd&&s.borrowedUsd>0&&"number"==typeof s.ts&&i-s.ts<2592e6&&t.set(e,s)}catch{}return t}(eL):new Map},[eL]);let eF=(0,r.useRef)(new Map);(0,r.useEffect)(()=>
2{eF.current=new Map},[eL]);let eR=(0,r.useRef)(new Set),[eD,eI]=(0,r.useState)(new Map),[eU,eO]=(0,r.useState)(new Map),[eB,ez]=(0,r.useState)(null),e$=(0,r.useCallback)(e=>{ez(t=>t===e?t:e)},[]),[eV,eH]=(0,r.useState)(new Set),[eW,eq]=(0,r.useState)(new Set),eK=(0,r.useCallback)(e=>{let t=Date.now();eN(r=>r.map(r=>{if(null!==r.userReceived||t-r.closedAt>5e3)return r;let i="long"===r.side?eu:ec;return e.mint!==i?r:{...r,userReceived:e.change.toString(),userReceivedMint:e.mint,status:"confirmed"}}))},[]);(0,v.useUserTokenAccounts)(C,eK);let{onBalanceIncrease:eG}=(0,w.useWsolBalance)();(0,r.useEffect)(()=>eG(e=>{eK({mint:eu,previousBalance:e.previousBalance,newBalance:e.newBalance,change:e.change,timestamp:e.timestamp})}),[eG,eK]);let eY=(0,r.useCallback)(()=>{eA.current&&clearInterval(eA.current),e_.current&&clearTimeout(e_.current),eA.current=setInterval(()=>{er.refetchQueries({queryKey:["jupiter-positions",C?.toBase58()]},{cancelRefetch:!1})},2e3),e_.current=setTimeout(()=>{eA.current&&(clearInterval(eA.current),eA.current=null)},2e4)},[er,C]),eX=(0,r.useCallback)(e=>{let t=(0,N.getMarketMintFromAsset)(e.asset),r=em.find(r=>"pending"===r.status&&("opening"===r.type||"increasing"===r.type)&&r.isLong===("long"===e.side)&&((0,f.pendingMarketIdentifier)(r)===t||(0,f.pendingMarketIdentifier)(r)===e.asset));r&&ex(r.id,"confirmed");let i=Array.from(eP.entries()).find(([,t])=>t.asset===e.asset&&t.side===e.side);if(i){let[e]=i;eT(t=>{let r=new Map(t);return r.delete(e),r})}(i||r)&&(0,V.playSound)("orderFilled"),eY()},[eP,em,ex,eY]),eQ=(0,r.useCallback)((e,t)=>{(0,V.playSound)("positionClosed"),(0,H.requestProfileBalancesBurstRefresh)(),eb(e);let r=em.some(e=>"closing"===e.type&&"pending"===e.status),i={positionPda:e,asset:t.asset,side:t.side,sizeUsd:t.sizeUsd.toString(),collateralUsd:t.collateralUsd.toString(),entryPrice:t.priceUsd.toString(),exitPrice:eS?.[t.asset]?.toString()||"0",pnlUsd:t.realisedPnlUsd.toString(),userReceived:null,userReceivedMint:null,tx3Signature:null,closedAt:Date.now(),status:r?"confirming":"liquidated"};eN(e=>[i,...e]),er.invalidateQueries({queryKey:["jupiter-positions",C?.toBase58()]}),er.invalidateQueries({queryKey:["jupiter-lifecycles",C?.toBase58()]})},[em,eS,er,C,eb]),eJ=ey||ev?12e4:3e4,eZ=C?.toBase58()??null,{data:e0,isLoading:e1,availability:e2}=(0,i.useAccountQuery)({request:eZ?{wallet:eZ,resource:"positions"}:null,select:e=>e.dataList,interval:eJ}),{data:e5,availability:e3}=(0,i.useIndependentAccountQuery)({key:["phoenix-direct-positions",eZ],fetcher:e=>(0,P.fetchPhoenixDirectPositions)(eZ,!0,e),enabled:!!eZ,interval:eJ}),e4=(0,r.useMemo)(()=>[...e0??[],...e5??[]],[e0,e5]),{data:e6,availability:e8,isFetching:e9}=(0,i.useIndependentAccountQuery)({key:["jupiter-orders",eZ],fetcher:e=>(0,P.fetchCombinedOrders)(eZ,!0,e),coverage:"unknown",enabled:!!eZ,staleTime:3e4,interval:eJ}),e7=(0,r.useMemo)(()=>(0,F.collectKnownProfileIndices)(Q,[...e4,...e2.exits],e6?.passthroughOrders),[Q,e4,e6,e2.exits]),te=(0,b.useChainOrderPdas)(C,e7),{data:tt}=(0,o.useQuery)({queryKey:["jupiter-direct-tpsl",C?.toBase58(),e7],queryFn:async()=>{if(!C)return new Map;let e=e7.map(e=>(0,L.getProfilePda)(C,e)[0].toBase58());return(0,P.fetchJupiterTpSlDirect)(C.toBase58(),e)},enabled:!!C,staleTime:15e3,refetchInterval:eJ,placeholderData:e=>e}),tr=(0,r.useMemo)(()=>{let e=e6?.passthroughOrders?.map(e=>e.orderPda)||[],t=[];return tt?.forEach(e=>{e.forEach(e=>{e.orderPda&&t.push(e.orderPda)})}),[...new Set([...te,...e,...t,...eV])]},[te,e6,eV,tt]),ti=(0,r.useMemo)(()=>{let e=new Map;if(C&&(0,K.getPositionPdasForProfiles)(C,e7).forEach(t=>{e.set(t.pda.toBase58(),t)}),C){let t=(0,X.getGlobalGmTradeRegistry)();if(t){let r=["long","short"];for(let i of e7){let[s]=(0,L.getProfilePda)(C,i),n=i===Q;for(let l of n?t.getAllMarkets():t.getAllMarkets().filter(e=>e4?.some(t=>"gmtrade"===t.underwriter&&t.profileIndex===i&&t.asset===e.symbol))){let t=new a.PublicKey(l.marketTokenMint);for(let o of r){if(!n&&!e4?.some(e=>"gmtrade"===e.underwriter&&e.profileIndex===i&&e.asset===l.symbol&&e.side===o))continue;let r=(0,X.getGmTradeCollateralMintForSide)({longTokenMint:new a.PublicKey(l.longTokenMint),shortTokenMint:new a.PublicKey(l.shortTokenMint)},o),d=(0,X.deriveGmTradePosition)(s,t,r,"long"===o),c=d.toBase58();e.has(c)||e.set(c,{pda:d,asset:l.symbol,side:o,custody:t,collateralCustody:r,profileIndex:i,isGmTrade:!0})}}}}}return eP.forEach((t,r)=>{e.has(r)||e.set(r,(0,K.getPositionPdaInfo)(r,t.asset,t.side))}),eD.forEach((t,r)=>{e.has(r)||e.set(r,t)}),Array.from(e.values())},[C,e7,Q,e4,eP,eD,ei]),{positions:ts,closedOrEmptyPdas:tn,isLoading:ta,isConnected:tl,lastUpdate:to}=(0,x.useRealtimePositionUpdates)(ti,eX,eQ),{positions:td,emptyTraderPdas:tc,observedCrossSeats:tu}=(0,J.usePhoenixRealtimePositions)(C,e7,Q??0,eQ),th=(0,r.useMemo)(()=>[...td.map(e=>e.asset),...(e4??[]).filter(e=>"phoenix"===e.underwriter).map(e=>e.asset)],[td,e4]),tp=(0,ee.usePhoenixMarkPrices)(th),tm=(0,r.useMemo)(()=>Array.from(new Set([...(e4??[]).filter(e=>"sunrise"===e.underwriter&&e.asset).map(e=>e.asset),...eU.keys(),...em.filter(e=>"sunrise"===(0,R.underwriterLiteralFrom)(e.venue)&&e.asset).map(e=>e.asset),...eB?[eB]:[]])),[e4,eU,eB,em]),{positions:tf,observedProfiles:tx,closedPositionSlots:tg,isInitialLoading:tb,refresh:tv}
2=(0,Z.useSunrisePositions)(C,e7,tm),ty=(0,r.useRef)(null),tw=C?.toBase58()??null,tj=(0,r.useRef)(()=>{});tj.current=(e,t)=>{if("confirmed"===t)return void eg(e);let r=em.find(t=>t.id===e&&"pending"===t.status);if(!r)return;ex(e,"failed");let i="opening"===r.type?"open":"increasing"===r.type?"increase":"close",s=r.venue?(0,D.getVenueLabel)(r.venue):null;u.toast.error(s?k("pendingIntentTimeoutVenue",{verb:i,venue:s}):k("pendingIntentTimeout",{verb:i}))},(0,r.useEffect)(()=>{if(!tw)return;let e=(0,A.createSunriseSettlementRefresh)(e=>(0,A.confirmedSunriseSlot)((0,_.getSunriseConnection)(),e),tv,void 0,(e,t)=>tj.current(e,t));return ty.current=e,()=>{e.dispose(),ty.current=null}},[tw,tv]);let tS=(0,r.useCallback)(e=>ty.current?.outcome(e),[]);(0,r.useEffect)(()=>{for(let e of em)"failed"!==e.status&&e.settledAtSubmit&&e.asset&&"sunrise"===(0,R.underwriterLiteralFrom)(e.venue)&&e.owner.toBase58()===tw&&ty.current?.enqueue({signature:e.id,profileIndex:e.profileIndex??0,symbol:e.asset});for(let e of(0,A.indexedSunriseSettlements)(e4,tw))ty.current?.enqueue(e)},[em,e4,tw]);let tk=(0,r.useCallback)(()=>{(0,V.playSound)("orderFilled")},[]),{orders:tN,isConnected:tP,lastUpdate:tT,deletedOrders:tC}=(0,g.useRealtimeOrders)(tr,tk),[tM,t_]=(0,r.useState)(0);(0,r.useEffect)(()=>(0,B.subscribePhoenixRegistry)(()=>t_(e=>e+1)),[]),(0,r.useEffect)(()=>()=>{e_.current&&clearTimeout(e_.current),eA.current&&clearInterval(eA.current)},[]),(0,r.useEffect)(()=>{let e=Date.now();eN(t=>t.filter(t=>e-t.closedAt<3e5))},[to]),(0,r.useEffect)(()=>{let e=em.filter(e=>"pending"===e.status&&("opening"===e.type||"increasing"===e.type));if(0===e.length)return;let t=(e,t)=>{let r=(0,N.getMarketMintFromAsset)(t.asset),i=(0,f.pendingMarketIdentifier)(e),s=void 0!==i&&(i===r||i===t.asset),n=e.isLong===("long"===t.side);return s&&n};for(let r of e)(ts.find(e=>t(r,e))||td.find(e=>t(r,e))||tf.find(e=>t(r,e)))&&ex(r.id,"confirmed")},[ts,td,tf,em,ex]),(0,r.useEffect)(()=>{let e=!1;for(let t of em)"pending"===t.status&&("opening"===t.type||"increasing"===t.type)&&(eR.current.has(t.id)||(eR.current.add(t.id),e=!0));e&&eY()},[em,eY]),(0,r.useEffect)(()=>{let e=em.filter(e=>"sunrise"===(0,R.underwriterLiteralFrom)(e.venue)&&e.asset).map(e=>e.asset);if(0===e.length)return;let t=Date.now();eO(r=>{let i=!1,s=new Map(r);for(let r of e)s.has(r)||(s.set(r,t),i=!0);return i?s:r})},[em]),(0,r.useEffect)(()=>{if(0===eU.size)return;let e=Date.now(),t=new Set((e4??[]).filter(e=>"sunrise"===e.underwriter&&e.asset).map(e=>e.asset));eO(r=>{let i=!1,s=new Map(r);for(let[n,a]of r)ty.current?.isPending(n)||(t.has(n)||!(e-a<=3e5))&&(s.delete(n),i=!0);return i?s:r})},[e4,eU]),(0,r.useEffect)(()=>{let e=new Map,t=Date.now();for(let r of em){if("opening"!==r.type||!r.asset||!r.loanSlTriggerPriceUsd)continue;let i=parseFloat(r.loanSlTriggerPriceUsd);if(!Number.isFinite(i)||i<=0)continue;let s=r.isLong?"long":"short";e.set(`${r.asset}:${s}:${r.profileIndex??0}`,{price:i,ts:t}),r.collateral&&r.collateral>0&&r.size&&r.size>0&&eE.current.set(eo(r.asset,s,r.profileIndex),{collateralUsd:r.collateral,leverageX:r.size/r.collateral,ts:t})}0!==e.size&&eM(r=>{let i=new Map(r);for(let[e,r]of i)t-r.ts>3e5&&i.delete(e);for(let[t,r]of e)i.set(t,r);return i})},[em]),(0,r.useEffect)(()=>{if(e6?.passthroughOrders){let e=new Set(e6.passthroughOrders.map(e=>e.orderPda));eH(t=>{let r=new Set;return t.forEach(t=>{e.has(t)||r.add(t)}),r.size!==t.size?r:t})}},[e6]),(0,r.useEffect)(()=>{if(0===eW.size)return;let e=new Set;e6?.passthroughOrders?.forEach(t=>e.add(t.orderPda)),e4?.forEach(t=>t.tpslOrders?.forEach(t=>{t.orderPda&&e.add(t.orderPda)})),tt?.forEach(t=>t.forEach(t=>{t.orderPda&&e.add(t.orderPda)})),eq(t=>{let r=new Set;return t.forEach(t=>{e.has(t)&&r.add(t)}),r.size!==t.size?r:t})},[e6,e4,tt,eW.size]);let tA=(0,r.useMemo)(()=>{let e=[],t=new Set,r=C?.toBase58(),i=new Map(C?e7.map(e=>[e,(0,L.getProfilePda)(C,e)[0].toBase58()]):[]),s=(e,t)=>(0,l.resolvePositionWalletOwner)(e,r,null==t?void 0:i.get(t));ts.forEach(r=>{let i;if(tu.has(r.positionPda)||tc.has(r.positionPda)||e4?.some(e=>e.positionPda===r.positionPda&&"phoenix"===e.underwriter))return;t.add(r.positionPda);let n=s(r.owner,r.profileIndex),a=e4?.find(e=>!!n&&e.wallet===n&&e.positionPda===r.positionPda),l=eP.get(r.positionPda),o=eS?.[r.asset]||r.priceUsd,d=Number.isFinite(i=a?.collateralUsd?parseFloat(a.collateralUsd):NaN)&&i>0?i:r.isGmTrade&&"long"===r.side&&("SOL"===r.asset||"BTC"===r.asset||"ETH"===r.asset)&&o>0?r.collateralUsd*o:r.collateralUsd,c=r.priceUsd||parseFloat(a?.entryPrice||"0"),u=(0,U.calculateLiquidationInfo)({entryPrice:c,sizeUsd:r.sizeUsd,collateralUsd:d,isLong:"long"===r.side},o),h=(0,U.calculateUnrealizedPnl)(c,o,r.sizeUsd,"long"===r.side),p=(0,z.consistentLeverageX)({apiLeverageXRaw:a?.leverageX,apiSizeUsdRaw:a?.sizeUsd,apiCollateralUsdRaw:a?.collateralUsd,wsSizeUsd:r.sizeUsd,wsCollateralUsd:d}),m=Date.now()-r.lastWsUpdate>5e3;e.push({positionPda:r.positionPda,wallet:n,ownership:n&&null!=r.profileIndex?"imperial":void 0,asset:r.asset,side:r.side,sizeUsd:r.sizeUsd.toString(),collateralUsd:d.toString(),entryPrice:c.toString(),markPrice:o.toString(),liquidationPrice:u.liquidationPrice.toString(),unrealizedPnl:h.pnlUsd.toFixed(2),unrealizedPnlPercent:h.pnlPercent.toFixed(2),leverageX:p.toFixed(2),depositedAmount:l?.tx1Data.depositedAmount||a?.collateralUsd||null,estimatedFees:l?.tx1Data.expectedFees||a?.totalFeesUsd||null,status:"open",dataSource:l?"ws+tx1":a?"merged":"ws",isStale:m,lastWsUpdate:r.lastWsUpdate,openTime:r.openTime,tpslOrders:[],apiData:a||null,profileIndex:r.profileIndex??a?.profileIndex,underwriter:r.isGmTrade?"gmtrade":(0,R.underwriterLiteralFrom)(a?.underwriter)??void 0,hedgeVenue:a?.hedgeVenue})});let n=(0,E.resolveCrossSeatVenues)({apiVenues:e4?.map(e=>e.directVenue)??[],remembered:eF.current,observedSeats:tu,emptySeats:tc});for(let r of(td.forEach(r=>{let i=eo(r.asset,r.side,r.profileIndex),a=(0,Y.phoenixPositionKey)(r);if(t.has(a))return;t.add(a);let l=s(r.owner,r.profileIndex),o=e4?.find(e=>
2!!l&&e.wallet===l&&(0,Y.matchesPhoenixApiPosition)(e,r,(0,G.phoenixToCanonicalSymbol)(e.asset)));o&&t.add(o.positionPda);let d=tp[r.asset]||eS?.[r.asset]||r.priceUsd,c=o?.collateralUsd?parseFloat(o.collateralUsd):NaN,u=Number.isFinite(c)&&c>0?c:r.collateralUsd,h="long"===r.side,p=(0,B.getPhoenixMarketInfoBySymbol)(r.asset),m=(0,O.estimatePhoenixLiq)({venue:"phoenix",entryPrice:r.priceUsd,sizeUsd:r.sizeUsd,collateralUsd:r.collateralUsd,isLong:h,phoenix:p?{maxLeverage:p.maxLeverage}:void 0}).priceUsd,f=m&&m>0?m:(0,U.calculateLiquidationInfo)({entryPrice:r.priceUsd,sizeUsd:r.sizeUsd,collateralUsd:r.collateralUsd,isLong:h},d).liquidationPrice;if(!o&&f>0){let e=eC.get(`${r.asset}:${r.side}:${r.profileIndex??0}`);e&&e.price>0&&(h?e.price>f:e.price<f)&&(f=e.price)}let x=(0,U.calculateUnrealizedPnl)(r.priceUsd,d,r.sizeUsd,"long"===r.side),g=(0,z.consistentLeverageX)({apiLeverageXRaw:o?.leverageX,apiSizeUsdRaw:o?.sizeUsd,apiCollateralUsdRaw:o?.collateralUsd,wsSizeUsd:r.sizeUsd,wsCollateralUsd:u}),b=u;if(o){let e=o.borrowedCollateralUsd&&parseFloat(o.borrowedCollateralUsd)||0;if(e>0){let t=eE.current.get(i);eE.current.set(i,{collateralUsd:u,leverageX:g,borrowedUsd:e,ts:Date.now()}),(!t||Math.abs((t.borrowedUsd??0)-e)>.005||Math.abs(t.collateralUsd-u)>.005)&&eL&&ed(eL,eE.current)}else eE.current.delete(i)&&eL&&ed(eL,eE.current)}else{let e=eE.current.get(i);if(e&&(e.borrowedUsd??0)>0){let t=Math.max(0,r.collateralUsd-e.borrowedUsd);b=t,t>0&&(g=r.sizeUsd/t)}else e&&Date.now()-e.ts<3e5&&(b=e.collateralUsd,g=e.leverageX)}e.push({positionPda:o?.positionPda??r.positionPda,wallet:l,ownership:l&&null!=r.profileIndex?"imperial":void 0,asset:r.asset,side:r.side,sizeUsd:r.sizeUsd.toString(),collateralUsd:b.toString(),entryPrice:r.priceUsd.toString(),markPrice:d.toString(),liquidationPrice:f.toString(),unrealizedPnl:x.pnlUsd.toFixed(2),unrealizedPnlPercent:x.pnlPercent.toFixed(2),leverageX:g.toFixed(2),depositedAmount:o?.collateralUsd||null,estimatedFees:o?.totalFeesUsd||null,status:"open",dataSource:o?"merged":"ws",isStale:!1,lastWsUpdate:r.lastWsUpdate,openTime:0,tpslOrders:[],apiData:o||null,profileIndex:r.profileIndex,underwriter:"phoenix",directVenue:r.isPhoenixCrossSeat?o?.directVenue??n.get(r.positionPda):o?.directVenue,isPhoenixCrossSeat:r.isPhoenixCrossSeat,phoenixAccountCollateralUsd:r.isPhoenixCrossSeat?r.collateralUsd.toString():void 0})}),(0,T.mergeSunrisePositions)(tf,e4,eS)))t.add(r.positionPda),r.apiData&&t.add(r.apiData.positionPda),e.push(r);e4?.forEach(r=>{if(tn.has(r.positionPda)||(0,M.isSunriseApiPositionClosed)(r,tg)||(0,T.hasSunriseChainPosition)(r,tf)||"phoenix"===r.underwriter&&tc.has(r.positionPda)||"phoenix"===r.underwriter&&"venue_direct"!==r.ownership&&tu.has(r.positionPda))return;let i="phoenix"===r.underwriter?(0,G.phoenixToCanonicalSymbol)(r.asset):r.asset;if(!("phoenix"===r.underwriter&&"venue_direct"!==r.ownership&&t.has((0,Y.phoenixPositionKey)({...r,asset:i})))&&!t.has(r.positionPda)){t.add(r.positionPda);let s=("phoenix"===r.underwriter?tp[i]:void 0)||eS?.[i]||parseFloat(r.markPrice||"0");e.push({positionPda:r.positionPda,wallet:r.wallet||void 0,asset:i,side:r.side,sizeUsd:r.sizeUsd||"0",collateralUsd:"sunrise"===r.underwriter?r.collateralUsd:r.collateralUsd||"0",entryPrice:r.entryPrice||"0",markPrice:s.toString(),liquidationPrice:r.liquidationPrice||"0",unrealizedPnl:r.pnlUsd||"0",unrealizedPnlPercent:r.pnlPercent||"0",leverageX:r.leverageX||"0",depositedAmount:r.collateralUsd,estimatedFees:r.totalFeesUsd,status:"open",dataSource:"api",isStale:!tl,lastWsUpdate:null,openTime:r.openedAt,tpslOrders:[],apiData:r,profileIndex:r.profileIndex,underwriter:r.underwriter,ownership:r.ownership??"imperial",directVenue:r.directVenue,sunriseMarginSeat:r.sunriseMarginSeat,isSunriseCrossMargin:"sunrise"===r.underwriter?null==r.sunriseMarginSeat:void 0})}}),eP.forEach((r,i)=>{t.has(i)||e.push({positionPda:i,asset:r.asset,side:r.side,sizeUsd:"0",collateralUsd:r.tx1Data.depositedAmount,entryPrice:"0",markPrice:(eS?.[r.asset]||0).toString(),liquidationPrice:"0",unrealizedPnl:"0",unrealizedPnlPercent:"0",leverageX:"0",depositedAmount:r.tx1Data.depositedAmount,estimatedFees:r.tx1Data.expectedFees,status:"pending",dataSource:"pending",isStale:!1,lastWsUpdate:null,openTime:Date.now()/1e3,tpslOrders:[],apiData:null})});let a=new Map;for(let t of e){let e=`${t.positionPda}:${t.asset}:${t.side}`,r=a.get(e);if(!r){a.set(e,t);continue}2*!!t.directVenue+ +("api"!==t.dataSource)>2*!!r.directVenue+ +("api"!==r.dataSource)&&a.set(e,t)}return Array.from(a.values())},[C,e7,ts,td,tf,tx,tg,e4,eP,eC,eS,tp,tl,tn,tc,tu]),tE=(0,r.useMemo)(()=>{let e=[],t=new Set,r=new Map;if(C)for(let e of e7){let[t]=(0,L.getProfilePda)(C,e);r.set(t.toBase58(),e)}let i=new Map,s=new Map,n=new Map,a=new Map,l=new Map,o=new Map;
2return e6?.passthroughOrders?.forEach(e=>{void 0!==e.profileIndex&&i.set(e.orderPda,e.profileIndex),e.creationSignature&&s.set(e.orderPda,e.creationSignature),null!=e.creationSlot&&e.creationSlot>0&&n.set(e.orderPda,e.creationSlot),e.currentBestPriceUsd&&a.set(e.orderPda,parseFloat(e.currentBestPriceUsd)),e.parentOrderPda&&l.set(e.orderPda,e.parentOrderPda),e.botState&&o.set(e.orderPda,e.botState)}),e4?.forEach(e=>{e.tpslOrders?.forEach(e=>{e.orderPda&&e.currentBestPriceUsd&&a.set(e.orderPda,parseFloat(e.currentBestPriceUsd))})}),tN.forEach(d=>{let c,u,h,p,m,f;t.add(d.orderPda);let x=r.get(d.userAccount),g=void 0!==x?C?.toBase58():void 0;switch(d.orderType){case"ratchet":c="ratchet";break;case"ratchet_entry":c="ratchet_entry";break;case"indicator":c="indicator";break;case"indicator_ratchet":c="indicator_ratchet";break;case"landmine":c="landmine";break;case"dca":c="dca";break;case"fib_ratchet":c="fib_ratchet";break;case"fib_ratchet_entry":c="fib_ratchet_entry";break;case"dca_close":c="dca_close";break;case"dca_time_close":c="dca_time_close";break;case"dca_ratchet_close":c="dca_ratchet_close";break;case"dca_time":c="dca_time";break;case"dca_ratchet":c="dca_ratchet";break;case"limit":default:c="limit";break;case"stop_limit":c="long"===d.side==("above"===d.triggerCondition)?"tp":"sl"}let b=d.triggerPrice;if("limit"===c&&"phoenix"===d.underwriter&&d.phoenix&&d.phoenix.priceInTicks>0){let e=(0,B.getGlobalPhoenixRegistry)(),t=e&&d.marketMint?(0,B.resolvePhoenixSymbol)(d.marketMint):void 0,r=t?e?.getMarketBySymbol(t)??null:null;r&&(b=(0,B.phoenixPriceInTicksToUsd)(d.phoenix.priceInTicks,r))}e.push({orderPda:d.orderPda,wallet:g,source:"imperial_passthrough",orderType:c,triggerPriceUsd:b.toString(),sizeUsd:d.sizeUsd.toString(),closeBps:d.closeBps,status:"active",dataSource:"ws",lastWsUpdate:d.lastWsUpdate,landMineStatus:"not_applicable"===d.landMineStatus?void 0:d.landMineStatus,ratchetBestPrice:d.ratchet.bestPriceSeen>0?d.ratchet.bestPriceSeen.toString():void 0,ratchetCurrentTrigger:d.ratchet.currentTriggerPrice>0?d.ratchet.currentTriggerPrice.toString():void 0,marketMint:d.marketMint,side:d.side,action:d.action,triggerCondition:d.triggerCondition,collateralAmount:d.collateralAmount,createdAt:d.createdAt,loanMultiplierMicro:d.loanMultiplierMicro,landMine:d.landMine,ratchet:d.ratchet?(u=a.get(d.orderPda))&&u>0?{...d.ratchet,bestPriceSeen:u}:d.ratchet:void 0,indicator:d.indicator,dca:d.dca?{...d.dca,weightingType:d.dca.weightingType}:void 0,dcaClose:d.dcaClose?{...d.dcaClose,weightingType:d.dcaClose.weightingType}:void 0,dcaTimeClose:d.dcaTimeClose?{...d.dcaTimeClose,weightingType:d.dcaTimeClose.weightingType}:void 0,dcaRatchetClose:d.dcaRatchetClose?(h={...d.dcaRatchetClose,weightingType:d.dcaRatchetClose.weightingType},(p=a.get(d.orderPda))&&p>0?{...h,bestPriceSeen:p}:h):void 0,dcaTime:d.dcaTime?{...d.dcaTime,weightingType:d.dcaTime.weightingType}:void 0,dcaRatchet:d.dcaRatchet?(m={...d.dcaRatchet,weightingType:d.dcaRatchet.weightingType},(f=a.get(d.orderPda))&&f>0?{...m,bestPriceSeen:f}:m):void 0,profileIndex:x??i.get(d.orderPda),underwriter:(0,R.underwriterLiteralFrom)(d.underwriter)??void 0,creationSignature:s.get(d.orderPda),creationSlot:n.get(d.orderPda),priority:d.priority??0,fundingStatus:d.fundingStatus??0,parentOrderPda:l.get(d.orderPda),botState:o.get(d.orderPda)})}),e6?.passthroughOrders?.forEach(r=>{if(!tC.has(r.orderPda)&&!t.has(r.orderPda)){let t,i;switch(r.orderType){case"ratchet":t="ratchet";break;case"ratchet_entry":t="ratchet_entry";break;case"indicator":t="indicator";break;case"indicator_ratchet":t="indicator_ratchet";break;case"landmine":t="landmine";break;case"dca":t="dca";break;case"fib_ratchet":t="fib_ratchet";break;case"fib_ratchet_entry":t="fib_ratchet_entry";break;case"dca_close":t="dca_close";break;case"dca_time_close":t="dca_time_close";break;case"dca_ratchet_close":t="dca_ratchet_close";break;case"dca_time":t="dca_time";break;case"dca_ratchet":t="dca_ratchet";break;case"limit":default:t="limit";break;case"stop_limit":if("phoenix"===r.underwriter&&"increase"===r.action){t="limit";break}t="long"===r.side==("above"===r.triggerCondition)?"tp":"sl"}let s=parseFloat(r.triggerPrice||"0")/q.PRICE_SCALE;if("limit"===t&&"phoenix"===r.underwriter&&r.venueOrderState?.data.kind==="resting_limit"){let e=(0,B.getGlobalPhoenixRegistry)(),t=e?(0,B.resolvePhoenixSymbol)(r.marketMint):void 0,i=t?e?.getMarketBySymbol(t)??null:null,n=r.venueOrderState.data.price_in_ticks;i&&n>0&&(s=(0,B.phoenixPriceInTicksToUsd)(n,i))}e.push({orderPda:r.orderPda,wallet:r.wallet||void 0,source:"imperial_passthrough",orderType:t,triggerPriceUsd:s.toString(),sizeUsd:(parseFloat(r.sizeUsd)/1e6).toString(),closeBps:"number"==typeof r.orderData?.close_bps?r.orderData.close_bps:void 0,status:"active",dataSource:"api",lastWsUpdate:null,marketMint:r.marketMint,side:r.side,action:r.action,triggerCondition:r.triggerCondition,collateralAmount:parseFloat(r.collateralAmount)/1e6,createdAt:r.createdAt,profileIndex:r.profileIndex,creationSignature:r.creationSignature,creationSlot:r.creationSlot,underwriter:(0,R.underwriterLiteralFrom)(r.underwriter)??void 0,hedgeVenue:r.hedgeVenue,priority:r.priority??0,fundingStatus:r.fundingStatus??0,botState:r.botState,landMine:r.orderData?{waitPrice:(r.orderData.wait_price??0)/q.PRICE_SCALE,waitDurationSeconds:r.orderData.wait_duration_seconds??0,waitZoneEnteredAt:0,isArmed:!1}:void 0,ratchet:r.orderData?{worstPrice:(r.orderData.worst_price??0)/q.PRICE_SCALE,ratchetSize:(r.orderData.ratchet_size??0)
2/("indicator"===r.orderType||"indicator_ratchet"===r.orderType?1e6:q.PRICE_SCALE),bestPriceSeen:r.currentBestPriceUsd?parseFloat(r.currentBestPriceUsd):0,lastUpdateTimestamp:0,currentTriggerPrice:0,isReverseFib:!0===r.orderData.reverse||void 0,stopTriggerPrice:(r.orderData.stop_trigger_price??0)/q.PRICE_SCALE}:void 0,indicator:("indicator"===r.orderType||"indicator_ratchet"===r.orderType)&&r.orderData?{indicatorType:255&(i=r.orderData.indicator_config??0),timeframeCode:i>>8&255,period:i>>16&255,indicatorCondition:i>>24&255,thresholdValue:(r.orderData.threshold_value??0)/1e6,phase:r.orderData.indicator_phase??0,phaseTransitionPrice:(r.orderData.phase_transition_price??0)/q.PRICE_SCALE,currentValue:r.currentIndicatorValue??void 0}:void 0,dca:"dca"===r.orderType&&r.orderData?{startPrice:(r.orderData.start_price??0)/q.PRICE_SCALE,endPrice:(r.orderData.end_price??0)/q.PRICE_SCALE,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0,triggerType:r.orderData.trigger_type??0,leverageWeightingType:r.orderData.leverage_weighting_type??0,startLeverageScaled:r.orderData.start_leverage_scaled??0,endLeverageScaled:r.orderData.end_leverage_scaled??0}:void 0,dcaClose:"dca_close"===r.orderType&&r.orderData?{startPrice:(r.orderData.start_price??0)/q.PRICE_SCALE,endPrice:(r.orderData.end_price??0)/q.PRICE_SCALE,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0}:void 0,dcaTimeClose:"dca_time_close"===r.orderType&&r.orderData?{priceLimit:(r.orderData.price_limit??0)/q.PRICE_SCALE,intervalSeconds:r.orderData.interval_seconds??0,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0,lastLegTimestamp:r.orderData.last_leg_timestamp??0,startAt:r.orderData.start_at??0}:void 0,dcaRatchetClose:"dca_ratchet_close"===r.orderType&&r.orderData?{priceLimit:(r.orderData.price_limit??0)/q.PRICE_SCALE,intervalSeconds:r.orderData.interval_seconds??0,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0,ratchetSize:(r.orderData.ratchet_size??0)/q.PRICE_SCALE,bestPriceSeen:r.currentBestPriceUsd?parseFloat(r.currentBestPriceUsd):(r.orderData.best_price_seen??0)/q.PRICE_SCALE,lastLegTimestamp:r.orderData.last_leg_timestamp??0}:void 0,dcaTime:"dca_time"===r.orderType&&r.orderData?{priceLimit:(r.orderData.price_limit??0)/q.PRICE_SCALE,intervalSeconds:r.orderData.interval_seconds??0,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0,lastLegTimestamp:r.orderData.last_leg_timestamp??0,leverageWeightingType:r.orderData.leverage_weighting_type??0,startLeverageScaled:r.orderData.start_leverage_scaled??0,endLeverageScaled:r.orderData.end_leverage_scaled??0,startAt:r.orderData.start_at??0}:void 0,dcaRatchet:"dca_ratchet"===r.orderType&&r.orderData?{priceLimit:(r.orderData.price_limit??0)/q.PRICE_SCALE,intervalSeconds:r.orderData.interval_seconds??0,numLegs:r.orderData.num_legs??0,weightingType:r.orderData.weighting_type??0,legsExecuted:r.orderData.legs_executed??0,ratchetSize:(r.orderData.ratchet_size??0)/q.PRICE_SCALE,bestPriceSeen:r.currentBestPriceUsd?parseFloat(r.currentBestPriceUsd):(r.orderData.best_price_seen??0)/q.PRICE_SCALE,lastLegTimestamp:r.orderData.last_leg_timestamp??0,leverageWeightingType:r.orderData.leverage_weighting_type??0,startLeverageScaled:r.orderData.start_leverage_scaled??0,endLeverageScaled:r.orderData.end_leverage_scaled??0}:void 0,venueOrderState:r.venueOrderState,parentOrderPda:r.parentOrderPda})}}),e},[tN,e6,tC,C,e7,e4,tM]),tL=(0,et.usePhoenixOrderbookFills)(tE),tF=(0,r.useMemo)(()=>{let e=new Set,t=Date.now();for(let r of tE){let i=tL.get(r.orderPda),s=null!=r.createdAt&&r.createdAt>0?1e3*r.createdAt:void 0;(0,et.isPhoenixOrderGoneFromBook)(r,i,t,s,r.creationSlot)&&e.add(r.orderPda)}return e},[tE,tL]),tR=(0,r.useMemo)(()=>0===tF.size?tE:tE.filter(e=>!tF.has(e.orderPda)),[tE,tF]),{displayOrders:tD,limitCloseOrders:tI}=(0,r.useMemo)(()=>{let e=[],t=[],r=new Set(tA.filter(e=>"venue_direct"!==e.ownership||"phoenix"!==e.underwriter).map(e=>{let t=es(e.asset,e.underwriter);return`${t?en(t):e.asset.toLowerCase()}:${e.side}:${e.profileIndex??""}`})),i=tR.filter(e=>"increase"===e.action),s=new Set(i.map(e=>e.orderPda)),n=new Set(i.map(e=>`${en(e.marketMint||"")}:${e.side}:${e.profileIndex??""}`));for(let i of tR)if("decrease"===i.action){let a=`${en(i.marketMint||"")}:${i.side}:${i.profileIndex??""}`;if(r.has(a)){e.push(i);continue}let l=!!i.parentOrderPda&&s.has(i.parentOrderPda),o=!i.parentOrderPda&&n.has(a);(l||o)&&t.push(i)}else e.push(i);return{displayOrders:e,limitCloseOrders:t}}
2,[tR,tA]),tU=(0,r.useMemo)(()=>tR.filter(e=>"decrease"===e.action),[tR]),tO=(0,r.useMemo)(()=>C?tl?"connected":to>0?"reconnecting":"disconnected":"disconnected",[C,tl,to]),tB=(0,r.useMemo)(()=>C&&0!==tr.length?tP?"connected":tT>0?"reconnecting":"disconnected":"disconnected",[C,tr.length,tP,tT]),tz=(0,r.useCallback)((e,t,r,i)=>{eT(s=>{let n=new Map(s);return n.set(e,{asset:t,side:r,tx1Data:i}),n}),eI(t=>{let r=new Map(t);return r.delete(e),r})},[]),t$=(0,r.useCallback)(e=>{let t=e.pda.toBase58();eI(r=>{let i=new Map(r);return i.set(t,e),i})},[]),tV=(0,r.useCallback)(e=>{eI(t=>{let r=new Map(t);return r.delete(e),r})},[]),tH=(0,r.useCallback)(e=>{eH(t=>new Set([...t,e]))},[]),tW=(0,r.useCallback)(e=>{eH(t=>{let r=new Set(t);return r.delete(e),r})},[]),tq=(0,r.useCallback)(e=>{eq(t=>{let r=new Set(t);return e.forEach(e=>r.add(e)),r})},[]),tK=(0,r.useCallback)((e=!0)=>{tv(),er.invalidateQueries({queryKey:["jupiter-positions",C?.toBase58()]}),er.invalidateQueries({queryKey:["phoenix-direct-positions",C?.toBase58()]},{cancelRefetch:e}),er.invalidateQueries({queryKey:["jupiter-lifecycles",C?.toBase58()]}),er.invalidateQueries({queryKey:["jupiter-orders",C?.toBase58()]},{cancelRefetch:e}),er.invalidateQueries({queryKey:["jupiter-direct-tpsl",C?.toBase58()]})},[er,C,tv]),tG=(0,r.useCallback)(()=>tK(!1),[tK]);(0,S.useResumeSignal)(tG);let tY=(0,r.useRef)({api:ey,account:ev});(0,r.useEffect)(()=>{let e=tY.current,t=ey&&!e.api||ev&&!e.account;tY.current={api:ey,account:ev},t&&tK(!1)},[ey,ev,tK]);let tX=(0,r.useMemo)(()=>{let e=tR.filter(e=>"decrease"===e.action&&"active"===e.status);return tA.map(t=>{let r=es(t.asset,t.underwriter),i=t.apiData?.profileIndex??t.profileIndex,s=e.filter(e=>!(eW.has(e.orderPda)||e.orderPda&&tC.has(e.orderPda))&&!!r&&en(e.marketMint||"")===en(r)&&e.side===t.side&&(void 0!==e.profileIndex&&void 0!==i?e.profileIndex===i:void 0===e.profileIndex&&void 0!==i?1===tA.filter(e=>{let i=es(e.asset,e.underwriter);return i&&en(i)===en(r)&&e.side===t.side}).length:void 0===i&&void 0===e.profileIndex)),n=tt?.get(t.positionPda)??[],a=new Set(s.map(e=>e.orderPda)),l=[...s,...n.filter(e=>!(e.orderPda&&eW.has(e.orderPda)||e.orderPda&&a.has(e.orderPda)||e.orderPda&&tC.has(e.orderPda))).map(e=>({orderPda:e.orderPda||"",source:"jupiter_native",orderType:e.orderType,triggerPriceUsd:e.triggerPriceUsd,sizeUsd:e.sizeUsd,status:"active",dataSource:"api",lastWsUpdate:null}))],o=t.apiData,d=!!o?.tpslOrders?.length&&o.tpslOrders.some(e=>e.orderPda&&(eW.has(e.orderPda)||tC.has(e.orderPda)||tF.has(e.orderPda)));if(o&&d){let e=o.tpslOrders.filter(e=>!e.orderPda||!eW.has(e.orderPda)&&!tC.has(e.orderPda)&&!tF.has(e.orderPda));o={...o,tpslOrders:e}}return 0===l.length&&o===t.apiData?t:{...t,tpslOrders:l,apiData:o}})},[tA,tR,tt,eW,tC,tF]),tQ=(0,r.useCallback)(e=>tX.find(t=>t.positionPda===e)||null,[tX]),tJ=(0,r.useRef)(new Set),tZ=(0,r.useRef)(new Set),t0=(0,r.useRef)(!1);(0,r.useEffect)(()=>{let e=(e,t,r)=>`${e}|${t}|${r??0}`,t=new Set,r=new Map,i=(e,t)=>{let i=r.get(e);(void 0===i||t>i)&&r.set(e,t)};for(let r of ts){let s=e(r.asset,r.side,r.profileIndex);t.add(s),i(s,r.sizeUsd)}for(let r of td){let s=e(r.asset,r.side,r.profileIndex);t.add(s),i(s,r.sizeUsd)}for(let r of tf){let s=e(r.asset,r.side,r.profileIndex);t.add(s),i(s,r.sizeUsd)}let s={sunrise:{keys:new Set(tf.map(t=>e(t.asset,t.side,t.profileIndex))),observedProfiles:tx}};t.size>0&&(t0.current=!0);let n=new Set;for(let e of tJ.current)t.has(e)||n.add(e);tJ.current=t;let a={liveKeys:t,sizeByKey:r,disappeared:n,hasSeenLive:t0.current,venues:s};for(let t of em){if("pending"!==t.status||"closing"!==t.type&&"reducing"!==t.type||!t.asset||void 0===t.isLong)continue;let r=!tZ.current.has(t.id);r&&tZ.current.add(t.id),(0,I.closeConfirmSignal)({key:e(t.asset,t.isLong?"long":"short",t.profileIndex),profileIndex:t.profileIndex??0,type:t.type,sizeUsdAtIntent:t.sizeUsdAtIntent,venue:t.venue,firstSight:r},a)&&ex(t.id,"confirmed")}},[ts,td,tf,tx,em,ex]);let t1=(0,r.useRef)(new Set);(0,r.useEffect)(()=>{let e=em.filter(e=>"pending"===e.status&&(0,I.settlementProven)(e));if(0===e.length)return;let t=setInterval(()=>{let t=Date.now(),r=e.filter(e=>!t1.current.has(e.id)&&(0,I.settledIntentAwaitingView)(e,t));if(0!==r.length){for(let e of r)t1.current.add(e.id),ex(e.id,"confirmed");tK(),u.toast.success(k("pendingOrderSettledViewLag"))}},1e3);return()=>clearInterval(t)},[em,ex,tK,k]);let t2=(0,r.useMemo)(()=>(0,n.visibleIndexedExits)(e2.exits,{wallet:eZ,closedPdas:tn,phoenixEmpty:tc,phoenixCross:tu,sunriseClosed:tg,full:tX}),[e2.exits,eZ,tn,tc,tu,tg,tX]),t5=(0,r.useMemo)(()=>(0,s.manualPriceObservationsFor)([...tX,...t2.rows],ew,ej),[tX,t2.rows,ew,ej]),t3=(0,r.useMemo)(()=>({positions:tX,partialPositions:t2.rows,manualClosePriceObservations:t5,ordersAvailability:e8,ordersLoading:e9,blockedPartialIds:t2.blocked,positionsAvailability:e2,phoenixAvailability:e3,recentlyClosedPositions:ek,pendingOperations:em,connectionStatus:tO,lastUpdate:to,isLoading:W||ta||e1||tb,walletState:W?"settling":C?"connected":"disconnected",addPendingTx1:tz,refreshPositions:tK,sunriseSettlementOutcome:tS,getPositionByPda:tQ,orders:tD,limitCloseOrders:tI,allCloseOrders:tU,ordersConnectionStatus:tB,registerSpeculativePda:t$,unregisterSpeculativePda:tV,watchSunriseMarket:e$,registerSpeculativeOrderPda:tH,unregisterSpeculativeOrderPda:tW,markOrderCancelled:tq}),[tX,t2,t5,e8,e9,e2,e3,ek,em,tO,to,W,C,ta,e1,tb,tz,tK,tS,tQ,tD,tI,tU,tB,t$,tV,e$,tH,tW,tq]);return(0,t.jsx)(ea.Provider,{value:t3,children:e})}function em(){let e=(0,r.useContext)(ea);if(!e)throw Error("useUnifiedPositions must be used within a UnifiedPositionProvider");return e}},703206,e=>{"use strict";var t=e.i(591318),r=e.i(394390),i=e.i(183023),s=e.i(21859),n=e.i(985604),a=e.i(994754);e.i(875574);var l=e.i(142298),o=e.i(214732);let d=(0,i.createContext)(void 0);function c(e){if(e.data.length<72)return 0;let r=e.data.slice(64,72);return Number(BigInt("0x"+t.Buffer.from(r).reverse().toString("hex")))/1e9}e.s(["WsolBalanceProvider",0,function({children:e}){(0,a.useConnection)();let{publicKey:t}=(0,l.useUnifiedWallet)(),[u,h]=(0,i.useState)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(new Set);(0,i.useEffect)(()=>
2{if(!t){h(null),p.current=null;return}(0,s.getAssociatedTokenAddress)(n.NATIVE_MINT,t,!1).then(h).catch(()=>h(null))},[t]);let{data:f,isLoading:x,refetch:g}=(0,o.useAccountSubscription)({account:u,decoder:c,commitment:"processed",enabled:!!u}),b=f??0;(0,i.useEffect)(()=>{let e=p.current;if(null!==e&&b>e){let t={previousBalance:e,newBalance:b,change:b-e,timestamp:Date.now()};m.current.forEach(e=>e(t))}p.current=b},[b]);let v=(0,i.useCallback)(async()=>{await g()},[g]),y=(0,i.useCallback)(e=>(m.current.add(e),()=>{m.current.delete(e)}),[]),w=(0,i.useMemo)(()=>({balance:b,isLoading:x,refreshBalance:v,onBalanceIncrease:y}),[b,x,v,y]);return(0,r.jsx)(d.Provider,{value:w,children:e})},"useWsolBalance",0,function(){let e=(0,i.useContext)(d);if(void 0===e)throw Error("useWsolBalance must be used within a WsolBalanceProvider");return e}])},157157,e=>{"use strict";var t=e.i(183023),r=e.i(43690);let i={jupiter:"jupiter",flash_trade:"flash",flash_v2:"flash",phoenix:"phoenix",gmtrade:"gmtrade",pairs:"pairs",touch:null,armada:"sunrise"};async function s(){let e=new Map;try{let t=await fetch("https://api.imperial.space/api/v1/funding-rates");if(!t.ok)return e;for(let r of(await t.json()).rows??[])e.set(r.symbol.toUpperCase(),r)}catch{}return e}function n(){return{queryKey:["funding-rates"],queryFn:s,staleTime:25e3,refetchInterval:3e4,refetchOnWindowFocus:!0}}e.s(["useFundingRates",0,function(){return(0,r.useQuery)(n())},"useVenueFundingRate",0,function(e,s){let a=(0,t.useCallback)(t=>(function(e,t,r){let s=i[r],n=s?e?.get(t.toUpperCase())?.[s]:void 0;if(!n)return null;let{longFundingRatePerHourPercent:a,shortFundingRatePerHourPercent:l}=n;if(null!==a&&null!==l)return{kind:"funding",longPerHourPct:a,shortPerHourPct:l};let{longBorrowRatePerHourPercent:o,shortBorrowRatePerHourPercent:d}=n;return null!==o||null!==d?{kind:"borrow",longPerHourPct:o??0,shortPerHourPct:d??0}:null})(t,e,s),[e,s]),{data:l,isPending:o}=(0,r.useQuery)({...n(),select:a});return{rate:l??null,isPending:o}}],157157)},403628,47280,824088,e=>{"use strict";var t=e.i(413358),r=e.i(43690);async function i(){let e=await fetch("https://api.imperial.space/api/v1/gmtrade/markets");if(!e.ok)throw Error("Failed to fetch GMTrade markets");return e.json()}e.s(["useGmTradeMarkets",0,function(){return(0,r.useQuery)({queryKey:["gmtrade-markets"],queryFn:i,staleTime:3e5,refetchInterval:3e5,placeholderData:[]})}],403628);var s=e.i(394390),n=e.i(183023),a=e.i(810638),l=e.i(994754),o=e.i(722732);class d{entries=new Map;socket=null;reconnect;connected=!1;parseFailures=0;url;createSocket;constructor(e,t=e=>"u"<typeof WebSocket?null:new WebSocket(e)){this.url=e,this.createSocket=t}retain(e,t){let r=this.entries.get(e.key);!r&&(r={subscription:e,listeners:new Set},this.entries.set(e.key,r),this.connected&&this.send(e.subscribe)),r.listeners.add(t),t.connection(this.connected),1===this.entries.size&&1===r.listeners.size&&(window.addEventListener("online",this.resume),window.addEventListener("pageshow",this.resume),window.addEventListener("focus",this.resume)),this.connect();let i=!1;return()=>{i||(i=!0,r.listeners.delete(t),0===r.listeners.size&&this.entries.get(e.key)===r&&(r.subscription.unsubscribe&&this.send(r.subscription.unsubscribe),this.entries.delete(e.key)),0===this.entries.size&&this.stop())}}getSnapshot(){return{connected:this.connected,socketCount:+!!this.socket,subscriptions:this.entries.size,listeners:[...this.entries.values()].reduce((e,t)=>e+t.listeners.size,0)}}send(e){this.socket?.readyState===1&&this.socket.send(JSON.stringify(e))}notifyConnection(e){if(this.connected!==e)for(let t of(this.connected=e,this.entries.values()))for(let r of[...t.listeners])r.connection(e)}resume=()=>{(!this.socket||this.socket.readyState>=2)&&(clearTimeout(this.reconnect),this.reconnect=void 0,this.socket=null,this.notifyConnection(!1),this.connect())};restart(){this.socket?.close()}connect(){if(this.socket||this.reconnect||0===this.entries.size)return;let e=this.createSocket(this.url);if(!e)return;this.socket=e,e.binaryType="arraybuffer";let t=()=>this.socket===e&&this.entries.size>0;e.onopen=()=>
2{if(!t())return void e.close();for(let e of(this.parseFailures=0,this.entries.values()))this.send(e.subscription.subscribe);this.notifyConnection(!0)},e.onmessage=r=>{let i;if(t()){try{let e=r.data instanceof ArrayBuffer?new TextDecoder().decode(r.data):r.data;if(!(i=JSON.parse(e))||"object"!=typeof i)return}catch{++this.parseFailures>=10&&e.close();return}if(this.parseFailures=0,"ping"===i.type)return void this.send({type:"pong",nonce:i.nonce});for(let e of this.entries.values())if(e.subscription.matches(i)){for(let t of[...e.listeners])if(e.listeners.has(t))try{t.message(i)}catch(e){console.error("[market-stream] consumer error",e)}}}},e.onclose=()=>{t()&&(this.socket=null,this.notifyConnection(!1),this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.connect()},3e3))},e.onerror=()=>{t()&&e.close()}}stop(){clearTimeout(this.reconnect),this.reconnect=void 0;let e=this.socket;this.socket=null,this.connected=!1,e?.close(),window.removeEventListener("online",this.resume),window.removeEventListener("pageshow",this.resume),window.removeEventListener("focus",this.resume)}}let c=new d(t.default.env.NEXT_PUBLIC_PHOENIX_WS_URL||"wss://perp-api.phoenix.trade/ws"),u=new d(t.default.env.NEXT_PUBLIC_GMTRADE_WS_URL||"wss://gmtrade-web-backend.gmtrade.xyz/ws");function h(e,t){return u.retain({key:e,subscribe:{subscribe:e},matches:t=>t.type===e},t)}function p(e=!1){e?u.restart():u.resume()}function m(e,t){let r=new DataView(e.buffer,e.byteOffset+t,16),i=r.getBigUint64(0,!0);return r.getBigUint64(8,!0)<<BigInt(64)|i}function f(e){return Number(e/BigInt(1e10))/1e10}function x(e,t){return f(m(e,t))}function g(e){return null==e?0:Number(e)/1e18}e.s(["reconnectGmTradeMarketStream",0,p,"retainGmTradeChannel",0,h,"retainPhoenixMarket",0,function(e,t){return c.retain({key:`market:${e}`,subscribe:{type:"subscribe",subscription:{channel:"market",symbol:e}},unsubscribe:{type:"unsubscribe",subscription:{channel:"market",symbol:e}},matches:t=>"market"===t.channel&&t.symbol===e},t)}],47280);let b=(0,n.createContext)({symbols:[],indexTokens:new Map}),v=(0,n.createContext)({tickers:new Map,indexTokens:new Map,marketFees:new Map,connected:!1,getPrice
2:()=>void 0,getClosePrice:()=>void 0,get24hChange:()=>void 0,getMaxLeverage:()=>void 0,getMarketFees:()=>void 0,getMarketLiquidity:()=>void 0,symbols:[]});e.s(["GmTradeWsProvider",0,function({enabled:t,children:r}){let i=function(e){let t=(0,n.useRef)(0),[r,i]=(0,n.useState)(()=>({metadata:{symbols:[],indexTokens:new Map},tickers:new Map,indexTokens:new Map,marketFees:new Map,tokenPrices:new Map,connected:!1}));return(0,n.useEffect)(()=>{if(!e)return;let r=!0,s=e=>{if(!r)return;let s=e.payload;try{if("heartbeat"===e.type)return;"tickers"===e.type&&Array.isArray(s)&&i(e=>{let t=null;for(let r of s){if(!r||"object"!=typeof r)continue;let i=function(e){if(null==e)return 0;let t=String(e);return/^\d+$/.test(t)?Number(BigInt(t)/BigInt(1e10))/1e10:Number(e)/1e20}(r.price);if("string"!=typeof r.symbol||!Number.isFinite(i)||i<=0)continue;let s=Number(r.unitPrice),n=Number(r.minUnitPrice),a=Number(r.maxUnitPrice),l=s>0?n/s*i:i,o=s>0?a/s*i:i,d=e.tickers.get(r.symbol);d&&d.price===i&&d.minPrice===l&&d.maxPrice===o||(null===t&&(t=new Map(e.tickers)),t.set(r.symbol,{symbol:r.symbol,price:i,minPrice:l,maxPrice:o,timestamp:r.timestamp}))}return null===t?e:{...e,tickers:t,metadata:t.size===e.tickers.size?e.metadata:{...e.metadata,symbols:[...t.keys()].sort()}}}),"indexTokens"===e.type&&Array.isArray(s)&&i(e=>{let t=new Map(e.indexTokens),r=new Map(e.marketFees),i=new Map(e.tokenPrices),n=null;for(let a of s){if(!a||"object"!=typeof a||!a.symbol||!a.indexToken)continue;let s=Number(a.percentChange24h??0)/100,l=Number(a.maxLeverage??0)/1e20;t.set(a.symbol,{symbol:a.symbol,indexToken:a.indexToken,percentChange24h:s,maxLeverage:l});let o=(n??e.metadata.indexTokens).get(a.symbol);o&&o.indexToken===a.indexToken&&Object.is(o.maxLeverage,l)||(n??=new Map(e.metadata.indexTokens)).set(a.symbol,{symbol:a.symbol,indexToken:a.indexToken,maxLeverage:l});let d="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",c=new Set(["So11111111111111111111111111111111111111112","3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh","7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",d]),u=e=>{let t=e.longToken===d?0:c.has(e.longToken)?1:2;return 10*!!e.closed+t},h=Array.isArray(a.marketInfos)?a.marketInfos:[],p=h.length>0?h.reduce((e,t)=>u(t)<u(e)?t:e,h[0]):null;if(p){r.set(a.symbol,{openFeePositivePercent:g(p.oFFForPositive),openFeeNegativePercent:g(p.oFFForNegative),longNetRatePerHourPercent:g(p.longNetRatePerHour),shortNetRatePerHourPercent:g(p.shortNetRatePerHour),longBorrowRatePerHourPercent:g(p.longBorrowingFeeRateHour),shortBorrowRatePerHourPercent:g(p.shortBorrowingFeeRateHour),longFundingRatePerHourPercent:g(p.longFundingFeeRateHour),shortFundingRatePerHourPercent:g(p.shortFundingFeeRateHour)});let e=p.prices;e&&e.length>=6&&i.set(a.symbol,{longTokenPrice:BigInt(e[2]),shortTokenPrice:BigInt(e[4])})}}return{...e,indexTokens:t,marketFees:r,tokenPrices:i,metadata:n?{...e.metadata,indexTokens:n}:e.metadata}})}catch(e){t.current+=1,t.current<=3&&console.error("[gmtrade-ws] parse error:",e),t.current>=10&&(console.error("[gmtrade-ws] parse error threshold reached; reconnecting"),t.current=0,p(!0))}},n=h("tickers",{message:s,connection:e=>{r&&(e&&(t.current=0),i(t=>t.connected===e?t:{...t,connected:e}))}}),a=h("indexTokens",{message:s,connection:()=>{}});return()=>{r=!1,n(),a()}},[e]),(0,a.useResumeSignal)(()=>{e&&p()}),r}(t),{connection:d}
2=(0,l.useConnection)(),[c,u]=(0,n.useState)(new Map),y=(0,n.useRef)(i.tokenPrices);y.current=i.tokenPrices,(0,n.useEffect)(()=>{if(!t)return;let r=!0;async function i(){let t=(0,o.getGlobalGmTradeRegistry)();if(!t)return;let i=(0,o.getGmTradeRegistryVersion)(),s=()=>r&&(0,o.getGlobalGmTradeRegistry)()===t&&(0,o.getGmTradeRegistryVersion)()===i,n=t.getAllMarkets(),a=new Set,l=[];for(let e of n){let r=t.getMarketBySymbol(e.symbol);if(!r)continue;let i=r.market.toBase58();a.has(i)||(a.add(i),l.push({symbol:e.symbol,marketKey:i}))}if(0===l.length)return;let{PublicKey:c}=await e.A(406472);if(!s())return;let h=l.map(e=>new c(e.marketKey)),p=await d.getMultipleAccountsInfo(h);if(!s())return;let g=y.current;u(e=>{if(!s())return e;let t=new Map(e);for(let e=0;e<l.length;e++){let r=p[e];if(!r?.data||r.data.length<2920)continue;let i=r.data instanceof Uint8Array?r.data:new Uint8Array(r.data),s=l[e].symbol,n=g.get(s);if(!n)continue;let a=x(i,2184)+x(i,2200),o=x(i,2248)+x(i,2264),d=x(i,1208),c=x(i,1224),u=f(m(i,968)),h=m(i,1992)-m(i,2824)-m(i,2888)-m(i,2120),b=m(i,2008)-m(i,2840)-m(i,2904)-m(i,2136),v=i.slice(152,184),y=i.slice(184,216);if(v.every((e,t)=>e===y[t])){let e=h/BigInt(2);h=e,b=e}let w=Number(h*n.longTokenPrice/BigInt(1e10))/1e10,j=Number(b*n.shortTokenPrice/BigInt(1e10))/1e10,S=Math.max(0,Math.min(d-a,w*u-a)),k=Math.max(0,Math.min(c-o,j*u-o)),N=f(m(i,488)),P=f(m(i,504)),T=f(m(i,520));t.set(s,{longAvailableUsd:S,shortAvailableUsd:k,totalOiLongUsd:a,totalOiShortUsd:o,positionImpactExponent:N,positionImpactPositiveFactor:P,positionImpactNegativeFactor:T})}return t})}let s=setTimeout(()=>{r&&i().catch(()=>{})},5e3),n=setInterval(()=>{r&&i().catch(()=>{})},3e4);return()=>{r=!1,clearTimeout(s),clearInterval(n)}},[t,d]);let w=(0,n.useCallback)(e=>i.tickers.get(e)?.price,[i.tickers]),j=(0,n.useCallback)((e,t)=>{let r=i.tickers.get(e);if(!r)return;let s=t?r.minPrice:r.maxPrice;return s>0?s:r.price},[i.tickers]),S=(0,n.useCallback)(e=>i.indexTokens.get(e)?.percentChange24h,[i.indexTokens]),k=(0,n.useCallback)(e=>{let t=i.indexTokens.get(e)?.maxLeverage;return t&&t>0?t:void 0},[i.indexTokens]),N=(0,n.useCallback)(e=>i.marketFees.get(e),[i.marketFees]),P=(0,n.useCallback)(e=>c.get(e),[c]),T=i.metadata.symbols,C=(0,n.useMemo)(()=>({...i,getPrice:w,getClosePrice:j,get24hChange:S,getMaxLeverage:k,getMarketFees:N,getMarketLiquidity:P,symbols:T}),[i,w,j,S,k,N,P,T]);return(0,s.jsx)(b.Provider,{value:i.metadata,children:(0,s.jsx)(v.Provider,{value:C,children:r})})},"useGmTradeMarketMetadata",0,function(){return(0,n.useContext)(b)},"useGmTradeWs",0,function(){return(0,n.useContext)(v)}],824088)},547371,945592,846140,389896,48813,157265,650883,460174,900165,284139,889563,875722,376260,737866,612483,691054,e=>{"use strict";e.s(["useTradeMarkers",()=>g],945592);var t=e.i(183023),r=e.i(435023),i=e.i(514049),s=e.i(689384),n=e.i(432533),a=e.i(265172),l=e.i(937505),o=e.i(989714),d=e.i(744030);let c=e=>e.dataList,u=e=>e;e.s(["useJupiterHistory",0,function({walletAddress:e,refreshIntervalMs:o=6e4}){let h=(0,i.useQueryClient)(),{cache:p,auth:m,jwt:f,ready:x}=(0,n.useAccountReadSession)(),g=e??null,b=(0,n.useAccountQuery)({request:g?{wallet:g,resource:"positions"}:null,select:c,interval:o}),v=(0,n.useAccountQuery)({request:g?{wallet:g,resource:"trades",page:{limit:d.HISTORY_PAGE_SIZE,offset:0}}:null,select:u,interval:o}),y=(0,d.headSignature)(v.data),w=g?h.getQueryCache().findAll({queryKey:["jupiter-lifecycle-pages",g]}).map(e=>e.queryKey[2]).filter(e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>0).sort((e,t)=>e-t):[],j=(0,r.useQueries)({queries:w.map(e=>({queryKey:(0,l.historyKey)(g,e),enabled:!1,retry:!1}))}),S=w.map(e=>({offset:e,key:(0,l.historyKey)(g,e),data:p.data((0,l.historyKey)(g,e),m)})),k=j.some(e=>e.isFetching),N=S.find(e=>!e.data||!p.pageMatches(e.key,m,y)),P=(0,d.mergeHistoryPages)(v.data?.dataList??[],S.flatMap(e=>e.data?[e.data.dataList]:[])),T=S.at(-1),C=!!v.data&&(0===S.length?(0,d.headHasMore)(v.data):!!N||!T?.data||T.data.dataList.length>0&&P.length<v.data.totalCount),M=async e=>{if(!g||!x||!v.data||h.getQueryCache().findAll({queryKey:["jupiter-lifecycle-pages",g]}).some(e=>"fetching"===e.state.fetchStatus))return;let t=(0,l.historyKey)(g,e),r={wallet:g,resource:"trades",page:{limit:d.HISTORY_PAGE_SIZE,offset:e}};await h.fetchQuery({queryKey:t,retry:!1,staleTime:0,queryFn:()=>p.read(t,r,m,e=>(0,a.fetchAccountRead)(r,f,e),u,y)}).catch(()=>{})},_=N??S.find(e=>p.stale(e.key,m))??T,A=()=>M(_?.offset??d.HISTORY_PAGE_SIZE);(0,t.useEffect)(()=>
2{if(!g||!x)return;let e=!1;return(0,s.syncJupiterHistory)(g).then(()=>{!e&&p.isCurrent(m)&&(h.invalidateQueries({queryKey:["jupiter-lifecycles",g]},{cancelRefetch:!1}),h.invalidateQueries({queryKey:["jupiter-positions",g]},{cancelRefetch:!1}))}).catch(()=>{}),()=>{e=!0}},[g,x,p,m,h]);let E=v.data,L=(0,t.useMemo)(()=>E?{collateralUsd:E.lifetimeCollateralUsd,pnlUsd:E.lifetimeNetPnlUsd??E.lifetimePnlUsd,feesUsd:E.lifetimeFeesUsd,feeBreakdown:E.lifetimeFeeBreakdown,cumulativeSizeUsd:"0.00"}:null,[E]),F=(0,t.useRef)(null),R=(0,t.useCallback)(()=>{F.current&&(clearInterval(F.current.interval),clearTimeout(F.current.timeout),F.current=null)},[]);(0,t.useEffect)(()=>R,[g,m,R]);let D=(0,t.useCallback)(()=>{if(R(),!g||!p.isCurrent(m))return;let e=e=>{h.invalidateQueries({queryKey:[e,g]},{cancelRefetch:!1})};e("jupiter-positions"),e("jupiter-lifecycles"),h.invalidateQueries({queryKey:["jupiter-lifecycle-pages",g],refetchType:"none"});let t=0;F.current={interval:setInterval(()=>{if(!p.isCurrent(m))return R();t+=1,e("jupiter-positions"),t%2==0&&e("jupiter-lifecycles")},1e3),timeout:setTimeout(R,2e4)}},[g,p,m,h,R]),I=_?p.available(_.key,m):null,U=S.some(e=>!p.pageMatches(e.key,m,y)||p.stale(e.key,m));return{openPositions:b.data??[],unavailablePositionDetails:b.availability.exits,lifecycles:P,lifetimeStats:L,totalCount:E?.totalCount??null,hasMore:C,isFetchingNextPage:k,fetchNextPage:()=>M(N?.offset??(T?T.offset+(T.data?.dataList.length??0):d.HISTORY_PAGE_SIZE)),refreshOlderPage:A,hasOlderPages:S.length>0,positionsAvailability:b.availability,historyAvailability:v.availability,olderAvailability:I,historyRead:{availability:v.availability,stale:v.stale,loading:v.isFetching,olderAvailability:I,olderStale:U,hasOlderPages:S.length>0,olderLoading:k,refresh:()=>{v.refetch({cancelRefetch:!1})},refreshOlder:()=>{A()}},positionsStale:b.stale,historyStale:v.stale,olderStale:U,positionsLoading:b.isLoading,historyLoading:v.isLoading,isLoading:b.isLoading||v.isLoading,isSyncing:!1,isEnriching:!1,error:b.error?.message??v.error?.message??j.find(e=>e.error)?.error?.message??null,invalidate:D,refetch:()=>{b.refetch({cancelRefetch:!1}),v.refetch({cancelRefetch:!1})}}},"usePassthroughOrders",0,function({walletAddress:e,status:t,refreshIntervalMs:r=3e4}){let l=(0,i.useQueryClient)(),d=1e3*(0,o.useTickingNowSecs)(),c=(0,n.useIndependentAccountQuery)({key:["passthrough-orders",e,t],fetcher:r=>{if(!e)throw Error("No account selected");return(0,s.fetchPassthroughOrders)(e,t,r)},enabled:!!e,interval:r,refetchOnWindowFocus:!0});return{orders:c.data??[],availability:c.availability,stale:null===c.availability.lastReadAt||d-c.availability.lastReadAt>=a.READ_STALE_MS,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error?.message??null,invalidate:()=>{l.invalidateQueries({queryKey:["passthrough-orders",e]})},refetch:c.refetch}}],547371);var h=e.i(687229),p=e.i(594651),m=e.i(622463),f=e.i(722732),x=e.i(299959);function g({lifecycles:e,marketMint:r,enabled:i}){let s=(0,x.useFormatters)(),n=(0,m.getPhoenixRegistryVersion)(),a=(0,f.getGmTradeRegistryVersion)();return(0,t.useMemo)(()=>{if(!i||!r)return[];let t=(0,h.mintToMatchingKey)(r),n=[],a=new Set;for(let r of e){let e=(0,p.assetToMint)(r.asset,r.underwriter);if(e&&(0,h.mintToMatchingKey)(e)===t)for(let e of r.actions){let t=function(e,t,r){if("failed"===t.status)return null;let i="increase"===t.actionType,s="decrease"===t.actionType||"liquidation"===t.actionType;if(!i&&!s)return null;let n=Math.abs(parseFloat(t.sizeDelta??""));if(!(n>0))return null;let a=parseFloat(t.entryPrice??""),l=t.tx2Timestamp??t.tx1Timestamp;if(!(a>0)||!l)return null;let o="long"===e.side?i:s,d="liquidation"===t.actionType?"Liquidated":o?"Bought":"Sold";return{id:`trade-${t.id}`,time:l,price:a,direction:o?"buy":"sell",label:`${d} $${n.toLocaleString(r,{minimumFractionDigits:2,maximumFractionDigits:2})}`}}(r,e,s.intlTag);!t||a.has(t.id)||(a.add(t.id),n.push(t))}}return n},[e,r,i,n,a,s])}let b="imperial_chart_label_mode";e.s(["useChartLabelMode",0,function(){let[e,r]=(0,t.useState)("pnl");return(0,t.useEffect)(()=>{let e=localStorage.getItem(b);
2("pnl"===e||"size"===e)&&r(e)},[]),{mode:e,setMode:(0,t.useCallback)(e=>{r(e),localStorage.setItem(b,e)},[])}}],846140);var v=e.i(413358),y=e.i(810638),w=e.i(362221),j=e.i(98788);let S=v.default.env.NEXT_PUBLIC_PHOENIX_WS_URL||"wss://perp-api.phoenix.trade/ws",k=0,N={...(0,j.initialPhoenixBook)(),trades:[],marketStats:null,funding:null,traderState:null,connected:!1};e.s(["usePhoenixWs",0,function(e,r,i=0){let s=(0,t.useRef)(null),n=(0,t.useRef)(void 0),a=(0,t.useRef)(()=>{}),l=(0,t.useRef)(void 0),o=(0,t.useRef)(0),[d,c]=(0,t.useState)({...N,...(0,j.initialPhoenixBook)(),symbol:e,profilePda:r}),u=(0,t.useCallback)((e,t,r)=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"subscribe",subscription:{channel:t,symbol:r}}))},[]);if((d.symbol!==e||d.profilePda!==r)&&((0,j.revokePhoenixBookGeneration)(d.orderbookGeneration),c({...N,...(0,j.initialPhoenixBook)(),symbol:e,profilePda:r})),(0,t.useEffect)(()=>{let t,d,h;if(!e)return;let p=!0,m={...N,...(0,j.initialPhoenixBook)(),symbol:e,profilePda:r},f=-1/0,x=0,g=null,b=-1/0,v=0,y=0,P=e=>{let t=Date.now();y=Math.min(y+1,4),v=t+(0,j.phoenixBookRetryDelay)(y),k=Math.max(k,(0,j.phoenixBookRetryAfterUntil)(e,t))},T=()=>{},C=()=>{h&&(clearTimeout(h.timer),h.controller.abort(),h=void 0)},M=()=>{clearTimeout(d),d=void 0,p&&(f=Date.now(),c(m=(0,j.expirePhoenixBook)(m,f)))},_=(e,t=!1)=>{m=e((0,j.expirePhoenixBook)(m,Date.now()));let r=i-(Date.now()-f);t||r<=0?M():void 0===d&&(d=setTimeout(M,r))},A=()=>{let e=(0,j.expirePhoenixBook)(m,Date.now());e!==m&&_(()=>e,!0),T()},E=(e,r,i=!1)=>{y=0,v=0,_(t=>{let i=t.orderbook.bids.length>0&&!e.bids.length||t.orderbook.asks.length>0&&!e.asks.length;return{...t,orderbook:e,displayOrderbook:e,orderbookReceivedAt:r,orderbookStatus:e.bids.length||e.asks.length?"live":"empty",orderbookGeneration:i?(0,j.nextPhoenixBookGeneration)(t.orderbookGeneration):t.orderbookGeneration}},i),clearTimeout(t),t=setTimeout(A,Math.max(0,j.PHOENIX_BOOK_FRESH_MS-(Date.now()-r)))},L=(0,w.canonicalToPhoenixSymbol)(e);function F(){if(!p||!L)return;let e=s.current;if(e?.readyState===WebSocket.OPEN||e?.readyState===WebSocket.CONNECTING)return;clearTimeout(n.current);let i=new WebSocket(S);i.binaryType="arraybuffer",s.current=i,C(),clearTimeout(t),_(e=>({...(0,j.invalidatePhoenixBook)(e,null===e.orderbookReceivedAt?"loading":"disconnected"),connected:!1}),!0);let a=()=>p&&s.current===i,d=0;T=()=>{let e=Date.now();if(!a()||i.readyState!==WebSocket.OPEN||!m.connected||e-o.current>j.PHOENIX_BOOK_FRESH_MS||"stale"!==m.orderbookStatus&&e-d<j.PHOENIX_BOOK_FRESH_MS||"live"===m.orderbookStatus||"empty"===m.orderbookStatus||h||e<v||e<k||e-b<j.PHOENIX_BOOK_FRESH_MS)return;b=e;let t=x,r={controller:new AbortController,timer:void 0};h=r,r.timer=setTimeout(()=>{h===r&&a()&&P(),r.controller.abort(),h===r&&(h=void 0)},4e3),fetch(new URL(`/v1/view/orderbook/${encodeURIComponent(L)}`,S.replace(/^ws/,"http")).toString(),{signal:r.controller.signal,cache:"no-store"}).then(async s=>{if(r.controller.signal.aborted||!a())return;if(!s.ok)return void P(429===s.status||503===s.status?s.headers?.get("Retry-After"):null);let n=await s.json();if(r.controller.signal.aborted||!a()||t!==x)return;let l=n?.symbol===L?(0,j.parsePhoenixBook)(n):null,d=n?.slot,c=Date.now();!l||!Number.isSafeInteger(d)||d<0||null!==g&&d<g||i.readyState!==WebSocket.OPEN||!m.connected||c-o.current>j.PHOENIX_BOOK_FRESH_MS||c-e>=j.PHOENIX_BOOK_FRESH_MS?P():(g=d,E(l,e,!0))}).catch(()=>{!r.controller.signal.aborted&&a()&&P()}).finally(()=>{clearTimeout(r.timer),h===r&&(h=void 0)})},i.onopen=()=>{a()?(o.current=d=Date.now(),_(e=>({...e,connected:!0}),!0),u(i,"orderbook",L),u(i,"trades",L),u(i,"market",L),u(i,"fundingRate",L),r&&i.send(JSON.stringify({type:"subscribe",subscription:{channel:"traderState",authority:r,traderPdaIndex:0}}))):i.close()},i.onmessage=e=>{if(a()&&i.readyState===WebSocket.OPEN){A();try{let t=e.data instanceof ArrayBuffer?new TextDecoder().decode(e.data):e.data,r=JSON.parse(t),s=r?.channel==="orderbook"?(0,j.parsePhoenixBook)(r.orderbook):null;if(!(0,j.isPhoenixTransportFrame)(r,s))return;if(o.current=Date.now(),"ping"===r.type)return void i.send(JSON.stringify({type:"pong",nonce:r.nonce}));if("traderState"!==r.channel&&r.symbol&&r.symbol!==L)return;if("orderbook"===r.channel&&s)x++,C(),E(s,Date.now());else if("trades"===r.channel){let e=(r.trades||[]).map(e=>({side:"bid"===e.side?"buy":"sell",baseAmount:Math.abs(e.baseAmount??0),quoteAmou
2nt:Math.abs(e.quoteAmount??0),timestamp:e.timestamp,price:e.quoteAmount&&e.baseAmount?Math.abs(e.quoteAmount/e.baseAmount):0}));e.length>0&&_(t=>({...t,trades:[...e,...t.trades].slice(0,100)}))}else if("market"===r.channel)_(e=>({...e,marketStats:{markPx:r.markPx??0,oraclePx:r.oraclePx??0,prevDayPx:r.prevDayPx??0,dayNtlVlm:r.dayNtlVlm??0,openInterest:r.openInterest??0,funding:r.funding??0}}));else if("fundingRate"===r.channel)_(e=>({...e,funding:{cumulativeFundingRate:r.cumulativeFundingRate??0,previousSettledFundingRate:r.previousSettledFundingRate??r.funding??0,fundingStartIntervalTimestamp:r.fundingStartIntervalTimestamp??r.fundingStartTimestamp??0}}));else if("traderState"===r.channel){let e=r.subaccounts??[],t=[],i=0;for(let r of e)for(let e of(i+=parseFloat(r.collateral??"0"),r.positions??[])){let r=parseFloat(e.basePositionLots??"0");0!==r&&t.push({symbol:e.symbol??"",basePositionLots:Math.abs(r),entryPriceUsd:parseFloat(e.entryPriceUsd??"0"),side:r>0?"long":"short"})}_(e=>({...e,traderState:{collateral:i/1e6,positions:t}}),!0)}}catch{}}},i.onclose=()=>{a()&&(s.current=null,clearInterval(l.current),C(),clearTimeout(t),_(e=>({...(0,j.invalidatePhoenixBook)(e,"disconnected"),connected:!1}),!0),n.current=setTimeout(F,3e3))};let c=()=>{a()&&(C(),clearTimeout(t),_(e=>({...(0,j.invalidatePhoenixBook)(e,"disconnected"),connected:!1}),!0),i.close())};i.onerror=c,clearInterval(l.current),l.current=setInterval(()=>{a()&&(A(),Date.now()-o.current>j.PHOENIX_BOOK_FRESH_MS&&i.readyState===WebSocket.OPEN&&c())},2e3)}return F(),a.current=()=>{if(!p)return;A();let e=s.current;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(clearTimeout(n.current),F())},fetch(`https://perp-api.phoenix.trade/v1/trades/${L}/fills?limit=50`).then(e=>e.json()).then(e=>{if(!p||!e.data)return;let t=e.data.map(e=>({side:0>parseFloat(e.baseQty)?"sell":"buy",baseAmount:Math.abs(parseFloat(e.baseQty)),quoteAmount:Math.abs(parseFloat(e.quoteQty)),timestamp:new Date(e.timestamp).getTime().toString(),price:parseFloat(e.price)}));_(e=>({...e,trades:e.trades.length>0?e.trades:t}))}).catch(()=>{}),()=>{p=!1,T=()=>{},C(),(0,j.revokePhoenixBookGeneration)(m.orderbookGeneration),clearTimeout(d),clearTimeout(t),a.current=()=>{},clearTimeout(n.current),clearInterval(l.current),s.current&&(s.current.close(),s.current=null)}},[e,r,u,i]),(0,y.useResumeSignal)(()=>a.current()),d.symbol!==e||d.profilePda!==r)return N;let h=(0,j.expirePhoenixBook)(d,Date.now());return h!==d&&c(h),h}],389896);var P=e.i(568299);function T(e,r){let[i,s]=(0,t.useState)(e),n=(0,t.useRef)(0),a=(0,t.useRef)(e),l=(0,t.useRef)(null);return(0,t.useEffect)(()=>{a.current=e;let t=Date.now()-n.current;t>=r?(n.current=Date.now(),s(e)):null===l.current&&(l.current=setTimeout(()=>{l.current=null,n.current=Date.now(),s(a.current)},r-t))},[e,r]),(0,t.useEffect)(()=>()=>{null!==l.current&&clearTimeout(l.current)},[]),i}e.s(["useThrottledValue",0,T],48813),e.s(["usePhoenixExecutionBook",0,function(e,r,i){let s=(0,P.useRoutingContext)()?.setPhoenixBook,n=T((0,t.useMemo)(()=>({symbol:e,orderbook:i.orderbook,generation:i.orderbookGeneration,receivedAt:i.orderbookReceivedAt}),[e,i.orderbook,i.orderbookGeneration,i.orderbookReceivedAt]),1500),a=r&&i.connected&&"live"===i.orderbookStatus&&n.symbol===e&&n.generation===i.orderbookGeneration&&!(0,j.isPhoenixBookRevoked)(n.generation)&&(0,j.isPhoenixBookFresh)(n.receivedAt)?n.orderbook:void 0;return(0,t.useEffect)(()=>{if(!s)return;if(!r)return void s(null);let t={symbol:e,status:"live"===i.orderbookStatus?"loading":i.orderbookStatus,generation:i.orderbookGeneration,receivedAt:n.symbol===e?n.receivedAt:null,mid:0,bids:[],asks:[]};if(!a)return void s(t);let l=1/0;for(let[e]of a.asks)e<l&&(l=e);let o=0;for(let[e]of a.bids)e>o&&(o=e);!Number.isFinite(l)||o<=0?s(t):s({symbol:e,status:"live",generation:n.generation,receivedAt:n.receivedAt,mid:(l+o)/2,bids:a.bids.map(([e,t])=>({price:e,sizeBase:t})),asks:a.asks.map(([e,t])=>({price:e,sizeBase:t}))})},[s,r,e,a,i.orderbookStatus,i.orderbookGeneration,n.symbol,n.receivedAt,n.generation]),{phoenixOrderbook:a,phoenixOrderbookReceivedAt:n.receivedAt,phoenixOrderbookGeneration:n.generation}}],157265);var C=e.i(394390),M=t,_=e.i(586569);class A extends M.default.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error("ErrorBoundary caught:",e,t.componentStack)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:(0,C.jsxs)("div",{className:"flex flex-col items-center justify-center h-full min-h-[200px] bg-canvas text-muted-foreground gap-3",children:[(0,C.jsx)("p",{className:"text-sm",children:(0,_.message)("common","somethingWentWrong")}),(0,C.jsx)("button",{onClick:()=>this.setState({hasError:!1}),className:"px-3 py-1.5 text-xs rounded bg-surface-raised hover:bg-surface-interactive text-secondary-foreground transition-colors",children:(0,_.message)("common","retry")})]}):this.props.children}}function E(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function L(){return"visible"===document.visibilityState}e.s(["ErrorBoundary",0,A],650883),e.s(["useOnScreen",0,function(e){let[r,i]=(0,t.useState)(!0);return(0,t.useEffect)(()=>
2{if(!e||"u"<typeof IntersectionObserver)return;let t=new IntersectionObserver(([e])=>i(e.isIntersecting));return t.observe(e),()=>t.disconnect()},[e]),r}],460174),e.s(["useChartLayerRecovery",0,function(e,r){let i=(0,t.useSyncExternalStore)(E,L,()=>!1),s=r&&i,{back:n,failedKey:a}=(0,t.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot);return(0,y.useResumeSignal)(()=>{r&&L()&&e.clearFailed()}),(0,t.useEffect)(()=>{let t=()=>{r&&L()&&e.clearFailed()};return window.addEventListener("online",t),()=>window.removeEventListener("online",t)},[e,r]),(0,t.useEffect)(()=>{if(!s||!n)return;let t=setTimeout(()=>{L()&&e.getSnapshot().back?.id===n.id&&e.markFailed(n.key)},45e3);return()=>clearTimeout(t)},[e,s,n]),(0,t.useEffect)(()=>{if(!s||null===a)return;let t=setTimeout(()=>{L()&&e.getSnapshot().failedKey===a&&e.clearFailed()},3e4);return()=>clearTimeout(t)},[e,s,a]),s}],900165);class F{active=0;queue=[];inflight=new Map;concurrency;constructor(e=2){if(!Number.isInteger(e)||e<1)throw Error("Invalid history concurrency");this.concurrency=e}run(e,t,r={}){if(r.signal?.aborted)return Promise.reject(r.signal.reason);let i=this.inflight.get(e);i||(i={key:e,load:t,controller:new AbortController,started:!1,consumers:new Set},this.inflight.set(e,i),this.queue.push(i));let s=i,n=new Promise((t,i)=>{let n=()=>{s.consumers.delete(a),a.cleanup(),i(r.signal?.reason??new DOMException("Chart closed","AbortError")),s.consumers.size>0||(this.inflight.get(e)===s&&this.inflight.delete(e),s.started||(this.queue=this.queue.filter(e=>e!==s)),s.controller.abort(new DOMException("No chart retains this history","AbortError")))},a={options:r,resolve:e=>t(e),reject:i,cleanup:()=>r.signal?.removeEventListener("abort",n)};s.consumers.add(a),r.signal?.addEventListener("abort",n,{once:!0})});return this.drain(),n}getSnapshot(){return{active:this.active,queued:this.queue.length,requests:this.inflight.size}}priority(e){return Math.max(...[...e.consumers].map(({options:e})=>{let t="function"==typeof e.priority?e.priority():e.priority;return Number.isFinite(t)?t:0}))}drain(){for(;this.active<this.concurrency&&this.queue.length>0;){let e=0;for(let t=1;t<this.queue.length;t++)this.priority(this.queue[t])>this.priority(this.queue[e])&&(e=t);let t=this.queue.splice(e,1)[0];t.started=!0,this.active++;let r=(e,r)=>{for(let i of t.consumers)i.cleanup(),e?i.resolve(r):i.reject(r);t.consumers.clear(),this.inflight.get(t.key)===t&&this.inflight.delete(t.key),this.active--,this.drain()};Promise.resolve().then(()=>(t.controller.signal.throwIfAborted(),t.load(t.controller.signal))).then(e=>r(!0,e),e=>r(!1,e))}}}let R=new F,D=(e,t)=>AbortSignal.any([e,t]),I="https://api.imperial.space/api/v1/pyth/history",U={"1m":"1","5m":"5","15m":"15","30m":"30","1H":"60","2H":"120","4H":"240","1D":"1D"},O=new Map;async function B(e,t,r,i,s){let n,a;s?.signal?.throwIfAborted();let l=`${e}|${t}|${r}|${i}`,o=O.get(l);if(o&&Date.now()-o.ts<3e4)return o.data;let d=(n=`${I}:${l}`,a=async s=>{let n=async()=>{let n=new URLSearchParams({symbol:e,resolution:t,from:r.toString(),to:i.toString()}),a=await fetch(`${I}?${n}`,{signal:D(s,AbortSignal.timeout(15e3))});if(!a.ok)throw Error(`Pyth Benchmarks HTTP ${a.status} for ${e}`);let l=await a.json();if("no_data"===l.s)return[];if("ok"!==l.s||!Array.isArray(l.t))throw Error(`Pyth Benchmarks bad response for ${e}: s=${l.s}`);return l.t.map((e,t)=>({time:e,open:l.o[t],high:l.h[t],low:l.l[t],close:l.c[t],volume:l.v?.[t]??0}))};try{return await n()}catch{return s.throwIfAborted(),await new Promise(e=>setTimeout(e,500)),s.throwIfAborted(),n()}},R.run(n,a,s));return d.then(e=>{if(e.length>0){let t=Date.now();for(let[e,r]of O)t-r.ts>=3e4&&O.delete(e);for(;O.size>128;)O.delete(O.keys().next().value);O.set(l,{data:e,ts:Date.now()})}}).catch(()=>{}),d}async function z(e,t="1H",r,i,s){let n=U[t];if(!n)throw Error(`Unsupported interval for Pyth Benchmarks: ${t}`);let a=Math.floor(Date.now()/1e3),l=i||a,o=r||l-400*(({"1m":60,"5m":300,"15m":900,"30m":1800,"1H":3600,"2H":7200,"4H":14400,"1D":86400})[t]||3600),d=e.startsWith("Equity.US.")?e.replace(/\.(PRE|POST|ON)$/,""):e;return(await B(d,n,o,l,s)).map(e=>({...e})).sort((e,t)=>
2e.time-t.time)}e.s(["fetchPythBenchmarksOHLCV",0,z],284139);var $=e.i(828047),V=e.i(142910);async function H(e){try{let t=`https://frontend-api-v3.pump.fun/coins/${e}`,r=await fetch(`/api/proxy?url=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(15e3)});if(r.ok){let e=await r.json(),t=Number(e?.created_timestamp);if(t&&!isNaN(t))return t}}catch(e){console.error("Error fetching from pump.fun API:",e)}try{let t=await fetch(`https://datapi.jup.ag/v2/search?query=${e}&tokenExactCaseInsensitive=false`,{signal:AbortSignal.timeout(15e3)});if(t.ok){let e=await t.json();if(Array.isArray(e)&&e.length>0){let t=e[0]?.token,r=Number(t?.createdAt);if(r&&!isNaN(r))return r>1e10?r:1e3*r}}}catch(e){console.error("Error fetching from Jupiter API:",e)}return console.warn("Unable to get token creation timestamp, using 30 days ago"),Date.now()-2592e6}let W={"2m":{base:"1m",seconds:120},"3m":{base:"1m",seconds:180},"10m":{base:"5m",seconds:600},"30m":{base:"15m",seconds:1800},"45m":{base:"15m",seconds:2700},"3H":{base:"1H",seconds:10800},"8H":{base:"4H",seconds:28800},"12H":{base:"4H",seconds:43200},"3D":{base:"1D",seconds:259200},"4D":{base:"1D",seconds:345600},"1W":{base:"1D",seconds:604800},"1M":{base:"1D",seconds:2592e3}};function q(e,t){if(0===e.length)return[];let r=[],i=null;for(let s of e){let e=Math.floor(s.time/t)*t;i&&i.time===e?(i.high=Math.max(i.high,s.high),i.low=Math.min(i.low,s.low),i.close=s.close,i.volume=(i.volume??0)+(s.volume??0)):(i&&r.push(i),i={...s,time:e})}return i&&r.push(i),r}let K={"1m":"1m","3m":"3m","5m":"5m","15m":"15m","30m":"30m","1H":"1h","2H":"2h","4H":"4h","6H":"6h","8H":"8h","12H":"12h","1D":"24h","3D":"3d","1W":"1w","1M":"1M"};async function G(e,t="1H",r,i,s=1e3){try{let n=K[t];if(!n)throw Error(`Invalid time interval for pump.fun: ${t}`);let a=new URLSearchParams({interval:n,limit:s.toString(),currency:"SOL",createdTs:r.toString()});i&&a.append("beforeTs",i.toString());let l=`https://swap-api.pump.fun/v2/coins/${e}/candles?${a}`,o=new URLSearchParams({url:l,header_Origin:"https://www.pump.fun"}),d=await fetch(`/api/proxy?${o}`,{method:"GET",signal:AbortSignal.timeout(15e3)});if(!d.ok)throw Error(`Failed to fetch pump.fun OHLCV data: ${d.status} ${d.statusText}`);let c=await d.json();if(!Array.isArray(c))throw Error("Invalid response format from pump.fun API");let u=c.map(e=>({time:Math.floor(e.timestamp/1e3),open:parseFloat(e.open),high:parseFloat(e.high),low:parseFloat(e.low),close:parseFloat(e.close),volume:parseFloat(e.volume)}));return u.sort((e,t)=>e.time-t.time),u}catch(e){throw console.error("Error fetching pump.fun OHLCV data:",e),e}}async function Y(e,t,r="1H",i){if("pump"===t){let t=i?.createdTs;t||(t=await H(e));let s=K[r]?null:W[r],n=s?.base??r,a=await G(e,n,t,i?.beforeTs,i?.limit||1e3);return s?q(a,s.seconds):a}{let t,s=W[r],n=s?.base??r,a=(0,V.getLazerSymbol)(e)??(0,V.getLazerSymbolByAssetSymbol)(e);if(a)t=await z(a,n,i?.timeFrom,i?.timeTo,i?.historyConsumer);else if((0,$.sunriseListsSymbol)(e)){let r=(0,$.clampHistoryWindow)((0,$.sunriseHistoryFloor)(e),i?.timeFrom,i?.timeTo);t=r?await z(e.toUpperCase(),n,r.from,r.to,i?.historyConsumer):[]}else console.warn(`No Pyth Lazer feed for ${e}; returning empty chart history`),t=[];return s?q(t,s.seconds):t}}e.s(["getChartData",0,Y],889563);var X=e.i(798526);function Q(e,t){return void 0===t?e:void 0===e||t.time>=e.time?t:e}function J(e,t){e.pending.push(t),e.pending.length>500&&e.pending.splice(0,e.pending.length-500)}function Z(e,t,r,i=2){if(e.seeding)return;e.seeding=!0,e.pending=[];let s=0,n=()=>t().catch(()=>{if(++s<i)return new Promise(e=>setTimeout(e,2e3)).then(n)});n().finally(()=>{e.seeding=!1;let t=e.pending;
2for(let i of(e.pending=[],t))r(i)})}function ee(e,t){return void 0!==t?429!==t:!("u">typeof navigator&&!1===navigator.onLine||e instanceof DOMException&&"AbortError"===e.name)&&"AbortError"!==e?.name}let et=new Map,er=new Set,ei=0;function es(e){let t=et.get(e);return t||(t={recentFailures:[],lastSuccessAt:0},et.set(e,t)),t}function en(e,t){0!==e.recentFailures.length&&(e.recentFailures=e.recentFailures.filter(e=>t-e<6e4))}function ea(){for(let e of(ei++,er))e()}function el(e){let t=es(e),r=Date.now();en(t,r),t.recentFailures.push(r),ea()}function eo(e){let t=es(e);t.lastSuccessAt=Date.now(),0!==t.recentFailures.length&&(t.recentFailures=[],ea())}e.s(["getProviderHealthVersion",0,function(){return ei},"getProviderRecoveryAt",0,function(e){let t=et.get(e);return t&&0!==t.recentFailures.length?t.recentFailures[0]+6e4:null},"isOutageEvidence",0,ee,"isProviderDown",0,function(e){let t=et.get(e);return!!t&&(en(t,Date.now()),t.recentFailures.length>=2)},"reportProviderFailure",0,el,"reportProviderSuccess",0,eo,"subscribeProviderHealth",0,function(e){return er.add(e),()=>{er.delete(e)}}],875722);let ed={1:2592e6,2:2592e6,3:5184e6,5:7776e6,10:10368e6,15:15552e6,30:15552e6,45:15552e6,60:31536e6,120:31536e6,180:31536e6,240:63072e6,360:63072e6,480:63072e6,720:63072e6,"1D":94608e
26,D:94608e6,"3D":94608e6,"4D":94608e6,"1W":94608e6,W:94608e6,"1M":15768e7,M:15768e7};function ec(e,t,r){return Math.max(t,r-Math.floor((ed[e]??31536e6)/1e3))}async function eu(e,t={}){let r,i=t.retries??1,s=t.delayMs??500;for(let t=0;t<=i;t++)try{return await e()}catch(e){r=e,t<i&&await new Promise(e=>setTimeout(e,s))}throw r}let eh={1:"1m",2:"2m",3:"3m",5:"5m",10:"10m",15:"15m",30:"30m",45:"45m",60:"1H",120:"2H",180:"3H",240:"4H",360:"6H",480:"8H",720:"12H","1D":"1D",D:"1D","3D":"3D","4D":"4D","1W":"1W",W:"1W","1M":"1M",M:"1M"};function ep(e){return!Number.isFinite(e)||e<=0?1e5:e>=1e3?100:e>=10?1e3:e>=.1?1e4:e>=.001?1e6:1e8}function em(e){return({1:6e4,2:12e4,3:18e4,5:3e5,10:6e5,15:9e5,30:18e5,45:27e5,60:36e5,120:72e5,180:108e5,240:144e5,360:216e5,480:288e5,720:432e5,"1D":864e5,D:864e5,"3D":2592e5,"4D":3456e5,"1W":6048e5,W:6048e5,"1M":2592e6,M:2592e6})[e]||36e5}let ef=0;e.s(["MemeTokenDatafeed",0,class{source;supportsVolume;feedOwner;tokenAddress;tokenSymbol;tokenType;priceMode;solPrice;supportedResolutions;subscribers;barCache;noDataBefore;prefetchPromise;reseedCallbacks;deliveredBar;hiddenAt;visibilityCleanup;exchangeName;pricescalePromise;healthVenue;destroyed;historyAbort;historyConsumer;setHistoryPriority(e){this.historyConsumer.priority=e}constructor(e,t,r,i="USD",s=1,n="Imperial",a,l,o=!0){this.source=l,this.supportsVolume=o,this.feedOwner=`chart-feed-${++ef}`,this.supportedResolutions=["1","2","3","5","10","15","30","45","60","120","180","240","480","720","1D","3D","4D","1W","1M"],this.subscribers=new Map,this.barCache=new Map,this.noDataBefore=new Map,this.prefetchPromise=null,this.reseedCallbacks=new Map,this.deliveredBar=new Map,this.hiddenAt=null,this.visibilityCleanup=null,this.pricescalePromise=null,this.destroyed=!1,this.historyAbort=new AbortController,this.historyConsumer={signal:this.historyAbort.signal,priority:0},this.tokenAddress=e,this.tokenSymbol=t,this.tokenType=r,this.priceMode=i,this.solPrice=s,this.exchangeName=n,this.healthVenue=a,this.setupVisibilityDetection()}reportFetchOutcome(e,t){!this.destroyed&&this.healthVenue&&(e?eo(this.healthVenue):ee(t)&&el(this.healthVenue))}setupVisibilityDetection(){if("u"<typeof document)return;let e=()=>{"hidden"===document.visibilityState?this.hiddenAt=Date.now():"visible"===document.visibilityState&&this.hiddenAt&&(this.hiddenAt=null,this.reseedCallbacks.forEach(e=>e()))};document.addEventListener("visibilitychange",e),this.visibilityCleanup=()=>document.removeEventListener("visibilitychange",e)}destroy(){for(let e of(this.destroyed=!0,this.historyAbort.abort(),this.visibilityCleanup?.(),this.subscribers.keys()))this.unsubscribeBars(e)}getData(e,t){return this.source?this.source.history(e,t?.timeFrom,t?.timeTo,this.historyConsumer):Y(this.tokenAddress,this.tokenType,e,{...t,historyConsumer:this.historyConsumer})}convertPrice(e){return"pump"===this.tokenType?"SOL"===this.priceMode?e:e*this.solPrice:"SOL"===this.priceMode?e/this.solPrice:e}prefetchBars(e){let t=eh[e]||"1H",r=Math.floor(Date.now()/1e3),i=r-400*(em(e)/1e3);this.prefetchPromise=this.getData(t,{timeFrom:i,timeTo:r}).then(e=>{if(this.destroyed)return;let s=this.source&&e.length>0?Math.max(i,e[0].time):i;this.barCache.set(t,{bars:e,from:s,to:r}),this.reportFetchOutcome(!0)}).catch(e=>{this.reportFetchOutcome(!1,e)}).finally(()=>{this.prefetchPromise=null})}updatePriceMode(e,t){this.priceMode=e,this.solPrice=t}onReady(e){setTimeout(()=>{e({supported_resolutions:this.supportedResolutions,supports_marks:!1,supports_timescale_marks:!1,supports_time:!0})},0)}searchSymbols(e,t,r,i){i([{symbol:this.tokenSymbol,full_name:this.tokenSymbol,description:this.tokenSymbol,exchange:this.exchangeName,ticker:this.tokenSymbol,type:"crypto"}])}lastCachedClose(){for(let e of this.barCache.values()){let t=e.bars[e.bars.length-1]?.close;if("number"==typeof t&&t>0)return t}}async resolvePricescale(){return this.pricescalePromise||(this.pricescalePromise=(async()=>{try{let e=this.prefetchPromise;e&&await e;let t=this.lastCachedClose();if(void 0!==t)return ep(this.convertPrice(t));let r=Math.floor(Date.now()/1e3),i=await this.getData("1H",{timeFrom:r-86400,timeTo:r,beforeTs:r,limit:1}),s=i[i.length-1]?.close,n="number"==typeof s?this.convertPrice(s):0;return ep(n)}catch{return 1e5}})()),this.pricescalePromise}resolveSymbol(e,t){this.resolvePricescale().then(r=>{t({name:e,ticker:e,description:`${this.tokenSymbol}/${"SOL"===this.priceMode?"SOL":"USD"}`,type:"crypto",session:"24x7",timezone:"Etc/UTC",exchange:this.exchangeName,minmov:1,pricescale:r,has_intraday:!0,has_daily:!0,has_weekly_and_monthly:!0,supported_resolutions:this.supportedResolutions,visible_plots_set:this.supportsVolume?"ohlcv":"ohlc",...this.supportsVolume?{volume_precision:2}:{},data_status:"streaming"})})}getBars(e,t,r,i,s){var n,a;let l=eh[t]||"1H",{from:o,to:d}=r,c=ec(t,o,d);if(n=this.noDataBefore.get(t),a=Date.now(),n&&!(a-n.at>=3e5)&&d<=n.boundary)return void i([],{noData:!0});let u=()=>{let e=this.barCache.get(l);if(e&&c>=e.from&&d<=e.to+60){if(this.barCache.delete(l),0===e.bars.length)return i([],{noData:!0}),!0;let r=e.bars.map(e=>({time:1e3*e.time,open:this.convertPrice(e.open),high:this.convertPrice(e.high),low:this.convertPrice(e.low),close:this.convertPrice(e.close),...this.supportsVolume?{volume:e.volume}:{}}));return r.sort((e,t)=>
2e.time-t.time),this.noteDelivered(t,r),i(r,{noData:!1}),!0}return!1};if(u())return;let h=this.prefetchPromise;h?h.then(()=>{u()||this.fetchBars(l,c,d,i,s,t)}):this.fetchBars(l,c,d,i,s,t)}fetchBars(e,t,r,i,s,n){eu(()=>this.getData(e,"pump"===this.tokenType?{beforeTs:1e3*r}:{timeFrom:t,timeTo:r})).then(e=>{if(this.destroyed)return;if(this.reportFetchOutcome(!0),0===e.length){if(r<Math.floor(Date.now()/1e3)-900){let e=this.noDataBefore.get(n);(void 0===e||r>e.boundary)&&this.noDataBefore.set(n,{boundary:r,at:Date.now()})}i([],{noData:!0});return}let t=e.map(e=>({time:1e3*e.time,open:this.convertPrice(e.open),high:this.convertPrice(e.high),low:this.convertPrice(e.low),close:this.convertPrice(e.close),...this.supportsVolume?{volume:e.volume}:{}}));t.sort((e,t)=>e.time-t.time),this.noteDelivered(n,t),i(t,{noData:!1})}).catch(e=>{this.destroyed||(this.reportFetchOutcome(!1,e),console.error("Error fetching bars:",e),i([],{noData:!0}),s(e))})}noteDelivered(e,t){let r=Q(this.deliveredBar.get(e),t[t.length-1]);r&&this.deliveredBar.set(e,r)}subscribeBars(e,t,r,i,s){if(this.destroyed)return;this.unsubscribeBars(i);let n=this.source?this.tokenSymbol:(0,X.getFeedSymbol)(this.tokenAddress);"pump"!==this.tokenType&&n?this.subscribeViaWs(n,t,r,i):this.subscribeViaPoll(t,r,i)}subscribeViaWs(e,t,r,i){let s=em(t),n=!1,a=null,l={seeding:!1,pending:[]},o=this.deliveredBar.get(t)?.time??0,d=null,c=e=>{let i;if(n||this.destroyed)return;let l=(i=e.price,"SOL"===this.priceMode?i/this.solPrice:i),d=this.source?.barTime(e.timestamp,t)??Math.floor(e.timestamp/s)*s;d<o||(!a||d>a.time?a={time:d,open:l,high:l,low:l,close:l,...this.supportsVolume?{volume:e.volume}:{}}:(a.high=Math.max(a.high,l),a.low=Math.min(a.low,l),a.close=l),o=a.time,r({...a}))},u=()=>{if(n||this.destroyed)return;let e=eh[t]||"1H",i=Math.floor(Date.now()/1e3),s=o?Math.floor(o/1e3):i-3600;Z(l,async()=>{let t=await this.getData(e,{timeFrom:s,timeTo:i}).catch(e=>{throw n||this.reportFetchOutcome(!1,e),e});if(n||this.destroyed)return;this.reportFetchOutcome(!0);let l=e=>"SOL"===this.priceMode?e/this.solPrice:e;for(let e of t){let t=1e3*e.time;if(o&&t<o)continue;let i={time:t,open:l(e.open),high:l(e.high),low:l(e.low),close:l(e.close),...this.supportsVolume?{volume:e.volume}:{}};a=i,o=t,r({...i})}d&&Date.now()-d.receivedAt<3e4&&c(d.tick)},c)};u(),this.reseedCallbacks.set(i,()=>{a=null,u()});let h={disconnectedAt:null,lastReseedAt:null},p=`${this.feedOwner}:${i}`,m=p+"_conn",f=e=>{(function(e,t,r=Date.now()){if(!t)return null===e.disconnectedAt&&(e.disconnectedAt=r),!1;let i=e.disconnectedAt;return e.disconnectedAt=null,null!==i&&!(r-i<3e3)&&(null===e.lastReseedAt||!(r-e.lastReseedAt<3e4))&&(e.lastReseedAt=r,!0)})(h,e)&&(a=null,u())},x=e=>{(d={tick:e,receivedAt:Date.now()},l.seeding)?J(l,e):c(e)},g=this.source?this.source.subscribe(p,x,f):((0,X.addConnectionListener)(m,f),(0,X.addListener)(p,e,x),()=>{(0,X.removeListener)(p,e),(0,X.removeConnectionListener)(m)}),b=this.source?setInterval(()=>{"visible"===document.visibilityState&&u()},3e4):null;this.subscribers.set(i,()=>{n=!0,null!==b&&clearInterval(b),g()})}subscribeViaPoll(e,t,r){let i=eh[e]||"1H",s=!1,n=setInterval(async()=>{if(!s&&!this.destroyed)try{let e=Math.floor(Date.now()/1e3),r=await this.getData(i,"pump"===this.tokenType?{beforeTs:1e3*e,limit:1}:{timeFrom:e-3600,timeTo:e});if(s||this.destroyed)return;if(r.length>0){let e=r[r.length-1];t({time:1e3*e.time,open:this.convertPrice(e.open),high:this.convertPrice(e.high),low:this.convertPrice(e.low),close:this.convertPrice(e.close),...this.supportsVolume?{volume:e.volume}:{}})}}catch(e){console.error("Error fetching latest bar:",e)}},1e4);this.subscribers.set(r,()=>{s=!0,clearInterval(n)})}unsubscribeBars(e){let t=this.subscribers.get(e);t&&(t(),this.subscribers.delete(e)),this.reseedCallbacks.delete(e)}}],376260);var ex=e.i(495433);let eg=new Map,eb={"1m":{base:"1m",seconds:60,baseSeconds:60},"2m":{base:"1m",seconds:120,baseSeconds:60},"3m":{base:"1m",seconds:180,baseSeconds:60},"5m":{base:"5m",seconds:300,baseSeconds:300},"10m":{base:"5m",seconds:600,baseSeconds:300},"15m":{base:"15m",seconds:900,baseSeconds:900},"30m":{base:"30m",seconds:1800,baseSeconds:1800},"45m":{base:"15m",seconds:2700,baseSeconds:900}
2,"1H":{base:"1H",seconds:3600,baseSeconds:3600},"2H":{base:"1H",seconds:7200,baseSeconds:3600},"3H":{base:"1H",seconds:10800,baseSeconds:3600},"4H":{base:"4H",seconds:14400,baseSeconds:14400},"6H":{base:"1H",seconds:21600,baseSeconds:3600},"8H":{base:"4H",seconds:28800,baseSeconds:14400},"12H":{base:"4H",seconds:43200,baseSeconds:14400},"1D":{base:"1D",seconds:86400,baseSeconds:86400},"3D":{base:"1D",seconds:259200,baseSeconds:86400},"4D":{base:"1D",seconds:345600,baseSeconds:86400},"1W":{base:"1D",seconds:604800,baseSeconds:86400},"1M":{base:"1D",seconds:2592e3,baseSeconds:86400}};function ev(e,t){if("1M"===t){let t=new Date(1e3*e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1)/1e3}let r=eb[t].seconds,i=345600*("1W"===t);return Math.floor((e-i)/r)*r+i}async function ey(e,t,r,i,s){let n=eb[t],a=i??Math.floor(Date.now()/1e3),l=Math.max(ev(r??a-400*n.seconds,t),a-499*n.baseSeconds),o=(0,$.clampHistoryWindow)((0,$.sunriseHistoryFloor)(e),l,a);if(!o)return[];let d=await z(e.toUpperCase(),n.base,o.from,o.to,s),c=[];for(let e of d){let r=ev(e.time,t);if(n.seconds!==n.baseSeconds&&r<d[0].time)continue;let i=c[c.length-1];i?.time===r?(i.high=Math.max(i.high,e.high),i.low=Math.min(i.low,e.low),i.close=e.close,i.volume=(i.volume??0)+(e.volume??0)):c.push({...e,time:r})}return c}e.s(["createSunriseChartSource",0,function(e){return{history:(t,r,i,s)=>ey(e,t,r,i,s),subscribe:(t,r,i)=>(function(e,t,r,i){let s=t.toUpperCase(),n=eg.get(s);if(!n){let e,t=new Map,r=!1,i=null,a=async()=>{if(r||i||"hidden"===document.visibilityState)return;clearTimeout(e);let n=new AbortController;i=n;try{let e=await (0,ex.fetchSunriseOrderbook)("armada",s,1,n.signal);if(r||n.signal.aborted||"hidden"===document.visibilityState)return;let i=e?.stats.markPrice,a=e?.venueReachable===!0&&"number"==typeof i&&Number.isFinite(i)&&i>0;
2for(let e of t.values())e.connection(a),a&&e.tick({symbol:s,price:i,timestamp:Date.now(),volume:0})}finally{i=null,r||"hidden"===document.visibilityState||(e=setTimeout(a,1500))}},l=()=>{if("hidden"===document.visibilityState)for(let r of(clearTimeout(e),i?.abort(),t.values()))r.connection(!1);else a()},o=()=>{a()};document.addEventListener("visibilitychange",l),window.addEventListener("focus",o),window.addEventListener("online",o),n={listeners:t,stop(){r=!0,clearTimeout(e),i?.abort(),document.removeEventListener("visibilitychange",l),window.removeEventListener("focus",o),window.removeEventListener("online",o)}},eg.set(s,n),queueMicrotask(()=>{a()})}n.listeners.set(e,{tick:r,connection:i});let a=n;return()=>{a.listeners.delete(e),0===a.listeners.size&&(a.stop(),eg.get(s)===a&&eg.delete(s))}})(t,e,r,i),barTime:(e,t)=>1e3*ev(e/1e3,"D"===t?"1D":"W"===t?"1W":"M"===t?"1M":/[DWM]$/.test(t)?t:60>Number(t)?`${t}m`:`${Number(t)/60}H`)}}],737866);let ew=["open","high","low","close","markOpen","markHigh","markLow","markClose"],ej=[...ew,"volume","volumeQuote","tradeCount"],eS=["markOpen","markHigh","markLow","markClose","volume","volumeQuote","tradeCount"],ek="imperial_phoenix_candle_integrity",eN=[];function eP(e){if(0===eN.length&&"u">typeof sessionStorage)try{let e=JSON.parse(sessionStorage.getItem(ek)??"[]");Array.isArray(e)&&eN.push(...e.slice(-9))}catch{}for(eN.push(e);eN.length>10||eN.length>1&&JSON.stringify(eN).length>25e4;)eN.shift();try{"u">typeof sessionStorage&&sessionStorage.setItem(ek,JSON.stringify(eN))}catch{}e.repaired&&console.warn("[Phoenix candles] Rebuilt incomplete aggregates",{symbol:e.symbol,from:e.from,to:e.to,repaired:e.repaired})}function eT(e){return JSON.stringify([e.time,...ej.map(t=>e[t]),e.externalSource])}function eC(e){return ew.every(t=>Number.isFinite(e[t])&&e[t]>0)&&e.high>=Math.max(e.open,e.close)&&e.low<=Math.min(e.open,e.close)&&e.markHigh>=Math.max(e.markOpen,e.markClose)&&e.markLow<=Math.min(e.markOpen,e.markClose)}let eM={"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5};function e_(e,t,r){return Number.isFinite(e.time)&&e.time%r==0&&e.time+r<=t&&!1!==e.isFinal}function eA(e,t){return eS.every(r=>Math.abs(e[r]-t[r])<=Math.max(1e-12,1e-9*Math.abs(t[r])))}class eE{verified=new Map;flights=new Map;fetchMinutes;record;now;constructor(e,t=eP,r=Date.now){this.fetchMinutes=e,this.record=t,this.now=r}async verify(e,t,r,i=!1,s=36e5,n){let a=this.now();for(let[e,t]of this.verified)t.expires<=a&&this.verified.delete(e);let l=[...t],o=new Set,d=0;for(let r=0;r<t.length;r++){let i=this.verified.get(`${e}:${s}:${t[r].time}`);i?.fingerprint===eT(t[r])&&e_(t[r],a,s)&&(l[r]={...i.bar},o.add(r),!eA(t[r],i.bar)&&d++)}let c=i?[0,t.length-1]:function(e,t,r=36e5){let i=[];for(let s=1;s<e.length;s++){let n=e[s-1],a=e[s];e_(n,t,r)&&e_(a,t,r)&&a.time-n.time===r&&eC(n)&&eC(a)&&Math.abs(a.markOpen-n.markClose)>2*Math.max(n.markHigh-n.markLow,a.markHigh-a.markLow,1e-8*a.markClose)&&i.push(s)}return i.filter((e,t)=>t>=2&&e-i[t-2]<=8||t+2<i.length&&i[t+2]-e<=8).length?[0,e.length-1]:null}(t,a,s);if(!c)return{bars:l,repaired:d,pending:!1,pendingBars:[]};let u=t.map((e,t)=>t).filter(e=>e>=c[0]&&e<=c[1]&&e_(t[e],a,s)&&!o.has(e)),h=new Set(u),p=u.slice(0,720);for(;p.length&&!(n?.signal?.aborted||this.now()-a>2e4);){let i=t[p[0]].time,o=[];for(;p.length&&t[p[0]].time>=i&&t[p[0]].time<i+432e6;)o.push(p.shift());let c=Math.max(...o.map(e=>t[e].time))+s,u={at:a,symbol:e,status:"incomplete",candleRequest:r,minuteRequests:[],from:i,to:c,repaired:0,samples:[]},m=!1,f=!1;try{let r=`${e}:${i}:${c}`,p=n?this.fetchMinutes(e,i,c,n):this.flights.get(r);p||(p=this.fetchMinutes(e,i,c).finally(()=>{this.flights.delete(r)}),this.flights.set(r,p));let f=await p;if(n?.signal?.aborted)break;u.minuteRequests=f.requests;let x=new Map;for(let e of f.bars){let t=Math.floor(e.time/s)*s,r=x.get(t)??[];r.push(e),x.set(t,r)}for(let r of o){let i=t[r],n=x.get(i.time)??[],o=function(e,t,r,i=36e5){let s=i/6e4;if(!e_(e,r,i)||t.length!==s)return null;let n=[...t].sort((e,t)=>e.time-t.time);if(n.some((t,r)=>t.time!==e.time+6e4*r||!1===t.isFinal||!eC(t)||(t.externalSource??null)!==(e.externalSource??null)||![t.volume,t.volumeQuote,t.tradeCount].every(e=>Number.isFinite(e)&&e>=0)))return null;let a=n[s-1];return{...e,open:n[0].open,high:Math.max(...n.map(e=>e.high)),low:Math.min(...n.map(e=>
2e.low)),close:a.close,markOpen:n[0].markOpen,markHigh:Math.max(...n.map(e=>e.markHigh)),markLow:Math.min(...n.map(e=>e.markLow)),markClose:a.markClose,volume:n.reduce((e,t)=>e+t.volume,0),volumeQuote:n.reduce((e,t)=>e+t.volumeQuote,0),tradeCount:n.reduce((e,t)=>e+t.tradeCount,0),isFinal:!0}}(i,n,a,s);if(!o){m=!0,h.delete(r),h.add(r);continue}h.delete(r);let c=!eA(i,o),p=c?o:i;for(l[r]={...p},this.verified.set(`${e}:${s}:${i.time}`,{fingerprint:eT(i),bar:{...p},expires:a+6e5});this.verified.size>1e4;)this.verified.delete(this.verified.keys().next().value);c&&(d++,u.repaired++,u.samples.length<2&&u.samples.push({original:{...i},rebuilt:{...o},minutes:n.map(e=>({...e}))}))}}catch(e){if(n?.signal?.aborted)break;for(let e of(m=!0,f=!0,o))h.delete(e),h.add(e);u.status="failed",e instanceof eF&&(u.minuteRequests=e.requests)}if(u.repaired&&(u.status="repaired"),(u.repaired||m)&&this.record(u),f)break}return{bars:l,repaired:d,pending:h.size>0,pendingBars:[...h].map(e=>t[e])}}}let eL="https://perp-api.phoenix.trade/v1/candles_v2";class eF extends Error{requests;constructor(e){super("Phoenix minute verification unavailable"),this.requests=e}}async function eR(e,t,r,i){let s,n,a;return s=`phoenix-minutes:${eL}:${e}:${t}:${r}`,n=async i=>{let s=new AbortController,n=setTimeout(()=>s.abort(),12e3),a=[],l=[],o=new Set,d=new URLSearchParams({timeframe:"1m",from:String(t),to:String(r),limit:"10000",includePartial:"false"});try{for(let n=0;n<8;n++){let n=`${eL}/${encodeURIComponent(e)}?${d}`,c={url:n,fetchedAt:Date.now(),requestId:null,edge:null};a.push(c);let u=await fetch(n,{signal:D(i,s.signal),cache:"no-store"});if(c.requestId=u.headers.get("x-amz-cf-id")??u.headers.get("x-phoenix-ctr-hash"),c.edge=u.headers.get("x-amz-cf-pop"),!u.ok)break;let h=await u.json();if(h.symbol!==e||"1m"!==h.timeframe||!Array.isArray(h.bars)||h.bars.some(e=>!Number.isFinite(e.time)||e.time<t||e.time>=r)||(l.push(...h.bars),l.length>7200))break;if(!h.page?.hasMore)return{bars:l,requests:a};let p=h.page.nextCursor;if("string"!=typeof p||!p||o.has(p))break;o.add(p),d=new URLSearchParams({cursor:p})}throw new eF(a)}catch{throw new eF(a)}finally{clearTimeout(n)}},a=i?{signal:i.signal,priority:()=>(("function"==typeof i.priority?i.priority():i.priority)??0)-5}:{priority:-5},R.run(s,n,a)}var eD=e.i(47280);let eI={1:{tf:"1m",ms:6e4},2:{tf:"2m",ms:12e4},3:{tf:"3m",ms:18e4},5:{tf:"5m",ms:3e5},10:{tf:"10m",ms:6e5},15:{tf:"15m",ms:9e5},30:{tf:"30m",ms:18e5},45:{tf:"45m",ms:27e5},60:{tf:"1h",ms:36e5},120:{tf:"2h",ms:72e5},180:{tf:"3h",ms:108e5},240:{tf:"4h",ms:144e5},360:{tf:"6h",ms:216e5},720:{tf:"12h",ms:432e5},"1D":{tf:"1d",ms:864e5},D:{tf:"1d",ms:864e5},"1W":{tf:"1w",ms:6048e5},W:{tf:"1w",ms:6048e5}},eU=Object.fromEntries(Object.values(eI).map(e=>[e.tf,e.ms])),eO=new Set(["1m","5m","15m","30m","1h","4h","1d"]),eB={"2m":"1m","3m":"1m","10m":"5m","45m":"15m","2h":"1h","3h":"1h","6h":"1h","12h":"4h","1w":"1d"},ez={10:"5m",15:"1m",30:"5m",45:"15m",60:"5m",120:"15m",180:"1h",240:"1h",360:"1h",720:"1h","1D":"1h",D:"1h","1W":"1d",W:"1d"};function e$(e){let t=eI[e];return t?eO.has(t.tf)?t.tf:eB[t.tf]??null:null}function eV(e){let t=eI[e];return!!t&&!eO.has(t.tf)}function eH(e,t){if(0===e.length)return[];let r=[],i=null;for(let s of e){let e=Math.floor(s.time/t)*t;i&&i.time===e?(i.high=Math.max(i.high,s.high),i.low=Math.min(i.low,s.low),i.close=s.close,i.volume=(i.volume||0)+(s.volume||0)):(i&&r.push(i),i={...s,time:e})}return i&&r.push(i),r}function eW(e){return eI[e]?.ms??0}let eq=new Map,eK=new WeakMap,eG=new eE(eR);async function eY(e,t,r,i,s=1e3,n){let a;n?.signal?.throwIfAborted();let l=`${eL}/${e}?timeframe=${t}&from=${r}&to=${i}&limit=${s}&includePartial=true`,o=eq.get(l);if(o&&Date.now()-o.timestamp<3e3)return o.bars;let d=(a=async e=>{let t,r=new AbortController,i=setTimeout(()=>r.abort(new DOMException("Phoenix candles timed out","TimeoutError")),15e3);try{try{t=await fetch(l,{signal:D(e,r.signal)})}catch(e){throw(e?.name==="TimeoutError"||ee(e))&&el("phoenix"),e}if(!t.ok)throw ee(null,t.status)&&el("phoenix"),Error(`Phoenix candles API error: ${t.status}`);let i=await t.json();eo("phoenix");let s=Array.isArray(i)?i:i.bars??[];return eK.set(s,{url:l,fetchedAt:Date.now(),requestId:t.headers.get("x-amz-cf-id")??t.headers.get("x-phoenix-ctr-hash"),edge:t.headers.get("x-amz-cf-pop")}),s}finally{clearTimeout(i)}},R.run(l,a,n));return d.then(e=>{for(let[e,t]of eq)Date.now()-t.timestamp>=3e3&&eq.delete(e);for(;eq.size>=128;)eq.delete(eq.keys().next().value);eq.set(l,{bars:e,timestamp:Date.now()})}).catch(()=>{}),d}
2class eX{symbol;phoenixSymbol;supportedResolutions=["1","2","3","5","10","15","30","45","60","120","180","240","360","720","1D","1W"];subscribers=new Map;lastBar=new Map;releaseMarket=null;alive=!0;historyAbort=new AbortController;historyConsumer={signal:this.historyAbort.signal,priority:0};setHistoryPriority(e){this.historyConsumer.priority=e}hiddenAt=null;visibilityCleanup=null;hasConnectedOnce=!1;pricescalePromise=null;liveRefreshTimers=new Map;partialPollInFlight=new Map;noDataBefore=new Map;pendingIntegrity=new Map;integrityRetryTimer;integrityRetryInFlight=!1;historyInvalidationListeners=new Set;useLastPrice;constructor(e,t){this.symbol=e,this.phoenixSymbol=(0,w.canonicalToPhoenixSymbol)(e),this.useLastPrice=t?.useLastPrice??!1,this.setupVisibilityDetection(),this.connectWs()}pOpen(e){return this.useLastPrice?e.open||e.markOpen:e.markOpen||e.open}pHigh(e){return this.useLastPrice?e.high||e.markHigh:e.markHigh||e.high}pLow(e){return this.useLastPrice?e.low||e.markLow:e.markLow||e.low}pClose(e){return this.useLastPrice?e.close||e.markClose:e.markClose||e.close}destroy(){for(let[,e]of(this.alive=!1,this.historyAbort.abort(),this.visibilityCleanup?.(),this.releaseMarket?.(),this.releaseMarket=null,clearInterval(this.integrityRetryTimer),this.pendingIntegrity.clear(),this.historyInvalidationListeners.clear(),this.liveRefreshTimers))clearInterval(e);for(let e of(this.liveRefreshTimers.clear(),this.subscribers.values()))e.active=!1;this.subscribers.clear()}subscribeHistoryInvalidation(e){return this.historyInvalidationListeners.add(e),()=>{this.historyInvalidationListeners.delete(e)}}async verifyCandleHistory(e,t){let r=eM[t];if(!r)return e;let i=eK.get(e),s=await eG.verify(this.phoenixSymbol,e,i,!1,r,this.historyConsumer);if(this.alive&&s.pending){let e=s.pendingBars,t=`${r}:${e[0].time}:${e[e.length-1].time}`,n=this.pendingIntegrity.get(t);for(this.pendingIntegrity.set(t,{bars:e,period:r,request:i,attempts:n?.attempts??0,retryAt:n?.retryAt??Date.now()+3e4});this.pendingIntegrity.size>8;)this.pendingIntegrity.delete(this.pendingIntegrity.keys().next().value);this.integrityRetryTimer||(this.integrityRetryTimer=setInterval(()=>{this.retryCandleIntegrity()},3e4))}return s.bars}async retryCandleIntegrity(){if(!this.alive||this.integrityRetryInFlight||"u">typeof document&&"hidden"===document.visibilityState)return;let e=[...this.pendingIntegrity.entries()].find(([,e])=>e.retryAt<=Date.now());if(e){this.integrityRetryInFlight=!0;try{let[t,r]=e,i=await eG.verify(this.phoenixSymbol,r.bars,r.request,!0,r.period,this.historyConsumer);if(!this.alive)return;if(this.pendingIntegrity.get(t)===r&&(this.pendingIntegrity.delete(t),i.pending)){let e=i.pendingBars.length<r.bars.length?0:r.attempts+1;this.pendingIntegrity.set(t,{...r,bars:i.pendingBars,attempts:e,retryAt:Date.now()+Math.min(3e5,3e4*2**Math.min(e,4))})}if(i.repaired)for(let e of(this.lastBar.clear(),this.noDataBefore.clear(),this.historyInvalidationListeners))e();0===this.pendingIntegrity.size&&(clearInterval(this.integrityRetryTimer),this.integrityRetryTimer=void 0)}finally{this.integrityRetryInFlight=!1}}}setupVisibilityDetection(){if("u"<typeof document)return;let e=()=>{"hidden"===document.visibilityState?this.hiddenAt=Date.now():"visible"===document.visibilityState&&this.hiddenAt&&(this.hiddenAt=null,this.reseedAllSubscribers(),this.refreshAllLiveBars(),this.retryCandleIntegrity())};document.addEventListener("visibilitychange",e),this.visibilityCleanup=()=>document.removeEventListener("visibilitychange",e)}connectWs(){this.alive&&(this.releaseMarket=(0,eD.retainPhoenixMarket)(this.phoenixSymbol,{connection:e=>{this.alive&&e&&(this.hasConnectedOnce&&this.reseedAllSubscribers(),this.hasConnectedOnce=!0)},message:e=>{let t=Number(e.markPx);this.alive&&!this.useLastPrice&&Number.isFinite(t)&&t>0&&this.onPriceTick(t,Date.now())}}))}onPriceTick(e,t){for(let[,r]of this.subscribers){if(r.reseed.seeding){J(r.reseed,{price:e,timestamp:t});continue}this.applyTickToSubscriber(r,e,t)}}applyTickToSubscriber(e,t,r){if(!this.alive||!e.active)return;let i=eW(e.resolution);if(0===i)return;let s=Math.floor(r/i)*i;s<e.lastEmittedBarTime||(!e.currentBar||s>e.currentBar.time?e.currentBar={time:s,open:t,high:t,low:t,close:t,volume:0}:e.currentBar={...e.currentBar,high:Math.max(e.currentBar.high,t),low:Math.min(e.currentBar.low,t),close:t},e.lastEmittedBarTime=e.currentBar.time,e.callback({...e.currentBar}))}reseedAllSubscribers(){for(let[,e]of this.subscribers)this.reseedSubscriber(e)}refreshAllLiveBars(){for(let e of this.liveRefreshTimers.keys())this.refreshLiveBarForResolution(e).catch(()=>{})}refreshLiveBarForResolution(e){if(ez[e])return this.pollPartialBarForResolution(e);for(let[,t]of this.subscribers)t.resolution===e&&this.reseedSubscriber(t);return Promise.resolve()}async pollPartialBarForResolution(e){let t=ez[e];
2if(!t)return;let r=this.partialPollInFlight.get(e);if(r)return r;let i=(async()=>{let r=eW(e);if(0===r)return;let i=Date.now(),s=Math.floor(i/r)*r,n=(await eY(this.phoenixSymbol,t,s,i,1e3,this.historyConsumer)).filter(e=>(e.markClose||e.close)>0&&(e.markOpen||e.open)>0);if(0===n.length)return;let a=n[0],l=n[n.length-1],o=this.pOpen(a),d=this.pHigh(a),c=this.pLow(a),u=0;for(let e of n){let t=this.pHigh(e),r=this.pLow(e);t>d&&(d=t),r<c&&(c=r),u+=e.volumeQuote||0}let h=this.pClose(l);for(let[,t]of this.subscribers){if(t.resolution!==e)continue;let r=d,i=c;t.currentBar&&t.currentBar.time===s&&(t.currentBar.high>r&&(r=t.currentBar.high),t.currentBar.low<i&&(i=t.currentBar.low)),t.currentBar={time:s,open:o,high:r,low:i,close:h,volume:u},t.lastEmittedBarTime=s,t.callback({...t.currentBar})}})().finally(()=>{this.partialPollInFlight.delete(e)});return this.partialPollInFlight.set(e,i),i}ensureLiveRefresh(e){if(null===e$(e)||this.liveRefreshTimers.has(e))return;this.refreshLiveBarForResolution(e).catch(()=>{});let t=setInterval(()=>{this.refreshLiveBarForResolution(e).catch(()=>{})},3e4);this.liveRefreshTimers.set(e,t)}maybeStopLiveRefresh(e){for(let[,t]of this.subscribers)if(t.resolution===e)return;let t=this.liveRefreshTimers.get(e);t&&(clearInterval(t),this.liveRefreshTimers.delete(e))}reseedSubscriber(e){let t=e$(e.resolution),r=eW(e.resolution);if(!t||0===r)return;let i=eV(e.resolution),s=eU[t]??r,n=Date.now(),a=e.lastEmittedBarTime||n-5*r,l=Math.max(i?30:5,Math.ceil((n-a)/s)+5);Z(e.reseed,async()=>{let s=await eY(this.phoenixSymbol,t,a,n,l,this.historyConsumer);if(s=await this.verifyCandleHistory(s,t),!this.alive||!e.active)return;let o=s.map(e=>({time:e.time,open:this.pOpen(e),high:this.pHigh(e),low:this.pLow(e),close:this.pClose(e),volume:e.volumeQuote})).filter(e=>e.close>0&&e.high>0&&e.low>0&&e.open>0);for(let t of(i&&(o=eH(o,r)),o))e.lastEmittedBarTime&&t.time<e.lastEmittedBarTime||(e.currentBar=t,e.lastEmittedBarTime=t.time,e.callback({...t}))},t=>this.applyTickToSubscriber(e,t.price,t.timestamp))}onReady(e){setTimeout(()=>{e({supported_resolutions:this.supportedResolutions,supports_marks:!1,supports_timescale_marks:!1,supports_time:!0})},0)}searchSymbols(e,t,r,i){i([{symbol:this.symbol,full_name:this.symbol,description:`${this.symbol}/USD`,exchange:"Phoenix",ticker:this.symbol,type:"crypto"}])}async resolvePricescale(){return this.pricescalePromise||(this.pricescalePromise=(async()=>{try{var e;let t=Date.now(),r=await eY(this.phoenixSymbol,"1h",t-864e5,t,1,this.historyConsumer);return e=r[r.length-1]?.close??0,!Number.isFinite(e)||e<=0||e>=1e3?100:e>=10?1e3:e>=.1?1e4:e>=.001?1e6:1e8}catch{return 100}})()),this.pricescalePromise}resolveSymbol(e,t){this.resolvePricescale().then(r=>{this.alive&&t({name:e,ticker:e,description:`${this.symbol}/USD`,type:"crypto",session:"24x7",timezone:"Etc/UTC",exchange:"Phoenix",minmov:1,pricescale:r,has_intraday:!0,has_daily:!0,has_weekly_and_monthly:!1,supported_resolutions:this.supportedResolutions,volume_precision:2,data_status:"streaming"})})}getBars(e,t,r,i,s){let n=e$(t),a=eW(t);if(!n||0===a)return void i([],{noData:!0});let l=eU[n]??a,{from:o,to:d,countBack:c}=r,u=1e3*ec(t,Math.max(o,d-Math.ceil(Math.max(60,(c??300)+50)*a/1e3)),d),h=1e3*d,p=this.noDataBefore.get(t);if(void 0!==p&&h<=p)return void i([],{noData:!0});let m=Math.ceil((h-u)/l)+50;eu(()=>eY(this.phoenixSymbol,n,u,h,m,this.historyConsumer)).then(async e=>{if(e=await this.verifyCandleHistory(e,n),!this.alive)return;if(0===e.length){let e=this.noDataBefore.get(t);(void 0===e||h>e)&&this.noDataBefore.set(t,h),i([],{noData:!0});return}let r=e.map(e=>({time:e.time,open:this.pOpen(e),high:this.pHigh(e),low:this.pLow(e),close:this.pClose(e),volume:e.volumeQuote})).filter(e=>e.close>0&&e.high>0&&e.low>0&&e.open>0);eV(t)&&(r=eH(r,eW(t)));let s=r[0]?.time;if(void 0!==s&&s>u+a){let e=this.noDataBefore.get(t);(void 0===e||s>e)&&this.noDataBefore.set(t,s)}let l=Q(this.lastBar.get(t),r[r.length-1]);l&&this.lastBar.set(t,l),i(r,{noData:!1})}).catch(e=>{this.alive&&(console.error("Error fetching Phoenix candles:",e),i([],{noData:!0}),s(e))})}subscribeBars(e,t,r,i){if(!this.alive)return;this.unsubscribeBars(i);let s=this.lastBar.get(t),n={active:!0,resolution:t,callback:r,currentBar:s?{...s}:null,reseed:{seeding:!1,pending:[]},lastEmittedBarTime:s?.time??0};this.subscribers.set(i,n),this.ensureLiveRefresh(t)}unsubscribeBars(e){let t=this.subscribers.get(e);this.subscribers.delete(e),t&&(t.active=!1),t&&this.maybeStopLiveRefresh(t.resolution)}}e.s(["PhoenixDatafeed",0,eX],612483);let eQ={1:{tf:"1m",ms:6e4},3:{tf:"3m",ms:18e4},5:{tf:"5m",ms:3e5},15:{tf:"15m",ms:9e5},30:{tf:"30m",ms:18e5},60:{tf:"1h",ms:36e5},120:{tf:"2h",ms:72e5},240:{tf:"4h",ms:144e5},360:{tf:"6h",ms:216e5},720:{tf:"12h",ms:432e5},"1D":{tf:"1d",ms:864e5},D:{tf:"1d",ms:864e5},"1W":{tf:"1w",ms:6048e5},W:{tf:"1w",ms:6048e5}},eJ=new Set(["1m","5m","15m","1h","4h","1d"]),eZ={"3m":"1m","30m":"15m","2h":"1h","6h":"1h","12h":"4h","1w":"1d"},e0={"1m":6e4,"5m":3e5,"15m":9e5,"1h":36e5,"4h":144e5,"1d":864e5};function e1(e){let t=eQ[e];return t?eJ.has(t.tf)?t.tf:eZ[t.tf]??null:null}function e2(e){let t=eQ[e];return!!t&&!eJ.has(t.tf)}function e5(e){return eQ[e]?.ms??36e5}function e3(e,t){if(0===e.length)return[];let r=[],i=null;for(let s of e){let e=Math.floor(s.time/t)*t;i&&i.time===e?(i.high=Math.max(i.high,s.high),i.low=Math.min(i.low,s.low),i.close=s.close,i.volume=(i.volume||0)+(s.volume||0)):(i&&r.push(i),i={...s,time:e})}return i&&r.push(i),r}async function e4(e,t,r=2e3,i){let s,n=`https://gmtrade-web-backend.gmtrade.xyz/v2/cache/prices/candles?tokenSymbol=${e}&period=${t}&limit=${r}`;return(s=async e=>{let t,r=new AbortController,i=!1,s=setTimeout(()=>{i=!0,r.abort()},8e3);try{try{t=await fetch(n,{signal:D(e,r.signal)}
2)}catch(e){throw(i||ee(e))&&el("gmtrade"),e}if(!t.ok)throw ee(null,t.status)&&el("gmtrade"),Error(`GMTrade candles API error: ${t.status}`);let s=await t.json();return eo("gmtrade"),(s.candles||[]).map(e=>({time:1e3*e[0],open:e[1],high:e[2],low:e[3],close:e[4],volume:0}))}finally{clearTimeout(s)}},R.run(n,s,i)).then(e=>e.map(e=>({...e})))}class e6{symbol;supportedResolutions=["1","3","5","15","30","60","120","240","720","1D"];subscribers=new Map;lastBar=new Map;noDataBefore=new Map;partialPollTimers=new Map;partialPollInFlight=new Map;releaseMarket=null;alive=!0;historyAbort=new AbortController;historyConsumer={signal:this.historyAbort.signal,priority:0};setHistoryPriority(e){this.historyConsumer.priority=e}hiddenAt=null;visibilityCleanup=null;hasConnectedOnce=!1;pricescalePromise=null;constructor(e){this.symbol=e,this.setupVisibilityDetection(),this.connectWs()}destroy(){for(let[,e]of(this.alive=!1,this.historyAbort.abort(),this.visibilityCleanup?.(),this.releaseMarket?.(),this.releaseMarket=null,this.partialPollTimers))clearInterval(e);for(let e of(this.partialPollTimers.clear(),this.subscribers.values()))e.active=!1;this.subscribers.clear()}setupVisibilityDetection(){if("u"<typeof document)return;let e=()=>{"hidden"===document.visibilityState?this.hiddenAt=Date.now():"visible"===document.visibilityState&&this.hiddenAt&&(this.hiddenAt=null,this.reseedAllSubscribers())};document.addEventListener("visibilitychange",e),this.visibilityCleanup=()=>document.removeEventListener("visibilitychange",e)}connectWs(){this.alive&&(this.releaseMarket=(0,eD.retainGmTradeChannel)("tickers",{connection:e=>{this.alive&&e&&(this.hasConnectedOnce&&this.reseedAllSubscribers(),this.hasConnectedOnce=!0)},message:e=>{if(this.alive&&Array.isArray(e.payload))for(let t of e.payload){if(!t||"object"!=typeof t||t.symbol!==this.symbol)continue;let e=function(e){if(null==e)return 0;let t=String(e);return/^\d+$/.test(t)?Number(BigInt(t)/BigInt(1e10))/1e10:Number(e)/1e20}(t.price);Number.isFinite(e)&&e>0&&this.onPriceTick(e,Date.now());break}}}))}onPriceTick(e,t){for(let[,r]of this.subscribers){if(r.reseed.seeding){J(r.reseed,{price:e,timestamp:t});continue}this.applyTickToSubscriber(r,e,t)}}applyTickToSubscriber(e,t,r){if(!this.alive||!e.active)return;let i=e5(e.resolution),s=Math.floor(r/i)*i;s<e.lastEmittedBarTime||(!e.currentBar||s>e.currentBar.time?e.currentBar={time:s,open:t,high:t,low:t,close:t,volume:0}:e.currentBar={...e.currentBar,high:Math.max(e.currentBar.high,t),low:Math.min(e.currentBar.low,t),close:t},e.lastEmittedBarTime=e.currentBar.time,e.callback({...e.currentBar}))}reseedAllSubscribers(){for(let[,e]of this.subscribers)this.reseedSubscriber(e)}reseedSubscriber(e){let t=e1(e.resolution);if(!t)return;let r=e5(e.resolution),i=e2(e.resolution),s=i?30:5;Z(e.reseed,async()=>{let n=await e4(this.symbol,t,s,this.historyConsumer);if(!this.alive||!e.active)return;let a=n;for(let t of(i&&(a=e3(a,r)),a.sort((e,t)=>e.time-t.time),a))e.lastEmittedBarTime&&t.time<e.lastEmittedBarTime||(e.currentBar=t,e.lastEmittedBarTime=t.time,e.callback({...t}))},t=>this.applyTickToSubscriber(e,t.price,t.timestamp))}async pollPartialBarForResolution(e){let t=e1(e);if(!t)return;let r=this.partialPollInFlight.get(e);if(r)return r;let i=(async()=>{let r=e5(e),i=e2(e),s=await e4(this.symbol,t,i?30:3,this.historyConsumer);i&&(s=e3(s,r)),s.sort((e,t)=>e.time-t.time);let n=s[s.length-1];if(n)for(let[,t]of this.subscribers){if(t.resolution!==e||n.time<t.lastEmittedBarTime)continue;let r={...n};t.currentBar&&t.currentBar.time===n.time&&(r={...n,high:Math.max(n.high,t.currentBar.high),low:Math.min(n.low,t.currentBar.low)}),t.currentBar=r,t.lastEmittedBarTime=r.time,t.callback({...r})}})().finally(()=>{this.partialPollInFlight.delete(e)});return this.partialPollInFlight.set(e,i),i}ensurePartialPoll(e){if(!e1(e)||this.partialPollTimers.has(e))return;this.pollPartialBarForResolution(e).catch(()=>{});let t=setInterval(()=>{("u"<typeof document||"hidden"!==document.visibilityState)&&this.pollPartialBarForResolution(e).catch(()=>{})},3e4);this.partialPollTimers.set(e,t)}maybeStopPartialPoll(e){for(let[,t]of this.subscribers)if(t.resolution===e)return;let t=this.partialPollTimers.get(e);t&&(clearInterval(t),this.partialPollTimers.delete(e))}onReady(e){setTimeout(()=>{e({supported_resolutions:this.supportedResolutions,supports_marks:!1,supports_timescale_marks:!1,supports_time:!0})},0)}searchSymbols(e,t,r,i){i([{symbol:this.symbol,full_name:this.symbol,description:`${this.symbol}/USD`,exchange:"GMTrade",ticker:this.symbol,type:"crypto"}])}async resolvePricescale(){return this.pricescalePromise||(this.pricescalePromise=(async()=>{try{var e;let t=await e4(this.symbol,"1h",1,this.historyConsumer);return e=t[t.length-1]?.close??0,!Number.isFinite(e)||e<=0?1e5:e>=1e3?100:e>=10?1e3:e>=.1?1e4:e>=.001?1e6:1e8}catch{return 1e5}})()),this.pricescalePromise}resolveSymbol(e,t){this.resolvePricescale().then(r=>{this.alive&&t({name:e,ticker:e,description:`${this.symbol}/USD`,type:"crypto",session:"24x7",timezone:"Etc/UTC",exchange:"GMTrade",minmov:1,pricescale:r,has_intraday:!0,has_daily:!0,has_weekly_and_monthly:!1,supported_resolutions:this.supportedResolutions,volume_precision:2,data_status:"streaming"})})}getBars(e,t,r,i,s){let n=e1(t),a=e5(t);if(!n)return void i([],{noData:!0});let{from:l,to:o}=r,d=ec(t,l,o),c=Math.floor(Date.now()/1e3),u=1e3*o,h=this.noDataBefore.get(t);if(void 0!==h&&u<=h)return void i([],{noData:!0});let p=Math.min(Math.max(Math.ceil((c-d)/((e0[n]??a)/1e3))+10,20),2e3);eu(()=>e4(this.symbol,n,p,this.historyConsumer)).then(e=>{if(!this.alive)return;let r=1e3*d,s=e.filter(e=>e.time>=r&&e.time<=u);if(0===s.length){let e=this.noDataBefore.get(t);(void 0===e||u>e)&&this.noDataBefore.set(t,u),i([],{noData:!0});return}s.sort((e,t)=>
2e.time-t.time),e2(t)&&(s=e3(s,a));let n=Q(this.lastBar.get(t),s[s.length-1]);n&&this.lastBar.set(t,n),i(s,{noData:!1})}).catch(e=>{this.alive&&(console.error("Error fetching GMTrade candles:",e),i([],{noData:!0}),s(e))})}subscribeBars(e,t,r,i){if(!this.alive)return;this.unsubscribeBars(i);let s=this.lastBar.get(t),n={active:!0,resolution:t,callback:r,currentBar:s?{...s}:null,reseed:{seeding:!1,pending:[]},lastEmittedBarTime:s?.time??0};this.subscribers.set(i,n),this.ensurePartialPoll(t)}unsubscribeBars(e){let t=this.subscribers.get(e);this.subscribers.delete(e),t&&(t.active=!1),t&&this.maybeStopPartialPoll(t.resolution)}}e.s(["GmTradeDatafeed",0,e6],691054)},678872,438495,e=>{"use strict";var t=e.i(413358),r=e.i(43690);let i="https://api.imperial.space",s="simBorrow";function n(){let e=new URLSearchParams(window.location.search).get("simBorrow");null!=e&&("0"===e||"false"===e?window.localStorage.removeItem(s):window.localStorage.setItem(s,window.location.search||"?simBorrow=1"));let r=window.localStorage.getItem(s);return r||(t.default.env.NEXT_PUBLIC_SIM_BORROW_POWER?"?simBorrow=1":null)}e.s(["useBorrowPower",0,function(e){let t=function(){let e=n();if(null==e)return null;let t=new URLSearchParams(e),r=(e,r)=>t.get(e)??r,i=r("simAvail","5"),s=t.get("simGate");return{rationingEnabled:!0,borrowCapUsd:i,borrowedUsd:"0",availableUsd:i,seasonPoints:r("simPoints","0"),dailyStreak:0,streakBonusBps:0,utilizationBps:0,gatePointsRequired:r("simGatePts","1000"),gated:null!=s,premiumBps:parseInt(r("simPremiumBps","200"),10)||0,maxLoanBeforeUtilGateUsd:s,pointsPerUsdCap:r("simPtsPerUsd","10")}}();return(0,r.useQuery)({queryKey:["lending-pool-borrow-power",e,t?n():"live"],queryFn:async()=>{if(t)return t;let r=await fetch(`${i}/api/v1/pool/borrow-power/${e}`);if(!r.ok)throw Error(`borrow power ${r.status}`);return r.json()},enabled:!!e,refetchInterval:!t&&3e4})},"useLendingPoolState",0,function(){return(0,r.useQuery)({queryKey:["lending-pool-state"],queryFn:async()=>{let e=await fetch(`${i}/api/v1/pool/state`);if(!e.ok)throw Error(`pool state ${e.status}`);return e.json()},refetchInterval:3e4})},"useLpPosition",0,function(e){return(0,r.useQuery)({queryKey:["lending-pool-lp",e],queryFn:async()=>{let t=await fetch(`${i}/api/v1/pool/lp/${e}`);if(!t.ok)throw Error(`lp position ${t.status}`);return t.json()},enabled:!!e,refetchInterval:3e4})}],678872);var a=e.i(394390),l=e.i(183023),o=e.i(153517);e.s(["SlidingUnderline",0,function({activeKey:e,className:t,barClassName:r="bg-amber-500",children:i}){let s=(0,l.useRef)(null),[n,d]=(0,l.useState)(null);return(0,l.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{let t=[...e.querySelectorAll('[data-tab][data-active="true"]')].find(e=>e.offsetWidth>0);d(t?{left:t.offsetLeft,width:t.offsetWidth}:null)};t();let r=new ResizeObserver(t);return r.observe(e),e.querySelectorAll("[data-tab]").forEach(e=>r.observe(e)),()=>r.disconnect()},[e]),(0,a.jsxs)("div",{ref:s,className:(0,o.cn)("relative",t),children:[i,n&&(0,a.jsx)("div",{"aria-hidden":!0,className:(0,o.cn)("pointer-events-none absolute bottom-0 h-0.5 transition-[left,width] duration-200 ease-out motion-reduce:transition-none",r),style:{left:n.left,width:n.width}})]})}],438495)},387445,227631,e=>{"use strict";var t=e.i(183023),r=e.i(43690),i=e.i(267912);let s=new Set(["pending","active","partial","triggered","closing"]);e.s(["usePairLinks",0,function(e,n=!0){let{data:a,isLoading:l}=(0,r.useQuery)({queryKey:["pair-links",e],queryFn:()=>(0,i.fetchPairLinks)(e,{limit:50}),enabled:n&&!!e,staleTime:15e3,refetchInterval:3e4,retry:1}),o=(0,t.useMemo)(()=>(a?.links??[]).filter(e=>s.has(e.status)),[a]),d=(0,t.useMemo)(()=>{let e=new Map;for(let t of o)for(let r of t.legs)r.lifecycleId&&e.set(r.lifecycleId,t);return e},[o]);return{links:o,linkByLifecycle:d,isLoading:l}}],387445);let n=(0,e.i(504458).default)("link-2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);e.s(["Link2",0,n],227631)},808414,e=>{"use strict";var t=e.i(43690);async function r(){let e=await fetch("https://api.imperial.space/api/v1/pair-stats");if(!e.ok)throw Error(`pair-stats ${e.status}`);return e.json()}e.s(["usePairStats",0,function(e){let{data:i,isLoading:s,isError:n}=(0,t.useQuery)({queryKey:["pair-stats"],queryFn:r,enabled:e,staleTime:84e4,gcTime:36e5,retry:1});return{stats:i,isLoading:s,isError:n}}],808414)},208329,e=>{"use strict";e.i(413358);var t=e.i(43690);async function r(e,t){let r=await fetch(`https://api.imperial.space/api/v1/phoenix/margin-account?walletAddress=${e}&profileIndex=${t}`);if(!r.ok)throw Error("Failed to fetch margin account");return r.json()}e.s(["freeCollateralUsd",0,function(e){if(!e)return null;let t=parseFloat(e.effectiveCollateralUsd),r=parseFloat(e.initialMarginUsd??"0");return Number.isFinite(t)&&Number.isFinite(r)?Math.max(0,t-r):null},"parseAccountUsd",0,function(e){if(null==e)return null;let t=parseFloat(e);return Number.isFinite(t)?t:null},"usePhoenixMarginAccount",0,function(e,i,s){return(0,t.useQuery)({queryKey:["phoenix-margin-account",e,i],queryFn:()=>r(e,i),enabled:s&&!!e&&null!==i,staleTime:1e4,refetchInterval:15e3})},"withdrawableUsd",0,function(e){if(!e)return null;let t=parseFloat(e.effectiveCollateralForWithdrawalsUsd??""),r=parseFloat(e.initialMarginForWithdrawalsUsd??"");return Number.isFinite(t)&&Number.isFinite(r)?Math.max(0,t-r):null}])},76990,e=>{"use strict";var t=e.i(43690),r=e.i(362221);e.s(["usePhoenixMarkets",0,function(){return(0,t.useQuery)({queryKey:r.PHOENIX_MARKETS_QUERY_KEY,queryFn:r.fetchPhoenixMarkets,staleTime:3e5,refetchInterval:3e5,placeholderData:[]})}])},148292,e=>{"use strict";var t,r,i,s,n,a,l=e.i(43690),o=e.i(875574),d=e.i(799227),c=e.i(111526),u=["u8","u16","u32","u64","u128","i8","i16","i32","i64","i128","f32","f64"],h=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(2*this.buffer_size,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var r=t.substring(1),i=parseInt(r)/8;this.resize_if_necessary(i);var s="f"===t[0]?"setFloat".concat(r):"i"===t[0]?"setInt".concat(r):"setUint".concat(r);this.view[s](this.offset,e,!0),this.offset+=i},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),p=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error("Error in schema, the buffer is smaller than expected")},e.prototype.consume_value=function(e){var t=e.substring(1),r=parseInt(t)/8;this.assert_enough_buffer(r);var i="f"===e[0]?"getFloat".concat(t):"i"===e[0]?"getInt".concat(t):"getUint".concat(t),s=this.view[i](this.offset,!0);return this.offset+=r,s},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}
2(),m=(es=function(e,t){return(es=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}es(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});function f(e,t,r){if(typeof e!==t)throw Error("Expected ".concat(t," not ").concat(typeof e,"(").concat(e,") at ").concat(r.join(".")))}function x(e,t,r){if(e!==t)throw Error("Array length ".concat(e," does not match schema length ").concat(t," at ").concat(r.join(".")))}var g=u.concat(["bool","string"]),b=["option","enum","array","set","map","struct"],v=function(e){function t(t,r){var i="Invalid schema: ".concat(JSON.stringify(t)," expected ").concat(r);return e.call(this,i)||this}return m(t,e),t}(Error);function y(e){this.encoded=new h,this.fieldPath=["value"],this.checkTypes=e}y.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},y.prototype.encode_value=function(e,t){if("string"==typeof t){if(u.includes(t))return this.encode_integer(e,t);if("string"===t)return this.encode_string(e);if("bool"===t)return this.encode_boolean(e)}if("object"==typeof t){if("option"in t)return this.encode_option(e,t);if("enum"in t)return this.encode_enum(e,t);if("array"in t)return this.encode_array(e,t);if("set"in t)return this.encode_set(e,t);if("map"in t)return this.encode_map(e,t);if("struct"in t)return this.encode_struct(e,t)}},y.prototype.encode_integer=function(e,t){var r=parseInt(t.substring(1));r<=32||"f64"==t?(this.checkTypes&&f(e,"number",this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&function(e,t){var r=["number","string","bigint","boolean"].includes(typeof e),i="object"==typeof e&&null!==e&&"toString"in e;if(!r&&!i)throw Error("Expected bigint, number, boolean or string not ".concat(typeof e,"(").concat(e,") at ").concat(t.join(".")))}(e,this.fieldPath),this.encode_bigint(BigInt(e),r))},y.prototype.encode_bigint=function(e,t){for(var r=t/8,i=new Uint8Array(r),s=0;s<r;s++)i[s]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(i))},y.prototype.encode_string=function(e){this.checkTypes&&f(e,"string",this.fieldPath);for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}this.encoded.store_value(t.length,"u32"),this.encoded.store_bytes(new Uint8Array(t))},y.prototype.encode_boolean=function(e){this.checkTypes&&f(e,"boolean",this.fieldPath),this.encoded.store_value(+!!e,"u8")},y.prototype.encode_option=function(e,t){null==e?this.encoded.store_value(0,"u8"):(this.encoded.store_value(1,"u8"),this.encode_value(e,t.option))},y.prototype.encode_enum=function(e,t){this.checkTypes&&function(e,t){if("object"!=typeof e||null===e)throw Error("Expected object not ".concat(typeof e,"(").concat(e,") at ").concat(t.join(".")))}(e,this.fieldPath);for(var r=Object.keys(e)[0],i=0;i<t.enum.length;i++){var s=t.enum[i];if(r===Object.keys(s.struct)[0])return this.encoded.store_value(i,"u8"),this.encode_struct(e,s)}throw Error("Enum key (".concat(r,") not found in enum schema: ").concat(JSON.stringify(t)," at ").concat(this.fieldPath.join(".")))},y.prototype.encode_array=function(e,t){if(Array.isArray(e)||e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(0===e.length||e.length>0&&e.length-1 in e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error("Expected Array-like not ".concat(typeof e,"(").concat(e,") at ").concat(this.fieldPath.join(".")))},y.prototype.encode_arraylike=function(e,t){t.array.len?x(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,"u32");for(var r=0;r<e.length;r++)this.encode_value(e[r],t.array.type)},y.prototype.encode_buffer=function(e,t){t.array.len?x(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,"u32"),this.encoded.store_bytes(new Uint8Array(e))},y.prototype.encode_set=function(e,t){this.checkTypes&&f(e,"object",this.fieldPath);var r=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(r.length,"u32");for(var i=0;i<r.length;i++){var s=r[i];this.encode_value(s,t.set)}},y.prototype.encode_map=function(e,t){this.checkTypes&&f(e,"object",this.fieldPath);var r=e instanceof Map,i=r?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(i.length,"u32");for(var s=0;s<i.length;s++){var n=i[s];this.encode_value(n,t.map.key),this.encode_value(r?e.get(n):e[n],t.map.value)}},y.prototype.encode_struct=function(e,t){this.checkTypes&&f(e,"object",this.fieldPath);for(var r=0,i=Object.keys(t.struct);r<i.length;r++){var s=i[r];this.fieldPath.push(s),this.encode_value(e[s],t.struct[s]),this.fieldPath.pop()}};var w=function(){function e(e){this.buffer=new p(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if("string"==typeof e){if(u.includes(e))return this.decode_integer(e);if("string"===e)return this.decode_string();if("bool"===e)return this.decode_boolean()}if("object"==typeof e){if("option"in e)return this.decode_option(e);if("enum"in e)return this.decode_enum(e);
2if("array"in e)return this.decode_array(e);if("set"in e)return this.decode_set(e);if("map"in e)return this.decode_map(e);if("struct"in e)return this.decode_struct(e)}throw Error("Unsupported type: ".concat(e))},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||"f64"==e?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith("i"))},e.prototype.decode_bigint=function(e,t){void 0===t&&(t=!1);var r=e/8,i=new Uint8Array(this.buffer.consume_bytes(r)),s=i.reduceRight(function(e,t){return e+t.toString(16).padStart(2,"0")},"");return t&&i[r-1]?BigInt.asIntN(e,BigInt("0x".concat(s))):BigInt("0x".concat(s))},e.prototype.decode_string=function(){for(var e=this.decode_integer("u32"),t=new Uint8Array(this.buffer.consume_bytes(e)),r=[],i=0;i<e;++i){var s=t[i];if(s<128)r.push(s);else if(s<224)r.push((31&s)<<6|63&t[++i]);else if(s<240)r.push((15&s)<<12|(63&t[++i])<<6|63&t[++i]);else{var n=(7&s)<<18|(63&t[++i])<<12|(63&t[++i])<<6|63&t[++i];r.push(n)}}return String.fromCodePoint.apply(String,r)},e.prototype.decode_boolean=function(){return this.buffer.consume_value("u8")>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value("u8");if(1===t)return this.decode_value(e.option);if(0!==t)throw Error("Invalid option ".concat(t));return null},e.prototype.decode_enum=function(e){var t,r=this.buffer.consume_value("u8");if(r>e.enum.length)throw Error("Enum option ".concat(r," is not available"));var i=e.enum[r].struct,s=Object.keys(i)[0];return(t={})[s]=this.decode_value(i[s]),t},e.prototype.decode_array=function(e){for(var t=[],r=e.array.len?e.array.len:this.decode_integer("u32"),i=0;i<r;++i)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer("u32"),r=new Set,i=0;i<t;++i)r.add(this.decode_value(e.set));return r},e.prototype.decode_map=function(e){for(var t=this.decode_integer("u32"),r=new Map,i=0;i<t;++i){var s=this.decode_value(e.map.key),n=this.decode_value(e.map.value);r.set(s,n)}return r},e.prototype.decode_struct=function(e){var t={};for(var r in e.struct)t[r]=this.decode_value(e.struct[r]);return t},e}();function j(e,t,r){return void 0===r&&(r=!0),r&&function e(t){if(!("string"==typeof t&&g.includes(t))){if(t&&"object"==typeof t){var r=Object.keys(t);if(1===r.length&&b.includes(r[0])){var i=r[0];if("option"===i)return e(t[i]);if("enum"===i){var s=t[i];if(!Array.isArray(s))throw new v(s,"Array");for(var n=0;n<s.length;n++){var a=s[n];if("object"!=typeof a||!("struct"in a))throw Error('Missing "struct" key in enum schema');if("object"!=typeof a.struct||1!==Object.keys(a.struct).length)throw Error('The "struct" in each enum must have a single key');e({struct:a.struct})}return}if("array"===i){var l=t[i];if("object"!=typeof l)throw new v(l,"{ type, len? }");if(l.len&&"number"!=typeof l.len)throw Error("Invalid schema: ".concat(l));if("type"in l)return e(l.type);throw new v(l,"{ type, len? }")}if("set"===i)return e(t[i]);if("map"===i){var o=t[i];if("object"==typeof o&&"key"in o&&"value"in o)e(o.key),e(o.value);else throw new v(o,"{ key, value }");return}if("struct"===i){var d=t[i];if("object"!=typeof d)throw new v(d,"object");for(var c in d)e(d[c]);return}}}throw new v(t,b.join(", ")+" or "+g.join(", "))}}(e),new w(t).decode(e)}e.i(21859);var S=e.i(591318),k=e.i(114892);e.i(168227);var N=e.i(573445),P=e.i(408505);(en=eo||(eo={}))[en.Uninitialized=0]="Uninitialized",en[en.Initialized=1]="Initialized",en[en.Frozen=2]="Frozen";let T=(0,k.struct)([(0,N.publicKey)("mint"),(0,N.publicKey)("owner"),(0,P.u64)("amount"),(0,k.u32)("delegateOption"),(0,N.publicKey)("delegate"),(0,k.u8)("state"),(0,k.u32)("isNativeOption"),(0,P.u64)("isNative"),(0,P.u64)("delegatedAmount"),(0,k.u32)("closeAuthorityOption"),(0,N.publicKey)("closeAuthority")]);function C(e,t=!1){if(!e)return;let r=e.subarray(0,4).readUInt32LE(0);return e.subarray(4,4+r).toString().replace(/^\0/,t?"":"\0")}T.span;let M=new d.PublicKey("namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX");new d.PublicKey("8K9XmpN6nKy3ERnMovnoj5cbqWKPiGYN8hCRRyW4TLQV"),new d.PublicKey("AjheAtCgSwEcEYd6xi6thcQW25ELWd7wKCx6SKBGUtMQ");let _=new d.PublicKey("58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx");new d.PublicKey("jCebN34bUfdeUYJT13J1yG16XWQpt5PDx6Mse9GUqhR");let A=new d.PublicKey("33m47vH6Eav6jr5Ry86XjhRft2jRBLDnDgPSHoquXi2Z");new d.PublicKey("FvPH7PrVrLGKPfqaf3xJodFTjZriqrAXXLTVWEorTFBi"),new d.PublicKey("4YcexoW3r78zz16J2aqmukBLRwGq6rAvWzJpkYAXqebv"),new d.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),new d.PublicKey("3ogYncmMM5CmytsGCqKHydmXmKUZ6sGWvizkzqwT7zb1"),new d.PublicKey("DM1jJCkZZEwY5tmWbgvKRxsDFzXCdbfrYCCH1CtwguEs"),new d.PublicKey("ADCp4QXFajHrhy4f43pD6GJFtQLkdBY2mjS9DfCk7tNW"),new d.PublicKey("2XTgjw8yi1E3Etgj4CUyRD7Zk49gynH2U9gA5N2MY4NP"),new d.PublicKey("5PwNeqQPiygQks9R17jUAodZQNuhvCqqkrxSaeNE8qTR"),new d.PublicKey("8kJqxAbqbPLGLMgB6FhLcnw2SiUEavx2aEGM3WQGhtJF"),new d.PublicKey("HemvJzwxvVpWBjPETpaseAH395WAxb2G73MeUfjVkK1u"),new d.PublicKey("7hMiiUtkH4StMPJxyAtvzXTUjecTniQ8czkCPusf5eSW"),new d.PublicKey("DGpjHo4yYA3NgHvhHTp3XfBFrESsx1DnhfTr8D881ZBM"),new d.PublicKey("7vWSqSw1eCXZXXUubuHWssXELNQ8MLaDgAs2ErEfCKxn"),new d.PublicKey("5F6gcdzpw7wUjNEugdsD4aLJdEQ4Wt8d6E85vaQXZQSJ"),new d.PublicKey("XEy9o73JBN2pEuN7aspe8mVLaWbL4ozjJs1tNRxx8bL"),new d.PublicKey("D5cLoAGjNTHKU1UGv2bYwbnyRoGTMe3sbpLtJW3fRq91"),new d.PublicKey("FePcCmrr7vgjeFXcXtJHqShSXydaTrga2wfHRt9RrYvP"),new d.PublicKey("5D2zKog251d6KPCyFyLMt3KroWwXXPWSgTPyhV22K2gR"),new d.PublicKey("452cMqDHe5cf1Z96HxUNaQjiLckhMiZdZ5abe7oQ2iRB"),new d.PublicKey("8hmebGRQpZG8RpR3SFTfnuY2K4QgNxyAtqdhR9UuFksB"),new d.PublicKey("7siDgAEyXRCEhNjZcQ8VLVbMxXQaQY4hNcRbGbKj2i7u"),new d.PublicKey("AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J"),new d.PublicKey("GcWEQ9K78FV7LEHteFVciYApERk5YvQuFDQPk1yYJVXi"),new d.PublicKey("5D2zKog251d6KPCyFyLMt3KroWwXXPWSgTPyhV22K2gR"),new d.PublicKey("BPeXUQDqGbzxeK1LJby6ugvCBuo7kRSEUkjD726mUVsz"),new d.PublicKey("72aLKvXeV4aansAQtxKymeXDevT5ed6sCuz9iN62ugPT"),new d.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),new d.PublicKey("pyt2F414BA6dPttK6RddPZUdHfapoBN24GL5wbrPCou");var E=e.i(500521);let L=e=>{let t=(0,E.sha256)(c.Buffer.from("SPL Name Service"+e,"utf8"));return c.Buffer.from(t)},F=(e,t,r)=>{let i=[e];t?i.push(t.toBuffer()):i.push(c.Buffer.alloc(32)),r?i.push(r.toBuffer()):i.push(c.Buffer.alloc(32));let[s]=d.PublicKey.findProgramAddressSync(i,M);return s},R=new d.PublicKey("nftD3vbNkNqfj2Sd3HZwbpw4BxxKWr4AjGb9X38JeZk"),D=c.Buffer.from("tokenized_name"),I=async(e,t)=>{try{let r=(e=>{let[t]=d.PublicKey.findProgramAddressSync([D,e.toBuffer()],R);return t})(t),i=await e.getTokenLargestAccounts(r);if(0===i.value.length)return null;let s=await e.getAccountInfo(i.value[0].address);if(!s)return null;let n=T.decode(s.data);if("1"===n.amount.toString())return n.owner;return null}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&-32602===e.code)return null;throw e}};(ea=ed||(ed={})).InvalidSubdomain="InvalidSubdomain",ea.PrimaryDomainNotFound="PrimaryDomainNotFound",ea.InvalidBufferLength="InvalidBufferLength",ea.U64Overflow="U64Overflow",ea.InvalidRecordData="InvalidRecordData",ea.InvalidEvmAddress="InvalidEvmAddress",ea.InvalidInjectiveAddress="InvalidInjectiveAddress",ea.InvalidARecord="InvalidARecord",ea.InvalidAAAARecord="InvalidAAAARecord",ea.InvalidRecordInput="InvalidRecordInput",ea.AccountDoesNotExist="AccountDoesNotExist",ea.MultipleRegistries="MultipleRegistries",ea.InvalidReverseTwitter="InvalidReverseTwitter",ea.NoAccountData="NoAccountData",ea.InvalidInput
2="InvalidInput",ea.InvalidDomain="InvalidDomain",ea.InvalidCustomBg="InvalidCustomBackground",ea.MissingVerifier="MissingVerifier",ea.PythFeedNotFound="PythFeedNotFound",ea.InvalidRoa="InvalidRoa",ea.InvalidParent="InvalidParent",ea.NftRecordNotFound="NftRecordNotFound",ea.PdaOwnerNotAllowed="PdaOwnerNotAllowed",ea.DomainDoesNotExist="DomainDoesNotExist",ea.RecordMalformed="RecordMalformed",ea.CouldNotFindNftOwner="CouldNotFindNftOwner",ea.WrongValidation="WrongValidation",ea.UnsupportedTld="UnsupportedTld",ea.DomainExpired="DomainExpired",ea.CouldNotFindSrsOwner="CouldNotFindSrsOwner",ea.SnsSolResolutionMismatch="SnsSolResolutionMismatch";class U extends Error{constructor(e,t){super(t),this.name="SNSError",this.type=e,Error.captureStackTrace&&Error.captureStackTrace(this,U)}}class O extends U{constructor(e){super(ed.PrimaryDomainNotFound,e)}}class B extends U{constructor(e){super(ed.AccountDoesNotExist,e)}}class z extends U{constructor(e){super(ed.NoAccountData,e)}}class $ extends U{constructor(e){super(ed.InvalidInput,e)}}class V extends U{constructor(e){super(ed.NftRecordNotFound,e)}}class H{constructor(e){this.parentName=new d.PublicKey(e.parentName),this.owner=new d.PublicKey(e.owner),this.class=new d.PublicKey(e.class)}static deserialize(e){let t=new H(j(this.schema,e));return t.data=null==e?void 0:e.subarray(this.HEADER_LEN),t}static async retrieve(e,t){var r;let i=await e.getAccountInfo(t);if(!i)throw new B("The name account does not exist");let s=new H(j(this.schema,i.data));return s.data=null==(r=i.data)?void 0:r.subarray(this.HEADER_LEN),{registry:s,nftOwner:await I(e,t)}}static async _retrieveBatch(e,t){let r=await e.getMultipleAccountsInfo(t),i=e=>{if(!e)return;let t=new H(j(this.schema,e));return t.data=null==e?void 0:e.subarray(this.HEADER_LEN),t};return r.map(e=>i(null==e?void 0:e.data))}static async retrieveBatch(e,t){let r=[],i=[...t];for(;i.length>0;)r.push(...await this._retrieveBatch(e,i.splice(0,100)));return r}}
2async function W(e,t,r){let i=F(L(t.toBase58()),A,r),{registry:s}=await H.retrieve(e,i);if(!s.data)throw new z("The registry data is empty");return C(s.data,!!r)}H.HEADER_LEN=96,H.schema={struct:{parentName:{array:{type:"u8",len:32}},owner:{array:{type:"u8",len:32}},class:{array:{type:"u8",len:32}}}};let q=new d.PublicKey("85iDfUvr3HJyLM2zcq5BXSiDvUWfw6cSE1FfNBo8Ap29");class K{constructor(e){this.tag=e.tag,this.nameAccount=new d.PublicKey(e.nameAccount)}static deserialize(e){return new K(j(this.schema,e))}static async retrieve(e,t){let r=await e.getAccountInfo(t);if(!r||!r.data)throw new O("The primary account does not exist");return this.deserialize(r.data)}static async getKey(e,t){return await d.PublicKey.findProgramAddress([c.Buffer.from("favourite_domain"),t.toBuffer()],e)}static getKeySync(e,t){return d.PublicKey.findProgramAddressSync([c.Buffer.from("favourite_domain"),t.toBuffer()],e)}}K.schema={struct:{tag:"u8",nameAccount:{array:{type:"u8",len:32}}}};let G=async(e,t)=>{let[r]=K.getKeySync(q,new d.PublicKey(t)),i=await K.retrieve(e,r),{registry:s,nftOwner:n}=await H.retrieve(e,i.nameAccount),a=n||s.owner,l=await W(e,i.nameAccount,s.parentName.equals(_)?void 0:s.parentName);if(!s.parentName.equals(_)){let t=await W(e,s.parentName);l+=`.${t}`}return{domain:i.nameAccount,reverse:l,stale:!t.equals(a)}};async function Y(e,t){let r=[{memcmp:{offset:32,bytes:t.toBase58()}},{memcmp:{offset:0,bytes:_.toBase58()}}];return(await e.getProgramAccounts(M,{filters:r,dataSlice:{offset:0,length:0}})).map(e=>e.pubkey)}async function X(e,t){let r=[];for(let e of t){let t=F(L(e.toBase58()),A);r.push(t)}return(await H.retrieveBatch(e,r)).map(e=>{if(void 0!==e&&void 0!==e.data)return C(e.data)})}async function Q(e,t){let r=await Y(e,t),i=await X(e,r);return r.map((e,t)=>{let r=i[t];return r?{domain:r,key:e}:void 0}).filter(e=>void 0!==e)}var J=e.i(985604);(el=ec||(ec={}))[el.Uninitialized=0]="Uninitialized",el[el.CentralState=1]="CentralState",el[el.ActiveRecord=2]="ActiveRecord",el[el.InactiveRecord=3]="InactiveRecord";class Z{constructor(e){this.tag=e.tag,this.nonce=e.nonce,this.nameAccount=new d.PublicKey(e.nameAccount),this.owner=new d.PublicKey(e.owner),this.nftMint=new d.PublicKey(e.nftMint)}static deserialize(e){return new Z(j(this.schema,e))}static async retrieve(e,t){let r=await e.getAccountInfo(t);if(!r||!r.data)throw new V("NFT record not found: "+t.toBase58()
2);return this.deserialize(r.data)}static async findKey(e,t){return await d.PublicKey.findProgramAddress([c.Buffer.from("nft_record"),e.toBuffer()],t)}static findKeySync(e,t){return d.PublicKey.findProgramAddressSync([c.Buffer.from("nft_record"),e.toBuffer()],t)}}Z.LEN=98,Z.schema={struct:{tag:"u8",nonce:"u8",nameAccount:{array:{type:"u8",len:32}},owner:{array:{type:"u8",len:32}},nftMint:{array:{type:"u8",len:32}}}};let ee=async(e,t)=>{let r=[{dataSize:Z.LEN},{memcmp:{offset:0,bytes:"3"}},{memcmp:{offset:66,bytes:t.toBase58()}}];return await e.getProgramAccounts(R,{filters:r})},et=async(e,t)=>{let r=await ee(e,t.mint);if(1===r.length)return Z.deserialize(r[0].account.data)},er=async(e,t)=>{let r=[{memcmp:{offset:32,bytes:t.toBase58()}},{memcmp:{offset:64,bytes:"2"}},{dataSize:165}],i=(await e.getProgramAccounts(J.TOKEN_PROGRAM_ID,{filters:r})).map(e=>T.decode(e.account.data)).map(t=>et(e,t));return(await Promise.all(i)).filter(e=>void 0!==e)},ei=async(e,t)=>{let r=await er(e,t),i=await X(e,r.map(e=>e.nameAccount));return r.map((e,t)=>{let r=i[t];return r?{domain:r,key:e.nameAccount,mint:e.nftMint}:void 0}).filter(e=>void 0!==e)};var es,en,ea,el,eo,ed,ec,eu,eh=["u8","u16","u32","u64","u128","i8","i16","i32","i64","i128","f32","f64"],ep=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(2*this.buffer_size,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var r=t.substring(1),i=parseInt(r)/8;this.resize_if_necessary(i);var s="f"===t[0]?"setFloat".concat(r):"i"===t[0]?"setInt".concat(r):"setUint".concat(r);this.view[s](this.offset,e,!0),this.offset+=i},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),em=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error("Error in schema, the buffer is smaller than expected")},e.prototype.consume_value=function(e){var t=e.substring(1),r=parseInt(t)/8;this.assert_enough_buffer(r);var i="f"===e[0]?"getFloat".concat(t):"i"===e[0]?"getInt".concat(t):"getUint".concat(t),s=this.view[i](this.offset,!0);return this.offset+=r,s},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),ef=(eu=function(e,t){return(eu=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}eu(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});function ex(e,t,r){if(typeof e!==t)throw Error("Expected ".concat(t," not ").concat(typeof e,"(").concat(e,") at ").concat(r.join(".")))}function eg(e,t,r){if(e!==t)throw Error("Array length ".concat(e," does not match schema length ").concat(t," at ").concat(r.join(".")))}var eb=eh.concat(["bool","string"]),ev=["option","enum","array","set","map","struct"],ey=function(e){function t(t,r){var i="Invalid schema: ".concat(JSON.stringify(t)," expected ").concat(r);return e.call(this,i)||this}return ef(t,e),t}(Error);function ew(e){if("string"!=typeof e||!eb.includes(e)){if(e&&"object"==typeof e){var t=Object.keys(e);if(1===t.length&&ev.includes(t[0])){var r=t[0];if("option"===r)return ew(e[r]);if("enum"===r){var i=e[r];if(!Array.isArray(i))throw new ey(i,"Array");for(var s=0;s<i.length;s++){var n=i[s];if("object"!=typeof n||!("struct"in n))throw Error('Missing "struct" key in enum schema');if("object"!=typeof n.struct||1!==Object.keys(n.struct).length)throw Error('The "struct" in each enum must have a single key');ew({struct:n.struct})}return}if("array"===r){var a=e[r];if("object"!=typeof a)throw new ey(a,"{ type, len? }");if(a.len&&"number"!=typeof a.len)throw Error("Invalid schema: ".concat(a));if("type"in a)return ew(a.type);throw new ey(a,"{ type, len? }")}if("set"===r)return ew(e[r]);if("map"===r){var l=e[r];if("object"!=typeof l||!("key"in l)||!("value"in l))throw new ey(l,"{ key, value }");ew(l.key),ew(l.value);return}if("struct"===r){var o=e[r];if("object"!=typeof o)throw new ey(o,"object");for(var d in o)ew(o[d]);return}}}throw new ey(e,ev.join(", ")+" or "+eb.join(", "))}}var ej=function(){function e(e){this.encoded=new ep,this.fieldPath=["value"],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if("string"==typeof t){if(eh.includes(t))return this.encode_integer(e,t);if("string"===t)return this.encode_string(e);if("bool"===t)return this.encode_boolean(e)}if("object"==typeof t){if("option"in t)return this.encode_option(e,t);if("enum"in t)return this.encode_enum(e,t);if("array"in t)return this.encode_array(e,t);if("set"in t)return this.encode_set(e,t);if("map"in t)return this.encode_map(e,t);if("struct"in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var r=parseInt(t.substring(1));r<=32||"f64"==t?(this.checkTypes&&ex(e,"number",this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&function(e,t){if(!(["number","string","bigint","boolean"].includes(typeof e)||"object"==typeof e&&null!==e&&"toString"in e))throw Error("Expected bigint, number, boolean or string not ".concat(typeof e,"(").concat(e,") at ").concat(t.join(".")))}(e,this.fieldPath),this.encode_bigint(BigInt(e),r))},e.prototype.encode_bigint=function(e,t){for(var r=t/8,i=new Uint8Array(r),s=0;s<r;s++)i[s]=Number(e&BigInt(255)),e>>
2=BigInt(8);this.encoded.store_bytes(new Uint8Array(i))},e.prototype.encode_string=function(e){this.checkTypes&&ex(e,"string",this.fieldPath),this.encoded.store_value(e.length,"u32");for(var t=0;t<e.length;t++)this.encoded.store_value(e.charCodeAt(t),"u8")},e.prototype.encode_boolean=function(e){this.checkTypes&&ex(e,"boolean",this.fieldPath),this.encoded.store_value(+!!e,"u8")},e.prototype.encode_option=function(e,t){null==e?this.encoded.store_value(0,"u8"):(this.encoded.store_value(1,"u8"),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&function(e,t){if("object"!=typeof e||null===e)throw Error("Expected object not ".concat(typeof e,"(").concat(e,") at ").concat(t.join(".")))}(e,this.fieldPath);for(var r=Object.keys(e)[0],i=0;i<t.enum.length;i++){var s=t.enum[i];if(r===Object.keys(s.struct)[0])return this.encoded.store_value(i,"u8"),this.encode_struct(e,s)}throw Error("Enum key (".concat(r,") not found in enum schema: ").concat(JSON.stringify(t)," at ").concat(this.fieldPath.join(".")))},e.prototype.encode_array=function(e,t){if(Array.isArray(e)||e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(0===e.length||e.length>0&&e.length-1 in e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error("Expected Array-like not ".concat(typeof e,"(").concat(e,") at ").concat(this.fieldPath.join(".")))},e.prototype.encode_arraylike=function(e,t){t.array.len?eg(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,"u32");for(var r=0;r<e.length;r++)this.encode_value(e[r],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?eg(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,"u32"),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&ex(e,"object",this.fieldPath);var r=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(r.length,"u32");for(var i=0;i<r.length;i++){var s=r[i];this.encode_value(s,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&ex(e,"object",this.fieldPath);var r=e instanceof Map,i=r?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(i.length,"u32");for(var s=0;s<i.length;s++){var n=i[s];this.encode_value(n,t.map.key),this.encode_value(r?e.get(n):e[n],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&ex(e,"object",this.fieldPath);for(var r=0,i=Object.keys(t.struct);r<i.length;r++){var s=i[r];this.fieldPath.push(s),this.encode_value(e[s],t.struct[s]),this.fieldPath.pop()}},e}(),eS=function(){function e(e){this.buffer=new em(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if("string"==typeof e){if(eh.includes(e))return this.decode_integer(e);if("string"===e)return this.decode_string();if("bool"===e)return this.decode_boolean()}if("object"==typeof e){if("option"in e)return this.decode_option(e);if("enum"in e)return this.decode_enum(e);if("array"in e)return this.decode_array(e);if("set"in e)return this.decode_set(e);if("map"in e)return this.decode_map(e);if("struct"in e)return this.decode_struct(e)}throw Error("Unsupported type: ".concat(e))},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||"f64"==e?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith("i"))},e.prototype.decode_bigint=function(e,t){void 0===t&&(t=!1);var r=e/8,i=new Uint8Array(this.buffer.consume_bytes(r)),s=i.reduceRight(function(e,t){return e+t.toString(16).padStart(2,"0")},"");return t&&i[r-1]?BigInt.asIntN(e,BigInt("0x".concat(s))):BigInt("0x".concat(s))},e.prototype.decode_string=function(){var e=this.decode_integer("u32"),t=new Uint8Array(this.buffer.consume_bytes(e));return String.fromCharCode.apply(null,t)},e.prototype.decode_boolean=function(){return this.buffer.consume_value("u8")>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value("u8");if(1===t)return this.decode_value(e.option);if(0!==t)throw Error("Invalid option ".concat(t));return null},e.prototype.decode_enum=function(e){var t,r=this.buffer.consume_value("u8");if(r>e.enum.length)throw Error("Enum option ".concat(r," is not available"));var i=e.enum[r].struct,s=Object.keys(i)[0];return(t={})[s]=this.decode_value(i[s]),t},e.prototype.decode_array=function(e){for(var t=[],r=e.array.len?e.array.len:this.decode_integer("u32"),i=0;i<r;++i)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer("u32"),r=new Set,i=0;i<t;++i)r.add(this.decode_value(e.set));return r},e.prototype.decode_map=function(e){for(var t=this.decode_integer("u32"),r=new Map,i=0;i<t;++i){var s=this.decode_value(e.map.key),n=this.decode_value(e.map.value);r.set(s,n)}return r},e.prototype.decode_struct=function(e){var t={};for(var r in e.struct)t[r]=this.decode_value(e.struct[r]);return t},e}();function ek(e,t,r){return void 0===r&&(r=!0),r&&ew(e),new ej(r).encode(t,e)}class eN{constructor(e){this.tag=1,this.record=e.record,this.content=e.content}serialize(){return ek(eN.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eN.schema={struct:{tag:"u8",record:"string",content:{array:{type:"u8"}}}};class eP{constructor(e){this.tag=4,this.validation=e.validation,this.signature=e.signature,this.expectedPubkey=e.expectedPubkey}
2serialize(){return ek(eP.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eP.schema={struct:{tag:"u8",validation:"u8",signature:{array:{type:"u8"}},expectedPubkey:{array:{type:"u8"}}}};class eT{constructor(e){this.tag=0,this.contentLength=e.contentLength,this.record=e.record}serialize(){return ek(eT.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eT.schema={struct:{tag:"u8",contentLength:"u32",record:"string"}};class eC{constructor(e){this.tag=3,this.staleness=e.staleness}serialize(){return ek(eC.schema,this)}getInstruction(e,t,r,i,s,n,a,l,o){let c=S.Buffer.from(this.serialize()),u=[];return u.push({pubkey:t,isSigner:!1,isWritable:!1}),u.push({pubkey:r,isSigner:!1,isWritable:!1}),u.push({pubkey:i,isSigner:!0,isWritable:!0}),u.push({pubkey:s,isSigner:!1,isWritable:!0}),u.push({pubkey:n,isSigner:!1,isWritable:!0}),u.push({pubkey:a,isSigner:!1,isWritable:!0}),u.push({pubkey:l,isSigner:!1,isWritable:!1}),u.push({pubkey:o,isSigner:!0,isWritable:!0}),new d.TransactionInstruction({keys:u,programId:e,data:c})}}eC.schema={struct:{tag:"u8",staleness:"bool"}};class eM{constructor(e){this.tag=2,this.record=e.record,this.content=e.content}serialize(){return ek(eM.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eM.schema={struct:{tag:"u8",record:"string",content:{array:{type:"u8"}}}};class e_{constructor(){this.tag=5}serialize(){return ek(e_.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}e_.schema={struct:{tag:"u8"}};class eA{constructor(e){this.tag=6,this.roaId=e.roaId}serialize(){return ek(eA.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!0,isWritable:!0}),c.push({pubkey:l,isSigner:!1,isWritable:!1}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eA.schema={struct:{tag:"u8",roaId:{array:{type:"u8"}}}};class eE{constructor(){this.tag=7}serialize(){return ek(eE.schema,this)}getInstruction(e,t,r,i,s,n,a,l){let o=S.Buffer.from(this.serialize()),c=[];return c.push({pubkey:t,isSigner:!1,isWritable:!1}),c.push({pubkey:r,isSigner:!1,isWritable:!1}),c.push({pubkey:i,isSigner:!0,isWritable:!0}),c.push({pubkey:s,isSigner:!1,isWritable:!0}),c.push({pubkey:n,isSigner:!1,isWritable:!0}),c.push({pubkey:a,isSigner:!1,isWritable:!1}),c.push({pubkey:l,isSigner:!0,isWritable:!0}),new d.TransactionInstruction({keys:c,programId:e,data:o})}}eE.schema={struct:{tag:"u8"}};let eL=new d.PublicKey("HP3D4D1ZCmohQGFVms2SS4LCANgJyksBf5s1F77FuFjZ"),eF=new d.PublicKey("Ga872GkshNeNMDag7m1Bn54dN3NiHksfqnN2pH6A1H9F"),[eR]=d.PublicKey.findProgramAddressSync([eL.toBuffer()],eL),[eD]=d.PublicKey.findProgramAddressSync([eF.toBuffer()],eF);(t=s||(s={}))[t.None=0]="None",t[t.Solana=1]="Solana",t[t.Ethereum=2]="Ethereum",t[t.UnverifiedSolana=3]="UnverifiedSolana";class eI{constructor(e){this.stalenessValidation=e.stalenessValidation,this.rightOfAssociationValidation=e.rightOfAssociationValidation,this.contentLength=e.contentLength}static deserialize(e){var t;return new eI((ew(t=this.schema),new eS(e).decode(t)))}static async retrieve(e,t){let r=await e.getAccountInfo(t);if(!r||!r.data)throw Error("Record header account not found");return this.deserialize(r.data.slice(96,96+this.LEN))}}eI.LEN=8,eI.schema={struct:{stalenessValidation:"u16",rightOfAssociationValidation:"u16",contentLength:"u32"}},(r=n||(n={})).IPFS="IPFS",r.ARWV="ARWV",r.SOL="SOL",r.ETH="ETH",r.BTC="BTC",r.LTC="LTC",r.DOGE="DOGE",r.Email="email",r.Url="url",r.Discord="discord",r.Github="github",r.Reddit="reddit",r.Twitter="twitter",r.Telegram="telegram",r.Pic="pic",r.SH
2DW="SHDW",r.POINT="POINT",r.BSC="BSC",r.Injective="INJ",r.Backpack="backpack",r.A="A",r.AAAA="AAAA",r.CNAME="CNAME",r.TXT="TXT",r.Background="background",r.BASE="BASE",r.IPNS="IPNS",r.Bio="bio",n.SOL,n.ETH,n.BSC,n.Injective,n.A,n.AAAA,n.Background,(i=a||(a={}))[i.V1=1]="V1",i[i.V2=2]="V2";let eU=(e,t=_,r)=>{let i=L(e);return{pubkey:F(i,r,t),hashed:i}},eO=(e,t)=>{let r=t===a.V2?eR:void 0,i=e.split(".");if(2===i.length){let e=c.Buffer.from([t||0]).toString().concat(i[0]),{pubkey:s}=eU(i[1]);return{...eU(e,s,r),isSub:!0,parent:s}}if(3===i.length&&t){let{pubkey:e}=eU(i[2]),{pubkey:s}=eU("\0".concat(i[1]),e);return{...eU((t===a.V2?"\x02":"\x01").concat(i[0]),s,r),isSub:!0,parent:e,isSubRecord:!0}}if(i.length>=3)throw new $("The domain is malformed");return{...eU(e,_),isSub:!1,parent:void 0}};async function eB(e,t,r,i,s){let n;for(let a of(n=(e,t)=>e<t?-1:+(e>t),[...r].sort((e,t)=>n(e.domain,t.domain)||n(e.key.toBase58(),t.key.toBase58())))){if(s?.throwIfAborted(),!a.domain.trim())continue;let r=eO(a.domain);if(r.isSub||!r.pubkey.equals(a.key))continue;let n=await e.getAccountInfo(a.key);if(s?.throwIfAborted(),!n||!n.owner.equals(M))continue;let l=H.deserialize(n.data);if(l.parentName.equals(_)){if(l.owner.equals(t))return`${a.domain}.sns`;if(i){let r=await I(e,a.key);if(s?.throwIfAborted(),r?.equals(t))return`${a.domain}.sns`}}}return null}async function ez(e,t,r){r?.throwIfAborted();let i=new d.PublicKey(t);try{let t=await G(e,i);if(r?.throwIfAborted(),!1===t.stale&&t.reverse?.trim())return`${t.reverse}.sns`}catch(e){if(r?.throwIfAborted(),!(e instanceof O||e instanceof B))throw e}let s=await Q(e,i);r?.throwIfAborted();let n=await eB(e,i,s,!1,r);if(n)return n;let a=await ei(e,i);return r?.throwIfAborted(),eB(e,i,a,!0,r)}e.s(["usePrimaryDomain",0,function(e){let{connection:t}=(0,o.useUnifiedWalletContext)(),r=(0,l.useQuery)({queryKey:["sns-primary",t.rpcEndpoint,e??null],queryFn:({signal:r})=>ez(t,e,r),enabled:!!e,staleTime:6e4,gcTime:3e5,refetchInterval:6e4,refetchIntervalInBackground:!1,refetchOnWindowFocus:!0,retry:1,placeholderData:()=>void 0});return e&&!r.isError?r.data??null:null}],148292)},277590,e=>{"use strict";e.i(413358);var t=e.i(43690),r=e.i(924416);let i="https://api.imperial.space";async function s(e,t,r,s,n){let a=new URLSearchParams;t&&a.set("period",t),r&&a.set("underwriter",r);let l=await fetch(`${i}/api/v1/profile/${e}/stats?${a}`,{headers:s?{Authorization:`Bearer ${s}`}:void 0,signal:n,cache:"no-store"});if(!l.ok)throw Error("Failed to fetch profile stats");return l.json()}async function n(e,t,r,s){let n=new URLSearchParams;t&&n.set("period",t),r&&n.set("underwriter",r);let a=await fetch(`${i}/api/v1/profile/${e}/pnl-chart?${n}`,{signal:s,cache:"no-store"});if(!a.ok)throw Error("Failed to fetch PnL chart");return a.json()}e.s(["usePnlChart",0,function(e,r,i){return(0,t.useQuery)({queryKey:["profile-pnl-chart",e,r,i],queryFn:({signal:t})=>n(e,r,i,t),staleTime:6e4,enabled:!!e,retry:!1})},"useProfileStats",0,function(e,i,n){let a=(0,r.useSessionJwt)();return(0,t.useQuery)({queryKey:["profile-stats",e,i,n,a],queryFn:({signal:t})=>s(e,i,n,a,t),staleTime:6e4,enabled:!!e,retry:!1})}])},744900,926643,482317,822371,35e4,e=>{"use strict";var t=e.i(175701),r=e.i(43690),i=e.i(924416),s=e.i(406470);async function n(e,t){let r=await fetch(`https://api.imperial.space${e}`,{headers:t?{Authorization:`Bearer ${t}`}:void 0});if(!r.ok)throw Error(`Request failed: ${e} (${r.status})`);return r.json()}function a(e){return e/1e6}e.s(["PERSONAL_RANK_LADDER",0,[{slug:"freeman",pointsRequired:0,bonusBps:0},{slug:"plebeian",pointsRequired:100,bonusBps:500},{slug:"merchant",pointsRequired:500,bonusBps:1500},{slug:"equestrian",pointsRequired:2500,bonusBps:2e3},{slug:"patrician",pointsRequired:1e4,bonusBps:4e3},{slug:"senator",pointsRequired:25e3,bonusBps:6500},{slug:"emperor",pointsRequired:5e4,bonusBps:1e4}],"formatBonus",0,function(e,t){let r=e/1e4;if(0===r)return"+0.00";let i=r>0?"+":"";return`${i}${(0,s.formatFixed)(r,2,t)}`},"formatMultiplier",0,function(e,t){return`${(0,s.formatFixed)(e/1e4,2,t)}\xd7`},"formatPoints",0,function(e,t){let r=a(e);return 0===r?"0":r<1?(0,s.formatFixed)(r,2,t):r<1e3?(0,s.formatFixed)(r,1,t):r<1e6?`${(0,s.formatFixed)(r/1e3,1,t)}k`:`${(0,s.formatFixed)(r/1e6,2,t)}M`},"pointsFromMicros",0,a,"rankDisplay",0,function(e){return e?e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"—"},"useCurrentWeekPoints",0,function(e){return(0,r.useQuery)({queryKey:["season-points","current-week",e],queryFn:()=>n(`/api/v1/points/current-week/${e}`),enabled:!!e,staleTime:15e3,refetchInterval:3e4})},"useSeasonPoints",0,function(e){let t=(0,i.useSessionJwt)();return(0,r.useQuery)({queryKey:["season-points","me",e,t],queryFn:()=>n(`/api/v1/points/me/${e}`,t),enabled:!!e,staleTime:15e3,refetchInterval:3e4})},"useSeasonPointsHistory",0,function(e){return(0,r.useQuery)({queryKey:["season-points","history",e],queryFn:()=>n(`/api/v1/points/history/${e}`),enabled:!!e,staleTime:6e4})},"useSeasonPointsLeaderboard",0,function(e,r="points",i="desc",s="",a=null,l=50){let o=s.trim();return(0,t.useInfiniteQuery)({queryKey:["season-points","leaderboard",e,r,i,o,a,l],queryFn:({pageParam:t})=>{let s=new URLSearchParams({period:e,sort_by:r,sort_direction:i,limit:String(l),offset:String(t)});return o&&s.set("search",o),"week"===e&&null!=a&&s.set("week_number",String(a)),n(`/api/v1/points/leaderboard?${s.toString()}`)},initialPageParam:0,getNextPageParam:(e,t)=>{if(e.hasMore)return t.reduce((e,t)=>
2e+t.entries.length,0)},staleTime:3e4,refetchInterval:6e4})},"useSeasonWeeks",0,function(){return(0,r.useQuery)({queryKey:["season-points","weeks"],queryFn:()=>n("/api/v1/points/weeks"),staleTime:3e5})}],744900);let l=(e,t)=>"tp"===e===t,o=(e,t,r,i)=>l(e,i)?t>r:t<r;function d(e,t,r,i){return parseFloat(t)>0?null!==r&&r>0?o(e,parseFloat(t),r,i)?"valid":"wrongSide":"noBasis":"empty"}let c=()=>globalThis.crypto?.randomUUID?.()??`leg-${Date.now()}-${Math.random().toString(36).slice(2)}`,u=(e,t)=>{let r=e.find(e=>e.type===t);return r&&("tp"===r.type||"sl"===r.type)?r.triggerPrice:null};function h(e,t,r,i=c){let s=e.filter(e=>"tp"!==e.type&&"sl"!==e.type);if(parseFloat(t)>0){let r=e.find(e=>"tp"===e.type)?.id??i();s.push({id:r,type:"tp",triggerPrice:parseFloat(t)})}if(parseFloat(r)>0){let t=e.find(e=>"sl"===e.type)?.id??i();s.push({id:t,type:"sl",triggerPrice:parseFloat(r)})}return s.length===e.length&&u(s,"tp")===u(e,"tp")&&u(s,"sl")===u(e,"sl")?null:s}e.s(["legState",0,d,"mustBeAbove",0,l,"onRightSide",0,o,"syncTpSlLegs",0,h],926643),e.s(["popValue",0,function(e){e&&(e.classList.remove("value-pop"),e.offsetWidth,e.classList.add("value-pop"),e.addEventListener("animationend",()=>e.classList.remove("value-pop"),{once:!0}))}],482317);var p=e.i(394390),m=e.i(183023),f=e.i(684446),x=e.i(942553),g=e.i(1169);let b={type:"text",inputMode:"decimal",autoComplete:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"done"};e.s(["DECIMAL_INPUT_PROPS",0,b],822371);var v=e.i(657645),y=e.i(637740),w=e.i(806082),j=e.i(821043),S=e.i(299959);e.s(["InlineTpSl",0,function({items:e,onItemsChange:t,marketPrice:r,isLong:i,entryPrice:s,triggerBasis:n,awaitsLimitPrice:a,sizeUsd:o,collateralUsd:c,feesUsd:u,error:k=!1,dense:N=!1}){let P=(0,x.useTranslations)("trading"),T=(0,S.useFormatters)(),C=(0,S.useDecimalSeparator)(),M=e.find(e=>"tp"===e.type),_=e.find(e=>"sl"===e.type),A=!!M||!!_,[E,L]=(0,f.useDesktopTicketDraftState)("tpsl.expanded",A),F=(0,m.useRef)(null);(0,w.useRevealOnOpen)(E,F);let R=(0,m.useRef)(null),D=(0,m.useRef)(null);(0,m.useEffect)(()=>{let e=D.current;if(!e)return;let t=()=>L(!0);return e.addEventListener(v.KEYPAD_JUMP_EVENT,t),()=>e.removeEventListener(v.KEYPAD_JUMP_EVENT,t)},[]);let[I,U]=(0,f.useDesktopTicketDraftState)("tpsl.tpInput",M?.type==="tp"&&M.triggerPrice>0?String(M.triggerPrice):""),[O,B]=(0,f.useDesktopTicketDraftState)("tpsl.slInput",_?.type==="sl"&&_.triggerPrice>0?String(_.triggerPrice):""),z=d("tp",I,n,i),$=d("sl",O,n,i),V=[z,$].filter(e=>"empty"!==e),H=V.length>0&&V.every(e=>"valid"===e),W=(r,i)=>{U(r),B(i);let s=h(e,r,i);s&&t(s)},q=e=>W((0,j.sanitizeDecimalInput)(e,C),O),K=e=>W(I,(0,j.sanitizeDecimalInput)(e,C)),G=(0,m.useRef)(!1);(0,m.useLayoutEffect)(()=>{E&&G.current&&(G.current=!1,(0,v.focusKeypadField)(R.current))},[E]);let Y=r?T.number(r):"0.00",X=e=>"tp"===e?{value:I,leg:z,onValue:q}:{value:O,leg:$,onValue:K},Q=e=>T.number(e,{maximumFractionDigits:2}),J=e=>{let{value:t,leg:r,onValue:d}=X(e),h=P("tp"===e?"takeProfit":"stopLoss"),m="wrongSide"===r;return(0,p.jsxs)("div",{"data-keypad-reveal":!0,className:`flex h-[73px] flex-col justify-between rounded-field border px-[15px] pb-3 pt-[13px] transition-colors focus-within:ring-2 ${m?"border-destructive/70 focus-within:border-destructive focus-within:ring-destructive/30":"border-border-strong focus-within:border-primary/60 focus-within:ring-primary/40"} ${N?"bg-input":"bg-[var(--phone-chip)]"}`,children:[(0,p.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,p.jsx)("span",{className:"shrink-0 text-[12px] font-medium text-foreground/50",children:h}),(e=>{let{value:t,leg:r}=X(e);if("empty"===r)return null;if("wrongSide"===r&&n)return(0,p.jsx)("span",{className:"min-w-0 truncate text-[12px] font-medium text-destructive",children:P(l(e,i)?"tpSlMustBeAbove":"tpSlMustBeBelow",{price:`$${T.number(n)}`})});if("noBasis"===r)return(0,p.jsx)("span",{className:"min-w-0 truncate text-[12px] font-medium text-label-muted",children:P(a?"tpSlNeedsLimitFirst":"tpSlNeedsPrice")});if(!s||s<=0||o<=0)return null;let d=(parseFloat(t)-s)/s*o*(i?1:-1);if(!("tp"===e?d>0:d<0))return(0,p.jsxs)("span",{className:"flex shrink-0 items-baseline gap-1 text-[12px]",children:[(0,p.jsx)("span",{className:"text-label-muted whitespace-nowrap",children:P("estPnl")}),(0,p.jsx)("span",{className:"text-label-muted",children:"—"})]});let h=d-u,m=c>0?h/c*100:null,f=h>=0,x=f?"+":"-";return(0,p.jsxs)("span",{className:"flex min-w-0 items-baseline gap-1 text-[12px]",children:[(0,p.jsx)("span",{className:"shrink-0 text-label-muted",children:P("estPnl")}),(0,p.jsxs)("span",{className:`min-w-0 truncate font-mono tabular-nums ${f?"text-side-long":"text-side-short"}`,children:[x,"$",Q(Math.abs(h)),null!==m&&` (${x}${Q(Math.abs(m))}%)`]})]})})(e)]}),(0,p.jsxs)("div",{className:"flex items-center gap-1",children:[(0,p.jsx)("span",{className:"shrink-0 font-sans text-[22px] font-bold text-foreground
2/70",children:"$"}),(0,p.jsx)("input",{...b,ref:"tp"===e?R:void 0,value:t,"data-keypad-unit":"money","aria-label":h,"aria-invalid":m||void 0,onChange:e=>d(e.target.value),onWheel:e=>e.currentTarget.blur(),placeholder:Y,className:"min-w-0 flex-1 border-none bg-transparent font-sans text-[22px] font-bold tabular-nums text-foreground/70 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})]})]})},Z=["empty"!==z&&`TP $${I}`,"empty"!==$&&`SL $${O}`].filter(Boolean).join(" · "),ee=V.some(e=>"valid"!==e);return(0,p.jsxs)("div",{ref:D,"data-keypad-jump":"TP/SL",children:[(0,p.jsxs)("div",{className:`flex items-center pl-1.5 pr-3.5 ${N?"min-h-10":"min-h-12"}`,children:[(0,p.jsx)("label",{className:`flex w-12 shrink-0 cursor-pointer items-center justify-center ${N?"h-10":"h-12"}`,children:(0,p.jsx)(y.Switch,{"aria-label":"TP/SL",checked:H,onCheckedChange:e=>{if(e&&!E){G.current=!0,L(!0);return}L(!1),W("","")},trackPx:36,className:"h-[22px] w-9 data-[state=checked]:border-side-long/50 data-[state=checked]:bg-side-long/40"})}),(0,p.jsxs)("button",{type:"button","aria-expanded":E,onClick:()=>L(!E),className:`flex min-w-0 flex-1 items-center gap-2 text-left ${N?"min-h-10":"min-h-12"}`,children:[(0,p.jsx)("span",{className:`text-sm font-semibold ${k?"text-destructive":"text-foreground"}`,children:"TP/SL"}),(0,p.jsxs)("span",{className:"ml-auto flex min-w-0 items-center gap-2",children:[Z&&(0,p.jsx)("span",{className:`truncate font-mono text-xs tabular-nums ${k||ee?"text-destructive":"text-secondary-foreground"}`,children:Z}),(0,p.jsx)(g.ChevronDown,{className:`h-4 w-4 shrink-0 text-label-muted transition-transform ${E?"rotate-180":""}`})]})]})]}),E&&(0,p.jsxs)("div",{ref:F,className:"space-y-2 px-3.5 pb-3.5",children:[J("tp"),J("sl")]})]})}],35e4)},494286,538712,e=>{"use strict";var t=e.i(43690),r=e.i(936548);function i(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function s(e){return e?.liquidationPending===!0||e?.primeBound===!0}function n(e){if(s(e))return 0;let t=i(e?.heldProfitUsd);return null!=t&&t>=.005?t:0}function a(e){let t=i(e?.freeCollateralUsd);return null==t?null:Math.max(0,t)+n(e)}function l(e){return e?e.heldUsd>0?{kind:"settling",heldUsd:e.heldUsd,availableAt:e.availableAt}:e.capLimited?{kind:"moreShortly"}:null:null}let o=new Set(["SunriseProfitHeld","SunriseProfitPaused","SunriseProfitNotEnabled","ArmadaProfitHeld","ArmadaProfitPaused","ArmadaProfitNotEnabled"]),d=new Set(["SunriseWithdrawalLimit","ArmadaWithdrawalLimit"]);function c(e,t,r){return["sunrise-margin",e,t,r]}async function u(e,t,r){let i=new URLSearchParams({wallet:e,profileIndex:String(t)});r&&i.set("asset",r);let s=await fetch(`https://api.imperial.space/api/v1/armada/margin?${i.toString()}`);if(!s.ok)throw Error("Failed to fetch sunrise margin");return s.json()}function h(e){if(e?.liquidationPending||e?.primeBound)return 0;let t=e?.withdrawableNowUsd;return"number"==typeof t&&Number.isFinite(t)?t:null}e.s(["armadaAccountBalanceUsd",0,a,"armadaWithdrawRefusal",0,function(e,t){if(!(e instanceof r.ImperialUserError))return null;let s=e.details?.code??"";if(d.has(s))return{kind:"moreShortly"};if(!o.has(s))return null;let n=i(e.details?.retryAfterSecs);return{kind:"settling",availableAt:s.endsWith("ProfitHeld")&&null!=n&&n>0?Math.floor(t/1e3)+n:null}},"formatSettlingTime",0,function(e,t,r,i){let s=new Date(1e3*e),n=e=>new Intl.DateTimeFormat("en-CA",{timeZone:i,dateStyle:"short"}).format(e),a={timeZone:i,hour:"numeric",minute:"2-digit"};return n(s)===n(new Date(t))?new Intl.DateTimeFormat(r,a).format(s):new Intl.DateTimeFormat(r,{...a,...1e3*e-t<5184e5?{weekday:"short"}:{month:"short",day:"numeric"}}).format(s)},"withdrawAmountNote",0,function(e,t,r){return null==e||null==t||e<=t+1e-9?null:l(r)},"withdrawSettling",0,function(e){let t=n(e),r=!s(e)&&e?.profitCapLimited===!0;if(0===t&&!r)return null;let a=i(e?.profitAvailableAt);return{heldUsd:t,availableAt:t>0&&null!=a&&a>0?a:null,capLimited:r}},"withdrawSettlingLine",0,l],538712),e.s(["armadaAccountDrawableUsd",0,function(e){let t=e?.drawableUsd;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):null},"armadaAccountFreeUsd",0,function(e){return a(e)},"armadaAccountWithdrawableUsd",0,function(e){if(e?.liquidationPending||e?.primeBound)return 0;let t=e?.withdrawableTotalUsd;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):null},"armadaWithdrawWaitSecs",0,function(e){let t=e?.arrivingEtaSecs;return Math.max(60,"number"==typeof t&&Number.isFinite(t)?t:0)}
2,"fetchSunriseMargin",0,u,"sunriseArrivingUsd",0,function(e){let t=h(e),r=e?.withdrawableTotalUsd;return null!=t&&"number"==typeof r&&Number.isFinite(r)?Math.max(0,r-t):null},"sunriseMarginQueryKey",0,c,"sunriseMarginWalletKey",0,function(e){return["sunrise-margin",e]},"sunriseWithdrawableNowUsd",0,h,"useSunriseMargin",0,function(e,r,i,s){return(0,t.useQuery)({queryKey:c(e,r,i),queryFn:()=>u(e,r,i),enabled:s&&!!e&&null!==r,staleTime:1e4,refetchInterval:15e3})}],494286)},578866,e=>{"use strict";e.i(413358);var t=e.i(183023),r=e.i(43690),i=e.i(828047);async function s(){let e=await fetch("https://api.imperial.space/api/v1/armada/markets");if(!e.ok)throw Error("Failed to fetch Armada markets");return e.json()}e.s(["useSunriseMarkets",0,function(){let e=(0,r.useQuery)({queryKey:["sunrise-markets"],queryFn:s,staleTime:6e4,refetchInterval:6e4,placeholderData:[]}),n=e.isSuccess&&!e.isPlaceholderData?e.data:void 0;return(0,t.useEffect)(()=>{n&&(0,i.setGlobalSunriseMarkets)(n)},[n]),e.isError&&e.data?{...e,data:e.data.map(e=>({...e,armadaPrime:void 0,liquidation:null}))}:e}])},988408,436998,e=>{"use strict";var t=e.i(43690);let r={global:{medianHoldHours:12,medianNotionalUsd:1e3,medianLeverage:5,tradeCount:0,totalVolumeUsd:0},perAsset:{}};async function i(e){let t=await fetch(`https://api.imperial.space/api/v1/profile/${e}/trading-stats`);if(!t.ok)throw Error(`trading-stats ${t.status}`);return t.json()}e.s(["resolveHoldHours",0,function(e,t){return e?e.perAsset[t]?.medianHoldHours??e.global.medianHoldHours:r.global.medianHoldHours},"useTradingStats",0,function(e){return(0,t.useQuery)({queryKey:["trading-stats",e],queryFn:()=>i(e),enabled:!!e,staleTime:36e5,refetchOnWindowFocus:!1,placeholderData:r})}],988408);var s=e.i(183023);e.s(["useSunriseOpenAvailability",0,function(e,r,i,n){let a=`${e.toUpperCase()}:${r}:${i}
2`,[l,o]=(0,s.useState)(a);(0,s.useEffect)(()=>{let e=setTimeout(()=>o(a),200);return()=>clearTimeout(e)},[a]);let d=n&&l===a&&Number.isFinite(i)&&i>0,c=(0,t.useQuery)({queryKey:["sunrise-open-availability",e.toUpperCase(),r,i],enabled:d,queryFn:async({signal:t})=>{let s=new URLSearchParams({asset:e,side:r,notionalUsd:String(i)}),n=await fetch(`https://api.imperial.space/api/v1/armada/open-availability?${s}`,{signal:t,cache:"no-store"});if(!n.ok)throw Error("Unable to check Armada opening capacity");let a=await n.json();if("boolean"!=typeof a.available)throw Error("Invalid Armada opening capacity");return{available:a.available,reason:"account_data_unavailable"===a.reason||"capacity_unavailable"===a.reason||"risk_limit"===a.reason?a.reason:void 0}},staleTime:2e3,refetchInterval:2e3,gcTime:3e4,retry:!1}),[u,h]=(0,s.useState)(0);return(0,s.useEffect)(()=>{let e=c.dataUpdatedAt,t=setTimeout(()=>h(e),Math.max(0,e+5e3-Date.now()));return()=>clearTimeout(t)},[c.dataUpdatedAt]),d&&c.isFetchedAfterMount&&!c.isError&&c.dataUpdatedAt>u?c.data:void 0}],436998)},417059,641879,333379,e=>{"use strict";var t=e.i(43690),r=e.i(299959),i=e.i(994754),s=e.i(938425);e.s(["useUserPoints",0,function(e,n){var a;let l=(0,r.useFormatters)(),{connection:o}=(0,i.useConnection)(),d=(0,t.useQuery)({queryKey:["user-points",e?.toBase58(),n??null],queryFn:async()=>{if(!e||null==n)return BigInt(0);let[t]=(0,s.getUserAccountPda)(e),r=await o.getAccountInfo(t);if(!r||!r.data)return BigInt(0);let i=new DataView(r.data.buffer,r.data.byteOffset);return i.getUint32(72,!0)!==n?BigInt(0):i.getBigUint64(64,!0)},enabled:!!e&&null!=n,staleTime:3e4,refetchInterval:6e4,refetchOnWindowFocus:!0}),c=d.data??BigInt(0);return{points:c,formattedPoints:(a=l.intlTag,(c/BigInt(1e6)).toLocaleString(a)),isLoading:d.isLoading,error:d.error,refetch:d.refetch}}],417059);var n=e.i(183023);e.s(["useTimeUntilUtcMidnight",0,function(){let[e,t]=(0,n.useState)(()=>Date.now());(0,n.useEffect)(()=>{let e=window.setInterval(()=>t(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let r=new Date(e),i=Math.floor(Math.max(0,Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()+1,0,0,0)-e)/6e4),s=Math.floor(i/60),a=i%60;return s>0?`${s}h ${a}m`:`${a}m`}],641879);var a=e.i(446373),l=e.i(514049),o=e.i(406470),d=e.i(936548);let c="https://api.imperial.space";async function u(e,t){let r=await fetch(`${c}${e}`,{headers:{"Content-Type":"application/json",...t?.headers??{}},...t});if(!r.ok)throw await (0,d.errorFromResponse)(r);return r.json()}e.s(["formatBonusBps",0,function(e,t){return`+${(0,o.formatFixed)(e/1e4,2,t)}`},"formatClanPnl",0,function(e,t){let r=e/1e6,i=Math.abs(r),s=r<0?"-":"";return i<1e3?`${s}$${(0,o.formatFixed)(i,2,t)}`:i<1e6?`${s}$${(0,o.formatFixed)(i/1e3,2,t)}k`:`${s}$${(0,o.formatFixed)(i/1e6,2,t)}M`},"formatRoiBps",0,function(e,t){let r=e/100,i=r>0?"+":"";return`${i}${(0,o.formatFixed)(r,2,t)}%`},"useClanInvites",0,function(e,r){return(0,t.useQuery)({queryKey:["clans","invites",e,r?.Authorization??r?.["x-signature"]],queryFn:()=>u(`/api/v1/clans/${e}/invites`,{headers:r}),enabled:!!e&&!!r,staleTime:3e4})},"useClanLeaderboard",0,function(e,r="desc",i="",s=null,n=50){let a=i.trim();return(0,t.useQuery)({queryKey:["clans","leaderboard",e,r,a,s,n],queryFn:()=>{let t=new URLSearchParams({period:e,sort_direction:r,limit:String(n)});return a&&t.set("search",a),"week"===e&&null!=s&&t.set("week_number",String(s)),u(`/api/v1/clans/leaderboard?${t.toString()}`)},staleTime:6e4})},"useClanMembersLeaderboard",0,function(e,r){return(0,t.useQuery)({queryKey:["clans","members-leaderboard",e,r],queryFn:()=>u(`/api/v1/clans/${e}/members/leaderboard?period=${r}`),enabled:!!e,staleTime:3e4,refetchInterval:6e4})},"useCreateInvite",0,function(){let e=(0,l.useQueryClient)();return(0,a.useMutation)({mutationFn:e=>u(`/api/v1/clans/${e.clanId}/invites`,{method:"POST",headers:e.headers}),onSuccess:(t,r)=>e.invalidateQueries({queryKey:["clans","invites",r.clanId]})})},"useLeaveClan",0,function(){let e=(0,l.useQueryClient)();return(0,a.useMutation)({mutationFn:e=>{let t=new URLSearchParams({callerWallet:e.callerWallet,message:e.message,signature:e.signature});return u(`/api/v1/clans/${e.clanId}/members/${e.targetWallet}?${t.toString()}`,{method:"DELETE"})},onSuccess:()=>e.invalidateQueries({queryKey:["clans"]})})},"useMyClan",0,function(e){return(0,t.useQuery)({queryKey:["clans","my-clan",e],queryFn:async()=>e?u(`/api/v1/clans/membership/${e}`):null,enabled:!!e,staleTime:3e4})},"useRedeemInvite",0,function(){let e=(0,l.useQueryClient)();return(0,a.useMutation)({mutationFn:e=>u(`/api/v1/clans/invites/${encodeURIComponent(e.code)}/redeem`,{method:"POST",body:JSON.stringify({wallet:e.wallet,message:e.message,signature:e.signature})}),onSuccess:()=>e.invalidateQueries({queryKey:["clans"]})})},"useSetClanLogo",0,function(){let e=(0,l.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=new URLSearchParams({wallet:e.wallet,message:e.message,signature:e.signature}),r=new FormData;r.append("image",e.file);let i=await fetch(`${c}/api/v1/clans/${e.clanId}/logo?${t.toString()}`,{method:"PUT",body:r});if(!i.ok)throw await (0,d.errorFromResponse)(i);return i.json()},onSuccess:()=>e.invalidateQueries({queryKey:["clans"]})})}],333379)},214732,e=>{"use strict";var t=e.i(183023),r=e.i(994754),i=e.i(620242);let s=new WeakMap;
2class n{connection;account;commitment;onEmpty;snapshot;listeners;active;slot;streamRevision;subscriptionId;poll;stopResume;running;requested;waiters;constructor(e,t,r,i){this.connection=e,this.account=t,this.commitment=r,this.onEmpty=i,this.snapshot={info:null,hasValue:!1,error:null,revision:0},this.listeners=new Set,this.active=!0,this.slot=-1,this.streamRevision=0,this.subscriptionId=null,this.poll=null,this.stopResume=null,this.running=!1,this.requested=0,this.waiters=[]}subscribe(e){this.listeners.add(e),1===this.listeners.size&&(this.poll=setInterval(()=>this.requestRead(),3e4),this.stopResume=(0,i.subscribeToResumeSignal)(()=>this.requestRead()),this.requestRead());let t=!1;return{getSnapshot:()=>this.snapshot,refresh:()=>t?Promise.resolve(null):this.refresh(),release:()=>{t||(t=!0,this.listeners.delete(e),0===this.listeners.size&&this.dispose())}}}publish(e){if(this.active)for(let t of(this.snapshot=e,this.listeners))t(e)}accept(e,t){this.slot=t,this.publish({info:e,hasValue:!0,error:null,revision:this.snapshot.revision+1})}ensureListener(){if(null===this.subscriptionId)try{this.subscriptionId=this.connection.onAccountChange(this.account,(e,t)=>{this.active&&!(t.slot<this.slot)&&(this.streamRevision+=1,this.accept(e,t.slot))},{commitment:this.commitment})}catch(e){console.error("Error subscribing to account:",e)}}requestRead(){this.active&&(this.requested+=1,this.running||this.read())}refresh(){if(!this.active)return Promise.resolve(null);let e=++this.requested,t=new Promise(t=>this.waiters.push({request:e,resolve:t}));return this.running||this.read(),t}async read(){for(this.running=!0;this.active;){let e=this.requested;this.ensureListener();let t=this.streamRevision,r=null;try{let e=await this.connection.getAccountInfoAndContext(this.account,this.commitment);if(!this.active)return;let r=e.context.slot;(r>this.slot||r===this.slot&&t===this.streamRevision)&&this.accept(e.value,r)}catch(e){if(!this.active)return;r=e instanceof Error?e:Error("Failed to read account"),this.snapshot.hasValue||this.publish({...this.snapshot,error:r}),console.error("Error refreshing subscribed account:",e)}let i=this.waiters.filter(t=>t.request<=e);if(this.waiters=this.waiters.filter(t=>t.request>e),i.forEach(e=>e.resolve(r)),e===this.requested)break}this.running=!1}dispose(){this.active=!1,this.onEmpty(),null!==this.poll&&clearInterval(this.poll),this.stopResume?.(),null!==this.subscriptionId&&this.connection.removeAccountChangeListener(this.subscriptionId).catch(e=>{console.error("Error removing account subscription:",e)}),this.waiters.forEach(e=>e.resolve(null)),this.waiters=[]}}e.s(["useAccountSubscription",0,function({account:e,decoder:i,onData:a,commitment:l="processed",enabled:o=!0}){let{connection:d}=(0,r.useConnection)(),c=e?.toBase58()??null,u=(0,t.useMemo)(()=>({connection:d,accountKey:c,commitment:l,enabled:o}),[d,c,l,o]),h=!!c&&o,[p,m]=(0,t.useState)({scope:u,data:null,isLoading:h,error:null}),f=(0,t.useRef)({scope:u,decoder:i,onData:a});(0,t.useLayoutEffect)(()=>{f.current={scope:u,decoder:i,onData:a}},[u,i,a]);let x=(0,t.useRef)(null);(0,t.useEffect)(()=>{let t={scope:u,subscription:null,active:!0,pending:0};if(x.current=t,e&&h){let r=-1,i=e=>{if(t.active&&f.current.scope===u){if(!e.hasValue)return void m({scope:u,data:null,isLoading:!e.error||t.pending>0,error:e.error});if(e.revision!==r){r=e.revision;try{let r=e.info,i=null===r?null:f.current.decoder?f.current.decoder(r):r;m({scope:u,data:i,isLoading:t.pending>0,error:null}),f.current.onData?.(i,r)}catch(r){let e=r instanceof Error?r:Error("Failed to decode account");m(r=>({...r,scope:u,isLoading:t.pending>0,error:e})),console.error("Error decoding account data:",r)}}}};t.subscription=function(e,t,r,i){let a=s.get(e);a||(a=new Map,s.set(e,a));let l=`${t.toBase58()}:${r}`,o=a.get(l);if(!o){let i=a;o=new n(e,t,r,()=>i.delete(l)),a.set(l,o)}return o.subscribe(i)}(d,e,l,i),i(t.subscription.getSnapshot())}return()=>{t.active=!1,t.subscription?.release(),x.current===t&&(x.current=null),m({scope:u,data:null,isLoading:h,error:null})}},[u]);let g=(0,t.useCallback)(async()=>{let e=x.current;if(!e?.active||e.scope!==u||f.current.scope!==u||!e.subscription)return;e.pending+=1,m(e=>({...e,isLoading:!0}));let t=await e.subscription.refresh();e.active&&f.current.scope===u&&(e.pending-=1,m(r=>({...r,isLoading:e.pending>0,error:t??r.error})))},[u]),b=p.scope===u?p:{data:null,isLoading:h,error:null};return{data:b.data,isLoading:b.isLoading,error:b.error,refetch:g}},"useMultipleAccountSubscriptions",0,function({accounts:e,decoder:i,onData:s,commitment:n="processed",enabled:a=!0}){let{connection:l}=(0,r.useConnection)(),o=(0,t.useRef)([]),d=(0,t.useRef)(null),[c,u]=(0,t.useState)(new Map),[h,p]=(0,t.useState)(!0),[m,f]=(0,t.useState)(!1),x=(0,t.useRef)(null),g=(0,t.useRef)(i),b=(0,t.useRef)(s);g.current=i,b.current=s;let v=(0,t.useCallback)(()=>{x.current=Date.now(),f(!1)},[]);return(0,t.useEffect)(()=>
2{if(!a)return void f(!1);let e=setInterval(()=>{let e=x.current;f(null!==e&&Date.now()-e>9e4)},1e4);return()=>clearInterval(e)},[a]),(0,t.useEffect)(()=>{if(!a){u(new Map),p(!1);return}let t=e.filter(e=>null!==e);if(0===t.length){u(new Map),p(!1);return}let r=!0,i=e=>{if(e&&g.current)try{return g.current(e)}catch{return null}return e},s=async()=>{let e=await l.getMultipleAccountsInfo(t,n);if(!r)return;let s=new Map;e.forEach((e,r)=>{s.set(t[r].toBase58(),i(e))}),u(s),p(!1),v()};d.current=s,o.current=t.map((e,t)=>l.onAccountChange(e,s=>{if(!r)return;let n=i(s);u(t=>{let r=new Map(t);return r.set(e.toBase58(),n),r}),v(),b.current?.(t,n,s)},{commitment:n})),p(!0);let c=()=>{s().catch(e=>console.error("Error fetching subscribed accounts:",e))};c();let h=setInterval(c,3e4),m=()=>{"visible"===document.visibilityState&&c()};return document.addEventListener("visibilitychange",m),()=>{r=!1,d.current=null,clearInterval(h),document.removeEventListener("visibilitychange",m),o.current.forEach(e=>{null!==e&&l.removeAccountChangeListener(e)}),o.current=[]}},[e.map(e=>e?.toBase58()??"null").join(","),l,n,a,v]),{dataMap:c,isLoading:h,isStale:m,refetch:(0,t.useCallback)(async()=>{await d.current?.()},[])}},"useSolBalanceSubscription",0,function({publicKey:e,onBalanceChange:i,commitment:s="processed",enabled:n=!0}){let{connection:a}=(0,r.useConnection)(),l=(0,t.useRef)(null),[o,d]=(0,t.useState)(0),[c,u]=(0,t.useState)(!0),[h,p]=(0,t.useState)(!1),m=(0,t.useRef)(i);return m.current=i,(0,t.useEffect)(()=>{if(!e||!n){d(0),p(!1),u(!1);return}let t=!0;return(async()=>{try{p(!1),u(!0);let r=await a.getBalance(e,s);t&&(d(r),p(!0),u(!1),m.current?.(r)),l.current=a.onAccountChange(e,e=>{if(t){let t=e?.lamports??0;d(t),p(!0),m.current?.(t)}},{commitment:s})}catch(e){console.error("Error subscribing to SOL balance:",e),t&&(p(!1),u(!1))}})(),()=>{t=!1,null!==l.current&&(a.removeAccountChangeListener(l.current),l.current=null)}},[e?.toBase58(),a,s,n]),{balance:o,isLoading:c,known:h,refetch:(0,t.useCallback)(async()=>{if(!e)return;let t=await a.getBalance(e,s);d(t),p(!0),m.current?.(t)},[e,a,s])}}],214732)},122097,334992,e=>{"use strict";var t=e.i(591318),r=e.i(183023),i=e.i(21859),s=e.i(214732),n=e.i(653982);function a(e){if(e.data.length<72)return 0;let r=e.data.slice(64,72);return Number(BigInt("0x"+t.Buffer.from(r).reverse().toString("hex")))/1e6}let l=new Set;e.s(["requestProfileBalancesBurstRefresh",0,function(){for(let e of l)e()},"useAllProfileUsdcBalances",0,function(e){let t=(0,r.useMemo)(()=>e.map(e=>(0,i.getAssociatedTokenAddressSync)(n.USDC_MINT,e.pda,!0)),[e]),{dataMap:o,isLoading:d,isStale:c,refetch:u}=(0,s.useMultipleAccountSubscriptions)({accounts:t,decoder:a,commitment:"processed",enabled:e.length>0});return(0,r.useEffect)(()=>{let e=null,t=()=>{e&&clearInterval(e);let t=0;u(),e=setInterval(()=>{if(++t>=10){e&&clearInterval(e),e=null;return}u()},700)};return l.add(t),()=>{l.delete(t),e&&clearInterval(e)}},[u]),{balances:(0,r.useMemo)(()=>{let r=new Map;return e.forEach((e,i)=>{let s=t[i];if(s){let t=s.toBase58();o.has(t)&&r.set(e.index,o.get(t)??0)}}),r},[e,t,o]),isLoading:d,isStale:c}}],122097),e.s(["hasNonPhoenixLoan",0,function(e,t){for(let r=0;r<12;r++){let i=128+4*r;if(i+4>e.length)break;if((e[i+2]|e[i+3]<<8)>0&&e[i]===t&&2!==e[i+1])return!0}return!1}],334992)},29265,177194,e=>{"use strict";var t=e.i(183023),r=e.i(116082),i=e.i(936548),s=e.i(494286),n=e.i(432533),a=e.i(265172);function l(e){return e<=0?250*Math.random():Math.min(500*2**(e-1),5e3)*(.5+.5*Math.random())}function o(e=Date.now){let t=0,r=null;return{opened(){r=e()},closed:({refused:i=!1}={})=>(null!==r&&e()-r>=5e3&&(t=0),r=null,i)?3e4:l(t++)}}e.s(["createReconnectBackoff",0,o,"reconnectDelayMs",0,l],177194);let d="https://api.imperial.space".replace(/^http/,"ws")+"/ws";e.s(["useApiWebSocket",0,function(e){let{cache:l,auth:c,jwt:u,ready:h}=(0,n.useAccountReadSession)(),p=e?l.audience(e,c):0,m=(0,t.useMemo)(()=>({wallet:e,auth:c,audience:p}),[e,c,p]),[f,x]=(0,t.useState)(null);return(0,t.useEffect)(()=>{let t,n,p;if(!e||!h)return;let f=!1,g=null,b=o(),v=l.client,y=t=>
2{v.invalidateQueries({queryKey:[t,e]},{cancelRefetch:!1})},w=()=>{y("jupiter-positions"),y("jupiter-lifecycles"),v.invalidateQueries({queryKey:["jupiter-lifecycle-pages",e],refetchType:"none"})},j=()=>{if(f||!l.isCurrent(c)||g?.readyState===WebSocket.OPEN||g?.readyState===WebSocket.CONNECTING)return;let o=new WebSocket(d);g=o;let h=l.socket(e,c);p=h.retire;let S=()=>!f&&g===o&&h.current(),k=!1;o.onopen=()=>{S()&&(x(m),b.opened(),o.send(JSON.stringify({type:"subscribe",wallet:e,positionState:!0,accountReadVersion:1,...u?{token:u}:{}})),w(),y("jupiter-orders"),v.invalidateQueries({queryKey:(0,s.sunriseMarginWalletKey)(e)},{cancelRefetch:!1}),t=setInterval(()=>{S()&&o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"ping"}))},25e3))},o.onmessage=t=>{if(S())try{let n=JSON.parse(t.data);if((0,a.object)(n)&&"error"===n.type&&"position_state_wallet_limit"===n.code){k=!0;return}if(!(0,a.object)(n)||n.wallet!==e)return;"position_state"===n.type||"position_state_unavailable"===n.type?"refresh"===h.receive(n)&&y("jupiter-positions"):"positions_updated"===n.type?(w(),v.invalidateQueries({queryKey:(0,s.sunriseMarginWalletKey)(e)},{cancelRefetch:!1})):"orders_updated"===n.type?(y("jupiter-orders"),y("jupiter-lifecycles"),v.invali
2dateQueries({queryKey:["jupiter-lifecycle-pages",e],refetchType:"none"})):"order_rejected"===n.type&&(w(),y("jupiter-orders"),r.toast.error((0,i.errorFromPayload)(n,"The trading venue rejected this order. Check Trade History before trying again.").message))}catch{}},o.onclose=()=>{S()&&(h.retire(),g=null,t&&clearInterval(t),x(null),n=setTimeout(j,b.closed({refused:k})))},o.onerror=()=>{S()&&o.close()}};return j(),()=>{f=!0,p?.(),t&&clearInterval(t),n&&clearTimeout(n),g&&(g.onopen=null,g.onclose=null,g.onmessage=null,g.onerror=null,g.close(),g=null),x(null)}},[e,h,l,c,u,m]),{isConnected:h&&f===m}}],29265)},491681,786911,879630,e=>{"use strict";e.s(["useArmadaAccountPull",()=>Y],491681),e.s(["SunriseMarginAccounts",()=>K,"armadaAccountSeat",()=>W],879630),e.s(["MarginAccountSheet",()=>z],786911);var t=e.i(183023),r=e.i(942553),i=e.i(514049),s=e.i(21859),n=e.i(116082);e.i(875574);var a=e.i(142298),l=e.i(124431),o=e.i(938425),d=e.i(936548),c=e.i(739835),u=e.i(610021),h=e.i(538712),p=e.i(299959),m=e.i(702193),f=e.i(494286),x=e.i(148974),g=e.i(727322),b=e.i(394390),v=e.i(894771),y=e.i(889572),w=e.i(190459),j=e.i(599059),S=e.i(616341),k=e.i(943494),N=e.i(685576),P=e.i(623075),T=e.i(619966),C=e.i(153517),M=e.i(821043),_=e.i(308146),A=e.i(406470),E=e.i(670374),L=e.i(546642),F=e.i(275683),R=e.i(122097),D=e.i(208329),I=e.i(856255),U=e.i(161708),O=e.i(725452);let B=[10,20,50,80,100];function z(e){(0,r.useTranslations)("positions");let t=(0,r.useTranslations)("terms");return(0,T.useIsDesktop)()?(0,b.jsx)(P.Dialog,{open:e.open,onOpenChange:e.onOpenChange,children:(0,b.jsxs)(P.DialogContent,{className:"gap-0 sm:max-w-md",children:[(0,b.jsx)(P.DialogHeader,{children:(0,b.jsx)(P.DialogTitle,{className:"text-sm font-semibold",children:t(O.MARGIN_ACCOUNT_LABEL_KEY)})}),(0,b.jsx)($,{...e,variant:"dialog"})]})}):(0,b.jsx)(N.Sheet,{open:e.open,onOpenChange:e.onOpenChange,children:(0,b.jsxs)(N.SheetContent,{side:"bottom",className:"bg-canvas px-4 pt-4 overflow-y-auto overflow-x-hidden",children:[(0,b.jsx)(N.SheetTitle,{className:"text-foreground text-lg font-semibold mb-1",children:t(O.MARGIN_ACCOUNT_LABEL_KEY)}),(0,b.jsx)($,{...e,variant:"sheet"})]})})}function $({open:e,onOpenChange:i,seat:s,initialMode:l,onPositionChange:o,variant:h}){let m=(0,r.useTranslations)("positions"),y=(0,r.useTranslations)("common"),j=(0,p.useFormatters)(),[S,N]=(0,t.useState)(l),[P,T]=(0,t.useState)(""),[A,O]=(0,t.useState)(!1),{depositCollateral:z,withdrawCollateral:W}=(0,g.useTradeActions)(),{awaitingReturn:q,submitWithArrivingWait:K}=(0,x.useArrivingWithdrawal)(),{publicKey:G,connection:Y,signTransaction:X,sendTransaction:Q}=(0,a.useUnifiedWallet)(),{profiles:J}=(0,v.useProfile)(),{balances:Z}=(0,R.useAllProfileUsdcBalances)(J),ee=7===(0,w.underwriterByteFrom)(String(s.anchor?.underwriter??"")),{data:et,isLoading:er,refetch:ei}=(0,D.usePhoenixMarginAccount)(G?.toBase58()??null,s.profileIndex,e&&!ee),{data:es,isLoading:en,refetch:ea}=(0,f.useSunriseMargin)(G?.toBase58()??null,s.profileIndex,null,ee&&e),el=(0,f.sunriseWithdrawableNowUsd)(es),eo=(0,f.sunriseArrivingUsd)(es),ed="add"===S,ec=parseFloat(P)||0,eu=s.profileIndex??null,eh=null!=eu?Z.get(eu):void 0,ep=ee?en?null:el:(0,D.withdrawableUsd)(et),em=(0,t.useMemo)(()=>{if(ee)return 0;
2let e=(0,U.flatCollateralFeeBps)((0,U.feePolicy)(G?.toBase58()));return ec>0?ec*e/1e4:0},[ec,G,ee]),ef=(0,t.useMemo)(()=>{let e=ee?es?.effectiveCollateralUsd??NaN:parseFloat(et?.effectiveCollateralUsd??""),t=ee?es?.maintenanceMarginUsd??NaN:parseFloat(et?.maintenanceMarginUsd??"");return(0,F.previewMarginAccountEdit)({mode:S,amountUsd:ec,feeUsd:em,balanceUsd:ee?es?.collateralUsd??s.balanceUsd:et?parseFloat(et.accountCollateralUsd):s.balanceUsd,freeUsd:ee?es?.freeCollateralUsd??s.freeUsd:s.freeUsd,effectiveUsd:Number.isFinite(e)?e:0,maintenanceUsd:Number.isFinite(t)?t:0,maxUsd:ep})},[et,ec,em,ep,S,s.balanceUsd,s.freeUsd,ee,es]),ex=ed?eh??0:ep??0,eg=(ee?en:er)||ex<=0,eb=(0,L.pickMissingLabel)([[ee?en:er,m("mobileLoadingAccount")],[!s.anchor,m("mobileUnavailable")],[ec<=0,m("mobileEnterAmount")]]),ev=async()=>{let e=s.anchor;if(!e||ec<=0||ef.error)return void n.toast.error(ef.error??m("mobileEnterValidAmount"));let t=(0,E.getMarketMintFromAsset)(e.asset,e.underwriter);if(!t)return void n.toast.error(m("mobileMarketDataUnavailable"));O(!0);try{if(ed&&null!=s.profileIndex){if(null==eh)return void n.toast.error(m("mobileAccountBalanceLoading"));let e=Math.ceil(100*Math.max(0,ec-eh))/100;if(e>.01){if(!G||!Y||!X||!Q)return void n.toast.error(m("mobileConnectWalletToFund"));let t=await (0,I.getWalletUsdcBalance)(Y,G);if(t<e)return void n.toast.error(m("mobileNotEnoughUsdc",{account:V(eh,j.intlTag),wallet:V(t,j.intlTag)}));let r=n.toast.loading(m("mobileMovingUsdc",{amount:V(e,j.intlTag)}));try{await (0,I.fundProfileWithUsdc)({connection:Y,publicKey:G,signTransaction:X,sendTransaction:Q,profileIndex:s.profileIndex,amountUsdc:e})}catch(e){n.toast.error((0,c.isUserRejection)(e)?m("mobileDepositCancelled"):m("mobileWalletMoveFailed"));return}finally{n.toast.dismiss(r)}}}let r=ed?z:W;await K({requestedUsd:ec,submit:()=>r({positionPubkey:ee||ed?void 0:et?.traderAccount,marketMint:t,side:e.side,collateralAmount:ec,currentPrice:e.markPrice,slippageBps:g.DEFAULT_SLIPPAGE_BPS,profileIndex:s.profileIndex,underwriter:e.underwriter,sunriseMarginMode:ee?"cross":void 0}),readMargin:ee&&!ed&&G&&null!==eu?()=>(0,f.fetchSunriseMargin)(G.toBase58(),eu,null):void 0})&&(n.toast.success(ed?m("mobileMarginAdded"):m("mobileMarginRemoved")),i(!1),ee?ea():ei(),o?.())}catch(e){if((0,u.isSunriseArriving)(e))return void n.toast.info((0,d.displayClientError)(e));console.error("Margin account edit failed:",e),n.toast.error(ed?m("mobileMarginAddFailed"):m("mobileMarginRemoveFailed"))}finally{O(!1)}},ey=ee?es?.collateralUsd??s.balanceUsd:et?parseFloat(et.accountCollateralUsd):s.balanceUsd,ew="dialog"===h;return(0,b.jsxs)("div",{className:"flex flex-col",children:[(0,b.jsxs)("div",{className:(0,C.cn)("flex flex-col gap-3",ew&&"px-4 py-4"),children:[ee&&es?.liquidationPending&&(0,b.jsx)("p",{className:"text-sm text-amber-400",children:"Liquidation is in progress. Collateral is reserved until the position closes."}),ee&&es?.liquidationThresholdMaxUsd!=null&&(0,b.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Liquidation equity threshold: $",es.liquidationThresholdMinUsd?.toFixed(2)??"—","–$",es.liquidationThresholdMaxUsd.toFixed(2),". The threshold varies with available liquidity."]}),(0,b.jsx)("p",{className:"text-xs text-muted-foreground",children:m("mobileOneBalanceNote")}),(0,b.jsx)("div",{className:"grid grid-cols-2 gap-1 bg-surface border border-border-strong rounded-md p-1",children:["add","withdraw"].map(e=>(0,b.jsx)("button",{onClick:()=>{N(e),T("")},className:(0,C.cn)("py-1.5 text-sm font-medium rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",("add"===e?ed:!ed)?"bg-orange-500/15 text-orange-400":"text-label-muted hover:text-secondary-foreground"),children:"add"===e?m("mobileAdd"):m("mobileRemove")},e))}),(0,b.jsxs)("div",{"data-keypad-reveal":!0,className:"flex items-center bg-surface-raised border border-border-strong rounded-lg px-3 py-2.5",children:[(0,b.jsx)("input",{type:"text",inputMode:"decimal","data-keypad-unit":"money",placeholder:"0",value:P,onChange:e=>T((0,M.sanitizeDecimalInput)(e.target.value,j.decimalSeparator,6)),className:"flex-1 min-w-0 bg-transparent border-none text-foreground text-sm font-mono tabular-nums placeholder:text-label-muted focus:outline-none"}),(0,b.jsx)("span",{className:"text-xs text-muted-foreground ml-2 shrink-0",children:"USDC"})]}),(0,b.jsx)("div",{className:"flex items-center gap-1",children:B.map(e=>(0,b.jsxs)("button",{onClick:()=>{T((0,_.percentToDecimalString)(ex,e,6))},disabled:eg,className:"flex-1 py-1 text-xs rounded text-label-muted hover:text-foreground hover:bg-surface-interactive transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[e,"%"]},e))}),ee&&null!=eo&&eo>0&&(0,b.jsx)("div",{className:"text-[11px] text-amber-400/80",children:m("sunriseArrivingRest",{amount:V(eo,j.intlTag),secs:(0,f.armadaWithdrawWaitSecs)(es)})}),(0,b.jsx)("div",{className:"text-[11px] tabular-nums",children:(ee?en:er)?(0,b.jsx)("span",{className:"text-label-muted",children:m("mobileLoadingAccountEllipsis")}):ed?null==eh?(0,b.jsx)("span",{className:"text-label-muted",children:m("mobileLoadingBalance")}):eh<=0?(0,b.jsx)("span",{className:"text-amber-400/80",children:m("mobileNoUsdcInAccount")}
2):(0,b.jsx)("span",{className:"text-label-muted",children:m("mobileAvailableUsdc",{amount:V(eh,j.intlTag)})}):null==ep?(0,b.jsx)("span",{className:"text-amber-400/80",children:m("mobileNoRemovableAmount")}):ep<=0?ee&&null!=eo&&eo>0?null:(0,b.jsx)("span",{className:"text-amber-400/80",children:m("mobileNothingToRemove")}):(0,b.jsx)("span",{className:"text-label-muted",children:m("mobileMostYouCanRemove",{amount:V(ep,j.intlTag)})})}),(0,b.jsxs)("div",{className:"flex flex-col gap-2 pt-1",children:[(0,b.jsx)(H,{label:m("mobileSeatBalance"),current:V(ey,j.intlTag),next:ec>0?V(ef.nextBalanceUsd,j.intlTag):null}),(0,b.jsx)(H,{label:m("mobileSeatFreeMargin"),current:V(s.freeUsd,j.intlTag),next:ec>0?V(ef.nextFreeUsd,j.intlTag):null}),(0,b.jsx)(H,{label:m("mobileSeatHealth"),current:null==s.health?"—":`${Math.round(100*s.health)}%`,next:ec>0?null==ef.nextHealth?"—":`${Math.round(100*ef.nextHealth)}%`:null,nextClass:null!=ef.nextHealth&&ef.nextHealth<.25?"text-destructive":void 0}),em>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(H,{label:m("historyColFee"),current:V(em,j.intlTag),next:null}),(0,b.jsx)(H,{label:ed?m("mobileAccountReceives"):m("mobileYouReceiveLower"),current:V(ec-em,j.intlTag),next:null})]}),ef.error&&(0,b.jsx)("div",{className:"text-xs text-destructive",children:ef.error}),!ed&&(0,b.jsx)("p",{className:"text-[11px] text-muted-foreground",children:m("mobileRemoveMarginWarning")})]})]}),(0,b.jsxs)("div",{className:(0,C.cn)("flex items-center gap-3",ew?"px-4 py-3 border-t border-border justify-end":"pt-4 [&>button]:flex-1"),children:[(0,b.jsx)("button",{onClick:()=>i(!1),disabled:A&&!q,className:"px-8 py-2 text-sm font-medium rounded-md border border-orange-500/60 text-foreground hover:bg-orange-500/10 disabled:opacity-50",children:y("cancel")}),(0,b.jsx)("button",{onClick:ev,disabled:A||null!==eb||null!==ef.error||ee&&es?.liquidationPending===!0,className:"px-8 py-2 text-sm font-semibold rounded-md bg-orange-500 text-primary-foreground hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center min-w-[130px]",children:q?(0,b.jsxs)("span",{className:"flex items-center gap-2",children:[(0,b.jsx)(k.Loader2,{className:"h-4 w-4 animate-spin"}),m("sunriseWaitingForFunds")]}):A?(0,b.jsx)(k.Loader2,{className:"h-4 w-4 animate-spin"}):eb??(ed?m("mobileAdd"):m("mobileRemove"))})]})]})}function V(e,t){return`$${(0,A.formatNumber)(e,{maximumFractionDigits:2},t)}`}function H({label:e,current:t,next:r,nextClass:i}){return(0,b.jsxs)("div",{className:"flex items-center justify-between text-xs",children:[(0,b.jsx)("span",{className:"text-label-muted",children:e}),(0,b.jsxs)("span",{className:"text-foreground font-mono tabular-nums",children:[t,null!=r&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("span",{className:"text-label-muted mx-1.5",children:"→"}),(0,b.jsx)("span",{className:i,children:r})]})]})]})}function W(e,t){return t?.collateralUsd==null||null==t.freeCollateralUsd?null:{traderAccount:`sunrise:cross:${e}`,profileIndex:e,venueLabel:j.VENUE_LABELS.armada,balanceUsd:t.collateralUsd,freeUsd:t.freeCollateralUsd,usedUsd:t.initialMarginUsd??null,health:null==t.effectiveCollateralUsd||null==t.maintenanceMarginUsd?null:(0,y.seatHealth)(t.effectiveCollateralUsd,t.maintenanceMarginUsd),grossUsd:0,netUsd:0,openLegs:t.openPositions??0,anchor:{asset:"SOL",underwriter:"sunrise",side:"long",markPrice:0,sizeUsd:0}}}function q({profileIndex:e,desktop:r,onPositionChange:i}){let{publicKey:s}=(0,a.useUnifiedWallet)(),{data:n}=(0,f.useSunriseMargin)(s?.toBase58()??null,e,null,!0),[l,o]=(0,t.useState)(null),d=W(e,n);if(!d||(0,m.armadaAccountIsCash)(n))return null;let c=r?S.CrossSeatStrip:S.MobileCrossSeatCard;return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(c,{seat:d,onAddCollateral:()=>o("add"),onWithdrawCollateral:()=>o("withdraw")}),l&&(0,b.jsx)(z,{open:!0,seat:d,initialMode:l,onOpenChange:e=>{e||o(null)},onPositionChange:i})]})}function K({positions:e,desktop:t,onPositionChange:r}){let{activeProfileIndex:i}=(0,v.useProfile)(),s=new Set;for(let t of(null!=i&&s.add(i),e))7===(0,w.underwriterByteFrom)(String(t.underwriter??""))&&null===t.sunriseMarginSeat&&null!=t.profileIndex&&s.add(t.profileIndex);return(0,b.jsx)(b.Fragment,{children:Array.from(s).map(e=>(0,b.jsx)(q,{profileIndex:e,desktop:t,onPositionChange:r},e))})}let G=!1;function Y(){let e=(0,r.useTranslations)("wallet"),b=(0,p.useIntlTag)(),{publicKey:v,connection:y}=(0,a.useUnifiedWallet)(),w=(0,i.useQueryClient)(),{withdrawCollateral:j}=(0,g.useTradeActions)(),{submitWithArrivingWait:S}=(0,x.useArrivingWithdrawal)(),[k,N]=(0,t.useState)(!1),P=l.PROFILE_TOKEN_MINTS.find(e=>"USDC"===e.symbol).mint,T=(0,t.useCallback)(async e=>{if(!y||!v)return null;try{let[t]=(0,o.getProfilePda)(v,e),r=(0,s.getAssociatedTokenAddressSync)(P,t,!0);if(!await y.getAccountInfo(r,"confirmed"))return 0n;let i=await y.getTokenAccountBalance(r,"confirmed");return BigInt(i.value.amount)}catch{return null}},[y,v,P]);return{pullIntoProfile:(0,t.useCallback)(async({profileIndex:t,neededRaw:r,forOrder:i=!1,incompleteMessage:s,failedMessage:a,isAlive:l=()=>!0})=>{if(G)return n.toast.info(e("armadaPullInProgress")),null;G=!0;try{let o,p=v?.toBase58(),x=await T(t);if(!p||null===x)return n.toast.error(e("balanceStillLoading")),null;let y=(0,m.landedSpendRaw)(x,r);
2if(null!==y)return{spendRaw:y,pulled:!1};try{o=await (0,f.fetchSunriseMargin)(p,t,null)}catch{return n.toast.error(e("balanceStillLoading")),null}let k=(0,f.armadaAccountWithdrawableUsd)(o),P=i?(0,m.armadaOrderPullableUsd)(k,o):k,C=W(t,o),M=C?.anchor?(0,E.getMarketMintFromAsset)(C.anchor.asset,C.anchor.underwriter):null;if(null==P||!C?.anchor||!M)return n.toast.error(e("balanceStillLoading")),null;let _=(0,m.planArmadaPull)(r,x,P);if("enough"===_.kind)return{spendRaw:r,pulled:!1};if("uncoverable"===_.kind)return n.toast.error(e("amountExceedsProfileBalance")),null;let A=C.anchor;N(!0);try{let e=await S({requestedUsd:_.pullUsd,submit:()=>j({marketMint:M,side:A.side,collateralAmount:_.pullUsd,currentPrice:A.markPrice,slippageBps:g.DEFAULT_SLIPPAGE_BPS,profileIndex:t,underwriter:A.underwriter,sunriseMarginMode:"cross",silent:!0}),readMargin:()=>(0,f.fetchSunriseMargin)(p,t,null),cancelled:()=>!l()});if(w.invalidateQueries({queryKey:(0,f.sunriseMarginWalletKey)(p)}),!e)return null;let i=Date.now()+6e4;for(;l()&&Date.now()<i;){let e=(0,m.landedSpendRaw)(await T(t),r);if(null!==e)return{spendRaw:e,pulled:!0};await new Promise(e=>setTimeout(e,2e3))}return l()&&n.toast.info(s),null}catch(r){let t=(0,h.armadaWithdrawRefusal)(r,Date.now());return(0,u.isSunriseArriving)(r)?n.toast.info((0,d.displayClientError)(r)):t?(w.invalidateQueries({queryKey:(0,f.sunriseMarginWalletKey)(p)}),n.toast.info("moreShortly"===t.kind?e("moreAvailableShortly"):null!=t.availableAt?e("settlingRefusedAt",{time:(0,h.formatSettlingTime)(t.availableAt,Date.now(),b)}):e("settlingRefused"))):(0,c.isUserRejection)(r)||n.toast.error(a),null}}finally{G=!1,N(!1)}},[v,T,e,b,S,j,w]),pulling:k}}},706405,e=>{"use strict";var t=e.i(634692),r=e.i(190459),i=e.i(183023),s=e.i(942553),n=e.i(116082),a=e.i(267912),l=e.i(519527),o=e.i(727322);e.i(875574);var d=e.i(142298),c=e.i(616861),u=e.i(999069),h=e.i(124431),p=e.i(894771);e.s(["useCreatePair",0,function(){let{openPositionViaPassthrough:e,preflightOpenPosition:m}=(0,o.useTradeActions)(),{wallet:f,signMessage:x}=(0,d.useUnifiedWallet)(),{jwt:g,walletPubkey:b}=(0,c.useMobileAuth)(),{jwt:v,walletPubkey:y}=(0,u.useSponsorGas)(),{balances:w}=(0,h.useProfileBalance)(),{activeProfileIndex:j,activeProfileMarginMode:S,activeProfileExcludedVenues:k}=(0,p.useProfile)(),N=(0,t.useSunriseOpensAllowed)(),P=(0,s.useTranslations)("carry"),[T,C]=(0,i.useState)(!1);return{createPair:(0,i.useCallback)(async t=>{let{pair:i,collateralUsd:s,leverage:o,mintFor:d,legMarketFor:c,priceFor:u}=t,h=v||g,p=(y||b)?.toBase58()??f?.publicKey?.toBase58();if(!p)return n.toast.error(P("connectWallet")),null;let T=[{symbol:i.longSymbol,venue:i.longLeg.underwriter},{symbol:i.shortSymbol,venue:i.shortLeg.underwriter}].find(({venue:e})=>k.includes(e)||"armada"===e&&!N);if(T)return n.toast.error(P("notListed",{symbol:T.symbol})),null;let M=d(i.longSymbol),_=d(i.shortSymbol),A=c(i.longSymbol,i.longLeg.underwriter),E=c(i.shortSymbol,i.shortLeg.underwriter);if(!M||!_||!A||!E){let e=M&&A?i.shortSymbol:i.longSymbol;return n.toast.error(P("notListed",{symbol:e})),null}if(!(s>0)||!(o>0))return n.toast.error(P("enterCollateralAndLeverage")),null;let L=w.USDC;if(null!==L&&L<s)return n.toast.error(P("notEnoughUsdc",{needed:`$${s.toFixed(2)}`,held:`$${L.toFixed(2)}`})),null;C(!0);try{let t=j??0,d=(0,l.buildPairLegs)({underwriter:(0,r.underwriterLiteralFrom)(i.longLeg.underwriter),profileIndex:t,long:{symbol:i.longSymbol,legMarket:A},short:{symbol:i.shortSymbol,legMarket:E,underwriter:(0,r.underwriterLiteralFrom)(i.shortLeg.underwriter)}}),c=(e,r,s,n)=>({marketMint:r,profileIndex:t,side:s,collateralAmount:n,sizeUsd:n*o,leverage:o,underwriter:"long"===s?i.longLeg.underwriter:i.shortLeg.underwriter,sunriseSeat:"armada"===("long"===s?i.longLeg:i.shortLeg).underwriter?+("unified"!==S):void 0,slippageBps:150,currentPrice:u(e)??0}),[f,g]=await Promise.all([m(c(i.longSymbol,M,"long",s*i.wABps/1e4)),m(c(i.shortSymbol,_,"short",s*i.wBBps/1e4))]);if(null===f||null===g)return null;let b=f.ok?g.ok?null:{symbol:i.shortSymbol,reason:g.error}:{symbol:i.longSymbol,reason:f.error};if(b)return n.toast.error(P("legWouldBeRejected",{symbol:b.symbol,reason:b.reason??""}),{duration:1e4}),null;let v=await (0,a.createPairLink)(p,`${i.longSymbol}/${i.shortSymbol}`,d,h?void 0:x,h??void 0),y=s*v.wABps/1e4,w=s*v.wBBps/1e4,k=async(t,r,i,s)=>e(c(t,r,i,s)),N=await k(i.longSymbol,M,"long",y);if(!N)return n.toast.error(P("longLegNotPlaced",{symbol:i.longSymbol})),{link:v,longSignature:null,shortSignature:null};let T=await k(i.shortSymbol,_,"short",w);if(!T)return n.toast.error(P("shortLegNotPlaced",{long:i.longSymbol,short:i.shortSymbol}),{duration:15e3}),{link:v,longSignature:N,shortSignature:null};return n.toast.success(P("pairOpened",{long:i.longSymbol,short:i.shortSymbol,splitA:(v.wABps/100).toFixed(0),splitB:(v.wBBps/100).toFixed(0)})),{link:v,longSignature:N,shortSignature:T}}catch(t){let e=t instanceof Error?t.message:"unknown error";return n.toast.error(P("couldNotOpen",{reason:e})),null}finally{C(!1)}},[e,m,f,x,g,b,v,y,w.USDC,j,S,k,N,P]),isSubmitting:T}}])},419636,e=>{"use strict";var t=e.i(183023),r=e.i(116082),i=e.i(894771),s=e.i(875574),n=e.i(936548);e.s(["useFundingEntry",0,function(e,a){let{publicKey:l}=(0,s.useUnifiedWalletContext)(),{activeProfileIndex:o,createdProfiles:d,hasLoadedProfiles:c,ensureTradingProfile:u,setActiveProfileIndex:h}=(0,i.useProfile)(),[p,m]=(0,t.useState)(!1),f=(0,t.useRef)(!1),x=(0,t.useRef)(null),g=l?.toBase58();return(0,t.useEffect)(()=>(x.current={},()=>{x.current=null}),[g]),{startFunding:async t=>{if(!l||!c||f.current)return;if(d.some(e=>e.index===o))return void e(t);if(0===d.length){"deposit"===t&&a();return}let i=x.current;f.current=!0,m(!0);try{let r=await u();if(x.current!==i||!i)return;h(r),e(t)}catch(e){x.current===i&&i&&r.toast.error((0,n.displayClientError)(e))}finally{f.current=!1,m(!1)}},pending:p,needsSetup:!!l&&c&&0===d.length,disabled:!l||!c||p}}])},594651,917898,392836,e=>{"use strict";e.s(["assetToMint",()=>y,"useOrderLines",()=>j],594651);
2var t=e.i(183023),r=e.i(687229),i=e.i(653982);e.i(965155);var s=e.i(541043),n=e.i(643459),a=e.i(622463),l=e.i(722732),o=e.i(613448),d=e.i(828047),c=e.i(323116),u=e.i(134138);function h(e,t,r){let i,s,n,a=e.ratchet,l="long"===e.side,o="ratchet_entry"===e.orderType||"fib_ratchet_entry"===e.orderType,d="fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType,h=l!==o;if(d){let e=Math.abs(a.ratchetSize-a.worstPrice),t=(0,c.fibFirstThreshold)(a.isReverseFib??!1)*e/c.FIB_RATIO_SCALE;i=h?a.worstPrice+t:a.worstPrice-t}else i=h?a.worstPrice+a.ratchetSize:a.worstPrice-a.ratchetSize;let p=r??(a.bestPriceSeen>0?a.bestPriceSeen:t??0);void 0!==t&&(o?l&&t<p?p=t:!l&&t>p&&(p=t):l&&t>p?p=t:!l&&t<p&&(p=t));let m=d?function(e,t,r,i=!1){let s=Math.abs(t-e);if(s<=0)return 0;let n=((t<e?r<=e:r>=e)?Math.abs(r-e):0)*c.FIB_RATIO_SCALE/s,a=(0,c.fibLevel)(n,i),l=i?5-a:a;return s*c.FIB_RATIOS[l]/c.FIB_RATIO_SCALE}(a.worstPrice,a.ratchetSize,p,a.isReverseFib):a.ratchetSize;if(s=o?l?Math.min(p+m,a.worstPrice):Math.max(p-m,a.worstPrice):l?Math.max(p-m,a.worstPrice):Math.min(p+m,a.worstPrice),d){let e=Math.abs(a.ratchetSize-a.worstPrice),t=(a.ratchetSize<a.worstPrice?p<=a.worstPrice:p>=a.worstPrice)?Math.abs(p-a.worstPrice):0;n=e>0&&t*c.FIB_RATIO_SCALE/e>=(0,c.fibFirstThreshold)(a.isReverseFib??!1)}else n=h?p>=a.worstPrice+a.ratchetSize:p<=a.worstPrice-a.ratchetSize;let f="ratchet"===e.orderType?a.stopTriggerPrice??0:0,x=!n&&(0,u.isRatchetStopTripped)(f,a.bestPriceSeen,l);return{ratchet:a,isLong:l,dragPrice:i,liveTrigger:s,isTracking:n,bestKnown:p,stopTrigger:f,isStopArmed:x}}function p(e,r,i){let[s,n]=(0,t.useState)(()=>new Map),a=function(e,t,r,i){let s=new Map;for(let n of t){let t="dca_ratchet"===n.orderType?n.dcaRatchet:"dca_ratchet_close"===n.orderType?n.dcaRatchetClose:void 0,a=["ratchet","ratchet_entry","fib_ratchet","fib_ratchet_entry"].includes(n.orderType)?n.ratchet:void 0;if(!a&&!t||t&&t.legsExecuted>=t.numLegs)continue;let l="ratchet_entry"===n.orderType||"fib_ratchet_entry"===n.orderType||"dca_ratchet"===n.orderType,o=JSON.stringify([n.wallet,n.marketMint,n.profileIndex,n.underwriter,n.hedgeVenue,n.side,n.orderType,t?.legsExecuted]),d=s.get(n.orderPda)??e.get(n.orderPda),c=function(e,...t){let r=t.filter(e=>"number"==typeof e&&Number.isFinite(e)&&e>0);return 0===r.length?0:e?Math.max(...r):Math.min(...r)}("long"===n.side!==l,d?.identity===o?d.price:void 0,(a??t)?.bestPriceSeen,i?i(n):r);s.set(n.orderPda,{identity:o,price:c})}return s.size===e.size&&[...s].every(([t,r])=>{let i=e.get(t);return i?.identity===r.identity&&i.price===r.price})?e:s}(s,e,r,i);return a!==s&&n(a),a}e.s(["getRatchetInfo",0,h],917898),e.s(["useRatchetPrices",0,p],392836);var m=e.i(596331),f=e.i(670374),x=e.i(406470),g=e.i(26826),b=e.i(308759),v=e.i(299959);function y(e,t){let r=i.ASSET_TO_MINT[e];if(r)return r;let c=(0,o.pairsMintForPosition)(e,t);if(c)return c;for(let[t,r]of Object.entries(s.MINT_TO_PYTH_SYMBOL))if(r===e)return t;let u=(0,n.mintForSymbol)(e);if(u)return u;let h=(0,a.getGlobalPhoenixRegistry)();if(h){let t=h.getMarketBySymbol(e);if(t)return t.orderbook.toBase58()}let p=(0,l.getGlobalGmTradeRegistry)();if(p){let t=p.getMarketBySymbol(e)??p.getMarketBySymbol(e.toUpperCase());if(t)return t.indexTokenMint.toBase58()}if((0,d.sunriseListsSymbol)(e))return e.toUpperCase()}function w(e,t){return!!e.marketMint&&(0,r.mintToMatchingKey)(e.marketMint)===(0,r.mintToMatchingKey)(t)}function j({positions:e,orders:i,marketMint:s,livePrice:n,livePriceForVenue:o,activeProfileIndex:d,enabled:c,labelMode:u="pnl"}){let h=(0,v.useFormatters)(),P=p(c?[...e.filter(e=>{let t=y(e.asset,e.underwriter);return t&&(0,r.mintToMatchingKey)(t)===(0,r.mintToMatchingKey)(s)&&(0,b.matchesProfile)(e.profileIndex,d)}).flatMap(e=>e.tpslOrders),...i.filter(e=>w(e,s)&&(0,b.matchesProfile)(e.profileIndex,d))]:[],n,o?e=>o(e.underwriter):void 0),T=(0,a.getPhoenixRegistryVersion)(),C=(0,l.getGmTradeRegistryVersion)();return(0,t.useMemo)(()=>{if(!c)return[];let t=h.intlTag,a=[],l=new Set;for(let i of e){let e=y(i.asset,i.underwriter);if(!e||(0,r.mintToMatchingKey)(e)!==(0,r.mintToMatchingKey)(s)||!(0,b.matchesProfile)(i.profileIndex,d)||"open"!==i.status&&"pending"!==i.status)continue;let l=o?o(i.underwriter):n,c=(0,b.chartLinePrice)(i.entryPrice);if(null!==c){let e="long"===i.side?"Long":"Short",r=`${e} Entry $${(0,b.fmtPrice)(c,t)}`;if("size"===u){let t=i.apiData?.sizeTokenAmount??String(parseFloat(i.sizeUsd)/c),s=(0,x.formatSizeTokens)(t,i.asset,h.intlTag);
2s&&(r=`${e} Size: ${s} (${(0,x.formatRawUsd)(i.sizeUsd,h.intlTag)})`)}else if(void 0!==l&&l>0&&i.apiData){let{pnlUsd:t,pnlPercent:s}=(0,f.calculateLivePnl)(i.apiData,l),n=s>=0?"+":"-";r=`${e} PnL: ${(0,x.formatPnlNumber)(t,h.intlTag)} (${n}${h.fixed(Math.abs(s),2)}%)`}a.push({id:(0,b.positionLineId)("entry",i.positionPda,i.asset,i.side),price:c,color:"long"===i.side?"#34d399":"#f87171",label:r,lineStyle:"dashed"})}let p=i.apiData?(0,f.displayLiquidationPriceForLifecycle)(i.apiData):(0,g.quotableLiquidationPrice)(i.liquidationPrice),m=(0,b.chartLinePrice)(p);null!==m&&a.push({id:(0,b.positionLineId)("liq",i.positionPda,i.asset,i.side),price:m,color:"#f59e0b",label:`Liq $${(0,b.fmtPrice)(m,t)}`,lineStyle:"dashed"})}for(let i of e){let e=y(i.asset,i.underwriter);if(e&&(0,r.mintToMatchingKey)(e)===(0,r.mintToMatchingKey)(s)&&(0,b.matchesProfile)(i.profileIndex,d)){for(let e of i.tpslOrders)if(!l.has(e.orderPda)&&(!e.marketMint||(0,r.mintToMatchingKey)(e.marketMint)===(0,r.mintToMatchingKey)(s))){if(l.add(e.orderPda),"tp"===e.orderType){let r=parseFloat(e.triggerPriceUsd);if(r>0){let n={orderPda:e.orderPda,orderType:"tp",positionPda:i.positionPda,source:e.source,profileIndex:e.profileIndex??i.profileIndex,side:i.side,sizeUsd:parseFloat(e.sizeUsd),marketMint:s,underwriter:e.underwriter??i.underwriter};a.push({id:`tp-${e.orderPda}`,price:r,color:"#34d399",label:`TP $${(0,b.fmtPrice)(r,t)}`,lineStyle:"solid",draggable:!0,dragMeta:n})}}else if("sl"===e.orderType){let r=parseFloat(e.triggerPriceUsd);if(r>0){let n={orderPda:e.orderPda,orderType:"sl",positionPda:i.positionPda,source:e.source,profileIndex:e.profileIndex??i.profileIndex,side:i.side,sizeUsd:parseFloat(e.sizeUsd),marketMint:s,underwriter:e.underwriter??i.underwriter};a.push({id:`sl-${e.orderPda}`,price:r,color:"#f87171",label:`SL $${(0,b.fmtPrice)(r,t)}`,lineStyle:"solid",draggable:!0,dragMeta:n})}}("ratchet"===e.orderType||"ratchet_entry"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType)&&e.ratchet&&S(a,e,o?o(e.underwriter):n,P,h.intlTag),("dca_ratchet"===e.orderType||"dca_ratchet_close"===e.orderType)&&(e.dcaRatchet||e.dcaRatchetClose)&&k(a,e,o?o(e.underwriter):n,P,h.intlTag),"dca_close"===e.orderType&&e.dcaClose&&N(a,e,h.intlTag)}}}for(let e of i)if(!l.has(e.orderPda)&&w(e,s)&&(0,b.matchesProfile)(e.profileIndex,d))if(l.add(e.orderPda),"tp"===e.orderType){let r=parseFloat(e.triggerPriceUsd);r>0&&a.push({id:`tp-${e.orderPda}`,price:r,color:"#34d399",label:`TP $${(0,b.fmtPrice)(r,t)}`,lineStyle:"dashed"})}else if("sl"===e.orderType){let r=parseFloat(e.triggerPriceUsd);r>0&&a.push({id:`sl-${e.orderPda}`,price:r,color:"#f87171",label:`SL $${(0,b.fmtPrice)(r,t)}`,lineStyle:"dashed"})}else if(("ratchet"===e.orderType||"ratchet_entry"===e.orderType||"fib_ratchet"===e.orderType||"fib_ratchet_entry"===e.orderType)&&e.ratchet)S(a,e,o?o(e.underwriter):n,P,h.intlTag);else if("limit"===e.orderType){let r=parseFloat(e.triggerPriceUsd);if(r>0){let i="long"===e.side?"Long":"Short";a.push({id:`limit-${e.orderPda}`,price:r,color:"#60a5fa",label:`Limit ${i} $${(0,b.fmtPrice)(r,t)}`,lineStyle:"dashed"})}}else"dca"===e.orderType&&e.dca?function(e,t,r){let i=t.dca;if(i.numLegs<=0)return;let s=i.legsExecuted;if(s>=i.numLegs)return;let n=t.collateralAmount??0,a=1===i.numLegs?i.startPrice:i.startPrice+s*(i.endPrice-i.startPrice)/(i.numLegs-1),l=m.PassthroughClient.calculateDcaLegCollateral(n,i.numLegs,i.weightingType,s),o=`DCA ${s+1}/${i.numLegs} $${(0,b.fmtPrice)(a,r)} ($${(0,b.fmtPrice)(l,r)})`;e.push({id:`dca-${t.orderPda}-${s}`,price:a,color:"#22d3ee",label:o,lineStyle:"dashed"})}(a,e,h.intlTag):"dca_close"===e.orderType&&e.dcaClose?N(a,e,h.intlTag):("dca_ratchet"===e.orderType||"dca_ratchet_close"===e.orderType)&&(e.dcaRatchet||e.dcaRatchetClose)&&k(a,e,o?o(e.underwriter):n,P,h.intlTag);return a},[e,i,s,n,o,d,c,u,T,C,h,P])}function S(e,t,r,i,s){let n="fib_ratchet"===t.orderType||"fib_ratchet_entry"===t.orderType,a=n?"#e879f9":"#60a5fa",l=i.get(t.orderPda)?.price,o=h(t,r,l||void 0),d=n?"Fib Trailing SL":"Trailing SL";(o.isTracking||o.isStopArmed)&&e.push({id:`ratchet-trigger-${t.orderPda}`,price:o.liveTrigger,color:a,label:`${d} $${(0,b.fmtPrice)(o.liveTrigger,s)}`,lineStyle:"solid"}),o.isTracking||e.push({id:o.isStopArmed?`ratchet-activation-${t.orderPda}`:`ratchet-trigger-${t.orderPda}`,price:o.dragPrice,color:a,label:`${d} Activation $${(0,b.fmtPrice)(o.dragPrice,s)}`,lineStyle:"dashed"}),!(o.stopTrigger>0)||o.isTracking||o.isStopArmed||e.push({id:`ratchet-stop-trigger-${t.orderPda}`,price:o.stopTrigger,color:a,label:`${d} Stop Trigger $${(0,b.fmtPrice)(o.stopTrigger,s)}`,lineStyle:"dashed"})}function k(e,t,r,i,s){let n=t.dcaRatchet??t.dcaRatchetClose;if(!n||n.legsExecuted>=n.numLegs)return;let a="long"===t.side,l=t.dcaRatchetClose?a:!a,o="#22d3ee",d=i.get(t.orderPda)?.price??0,c=n.priceLimit,u=n.ratchetSize,h=l?c+u:c-u,p=d>0&&(l?d>=c+u:d<=c-u),m=`DCA Trailing ${n.legsExecuted+1}
2/${n.numLegs}`;if(p){let r=l?Math.max(d-u,c):Math.min(d+u,c);e.push({id:`dca-ratchet-trigger-${t.orderPda}`,price:r,color:o,label:`${m} Trigger $${(0,b.fmtPrice)(r,s)}`,lineStyle:"solid"}),e.push({id:`dca-ratchet-fill-${t.orderPda}`,price:h,color:`${o}80`,label:`${m} Fill $${(0,b.fmtPrice)(h,s)}`,lineStyle:"dashed"})}else e.push({id:`dca-ratchet-trigger-${t.orderPda}`,price:h,color:o,label:`${m} Trigger $${(0,b.fmtPrice)(h,s)}`,lineStyle:"dashed"})}function N(e,t,r){let i=t.dcaClose;if(i.numLegs<=0)return;let s=i.legsExecuted;if(s>=i.numLegs)return;let n=1===i.numLegs?i.startPrice:i.startPrice+s*(i.endPrice-i.startPrice)/(i.numLegs-1),a=`DCA Close ${s+1}/${i.numLegs} $${(0,b.fmtPrice)(n,r)}`;e.push({id:`dca-close-${t.orderPda}-${s}`,price:n,color:"#22d3ee",label:a,lineStyle:"dashed"})}},78091,692923,e=>{"use strict";var t=e.i(894771),r=e.i(578866),i=e.i(634692),s=e.i(942289),n=e.i(183023),a=e.i(76990),l=e.i(157157),o=e.i(808414);e.i(654249);var d=e.i(360525),c=e.i(601852);function u(e){let t=[],r=e.hedgeQualityWarnBelow??.45,i=e.carryDominanceWarnAboveDays??180,s=e.betaDriftWarnAbove??.2;for(let n of e.stats){if(n.correlation<e.minCorrelation||!(n.spreadDailyVol>0))continue;let a=(0,d.hedgeQuality)(n.correlation),l=n.wABps/1e4,o=n.wBBps/1e4,u=(0,c.selectCarryVenue)(e.capabilitiesBySymbol.get(n.longSymbol)??[],{},e.fundingRates?.get(n.longSymbol.toUpperCase()),"long",e.notionalUsd*l,e.costHorizonHours,e.leverage),h=(0,c.selectCarryVenue)(e.capabilitiesBySymbol.get(n.shortSymbol)??[],{},e.fundingRates?.get(n.shortSymbol.toUpperCase()),"short",e.notionalUsd*o,e.costHorizonHours,e.leverage);if(!u||!h)continue;let p=u.carryPerDayUsd+h.carryPerDayUsd,m=u.costExBorrowUsd+h.costExBorrowUsd,f=(0,d.scorePair)(p,n.spreadDailyVol);if(null===f)continue;let x=n.spreadDailyVol*e.notionalUsd,g=(0,d.carryDominanceDays)(p,x),b=(0,d.betaDrift)(n.beta,n.betaRecent);t.push({key:`${n.longSymbol}/${n.shortSymbol}`,longSymbol:n.longSymbol,shortSymbol:n.shortSymbol,beta:n.beta,betaIsFallback:n.betaIsFallback,wABps:n.wABps,wBBps:n.wBBps,correlation:n.correlation,spreadDailyVol:n.spreadDailyVol,zScore:n.zScore??null,overlapBars:n.overlapBars,netCarryPerDayUsd:p,roundTripFeeUsd:m,breakEvenHours:(0,d.breakEvenHours)(p,m),score:f,hedgeQuality:a,hedgeWeak:a<r,carryDominanceDays:g,payoffSlow:null===g||g>i,probProfitAtDominance:null===g?null:(0,d.probProfitAt)(p,m,x,g),recommendedMaxLeverage:null===g?null:(0,d.recommendedMaxLeverage)(n.spreadDailyVol,g),betaDrift:b,betaUnstable:null!==b&&b>s,longLeg:u,shortLeg:h})}return t.sort((e,t)=>t.score-e.score),t}e.s(["TOP_PAIRS_LIMIT",0,12,"rankPairs",0,u],692923),e.s(["usePairAnalysis",0,function(e){let d=e.enabled??!0,{stats:c,isLoading:h,isError:p}=(0,o.usePairStats)(d),m=function(e){let{data:l}=(0,a.usePhoenixMarkets)(),{data:o}=(0,r.useSunriseMarkets)(),d=(0,i.useSunriseOpensAllowed)(),{activeProfileExcludedVenues:c}=(0,t.useProfile)();return(0,n.useMemo)(()=>{let t=new Map;for(let r of e){let e=l?.find(e=>e.symbol===r),i=d?o?.find(e=>e.symbol.toUpperCase()===r.toUpperCase()):null;t.set(r,(0,s.buildCapabilities)({asset:r,phoenixMarket:e?{maxLeverage:e.maxLeverage,takerFeeMicro:e.takerFeeMicro,makerFeeMicro:e.makerFeeMicro}:null,sunriseMarket:i?.liquidation&&Number.isFinite(i.liquidation.fee1e6)&&i.liquidation.fee1e6>=0?{...i,feeBps:i.liquidation.fee1e6/100}:null,jupiterSupported:!1}).filter(e=>!s.OPENS_PAUSED_VENUES.has(e.venue)&&!c.includes(e.venue)))}return t},[e,l,o,d,c])}((0,n.useMemo)(()=>c?.symbols.map(e=>e.symbol)??[],[c])),{pairs:f,symbols:x}=(0,n.useMemo)(()=>(function(e,t,r){if(!e)return{pairs:[],symbols:[]};let i=new Set(e.symbols.filter(e=>r.get(e.symbol)?.some(e=>e.supported)).slice(0,t).map(e=>e.symbol));return{pairs:e.pairs.filter(e=>i.has(e.longSymbol)&&i.has(e.shortSymbol)),symbols:e.symbols.filter(e=>i.has(e.symbol))}})(c,e.universeCap,m),[c,e.universeCap,m]),g=(0,n.useMemo)(()=>x.map(e=>e.symbol),[x]),{data:b}=(0,l.useFundingRates)();return{candidates:(0,n.useMemo)(()=>u({stats:f,symbolStats:x,capabilitiesBySymbol:m,fundingRates:b,notionalUsd:e.notionalUsd,costHorizonHours:168,leverage:e.leverage,minCorrelation:e.minCorrelation}),[f,x,m,b,e.notionalUsd,e.leverage,e.minCorrelation]),universe:g,isLoading:h,isError:p,assetsWithData:x.length}}],78091)},656526,406513,e=>{"use strict";e.s(["usePairOpenResolvers",()=>m],656526),e.s(["useAllMarkets",()=>u],406513);var t=e.i(578866),r=e.i(183023),i=e.i(894771),s=e.i(76990),n=e.i(403628),a=e.i(824088),l=e.i(634692),o=e.i(942289);e.i(889723);var d=e.i(49332),c=e.i(465217);function u(){let{data:e}=(0,s.usePhoenixMarkets)(),{data:u}=(0,n.useGmTradeMarkets)(),{symbols:h,indexTokens:p}=(0,a.useGmTradeMarketMetadata)(),{data:m}=(0,t.useSunriseMarkets)(),f=(0,l.useSunriseOpensAllowed)(),{activeProfileExcludedVenues:x}=(0,i.useProfile)(),g=f&&!x.includes("armada");return(0,r.useMemo)(()=>{let t=new Map;for(let[e,r]of Object.entries(d.JUPITER_MARKETS))t.set(r.symbol,{mint:e,...r,leverageByUnderwriter:{},underwriters:["jupiter"]});if(e&&e.length>0)for(let r of e){let e=r.maxLeverage>0&&isFinite(r.maxLeverage)?r.maxLeverage:20,i=(0,o.phoenixEffectiveMaxLeverage)(e,r.takerFeeMicro),s=t.get(r.symbol);s?(s.underwriters.includes("phoenix")||s.underwriters.push("phoenix"),s.leverageByUnderwriter.phoenix=i):t.set(r.symbol,{mint:d.CORE_SYMBOL_TO_MINT[r.symbol]??r.symbol,symbol
2:r.symbol,name:r.symbol,image:(0,c.getFlashTokenImage)(r.symbol,r.logoUri),leverageByUnderwriter:{phoenix:i},underwriters:["phoenix"]})}if(u&&u.length>0)for(let e of u){if((0,d.isNonTradeableQuoteSymbol)(e.symbol))continue;let r=t.get(e.symbol);r?r.underwriters.includes("gmtrade")||r.underwriters.push("gmtrade"):t.set(e.symbol,{mint:e.symbol,symbol:e.symbol,name:e.symbol,image:(0,c.getFlashTokenImage)(e.symbol),leverageByUnderwriter:{},underwriters:["gmtrade"]})}for(let e of h){if((0,d.isNonTradeableQuoteSymbol)(e))continue;let r=p.get(e)?.maxLeverage;if(t.has(e)){let i=t.get(e);i.underwriters.includes("gmtrade")||i.underwriters.push("gmtrade"),r&&(i.leverageByUnderwriter.gmtrade=r)}else t.set(e,{mint:e,symbol:e,name:e,image:(0,c.getFlashTokenImage)(e),leverageByUnderwriter:r?{gmtrade:r}:{},underwriters:["gmtrade"]})}for(let e of g?m??[]:[]){let r=t.get(e.symbol);r?(r.underwriters.includes("armada")||r.underwriters.push("armada"),r.leverageByUnderwriter.armada=e.maxLeverage):t.set(e.symbol,{mint:e.symbol,symbol:e.symbol,name:e.symbol,image:(0,c.getFlashTokenImage)(e.symbol),leverageByUnderwriter:{armada:e.maxLeverage},underwriters:["armada"]})}for(let e of t.values()){let t=Object.entries(e.leverageByUnderwriter).filter(([e])=>!o.OPENS_PAUSED_VENUES.has(e)).map(([,e])=>e).filter(e=>"number"==typeof e&&isFinite(e)&&e>0);e.maxLeverage=t.length>0?Math.max(...t):void 0}return[...t.values()]},[e,u,h,p,m,g])}e.i(965155);var h=e.i(22156),p=e.i(541043);function m(){let e=u(),{data:i}=(0,s.usePhoenixMarkets)(),{data:n}=(0,t.useSunriseMarkets)(),{prices:a}=(0,h.useAllMarketsPricesThrottled)(),l=(0,r.useCallback)(t=>e.find(e=>e.symbol.toUpperCase()===t.toUpperCase())?.mint??null,[e]),o=(0,r.useCallback)((e,t)=>"armada"===t?n?.find(t=>t.symbol.toUpperCase()===e.toUpperCase())?.symbol??null:"phoenix"!==t?null:i?.find(t=>t.symbol.toUpperCase()===e.toUpperCase())?.orderbook??null,[i,n]);return{mintFor:l,legMarketFor:o,priceFor:(0,r.useCallback)(t=>{let r=e.find(e=>e.symbol.toUpperCase()===t.toUpperCase());return r?a[p.MINT_TO_PYTH_SYMBOL[r.mint]??r.symbol]??null:null},[e,a]),maxLeverageFor:(0,r.useCallback)((e,t)=>{var r,s;if("armada"===t)return n?.find(t=>t.symbol.toUpperCase()===e.toUpperCase())?.maxLeverage??null;if("phoenix"!==t)return null;let a=(i??[]).find(t=>t.symbol.toUpperCase()===e.toUpperCase());return a?(r=a.maxLeverage,s=a.takerFeeMicro,!Number.isFinite(r)||r<=0?19
2:Math.max(Math.floor(r/(1+r*((s>0&&Number.isFinite(s)?s:0)+0)/1e6)*100)/100,1)):null},[i,n])}}},728570,e=>{"use strict";var t=e.i(183023),r=e.i(111526),i=e.i(717421),s=e.i(622463);e.s(["isPhoenixOrderGoneFromBook",0,function(e,t,r,i,s,n=5e3){if(!t)return!1;let a=e.venueOrderState;return!!a&&"phoenix"===a.underwriter&&"resting_limit"===a.data.kind&&!!t.orderbookLoaded&&!t.isLive&&(null==s||!(s>0)||!(t.orderbookSlot<=s))&&null!=i&&!(r-i<n)},"usePhoenixOrderbookFills",0,function(e){let{accounts:n,subscribe:a,unsubscribe:l}=(0,i.useAccountSubscriptionContext)(),o=(0,t.useRef)([]),[d,c]=(0,t.useState)(0);(0,t.useEffect)(()=>(0,s.subscribePhoenixRegistry)(()=>c(e=>e+1)),[]);let u=(0,t.useMemo)(()=>{let t=(0,s.getGlobalPhoenixRegistry)();return t?e.map(e=>{if("executed"===e.status||"cancelled"===e.status||"deleted"===e.status)return null;let r=e.venueOrderState;if(!r||"phoenix"!==r.underwriter||"resting_limit"!==r.data.kind||!e.marketMint)return null;let i=(0,s.resolvePhoenixSymbol)(e.marketMint);if(!i)return null;let n=t.getMarketBySymbol(i);if(!n)return null;let a=r.data;return{orderPda:e.orderPda,orderbook:n.orderbook.toBase58(),priceInTicks:BigInt(a.price_in_ticks),encodedSeq:BigInt(a.order_sequence_number),initialBaseLots:a.initial_base_lots,indexerRemaining:a.remaining_base_lots}}).filter(e=>null!=e):[]},[e,d]);return(0,t.useEffect)(()=>{let e=Array.from(new Set(u.map(e=>e.orderbook))),t=new Set(o.current),r=new Set(e),i=e.filter(e=>!t.has(e)),s=o.current.filter(e=>!r.has(e));i.length&&a(i),s.length&&l(s),o.current=e},[u,a,l]),(0,t.useEffect)(()=>()=>{o.current.length&&(l(o.current),o.current=[])},[l]),(0,t.useMemo)(()=>{let e=new Map;for(let t of u){let i=n.get(t.orderbook),s=null,a=!!i?.data&&!i.isDeleted,l=i?.slot??0;a&&(s=function(e,t,r){if(e.length<32)return null;let i=e.length-32;for(let s=0;s<=i;s++)if(e.readBigUInt64LE(s)===t&&e.readBigUInt64LE(s+8)===r)return Number(e.readBigUInt64LE(s+24));return null}(r.Buffer.from(i.data,"base64"),t.priceInTicks,t.encodedSeq));let o=s??t.indexerRemaining,d=t.initialBaseLots,c=d>0?Math.max(0,Math.min(1,1-o/d)):0;e.set(t.orderPda,{remainingBaseLots:o,initialBaseLots:d,fillFraction:c,isLive:null!=s,orderbookLoaded:a,orderbookSlot:l})}return e},[u,n])}])},347554,e=>{"use strict";e.s(["usePortfolioValues",()=>c],347554);var t=e.i(435023),r=e.i(494286),i=e.i(183023),s=e.i(687229),n=e.i(894771),a=e.i(122097);e.i(875574);var l=e.i(142298),o=e.i(520639),d=e.i(670374);function c(){let{positions:e,orders:c,isLoading:u}=(0,s.useUnifiedPositions)(),{createdProfiles:h}=(0,n.useProfile)(),{balances:p,isLoading:m,isStale:f}=(0,a.useAllProfileUsdcBalances)(h),{publicKey:x}=(0,l.useUnifiedWallet)(),{usdcBalance:g,isLoading:b}=(0,o.useUserTokenAccounts)(x),v=(0,t.useQueries)({queries:h.map(e=>({queryKey:(0,r.sunriseMarginQueryKey)(x?.toBase58()??null,e.index,null),queryFn:()=>(0,r.fetchSunriseMargin)(x.toBase58(),e.index,null),enabled:!!x,staleTime:1e4,refetchInterval:15e3}))});return(0,i.useMemo)(()=>{let t=g??0,i=new Map;h.forEach(e=>{let t=p.get(e.index)??0;i.set(e.index,{profileIndex:e.index,investedValue:0,cashBalance:t,cashUnknown:!1,lockedInOrders:0,unrealizedValue:t})}),c.forEach(e=>{if("decrease"===e.action||"sunrise"===e.underwriter||1===e.fundingStatus)return;let t=e.profileIndex;if(null==t)return;let r=i.get(t);if(r){let t=e.dca??e.dcaTime??e.dcaRatchet;t&&t.legsExecuted>0?r.lockedInOrders+=function(e,t,r,i){if(0===t||i>=t)return 0;if(0===i)return e;let s=0;for(let n=0;n<i;n++)s+=function(e,t,r,i){if(0===t)return 0;switch(r){case 0:{let r=Math.floor(e/t);return i===t-1?e-r*(t-1):r}case 1:{let r=t*(t+1)/2;if(i===t-1){let i=0;for(let s=0;s<t-1;s++)i+=Math.floor(e*(t-s)/r);return e-i}return Math.floor(e*(t-i)/r)}case 2:{let r=t*(t+1)/2;if(i===t-1){let i=0;for(let s=0;s<t-1;s++)i+=Math.floor(e*(s+1)/r);return e-i}return Math.floor(e*(i+1)/r)}default:return Math.floor(e/t)}}(e,t,r,n);return e-s}(e.collateralAmount??0,t.numLegs,t.weightingType,t.legsExecuted):r.lockedInOrders+=e.collateralAmount??0}});let s=0,n=new Set,a=new Set,l=new Set;v.forEach((e,t)=>{let s=e.data?.collateralUsd,o=h[t];if(!o)return;if(null==s||!Number.isFinite(s))return void l.add(o.index);let d=i.get(o.index);if(!d)return;let c=(0,r.armadaAccountFreeUsd)(e.data),u=null==c?0:Math.min(c,s);d.investedValue+=s-u,d.cashBalance+=u,null==c&&l.add(o.index),s>0&&a.add(o.index),n.add(`sunrise:${o.index}`)}
2),e.forEach(e=>{let t,r=e.profileIndex??e.apiData?.profileIndex,l=function(e,t){let r=e.underwriter??e.apiData?.underwriter,i=e.directVenue??e.apiData?.directVenue;if("phoenix"===r&&(e.isPhoenixCrossSeat||i?.marginMode==="cross")){let r=Number.parseFloat(e.phoenixAccountCollateralUsd??i?.accountCollateralUsd??""),s=i?.traderAccount||e.positionPda;if(!Number.isFinite(r)||!s)return 0;let n=`phoenix:${s}`;return t.has(n)?0:(t.add(n),r)}let s=Number.parseFloat(e.collateralUsd??"");if(!Number.isFinite(s))return 0;let n=e.profileIndex??e.apiData?.profileIndex,a=e.isSunriseCrossMargin??null===e.sunriseMarginSeat;if("sunrise"===r&&a&&null!=n){let e=`sunrise:${n}`;if(t.has(e))return 0;t.add(e)}return s}(e,n);(e.underwriter??e.apiData?.underwriter)==="sunrise"&&null!=r&&a.add(r);let o=parseFloat(e.markPrice)||0;if(e.apiData&&o>0){let r={...e.apiData,entryPrice:e.entryPrice,sizeUsd:e.sizeUsd,collateralUsd:e.collateralUsd,totalFeesUsd:e.estimatedFees||e.apiData.totalFeesUsd||"0",side:e.side};t=(0,d.calculateLivePnl)(r,o).unrealizedPnl}else t=parseFloat(e.unrealizedPnl)||0;let c=l+t;if(null==r){s+=c;return}let u=i.get(r);u?u.investedValue+=c:s+=c});let o=0,x=0,y=!1,w=0;return i.forEach(e=>{e.cashUnknown=a.has(e.profileIndex)&&l.has(e.profileIndex),e.cashUnknown&&(y=!0),e.unrealizedValue=e.investedValue+e.cashBalance+e.lockedInOrders,o+=e.investedValue,x+=e.cashBalance,w+=e.lockedInOrders}),{profiles:i,global:{totalInvestedValue:o+s,totalCashBalance:x,cashUnknown:y,walletCashBalance:t,totalLockedInOrders:w,totalUnrealizedValue:o+x+s+t+w},isLoading:u||b||m||v.some(e=>e.isLoading),isStale:f||v.some(e=>e.isError||e.isSuccess&&e.data?.collateralUsd==null)}},[e,c,h,p,m,f,u,g,b,v])}},100555,e=>{"use strict";e.s(["useProfileFunding",()=>V]),e.i(413358);var t=e.i(394390),r=e.i(444080),i=e.i(183023),s=e.i(657645),n=e.i(860991),a=e.i(942553),l=e.i(435023),o=e.i(43690),d=e.i(451620),c=e.i(799227);e.i(943353);var u=e.i(356534),h=e.i(21859),p=e.i(568801),m=e.i(327139),f=e.i(985604),x=e.i(116082),g=e.i(936548),b=e.i(739835),v=e.i(308294);e.i(875574);var y=e.i(142298),w=e.i(894771),j=e.i(124431),S=e.i(122097),k=e.i(307052),N=e.i(432313),P=e.i(596331),T=e.i(938425),C=e.i(801637),M=e.i(711915),_=e.i(999069),A=e.i(821043),E=e.i(299959),L=e.i(308146),F=e.i(369018),R=e.i(616861),D=e.i(797699),I=e.i(858007),U=e.i(494286),O=e.i(491681),B=e.i(702193),z=e.i(538712);let $="https://api.imperial.space";function V({open:e,initialMode:H,onProgress:W,isCurrent:q,resetOnOpen:K=!0}){let G=(0,a.useTranslations)("wallet"),{publicKey:Y,connection:X,sendTransaction:Q,signTransaction:J,signMessage:Z,wallet:ee}=(0,y.useUnifiedWallet)(),{activeProfileIndex:et,activeProfilePda:er,createdProfiles:ei}=(0,w.useProfile)(),{balances:es}=(0,j.useProfileBalance)(),{balances:en}=(0,S.useAllProfileUsdcBalances)(ei),{balanceSol:ea,balanceKnown:el}=(0,M.useSolBalance)(),{isSponsorMode:eo,login:ed}=(0,_.useSponsorGas)(),{isJWTMode:ec}=(0,R.useMobileAuth)(),{pullIntoProfile:eu,pulling:eh}=(0,O.useArmadaAccountPull)(),ep=null!==et?ei.find(e=>e.index===et):null,[em,ef]=(0,i.useState)(H??"deposit"),[ex,eg]=(0,i.useState)(""),eb=(0,E.useDecimalSeparator)(),ev="USDC",[ey,ew]=(0,i.useState)(!1),ej=(0,i.useRef)(e);(0,i.useEffect)(()=>(ej.current=e,()=>{ej.current=!1}),[e]);let[eS,ek]=(0,i.useState)(null),eN=()=>{eg(""),ek(null)},[eP,eT]=(0,i.useState)(et);eP!==et&&(eT(et),eN());let eC=(0,o.useQuery)({queryKey:["active-battle-for-profile",Y?.toBase58(),et],queryFn:()=>(0,d.getActiveBattleForProfile)(Y.toBase58(),et),enabled:e&&!!Y&&null!==et,refetchInterval:3e4}),eM=eC.data?.activeBattle??null,e_=null!==eM&&"deposit"===em,eA=ec&&"deposit"===em,eE="transfer"===em&&(null===eS||eS===et),eL=j.PROFILE_TOKEN_MINTS.find(e=>"USDC"===e.symbol),eF=(0,i.useCallback)(e=>eg((0,A.sanitizeDecimalInput)(e,eb,eL.decimals)),[eb,eL.decimals]),eR=(0,i.useMemo)(()=>(0,L.decimalStringToBaseUnits)(ex,eL.decimals),[ex,eL.decimals]),eD=null===eR?null:Number(eR)/10**eL.decimals,eI=(0,i.useRef)(!1),eU=(0,N.useUsdcWalletBalance)(e?Y??null:null),eO=eU.known?eU.uiBalance:null,eB=eU.refetch,ez=(0,i.useCallback)(async()=>{if(!X||!eU.ata)return null;try{let e=await X.getTokenAccountBalance(eU.ata);return parseFloat(e.value.uiAmountString??"0")}catch{return eO}},[X,eU.ata,eO]);(0,i.useEffect)(()=>{e&&(ef(H??"deposit"),K&&eN())},[e,H,K]),(0,i.useEffect)(()=>
2{if("transfer"!==em||null!==eS)return;let e=ei.find(e=>e.index!==et);e&&ek(e.index)},[em,eS,ei,et]);let e$=es[ev],eV=(0,U.useSunriseMargin)(Y?.toBase58()??null,et,null,e),eH=(0,U.armadaAccountWithdrawableUsd)(eV.data),eW=null!=eH||eV.isError||!Y,eq=eW?(0,B.spendableWithArmadaAccount)(e$,eH):null,eK=eW?(0,B.spendableWithArmadaAccount)(e$,(0,z.armadaAccountBalanceUsd)(eV.data)??eH):null,eG="deposit"===em?eO:eq,eY="deposit"===em?null:(0,z.withdrawSettling)(eV.data),eX=(0,z.withdrawSettlingLine)(eY),eQ=Y?.toBase58()??null,eJ=(0,l.useQueries)({queries:ei.map(t=>({queryKey:(0,U.sunriseMarginQueryKey)(eQ,t.index,null),queryFn:()=>(0,U.fetchSunriseMargin)(eQ,t.index,null),enabled:e&&"transfer"===em&&!!eQ,staleTime:1e4,refetchInterval:15e3}))}),eZ=new Map;en.forEach((e,t)=>{let r=ei.findIndex(e=>e.index===t),i=r<0?null:eJ[r]?.data,s=(0,z.armadaAccountBalanceUsd)(i)??(0,U.armadaAccountWithdrawableUsd)(i);eZ.set(t,(0,B.spendableWithArmadaAccount)(e,s)??e)});let{blocked:e0}=(0,k.useProfileLoanBlock)(Y??null,et,e&&"deposit"!==em),e1="deposit"!==em&&e0,e2=(0,i.useCallback)(async()=>{if(ee?.publicKey&&Z)try{let e=ee.publicKey.toBase58(),t=Date.now().toString(),i=`imperial:mobile-connect:${e}:${t}`,s=new TextEncoder().encode(i),n=await Z(s),a=r.default.encode(n),l=await fetch(`${$}/api/v1/mobile/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wallet:e,message:i,signature:a})});if(!l.ok)throw Error("Failed to create session");let{code:o}=await l.json(),d=await fetch(`${$}/api/v1/mobile/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!d.ok)throw Error("Failed to exchange session code");let{jwt:c,expiresAt:u}=await d.json();ed(c,e,u),x.toast.success(G("gaslessEnabled"))}catch(e){(0,b.isUserRejection)(e)||x.toast.error((0,g.displayClientError)(e))}},[ee?.publicKey,Z,ed]),e5=async()=>{if(q&&!q())return{status:"not-started"};let e=null,r=!1,i=e=>{try{W?.(e)}catch(e){console.error("Funding progress observer failed:",e)}},s=t=>{e!==t&&(e=t,i({stage:"submitted",signature:t}))};if(!Y||!X||!J||!Q||!er)return x.toast.error(G("walletNotConnected")),{status:"not-started"};if(null===eR||eR<=BigInt(0))return x.toast.error(G("enterValidAmount")),{status:"not-started"};let a=Number(eR)/10**eL.decimals;if(e1)return x.toast.error(G("transfer"===em?"transferBlockedByLoan":"withdrawBlockedByLoan")),{status:"not-started"};if("deposit"===em){let e=(0,F.isMwaHandoffContext)(ee)?eO:await ez();
2if(q&&!q())return{status:"not-started"};if(null!=e&&a>e)return x.toast.error(G("amountExceedsWalletBalance")),{status:"not-started"}}else if(null==eG)return x.toast.error(G("balanceStillLoading")),{status:"not-started"};else if(a>eG)return x.toast.error(G("amountExceedsProfileBalance")),{status:"not-started"};let l=eR;if(eE)return x.toast.error(G("selectDestinationAccount")),{status:"not-started"};"deposit"===em&&(0,D.gtagEvent)("deposit_started",{value:a,currency:"USD",token:ev,source:"deposit_dialog"}),ew(!0),i({stage:"preparing"});try{if("deposit"!==em&&(0,B.spendMayNeedArmadaPull)(a,e$,eH)){let e=await eu({profileIndex:et,neededRaw:eR,incompleteMessage:G("withdraw"===em?"withdrawArmadaIncomplete":"armadaPullIncomplete"),failedMessage:G("withdraw"===em?"withdrawArmadaFailed":"armadaPullFailed"),isAlive:()=>ej.current});if(null===e)return{status:"not-started"};l=e.spendRaw}if("deposit"===em||"withdraw"===em){let a=await (0,C.planSelfPaidProfileTx)({connection:X,publicKey:Y,profileIndex:et,mint:eL.mint,amount:l,mode:em});if(a.canSelfPay){let e=new c.Transaction;a.instructions.forEach(t=>e.add(t));let{blockhash:t,lastValidBlockHeight:l}=await X.getLatestBlockhash();if(e.recentBlockhash=t,e.feePayer=Y,q&&!q())return{status:"not-started"};i({stage:"awaiting-wallet"}),r=!0;let o=await Q(e,void 0,s);s(o),await (0,n.confirmOrVerifyLanded)(X,{signature:o,blockhash:t,lastValidBlockHeight:l})}else try{e=await (0,C.sendSponsoredProfileTx)({publicKey:Y,signTransaction:J,profileIndex:et,amount:l,mode:em,isCurrent:q,onSigning:()=>i({stage:"awaiting-wallet"}),onSubmitting:()=>{r=!0,i({stage:"submitting"})}}),i({stage:"submitted",signature:e})}catch(e){throw(0,b.isUserRejection)(e)||(0,I.logErrorToServer)({type:"sponsored_profile_tx_failed",mode:em,wallet:Y.toBase58(),walletName:ee?.walletName,profileIndex:et,amount:Number(l),lamportsAvailable:a.lamportsAvailable,lamportsRequired:a.lamportsRequired,errorName:e?.name,errorStep:e?.step,errorMessage:e?.message??String(e),status:e?.
2status,body:e?.body}),e}let o=(0,L.baseUnitsToDecimalString)(l,eL.decimals);(0,D.gtagEvent)("deposit"===em?"profile_deposit":"profile_withdraw",{value:Number(l)/10**eL.decimals,currency:"USD",token:ev});let d="deposit"===em?"depositedAmount":"withdrewAmount";x.toast.success(G(d,{amount:o,token:ev})),"deposit"===em&&el&&ea<.01&&!eo&&!ec&&(0,x.toast)(G("enableGaslessPrompt"),{duration:1e4,action:{label:G("enableGasless"),onClick:()=>void e2()},icon:(0,t.jsx)(v.Zap,{className:"size-4 text-primary"})})}else{let e=new c.Transaction,t=(0,h.getAssociatedTokenAddressSync)(eL.mint,Y);e.add((0,p.createAssociatedTokenAccountIdempotentInstruction)(Y,t,Y,eL.mint));let a=new P.PassthroughClient(X);e.add(a.withdrawFromProfileIx({wallet:Y,profileIndex:et,mint:eL.mint,amount:new u.BN(l.toString())}));let[o]=(0,T.getProfilePda)(Y,eS),d=(0,h.getAssociatedTokenAddressSync)(eL.mint,o,!0);e.add((0,p.createAssociatedTokenAccountIdempotentInstruction)(Y,d,o,eL.mint)),e.add((0,m.createTransferInstruction)(t,d,Y,l,[],f.TOKEN_PROGRAM_ID));let{blockhash:g,lastValidBlockHeight:b}=await X.getLatestBlockhash();if(e.recentBlockhash=g,e.feePayer=Y,q&&!q())return{status:"not-started"};i({stage:"awaiting-wallet"}),r=!0;let v=await Q(e,void 0,s);s(v),await (0,n.confirmOrVerifyLanded)(X,{signature:v,blockhash:g,lastValidBlockHeight:b});let y=ei.find(e=>e.index===eS);(0,D.gtagEvent)("profile_transfer",{value:Number(l)/10**eL.decimals,currency:"USD",token:ev,from:et,to:eS}),x.toast.success(G("transferredAmount",{amount:(0,L.baseUnitsToDecimalString)(l,eL.decimals),token:ev,destination:y?.name??G("profileFallback",{index:String((eS??0)+1)})}))}if(eg(""),e)return i({stage:"confirmed",signature:e}),{status:"confirmed",signature:e};return{status:"not-started"}}catch(i){if(i instanceof C.ProfileTxCancelledError)return{status:"not-started"};console.error(`Error during ${em}:`,i);let t=(i instanceof Error?i.message:"").toLowerCase();if(t.includes("insufficient lamports")?x.toast.error(G("insufficientSolForFees")):(0,b.isUserRejection)(i)||("deposit"===em&&(t.includes("insufficient funds")||t.includes("unexpected error"))?x.toast.error(G("depositFailedNotEnoughUsdc")):x.toast.error((0,g.displayClientError)(i))),(0,b.isUserRejection)(i))return{status:"rejected"};if(i instanceof n.TransactionFailedOnChainError)return{status:"failed",...e?{signature:e}:{}};return r?{status:"unknown",signature:e}:{status:"failed"}}finally{ew(!1)}},e3=ep?.name??G("profileFallback",{index:String((et??0)+1)}),e4=[];"deposit"!==em||er||e4.push("noProfile"),e1&&e4.push("transfer"===em?"loanBlocksTransfer":"loanBlocksWithdraw"),ec&&"deposit"!==em&&e4.push("withdraw"===em?"jwtWithdraw":"jwtTransfer"),e_&&e4.push("battleLock");let e6=e4.length>0,e8=(0,i.useRef)(null),e9=(0,s.useKeypadAmountFocus)(e8,{active:e&&!eA,blocked:e6,busy:()=>eI.current,mode:em}),e7=(0,z.withdrawAmountNote)(eD,eG,eY),te=ey||null===eR||eR<=BigInt(0)||eE||e_||ec||e1||null!==e7;return{activeProfileIndex:et,activeProfilePda:er,activeProfile:ep,profileLabel:e3,createdProfiles:ei,allProfileBalances:eZ,publicKey:Y,mode:em,switchMode:e=>{ef(e),eN()},amount:ex,onAmountInput:eF,destProfileIndex:eS,setDestProfileIndex:ek,isProcessing:ey,armadaStep:eh,walletBalance:eO,profileBalance:eK,maxAmount:eG,settlingLine:eX,amountNote:e7,fetchTokenBalance:eB,lockedBattle:eM,receiveOnlyDeposit:eA,notices:e4,amountRef:e8,focusAmount:e9,handleMax:()=>{e1||eg(null!=eG&&eG>0?(0,L.numberToDecimalString)(eG,eL.decimals):"")},handleSubmit:async()=>{if(te||eI.current)return{status:"not-started"};eI.current=!0;try{return await e5()}finally{eI.current=!1}},submitDisabled:te}}},307052,e=>{"use strict";var t=e.i(43690),r=e.i(994754),i=e.i(334992),s=e.i(938425);e.s(["useProfileLoanBlock",0,function(e,n,a){let{connection:l}=(0,r.useConnection)(),o=(0,t.useQuery)({queryKey:["profile-loan-block",e?.toBase58(),n],queryFn:async()=>{if(!e||null===n)return!1;let[t]=(0,s.getUserAccountPda)(e),r=await l.getAccountInfo(t);return!!r?.data&&(0,i.hasNonPhoenixLoan)(r.data,n)},enabled:a&&!!e&&null!==n,refetchInterval:5e3,staleTime:0});return{blocked:!0===o.data,isLoading:o.isLoading}}])},224996,13294,323116,451720,86306,737707,520639,e=>{"use strict";var t=e.i(183023),r=e.i(111526),i=e.i(591318),s=e.i(799227),n=e.i(6
253982),a=e.i(938425),l=e.i(643459),o=e.i(722732);let d={SOL:n.SOL_MINT,BTC:n.BTC_MINT,ETH:n.ETH_MINT};function c(e){return n.CUSTODIES[e.toBase58()]}function u(e,t,r,a){return s.PublicKey.findProgramAddressSync([i.Buffer.from("position"),e.toBuffer(),n.JUPITER_POOL.toBuffer(),t.toBuffer(),r.toBuffer(),i.Buffer.from([a])],n.JUPITER_PERPS_PROGRAM_ID)}function h(e){let t=c(n.SOL_MINT),r=c(n.BTC_MINT),i=c(n.ETH_MINT),s=c(n.USDC_MINT),[a]=u(e,t,t,n.Side.Long),[l]=u(e,t,s,n.Side.Short),[o]=u(e,r,r,n.Side.Long),[d]=u(e,r,s,n.Side.Short),[h]=u(e,i,i,n.Side.Long),[p]=u(e,i,s,n.Side.Short);return{solLong:a,solShort:l,btcLong:o,btcShort:d,ethLong:h,ethShort:p}}function p(e){let t=d[e];if(t)return t;let r=(0,l.mintForSymbol)(e);if(r)return new s.PublicKey(r);let i=(0,o.getGlobalGmTradeRegistry)();if(i){let t=i.getMarketBySymbol(e);if(t)return t.indexTokenMint}return console.warn(`[getMarketMint] Unknown asset "${e}" not found in any registry`),null}e.s(["getMarketMint",0,p,"getPositionPdaInfo",0,function(e,t,r){let i=p(t)??n.SOL_MINT,a=n.CUSTODIES[i.toBase58()]??c(n.SOL_MINT),l=c(n.USDC_MINT);return{pda:new s.PublicKey(e),asset:t,side:r,custody:a,collateralCustody:"long"===r?a:l}},"getPositionPdasForProfiles",0,function(e,t){let r=c(n.SOL_MINT),i=c(n.BTC_MINT),s=c(n.ETH_MINT),l=c(n.USDC_MINT),o=[];for(let n of t){let[t]=(0,a.getProfilePda)(e,n),d=h(t);o.push({pda:d.solLong,asset:"SOL",side:"long",custody:r,collateralCustody:r,profileIndex:n},{pda:d.solShort,asset:"SOL",side:"short",custody:r,collateralCustody:l,profileIndex:n},{pda:d.btcLong,asset:"BTC",side:"long",custody:i,collateralCustody:i,profileIndex:n},{pda:d.btcShort,asset:"BTC",side:"short",custody:i,collateralCustody:l,profileIndex:n},{pda:d.ethLong,asset:"ETH",side:"long",custody:s,collateralCustody:s,profileIndex:n},{pda:d.ethShort,asset:"ETH",side:"short",custody:s,collateralCustody:l,profileIndex:n})}let d=h(e);return o.push({pda:d.solLong,asset:"SOL",side:"long",custody:r,collateralCustody:r},{pda:d.solShort,asset:"SOL",side:"short",custody:r,collateralCustody:l},{pda:d.btcLong,asset:"BTC",side:"long",custody:i,collateralCustody:i},{pda:d.btcShort,asset:"BTC",side:"short",custody:i,collateralCustody:l},{pda:d.ethLong,asset:"ETH",side:"long",custody:s,collateralCustody:s},{pda:d.ethShort,asset:"ETH",side:"short",custody:s,collateralCustody:l}),o}],13294);let m=8,f=40,x=72,g=104,b=136,v=144,y=152,w=153,j=161,S=169,k=177,N=185,P=201,T=209,C=T+1;function M(e,t){return new s.PublicKey(e.subarray(t,t+32))}function _(e,t){return e.readBigInt64LE(t)}function A(e,t){return e.readBigUInt64LE(t)}function E(e,t){let r=e.readBigUInt64LE(t);return e.readBigUInt64LE(t+8)<<BigInt(64)|r}function L(e,t){return e.readUInt8(t)}var F=e.i(717421);e.s(["useRealtimePositionUpdates",0,function(e,i,a){let{positions:l,closedOrEmptyPdas:d,...c}=function(e){let{accounts:i,isConnected:a,lastUpdate:l,subscribe:d,unsubscribe:c}=(0,F.useAccountSubscriptionContext)(),[u,h]=(0,t.useState)(!0),R=(0,t.useRef)(!1),D=(0,t.useRef)([]);(0,t.useEffect)(()=>{let t=e.map(e=>e.pda.toBase58()),r=new Set(D.current),i=new Set(t),s=t.filter(e=>!r.has(e)),n=D.current.filter(e=>!i.has(e));s.length>0&&d(s),n.length>0&&c(n),D.current=t},[e,d,c]),(0,t.useEffect)(()=>{!R.current&&i.size>0&&(R.current=!0,h(!1));let e=setTimeout(()=>{R.current||(R.current=!0,h(!1))},3e3);return()=>clearTimeout(e)},[i.size]);let{positions:I,closedOrEmptyPdas:U}=(0,t.useMemo)(()=>{let t=[],a=new Set;return e.forEach(e=>{var l;let d=e.pda.toBase58(),c=i.get(d);if(!c)return;if(c.isDeleted)return void a.add(d);let u=function(e,t,i){try{let n=r.Buffer.from(e,"base64");if(i){let e=(0,o.resolveGmTradeMarket)(t)?.indexTokenDecimals;return function(e,t){if(e.length<232)return null;let r=e.readUInt8(42),i=E(e,216),n=Number(i)/1e20,a=0;if(void 0!==t){let r=E(e,184);if(r>BigInt(0)&&i>BigInt(0)){let e=Number(r)/10**t;a=e>0?n/e:0}}let l=E(e,200),o=new s.PublicKey(e.subarray(120,152)).toBase58(),d=null;"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"===o?d=6:"So11111111111111111111111111111111111111112"===o?d=9:"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh"===o?d=8:"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"===o&&(d=8);let c=null===d?0:Number(l)/10**d,u=new s.PublicKey(e.subarray(56,88)),h=Number(e.readBigInt64LE(48)),p=Number(e.readBigInt64LE(160));return{owner:u.toBase58(),pool:"",custody:"",collateralCustody:"",openTime:h,updateTime:p,side:1===r?"long":2===r?"short":"none",priceUsd:a,sizeUsd:n,collateralUsd:c,realisedPnlUsd:0,leverageX:c>0?n/c:0,isEmpty:i<1e18}}
2(n,e)}return function(e){try{var t;let r,i,s;return t=function(e){let t=e.data;if(t.length<C)throw Error(`Invalid position data length: ${t.length}, expected at least ${C}`);return{owner:M(t,m),pool:M(t,f),custody:M(t,x),collateralCustody:M(t,g),openTime:_(t,b),updateTime:_(t,v),side:L(t,y),price:A(t,w),sizeUsd:A(t,j),collateralUsd:A(t,S),realisedPnlUsd:_(t,k),cumulativeInterestSnapshot:E(t,N),lockedAmount:A(t,P),bump:L(t,T)}}(e),r=Number(t.sizeUsd)/1e6,i=Number(t.collateralUsd)/1e6,s=Number(t.price)/1e6,{owner:t.owner.toBase58(),pool:t.pool.toBase58(),custody:t.custody.toBase58(),collateralCustody:t.collateralCustody.toBase58(),openTime:Number(t.openTime),updateTime:Number(t.updateTime),side:({0:"none",1:"long",2:"short"})[t.side],priceUsd:s,sizeUsd:r,collateralUsd:i,realisedPnlUsd:Number(t.realisedPnlUsd)/1e6,leverageX:i>0?r/i:0,isEmpty:0===r}}catch(e){return console.error("Failed to decode Jupiter position:",e),null}}({data:n,executable:!1,lamports:0,owner:null})}catch{return null}}(c.data,e.asset,e.isGmTrade);u&&null!==(l=u)&&!l.isEmpty&&"none"!==l.side?t.push({positionPda:d,asset:e.asset,side:e.side,marketMint:(p(e.asset)??n.SOL_MINT).toBase58(),custody:e.custody.toBase58(),collateralCustody:e.collateralCustody.toBase58(),owner:u.owner,openTime:u.openTime,updateTime:u.updateTime,priceUsd:u.priceUsd,sizeUsd:u.sizeUsd,collateralUsd:u.collateralUsd,realisedPnlUsd:u.realisedPnlUsd,leverageX:u.leverageX,lastWsUpdate:c.lastUpdate,profileIndex:e.profileIndex,isGmTrade:e.isGmTrade}):u&&a.add(d)}),{positions:t,closedOrEmptyPdas:a}},[e,i]),[O,B]=(0,t.useState)(!0);(0,t.useEffect)(()=>{if(!l)return void B(!0);B(Date.now()-l<5e3);let e=setInterval(()=>{B(Date.now()-l<5e3)},5e3);return()=>clearInterval(e)},[l]);let z=(0,t.useCallback)((e,t)=>I.find(r=>r.marketMint===e&&r.side===t)||null,[I]);return{positions:I,closedOrEmptyPdas:U,isLoading:u,isConnected:a&&O,lastUpdate:l,getPositionForMarket:z}}(e),u=(0,t.useRef)(new Map);return(0,t.useEffect)(()=>{let e=new Set(l.map(e=>e.positionPda)),t=new Set(u.current.keys());l.forEach(e=>{u.current.has(e.positionPda)||i?.(e)}),t.forEach(t=>{if(!e.has(t)){let e=u.current.get(t);e&&a?.(t,e)}}),u.current=new Map(l.map(e=>[e.positionPda,e]))},[l,i,a]),{positions:l,closedOrEmptyPdas:d,...c}}],224996);var R=e.i(622463),D=e.i(905843),I=e.i(190459);let U=[1e3,786,618,500,382,236];function O(e,t){let r=0,i=0;for(let s=0;s<5;s++)e>=(i+=U[t?5-s:s])&&r++;return r}e.s(["FIB_RATIOS",0,U,"FIB_RATIO_SCALE",0,1e3,"fibFirstThreshold",0,function(e){return e?U[5]:U[0]},"fibLevel",0,O],323116);function B(e){return new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function z(e,t){return new s.PublicKey(e.subarray(t,t+32))}function $(e,t){return B(e).getBigInt64(t,!0)}function V(e,t){return B(e).getBigUint64(t,!0)}function H(e,t){return B(e).getUint16(t,!0)}function W(e){try{let t=function(e){var t;let r,i,s,n,a,l,o,d,c,u,h,p,m,f=e.data;if(240!==f.length&&256!==f.length)throw Error(`Invalid order data length: ${f.length}, expected 240 or 256`);let x=!0;for(let e=0;e<64;e++)if(0!==f[e]){x=!1;break}if(x)throw Error("Order account is drained (all-zero userAccount/marketMint)");let g=V(f,96);return{userAccount:z(f,0),marketMint:z(f,32),side:f[64],orderType:f[65],action:f[66],bump:f[67],priority:f[68],fundingStatus:f[69],underwriter:f[70],sizeUsd:V(f,72),collateralAmount:V(f,80),slippageBps:H(f,88),closeBps:H(f,90),orderCounter:g,createdAt:$(f,104),data:(t=f,r=V(t,112),i=t[120],s=128,n={waitPrice:V(t,s+0),waitDurationSeconds:V(t,s+8),waitZoneEnteredAt:$(t,s+16),isArmed:(V(t,s+24)&BigInt(1))!==BigInt(0)},a={worstPrice:V(t,s+32),ratchetSize:V(t,s+40),bestPriceSeen:V(t,s+48),lastUpdateTimestamp:$(t,s+56),stopTriggerPrice:V(t,s+72)},l=(V(t,s+64)&BigInt(0x100000000))!==BigInt(0),o={indicatorConfig:V(t,s+72),thresholdValue:V(t,s+80),indicatorPhase:V(t,s+88),phaseTransitionPrice:V(t,s+96),indicatorAux:V(t,s+104)},d={startPrice:V(t,s+0),endPrice:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32),triggerType:V(t,s+40),leverageWeightingType:V(t,s+48),startLeverageScaled:V(t,s+56),endLeverageScaled:V(t,s+64)}
2,c={startPrice:V(t,s+0),endPrice:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32)},u={priceLimit:V(t,s+0),intervalSeconds:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32),lastLegTimestamp:$(t,s+40),startAt:$(t,s+88)},h={priceLimit:V(t,s+0),intervalSeconds:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32),ratchetSize:V(t,s+40),bestPriceSeen:V(t,s+48),lastLegTimestamp:$(t,s+56),startAt:$(t,s+88)},p={priceLimit:V(t,s+0),intervalSeconds:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32),lastLegTimestamp:$(t,s+40),leverageWeightingType:V(t,s+48),startLeverageScaled:V(t,s+56),endLeverageScaled:V(t,s+64),startAt:$(t,s+88)},m={orderSequenceNumber:V(t,s+0),priceInTicks:V(t,s+8),remainingBaseLots:V(t,s+40)},{triggerPrice:r,triggerCondition:i,landMine:n,ratchet:a,indicator:o,dca:d,dcaClose:c,dcaTimeClose:u,dcaRatchetClose:h,dcaTime:p,dcaRatchet:{priceLimit:V(t,s+0),intervalSeconds:V(t,s+8),numLegs:V(t,s+16),weightingType:V(t,s+24),legsExecuted:V(t,s+32),ratchetSize:V(t,s+40),bestPriceSeen:V(t,s+48),lastLegTimestamp:$(t,s+56),leverageWeightingType:V(t,s+64),startLeverageScaled:V(t,s+72),endLeverageScaled:V(t,s+80),startAt:$(t,s+88)},phoenix:m,isReverseFib:l}),loanMultiplierMicro:f.length>=256?V(f,240):BigInt(0),loanFlags:f.length>=256?f[248]:0}}(e);return function(e){var t;let r={[D.PassthroughSide.Long]:"long",[D.PassthroughSide.Short]:"short"},i=2===e.underwriter&&e.orderType===D.PassthroughOrderType.StopLimit&&e.action===D.PassthroughAction.Increase,s={[D.PassthroughOrderType.Market]:"market",[D.PassthroughOrderType.Limit]:"limit",[D.PassthroughOrderType.StopLimit]:"stop_limit",[D.PassthroughOrderType.LandMine]:"landmine",[D.PassthroughOrderType.Ratchet]:"ratchet",[D.PassthroughOrderType.PrivateTpSl]:"private_tpsl",[D.PassthroughOrderType.RatchetEntry]:"ratchet_entry",[D.PassthroughOrderType.Indicator]:"indicator",[D.PassthroughOrderType.IndicatorRatchet]:"indicator_ratchet",[D.PassthroughOrderType.Dca]:"dca",[D.PassthroughOrderType.FibRatchet]:"fib_ratchet",[D.PassthroughOrderType.FibRatchetEntry]:"fib_ratchet_entry",[D.PassthroughOrderType.DcaClose]:"dca_close",[D.PassthroughOrderType.DcaTimeClose]:"dca_time_close",[D.PassthroughOrderType.DcaRatchetClose]:"dca_ratchet_close",[D.PassthroughOrderType.DcaTime]:"dca_time",[D.PassthroughOrderType.DcaRatchet]:"dca_ratchet"},a={[D.PassthroughAction.Increase]:"increase",[D.PassthroughAction.Decrease]:"decrease"},o=e.marketMint.toBase58(),d=e.side===D.PassthroughSide.Long,c=e.orderType===D.PassthroughOrderType.Indicator||e.orderType===D.PassthroughOrderType.IndicatorRatchet,u=Number(e.data.ratchet.bestPriceSeen)/(c?1e6:D.PRICE_SCALE),h=Number(e.data.ratchet.ratchetSize)/(c?1e6:D.PRICE_SCALE),p=Number(e.data.ratchet.worstPrice)/D.PRICE_SCALE,m=0;if(e.orderType===D.PassthroughOrderType.Ratchet&&u>0)m=d?Math.max(u-h,p):Math.min(u+h,p);else if(e.orderType===D.PassthroughOrderType.RatchetEntry&&u>0)m=d?Math.min(u+h,p):Math.max(u-h,p);else if(e.orderType===D.PassthroughOrderType.FibRatchet&&u>0&&h>0){let t=Math.abs(h-p);if(t>0){let r=Math.abs(u-p),i=O(1e3*r/t,e.data.isReverseFib),s=t*U[e.data.isReverseFib?5-i:i]/1e3;m=d?Math.max(u-s,p):Math.min(u+s,p)}}else if(e.orderType===D.PassthroughOrderType.FibRatchetEntry&&u>0&&h>0){let t=Math.abs(h-p);if(t>0){let r=Math.abs(u-p),i=O(1e3*r/t,e.data.isReverseFib),s=t*U[e.data.isReverseFib?5-i:i]/1e3;m=d?Math.min(u+s,p):Math.max(u-s,p)}}else(e.orderType===D.PassthroughOrderType.Indicator||e.orderType===D.PassthroughOrderType.IndicatorRatchet)&&u>0&&(m=d?Math.min(u+h,p):Math.max(u-h,p));let f=Number(e.data.indicator.indicatorConfig),x=Number(e.data.indicator.thresholdValue),g=e.orderType===D.PassthroughOrderType.Indicator||e.orderType===D.PassthroughOrderType.IndicatorRatchet?{indicatorType:255&f,timeframeCode:f>>8&255,period:f>>16&255,indicatorCondition:f>>24&255,thresholdValue:x/1e6,phase:Number(e.data.indicator.indicatorPhase),phaseTransitionPrice:Number(e.data.indicator.phaseTransitionPrice)/D.PRICE_SCALE}:void 0;return{userAccount:e.userAccount.toBase58(),marketMint:o,asset:function(e){if(e===n.SOL_MINT.toBase58()
2)return"SOL";if(e===n.BTC_MINT.toBase58())return"BTC";if(e===n.ETH_MINT.toBase58())return"ETH";let t=(0,l.resolveMintSymbol)(e);if(t)return t;let r=(0,R.getGlobalPhoenixRegistry)();if(r){let t=r.getSymbolByOrderbook(e);if(t)return t}return"unknown"}(o),side:r[e.side],orderType:i?"limit":s[e.orderType],action:a[e.action],underwriter:(t=e.underwriter,(0,I.underwriterLiteralFromByte)(t)??"unknown"),priority:e.priority,fundingStatus:e.fundingStatus,sizeUsd:Number(e.sizeUsd)/1e6,collateralAmount:Number(e.collateralAmount)/1e6,slippageBps:e.slippageBps,closeBps:e.closeBps,orderCounter:Number(e.orderCounter),createdAt:Number(e.createdAt),loanMultiplierMicro:Number(e.loanMultiplierMicro),triggerPrice:Number(e.data.triggerPrice)/D.PRICE_SCALE,triggerCondition:({0:"above",1:"below"})[e.data.triggerCondition],landMine:{waitPrice:Number(e.data.landMine.waitPrice)/D.PRICE_SCALE,waitDurationSeconds:Number(e.data.landMine.waitDurationSeconds),waitZoneEnteredAt:Number(e.data.landMine.waitZoneEnteredAt),isArmed:e.data.landMine.isArmed},ratchet:{worstPrice:p,ratchetSize:h,bestPriceSeen:u,lastUpdateTimestamp:Number(e.data.ratchet.lastUpdateTimestamp),currentTriggerPrice:m,isReverseFib:e.data.isReverseFib,stopTriggerPrice:e.orderType===D.PassthroughOrderType.Ratchet?Number(e.data.ratchet.stopTriggerPrice)/D.PRICE_SCALE:0},indicator:g,dca:e.orderType===D.PassthroughOrderType.Dca?{startPrice:Number(e.data.dca.startPrice)/D.PRICE_SCALE,endPrice:Number(e.data.dca.endPrice)/D.PRICE_SCALE,numLegs:Number(e.data.dca.numLegs),weightingType:Number(e.data.dca.weightingType),legsExecuted:Number(e.data.dca.legsExecuted),triggerType:Number(e.data.dca.triggerType),leverageWeightingType:Number(e.data.dca.leverageWeightingType),startLeverageScaled:Number(e.data.dca.startLeverageScaled),endLeverageScaled:Number(e.data.dca.endLeverageScaled)}:void 0,dcaClose:e.orderType===D.PassthroughOrderType.DcaClose?{startPrice:Number(e.data.dcaClose.startPrice)/D.PRICE_SCALE,endPrice:Number(e.data.dcaClose.endPrice)/D.PRICE_SCALE,numLegs:Number(e.data.dcaClose.numLegs),weightingType:Number(e.data.dcaClose.weightingType),legsExecuted:Number(e.data.dcaClose.legsExecuted)}:void 0,dcaTimeClose:e.orderType===D.PassthroughOrderType.DcaTimeClose?{priceLimit:Number(e.data.dcaTimeClose.priceLimit)/D.PRICE_SCALE,intervalSeconds:Number(e.data.dcaTimeClose.intervalSeconds),numLegs:Number(e.data.dcaTimeClose.numLegs),weightingType:Number(e.data.dcaTimeClose.weightingType),legsExecuted:Number(e.data.dcaTimeClose.legsExecuted),lastLegTimestamp:Number(e.data.dcaTimeClose.lastLegTimestamp),startAt:Number(e.data.dcaTimeClose.startAt)}:void 0,dcaRatchetClose:e.orderType===D.PassthroughOrderType.DcaRatchetClose?{priceLimit:Number(e.data.dcaRatchetClose.priceLimit)/D.PRICE_SCALE,intervalSeconds:Number(e.data.dcaRatchetClose.intervalSeconds),numLegs:Number(e.data.dcaRatchetClose.numLegs),weightingType:Number(e.data.dcaRatchetClose.weightingType),legsExecuted:Number(e.data.dcaRatchetClose.legsExecuted),ratchetSize:Number(e.data.dcaRatchetClose.ratchetSize)/D.PRICE_SCALE,bestPriceSeen:Number(e.data.dcaRatchetClose.bestPriceSeen)/D.PRICE_SCALE,lastLegTimestamp:Number(e.data.dcaRatchetClose.lastLegTimestamp),startAt:Number(e.data.dcaRatchetClose.startAt)}:void 0,dcaTime:e.orderType===D.PassthroughOrderType.DcaTime?{priceLimit:Number(e.data.dcaTime.priceLimit)/D.PRICE_SCALE,intervalSeconds:Number(e.data.dcaTime.intervalSeconds),numLegs:Number(e.data.dcaTime.numLegs),weightingType:Number(e.data.dcaTime.weightingType),legsExecuted:Number(e.data.dcaTime.legsExecuted),lastLegTimestamp:Number(e.data.dcaTime.lastLegTimestamp),leverageWeightingType:Number(e.data.dcaTime.leverageWeightingType),startLeverageScaled:Number(e.data.dcaTime.startLeverageScaled),endLeverageScaled:Number(e.data.dcaTime.endLeverageScaled),startAt:Number(e.data.dcaTime.startAt)}:void 0,dcaRatchet:e.orderType===D.PassthroughOrderType.DcaRatchet?{priceLimit:Number(e.data.dcaRatchet.priceLimit)/D.PRICE_SCALE,intervalSeconds:Number(e.data.dcaRatchet.intervalSeconds),numLegs:Number(e.data.dcaRatchet.numLegs),weightingType:Number(e.data.dcaRatchet.weightingType),legsExecuted:Number(e.data.dcaRatchet.legsExecuted),ratchetSize:Number(e.data.dcaRatchet.ratchetSize)/D.PRICE_SCALE,bestPriceSeen:Number(e.data.dcaRatchet.bestPriceSeen)/D.PRICE_SCALE,lastLegTimestamp:Number(e.data.dcaRatchet.lastLegTimestamp),leverageWeightingType:Number(e.data.dcaRatchet.leverageWeightingType),startLeverageScaled:Number(e.data.dcaRatchet.startLeverageScaled),endLeverageScaled:Number(e.data.dcaRatchet.endLeverageScaled),startAt:Number(e.data.dcaRatchet.startAt)}:void 0,phoenix:2===e.underwriter&&e.orderType===D.PassthroughOrderType.Limit?{priceInTicks:Number(e.data.phoenix.priceInTicks),orderSequenceNumber:Number(e.data.phoenix.orderSequenceNumber),remainingBaseLots:Number(e.data.phoenix.remainingBaseLots)}:void 0}}(t)}catch(e){return console.error("Failed to decode Imperial order:",e),null}}function q(e,t){if("landmine"!==e.orderType)return"not_applicable";if(e.landMine.isArmed)return"armed";let r=e.landMine.waitZoneEnteredAt;return 0===r?"waiting":t-r>=e.landMine.waitDurationSeconds?"armed":"in_zone"}function K(e){try{let t=r.Buffer.from(e,"base64");return W({data:t,executable:!1,lamports:0,owner:null})}catch{return null}}e.s(["IMPERIAL_ORDER_SIZE",0,240,"IMPERIAL_ORDER_SIZE_WITH_LOAN_EXT",0,256,"dcaCountdownAnchor",0,function(e,t,r,i,s=Math.floor(Date.now()/1e3)){return 0===e&&i>
2s?i-r:t},"getLandMineStatus",0,q,"orderDecoder",0,W],451720),e.s(["useRealtimeOrders",0,function(e,r,i){let{accounts:s,isConnected:n,lastUpdate:a,subscribe:l,unsubscribe:o}=(0,F.useAccountSubscriptionContext)(),[d,c]=(0,t.useState)(!0),[u,h]=(0,t.useState)(new Set),p=(0,t.useRef)(new Map),m=(0,t.useRef)(new Map),f=(0,t.useRef)(!1),x=(0,t.useRef)([]);(0,t.useEffect)(()=>{let t=new Set(x.current),r=new Set(e),i=e.filter(e=>!t.has(e)),s=x.current.filter(e=>!r.has(e));i.length>0&&l(i),s.length>0&&o(s),x.current=e},[e,l,o]),(0,t.useEffect)(()=>{!f.current&&s.size>0&&(f.current=!0,c(!1));let e=setTimeout(()=>{f.current||(f.current=!0,c(!1))},3e3);return()=>clearTimeout(e)},[s.size]),(0,t.useEffect)(()=>{let t=Math.floor(Date.now()/1e3);e.forEach(e=>{let n=s.get(e);if(n){if(n.isDeleted){let t=p.current.get(e);u.has(e)||(h(t=>{let r=new Set(t);return r.add(e),r}),r?.({orderPda:e,lastKnownState:t||null,wasExecuted:!0}),p.current.delete(e),m.current.delete(e))}else if(n.data){let r=K(n.data);if(!r)return;p.current.set(e,r);let s=m.current.get(e),a=q(r,t),l={...r,orderPda:e,status:"active",lastWsUpdate:n.lastUpdate,landMineStatus:a};s&&(("ratchet"===r.orderType||"ratchet_entry"===r.orderType||"indicator"===r.orderType||"indicator_ratchet"===r.orderType)&&s.ratchet?.bestPriceSeen!==r.ratchet?.bestPriceSeen||"landmine"===r.orderType&&(s.landMineStatus!==a||s.landMine.waitZoneEnteredAt!==r.landMine.waitZoneEnteredAt))&&i?.(e,l),m.current.set(e,l)}}})},[s,e,u,r,i]);let g=(0,t.useMemo)(()=>{let t=[],r=Math.floor(Date.now()/1e3);return e.forEach(e=>{let i=s.get(e);if(i?.data&&!i.isDeleted&&!u.has(e)){let s=K(i.data);if(!s)return;let n=q(s,r);t.push({...s,orderPda:e,status:"active",lastWsUpdate:i.lastUpdate,landMineStatus:n})}}),t},[e,s,u]);(0,t.useEffect)(()=>{0===e.length?(h(new Set),p.current.clear(),m.current.clear()):h(t=>{let r=new Set(e),i=!1,s=new Set;return t.forEach(e=>{r.has(e)?s.add(e):i=!0}),i?s:t})},[e.length]);let[b,v]=(0,t.useState)(!0);return(0,t.useEffect)(()=>{if(!a||0===e.length)return void v(!0);v(Date.now()-a<5e3);let t=setInterval(()=>{v(Date.now()-a<5e3)},5e3);return()=>clearInterval(t)},[a,e.length]),{orders:g,isLoading:d,isConnected:n&&b,lastUpdate:a,deletedOrders:u}}],86306);var G=e.i(994754),Y=e.i(770989);e.s(["useChainOrderPdas",0,function(e,r){let{connection:i}=(0,G.useConnection)(),[s,n]=(0,t.useState)([]),l=(0,t.useRef)(null),o=r.join(",");return(0,t.useEffect)(()=>{if(!e||!i||0===r.length)return void n([]);let t=!1,s=async()=>{try{let s=r.map(t=>(0,a.getProfilePda)(e,t)[0]),l=await Promise.all(s.flatMap(e=>[240,256].map(t=>i.getProgramAccounts(Y.PASSTHROUGH_PROGRAM_ID,{commitment:"processed",dataSlice:{offset:0,length:0},filters:[{dataSize:t},{memcmp:{offset:0,bytes:e.toBase58()}}]}))));if(t)return;let o=l.flatMap(e=>e.map(e=>e.pubkey.toBase58())),d=Array.from(new Set(o));n(e=>e.length===d.length&&e.every((e,t)=>e===d[t])?e:d)}catch{}};return s(),l.current=setInterval(s,6e4),()=>{t=!0,l.current&&clearInterval(l.current)}},[e?.toBase58(),i,o]),s}],737707);var X=e.i(21859),Q=e.i(214732);e.s(["useUserTokenAccounts",0,function(e,r){let i=e?.toBase58()??null,a=(0,t.useMemo)(()=>({walletKey:i}),[i]),[l,o]=(0,t.useState)({scope:a,change:null}),d=(0,t.useRef)({scope:a,balance:null}),c=(0,t.useMemo)(()=>{if(!i)return null;try{return(0,X.getAssociatedTokenAddressSync)(n.USDC_MINT,new s.PublicKey(i))}catch{return null}},[i]),u=(0,t.useRef)(r);(0,t.useLayoutEffect)(()=>{u.current=r},[r]);let h=(0,t.useCallback)((e,t)=>{if(!e&&null!==t)return;let r=e?Number(e.amount)/Math.pow(10,e.decimals):0,i=d.current,s=i.scope===a?i.balance:null;if(null!==s&&r>s){let e={mint:n.USDC_MINT.toBase58(),previousBalance:s,newBalance:r,change:r-s,timestamp:Date.now()};o({scope:a,change:e}),u.current?.(e)}d.current={scope:a,balance:r}},[a]),{data:p,isLoading:m}=(0,Q.useAccountSubscription)({account:c,decoder:e=>(function(e){try{if(e.length<72)return null;let t=new s.PublicKey(e.subarray(0,32)).toBase58(),r=new s.PublicKey(e.subarray(32,64)).toBase58(),i=e.readBigUInt64LE(64),a=t===n.USDC_MINT.toBase58()?6:9;return{mint:t,owner:r,amount:i,decimals:a}}catch{return null}})(e.data),onData:h,commitment:"processed",enabled:!!c}),f=(0,t.useMemo)(()=>p?Number(p.amount)/Math.pow(10,p.decimals):null,[p]);return(0,t.useLayoutEffect)(()=>{d.current={scope:a,balance:null}},[a]),{usdcBalance:f,lastBalanceChange:l.scope===a?l.change:null,isLoading:m}}],520639)},777180,568299,467577,98788,91262,364589,759550,465027,815,806082,193568,670258,641971,e=>{"use strict";e.s(["useRoutedVenue",()=>$],777180);var t=e.i(183023),r=e.i(76990),i=e.i(403628),s=e.i(824088),n=e.i(988408),a=e.i(436998),l=e.i(578866),o=e.i(634692),d=e.i(678872),c=e.i(894771),u=e.i(687229),h=e.i(670374);e.i(875574);var p=e.i(142298),m=e.i(394390);let f=(0,t.createContext)(null);function x(){return(0,t.useContext)(f)}e.s(["RoutingProvider",0,function({children:e}){let[r,i]=(0,t.useState)({}),[s,n]=(0,t.useState)(null),[a,l]=(0,t.useState)({}),[o,d]=(0,t.useState)({}),c=(0,t.useCallback)((e,t)=>{l(r=>r[e]===t?r:{...r,[e]:t})},[]),u=(0,t.useCallback)((e,t)=>{d(r=>{if(null===t){if(!(e in r))return r;let t={...r};return delete t[e],t}return r[e]===t?r:{...r,[e]:t}})},[]),h=(0,t.useMemo)(()=>({inputs:r,setInputs:i,phoenixBook:s,setPhoenixBook:n,lastRoutedVenue:a,recordRoutedVenue:c,manualVenue:o,setManualVenue:u}),[r,s,a,c,o,u]);return(0,m.jsx)(f.Provider,{value:h,children:e})},"useRoutingContext",0,x],568299);var g=e.i(190459),b=e.i(942289);e.i(654249);var v=e.i(972015);function y(e,t){return Number(e.getBigUint64(t,!0))}function w(e,t){return Number(e.getBigInt64(t,!0))}function j(e,t,r,i){let s=("open"===i?e.openFeeBps:e.closeFeeBps)+function(e,t,r){if(!(t>0))return 0;let i=e.tradeImpactFeeScalarUsd,s=i>0?Math.ceil(1e4*t/i):0,{recentImbalanceUsd:n,thresholdUsd:a,feeFactor:l,exponent:o}=e.impact,d=0;
2if(l>0&&a>0){let e=Math.abs(n+("long"===r?t:-t));e>a&&(d=Math.ceil(Math.pow(e/a,o)/l))}return s+d}(e,t,r),n=e.impact.maxFeeBps;return n>0?Math.min(s,n):s}function S(e,t){let r="long"===t?e.longHeadroomUsd:e.shortHeadroomUsd;return Math.min(e.maxPositionSizeUsd,r)}e.s(["decodeJupiterCustodyPricing",0,function(e,t){if(e.length<1117)return null;let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=w(r,896),s=0;if(!(t-i>60))for(let e=0;e<60;e++)s+=w(r,416+8*e);let n=y(r,183)/1e6,a=y(r,191)/1e6,l=y(r,238)/1e6,o=y(r,246)/1e6;return{tradeImpactFeeScalarUsd:y(r,151)/1e6,openFeeBps:y(r,296),closeFeeBps:y(r,304),maxPositionSizeUsd:y(r,312)/1e6,longHeadroomUsd:Math.max(0,n-l),shortHeadroomUsd:Math.max(0,a-o),impact:{recentImbalanceUsd:s/1e6,thresholdUsd:y(r,916)/1e6,feeFactor:y(r,904),exponent:r.getFloat32(912,!0),maxFeeBps:y(r,924)}}},"jupiterMaxNotional",0,S,"jupiterTotalFeeBpsAt",0,j],467577);let k={bids:[],asks:[]},N=new WeakSet;function P(e){N.add(e)}function T(e){return!e||N.has(e)}function C(e){return e&&P(e),{}}function M(e,t=Date.now()){return null!=e&&Number.isFinite(e)&&t>=e&&t-e<1e4}function _(e,t){return e.orderbookStatus===t&&e.orderbook===k?e:{...e,orderbook:k,orderbookStatus:t,orderbookGeneration:C(e.orderbookGeneration)}}function A(e){if(!e||"object"!=typeof e)return null;let t=e=>Array.isArray(e)&&e.every(e=>Array.isArray(e)&&2===e.length&&Number.isFinite(e[0])&&e[0]>0&&Number.isFinite(e[1])&&e[1]>=0);return t(e.bids)&&t(e.asks)?{bids:e.bids.filter(([,e])=>e>0),asks:e.asks.filter(([,e])=>e>0)}:null}function E(e){let t={},r=e.phoenixBook;(e.phoenixListed||r?.symbol===e.asset)&&(t.phoenix={priceImpactBps:(t,i,s)=>{if(!r||r.symbol!==e.asset||"live"!==r.status||T(r.generation)||!M(r.receivedAt)||!Number.isFinite(r.mid)||r.mid<=0||!r.bids.length||!r.asks.length)return 1/0;let n="long"===("open"===s?i:"long"===i?"short":"long")?r.asks:r.bids;return(0,v.bookWalkPriceImpactBps)(n,r.mid,t)}});let i=e.gmtrade;i&&(t.gmtrade={priceImpactBps:(e,t,r)=>{if("open"===r){let r="long"===t?i.longAvailableUsd:i.shortAvailableUsd;if(null!=r&&isFinite(r)&&e>r)return 1/0}return(0,v.gmtradePositionImpactBps)(i.totalOiLongUsd,i.totalOiShortUsd,e,t,r,i.positionImpactExponent,i.positionImpactPositiveFactor,i.positionImpactNegativeFactor)}});let s=e.jupiter;return s&&(t.jupiter={priceImpactBps:(e,t,r)=>"open"===r&&e>S(s,t)?1/0:j(s,e,t,r)}),t}e.s(["PHOENIX_BOOK_FRESH_MS",0,1e4,"expirePhoenixBook",0,function(e,t=Date.now()){return("live"===e.orderbookStatus||"empty"===e.orderbookStatus)&&(T(e.orderbookGeneration)||!M(e.orderbookReceivedAt,t))?_(e,"stale"):e},"initialPhoenixBook",0,function(){return{orderbook:k,displayOrderbook:k,orderbookStatus:"loading",orderbookReceivedAt:null,orderbookGeneration:C()}},"invalidatePhoenixBook",0,_,"isPhoenixBookFresh",0,M,"isPhoenixBookRevoked",0,T,"isPhoenixTransportFrame",0,function(e,t){return!!e&&"object"==typeof e&&("ping"===e.type?null==e.nonce||"string"==typeof e.nonce||Number.isFinite(e.nonce):"traderState"===e.channel?Array.isArray(e.subaccounts):"string"==typeof e.symbol&&!!e.symbol&&("orderbook"===e.channel?(void 0===t?A(e.orderbook):t)!==null:"market"===e.channel?Number.isFinite(e.markPx)&&e.markPx>0:"fundingRate"===e.channel?Number.isFinite(e.cumulativeFundingRate)||Number.isFinite(e.previousSettledFundingRate)||Number.isFinite(e.funding):"trades"===e.channel&&Array.isArray(e.trades)&&e.trades.every(e=>e&&"object"==typeof e&&("bid"===e.side||"ask"===e.side)&&Number.isFinite(e.baseAmount)&&Number.isFinite(e.quoteAmount)&&"string"==typeof e.timestamp)))},"nextPhoenixBookGeneration",0,C,"parsePhoenixBook",0,A,"phoenixBookRetryAfterUntil",0,function(e,t){if(!e)return 0;let r=e.trim();if(/^\d+$/.test(r))return Math.min(Number.MAX_SAFE_INTEGER,t+1e3*Number(r));if(!/[A-Za-z]{3}/.test(r))return 0;let i=Date.parse(r);return Number.isFinite(i)&&i>t?i:0},"phoenixBookRetryDelay",0,function(e){return Math.min(6e4,1e4*2**Math.min(3,Math.max(0,e-1)))},"revokePhoenixBookGeneration",0,P],98788),e.s(["buildLiquidityMap",0,E],91262);var L=e.i(591872);let F="imperial_routing_leverage_",R="imperial_routing_size_";function D(e,t){return`${e}${t}`}function I(e){let t=localStorage.getItem(D(F,e));if(null===t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?r:null}function U(e){return function(e){let t=localStorage.getItem(D(R,e));if(null===t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?r:null}(e)??1e3}e.s(["getReferenceNotional",0,U,"getSavedLeverage",0,I,"setSavedLeverage",0,function(e,t){Number.isFinite(t)&&!(t<=0)&&localStorage.setItem(D(F,e),String(t))}
2,"setSavedSize",0,function(e,t){Number.isFinite(t)&&!(t<=0)&&localStorage.setItem(D(R,e),String(t))}],364589);let O=e=>{let t=parseFloat(e);return isFinite(t)?t:0};function B(e){if(!e||e.paused)return;let t=O(e.maxMultiplierMicro);if(!(t<=0))return{utilizationBps:e.utilizationBps,totalBorrowedUsd:O(e.totalBorrowedUsd),poolValueUsd:O(e.navUsd),vaultBalanceUsd:O(e.vaultUsdc),baseRateBps:e.baseRateBps,kinkUtilBps:e.kinkUtilBps,slope1Bps:e.slope1Bps,slope2Bps:e.slope2Bps,maxMultiplierMicro:t,maxPositionLoanBps:e.maxPositionLoanBps,perMarket:e.markets.filter(e=>null!==e.symbol).map(e=>({symbol:e.symbol,mint:e.mint,enabled:e.enabled,debtCeilingUsd:O(e.debtCeilingUsd),borrowedUsd:O(e.borrowedLongUsd)+O(e.borrowedShortUsd),riskMultBps:e.riskMultBps,skewLongBps:e.skewLongBps,skewShortBps:e.skewShortBps,premiumBps:e.premiumBps,maxLeverageMicro:e.maxLeverageMicro,minLoanBps:e.minLoanBps,minLoanBpsVenue:e.minLoanBpsVenue,premiumBpsVenue:e.premiumBpsVenue,phoenixMarketMint:e.venueMarketMints?.phoenix??null}))}}function z(e){return e?(0,g.venueFromUnderwriter)(e):null}function $(e){let{asset:m,side:f}=e,{data:v}=(0,r.usePhoenixMarkets)(),{data:y}=(0,i.useGmTradeMarkets)(),w=(0,s.useGmTradeWs)(),{activeProfileIndex:j,activeProfileUnderwriter:S,activeProfileExcludedVenues:k,activeProfileVenueLock:N}=(0,c.useProfile)(),{positions:P,orders:T}=(0,u.useUnifiedPositions)(),{publicKey:C}=(0,p.useUnifiedWallet)(),{data:M}=(0,n.useTradingStats)(C?.toBase58()),{data:_}=(0,d.useLendingPoolState)(),{data:A}=(0,l.useSunriseMarkets)(),F=x(),R=F?.phoenixBook,D=F?.lastRoutedVenue[m]??null,O=F?.manualVenue[m]??null,$=F?.recordRoutedVenue,V=(0,t.useMemo)(()=>v?.find(e=>e.symbol===m)??null,[v,m]),H=(0,t.useMemo)(()=>{let e=(y??[]).filter(e=>e.symbol===m);return e.length>0?e.some(e=>!e.closed):w.symbols.includes(m)},[y,w.symbols,m]),W=w.getMaxLeverage(m),q=w.getMarketFees(m),K=w.getMarketLiquidity(m),G=(0,t.useMemo)(()=>{if(null===j)return null;let e=e=>e&&!b.OPENS_PAUSED_VENUES.has(e)?e:null,t=P.filter(e=>e.profileIndex===j&&e.asset===m&&("open"===e.status||"pending"===e.status||"closing"===e.status)&&void 0!==e.underwriter).map(t=>e((0,g.venueFromUnderwriter)(t.underwriter,t.hedgeVenue))).find(e=>null!==e)??null;if(t)return{venue:t,source:"position"};let r=null;for(let t of T)t.profileIndex===j&&"increase"===t.action&&"deleted"!==t.status&&void 0!==t.underwriter&&t.marketMint===(0,h.getMarketMintFromAsset)(m,t.underwriter)&&e((0,g.venueFromUnderwriter)(t.underwriter,t.hedgeVenue))&&(!r||(t.createdAt??0)>(r.createdAt??0))&&(r=t);let i=r?.underwriter?(0,g.venueFromUnderwriter)(r.underwriter,r.hedgeVenue):null;return i?{venue:i,source:"orders"}:null},[P,T,j,m]),Y=G?.venue??null,X=(0,t.useMemo)(()=>{let e=(N?.venues??[]).map(z).filter(e=>null!==e);return e.length>0?e:null},[N]),Q=(0,t.useMemo)(()=>(A??[]).find(e=>e.symbol.toUpperCase()===m.toUpperCase())??null,[A,m]),J=(0,o.useSunriseOpensAllowed)(),Z=(0,a.useSunriseOpenAvailability)(m,f,e.notional??U(m),J&&null!==Q&&null===Y),ee=(0,t.useMemo)(()=>{let t=(0,b.buildCapabilities)({asset:m,sunriseMarket:J&&Q?{maxLeverage:Q.maxLeverage,mmr:Q.mmr,armadaPrime:!e.armadaPrimeMarketOpen||Y||X?void 0:Q.armadaPrime}:null,phoenixMarket:V?{maxLeverage:V.maxLeverage,takerFeeMicro:V.takerFeeMicro,makerFeeMicro:V.makerFeeMicro}:null,gmTradeMarket:H?{maxLeverage:W,openFeePositivePercent:q?.openFeePositivePercent,openFeeNegativePercent:q?.openFeeNegativePercent,longNetRatePerHourPercent:q?.longNetRatePerHourPercent,shortNetRatePerHourPercent:q?.shortNetRatePerHourPercent,longAvailableUsd:K?.longAvailableUsd,shortAvailableUsd:K?.shortAvailableUsd}:null}),r=e.desiredLeverage??I(m)??2,i=e.notional??U(m),s=(0,n.resolveHoldHours)(M,m),a=z(S),l=E({asset:m,phoenixBook:R,phoenixListed:null!==V,gmtrade:H&&K?K:null});return(0,L.computeRoute)({lighterOpenBlocked:Z?.available===!1,lighterOpenBlockedReason:Z?.reason,asset:m,side:f,notional:i,desiredLeverage:r,holdHours:s,subaccountDefaultVenue:a,stickyVenue:Y,stickySource:G?.source,currentVenue:D,manualVenue:O,capabilities:t,liquidity:l,excludedVenues:k,venueLock:X,poolState:B(_)})},[m,f,e.armadaPrimeMarketOpen,e.desiredLeverage,e.notional,V,R,H,W,q,K,S,k,X,G,Y,D,O,M,_,Q,J,Z]),et=ee?.venue,er=!1!==e.record;return(0,t.useEffect)(()=>{er&&et&&$&&$(m,et)},[er,et,$,m]),(0,t.useMemo)(()=>ee?{...ee,stickyVenue:Y&&ee.venue===Y?Y:null}:ee,[ee,Y])}async function V(e,t=0){let r=await fetch("https://api.imperial.space/api/v1/phoenix/register",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wallet:e,profileIndex:t})});if(!r.ok){let e=await r.text().catch(()=>"Unknown error");throw Error(`Phoenix registration failed: ${e}`)}return r.json()}e.s(["toRouterPoolState",0,B],759550);var H=e.i(116082),W=e.i(586569);e.s(["usePhoenixRegistration",0,function(){let{publicKey:e}=(0,p.useUnifiedWallet)();return{registerForPhoenix:(0,t.useCallback)(async t=>{if(!e)return H.toast.error((0,W.message)("wallet","walletNotConnected")),!1;try{return await V(e.toBase58(),t),!0}catch(e){return console.warn("Phoenix activation:",e),!1}},[e])}}],465027);let q=new Map;e.s(["useBackToClose",0,function(e,r,i,s=!1){let n=(0,t.useRef)(r);(0,t.useEffect)(()=>{n.current=r}),(0,t.useEffect)(()=>
2{if(!e)return;let t=q.get(i);s&&t&&(t.cancelled=!0,q.delete(i)),s&&window.history.state?.[i]||window.history.pushState({[i]:!0},"");let r=!0,a=e=>{!r||e.state?.[i]||(r=!1,n.current())};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a);let e=()=>{r&&window.history.state?.[i]&&window.history.back()};if(!s)return void e();let t={cancelled:!1};q.set(i,t),queueMicrotask(()=>{q.get(i)===t&&q.delete(i),t.cancelled||e()})}},[e,i,s])}],815),e.s(["useRevealOnOpen",0,function(e,r){(0,t.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>{r.current?.scrollIntoView({block:"nearest",inline:"nearest",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"})});return()=>cancelAnimationFrame(t)},[e,r])}],806082);var K=e.i(799227),G=e.i(21859),Y=e.i(905843),X=e.i(938425);e.i(596331);var Q=e.i(653982);let J={},Z={},ee={protocolFeeRecipient:null,feeSettings:null,userAccountExists:!1,userFundingAtaExists:J,protocolFeeAtaExists:!0,projectAlt:null,projectAlts:[],walletCollateralBalance:Z,isLoading:!0,error:null},et=ee,er=new Set,ei=null,es=null,en=null,ea=0,el=0,eo=0,ed=0,ec=null,eu=null,eh=null,ep=null,em=null,ef=new Map;function ex(e){et={...et,...e},er.forEach(e=>e())}function eg(){return et}function eb(){return ee}function ev(e){return er.add(e),ey(),()=>{er.delete(e),ey()}}function ey(){let e=er.size>0&&null!==ei,t=e&&null!==es;e&&!ep?ep=setInterval(()=>{ew(),ej()},3e5):!e&&ep&&(clearInterval(ep),ep=null),t&&!em?em=setInterval(()=>void eS(),3e4):!t&&em&&(clearInterval(em),em=null)}function ew(e=!1){let t=ei;return!t||!e&&Date.now()-el<3e5?Promise.resolve():ec||(ec=t.getAccountInfo(Y.GLOBAL_SETTINGS_PDA).then(e=>{if(!e)return;let t=new K.PublicKey(e.data.slice(64,96)),r={longSwapFeeBps:e.data.readUInt16LE(98),tier1FeeBps:e.data.readUInt16LE(100),tier2FeeBps:e.data.readUInt16LE(102),tier3FeeBps:e.data.readUInt16LE(104),tier4FeeBps:e.data.readUInt16LE(106),tier5FeeBps:e.data.readUInt16LE(108),oraclePriceToleranceBps:e.data.readUInt16LE(112)};el=Date.now(),ex({protocolFeeRecipient:t,feeSettings:r})}).catch(e=>{console.error("Failed to load global settings:",e)}).finally(()=>{ec=null}))}function ej(e=!1){let t=ei;return!t||!es||!e&&Date.now()-eo<3e5?Promise.resolve():eu||(eu=Promise.all(Y.PROJECT_ALT_ADDRESSES.map(e=>t.getAddressLookupTable(e))).then(e=>{let t=e.map(e=>e.value).filter(e=>null!==e);0!==t.length&&(eo=Date.now(),ex({projectAlt:t[0],projectAlts:t}))}).catch(e=>{console.error("Failed to load project ALTs:",e)}).finally(()=>{eu=null}))}function eS(e=!1){let t=ei,r=en;if(!t||!r||!e&&Date.now()-ed<3e4)return Promise.resolve();if(eh)return eh;let[i]=(0,X.getProfilePda)(r,ea),[s]=(0,X.getUserAccountPda)(r),n=[...ef.keys()].map(e=>{try{return{key:e,mint:new K.PublicKey(e)}}catch{return null}}).filter(e=>null!==e),a=et.protocolFeeRecipient;return eh=Promise.all([t.getAccountInfo(s).then(e=>({userAccountExists:null!==e})).catch(e=>(console.error("Failed to check user account:",e),null)),Promise.all([...n,{key:Q.USDC_MINT.toBase58(),mint:Q.USDC_MINT}].map(async({key:e,mint:r})=>{let s=(0,G.getAssociatedTokenAddressSync)(r,i,!0);return{key:e,exists:null!==await t.getAccountInfo(s)}})).then(e=>{let t={};return e.forEach(e=>{t[e.key]=e.exists}),{userFundingAtaExists:t}}).catch(e=>(console.error("Failed to check ATAs:",e),null)),a?t.getAccountInfo((0,G.getAssociatedTokenAddressSync)(Q.USDC_MINT,a)).then(e=>({protocolFeeAtaExists:null!==e})).catch(()=>({protocolFeeAtaExists:!0})):Promise.resolve(null),Promise.all(n.map(async({key:e,mint:i})=>{let s=(0,G.getAssociatedTokenAddressSync)(i,r);try{let r=await t.getTokenAccountBalance(s);return{key:e,amount:BigInt(r.value.amount)}}catch{return{key:e,amount:BigInt(0)}}})).then(e=>{let t={};return e.forEach(e=>{t[e.key]=e.amount}),{walletCollateralBalance:t}})]).then(e=>
2{if(en?.toBase58()!==r.toBase58())return;let t={};for(let r of e)r&&Object.assign(t,r);ed=Date.now(),ex(t)}).finally(()=>{eh=null})}async function ek(e=!1){ei&&await Promise.all([ew(e),ej(e),eS(e)]),et.isLoading&&ex({isLoading:!1})}async function eN(){ex({isLoading:!0,error:null});try{await ek(!0)}catch(e){ex({error:e instanceof Error?e.message:"Failed to preload trading data"})}finally{ex({isLoading:!1})}}e.s(["useTradingPreload",0,function(e){let{publicKey:r,connection:i}=(0,p.useUnifiedWallet)(),{activeProfileIndex:s}=(0,c.useProfile)(),n=(0,t.useSyncExternalStore)(ev,eg,eb),a=r?.toBase58()??null,l=s??0;return(0,t.useEffect)(()=>{var e;let t,r,s;t=ei!==(e={connection:i??null,walletAddress:a,profileIndex:l}).connection,r=es!==e.walletAddress,s=ea!==e.profileIndex,t&&(ei=e.connection,el=0,eo=0),r&&(es=e.walletAddress,en=e.walletAddress?new K.PublicKey(e.walletAddress):null),ea=e.profileIndex,(r||s||t)&&(en?ed=0:(ed=0,ex({userAccountExists:!1,userFundingAtaExists:J,protocolFeeAtaExists:!0,walletCollateralBalance:Z}))),ey(),ek()},[i,a,l]),(0,t.useEffect)(()=>(function(e){if(!e)return()=>{};let t=ef.get(e)??0;return ef.set(e,t+1),0===t&&en&&(ed=0,eS()),()=>{let t=(ef.get(e)??1)-1;t<=0?ef.delete(e):ef.set(e,t)}})(e),[e]),(0,t.useMemo)(()=>({...n,refresh:eN}),[n])}],193568);var eP=e.i(504458);let eT=(0,eP.default)("flame",[["path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",key:"1slcih"}]]);e.s(["Flame",0,eT],670258);let eC=(0,eP.default)("arrow-right-left",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);e.s(["ArrowRightLeft",0,eC],641971)},989714,e=>{"use strict";var t=e.i(183023);let r=Math.floor(Date.now()/1e3),i=new Set,s=null;function n(e){return i.add(e),null===s&&(r=Math.floor(Date.now()/1e3),s=setInterval(()=>{let e=Math.floor(Date.now()/1e3);if(e!==r)for(let t of(r=e,i))t()},1e3)),()=>{i.delete(e),0===i.size&&null!==s&&(clearInterval(s),s=null)}}let a=()=>()=>{};e.s(["useTickingNowSecs",0,function(e=!0){return(0,t.useSyncExternalStore)(e?n:a,()=>r,()=>r)}])},979804,e=>{"use strict";var t=e.i(183023),r=e.i(913451);e.s(["useTokenIconsVersion",0,function(){return(0,t.useSyncExternalStore)(r.subscribePhoenixTokenIcons,r.getPhoenixTokenIconsVersion,r.getServerPhoenixTokenIconsVersion)}])},390431,5364,e=>{"use strict";var t=e.i(183023),r=e.i(78091),i=e.i(937626),s=e.i(360525);let n=Number.MAX_SAFE_INTEGER;e.s(["useTopPairs",0,function(e,a=3,l){let o=(0,i.usePairTicket)(),d=l&&l.collateralUsd>0&&l.leverage>0?l:o,c=d.collateralUsd>0&&d.leverage>0?d.collateralUsd*d.leverage:100,u=d.leverage>0?d.leverage:3,{candidates:h,isLoading:p}=(0,r.usePairAnalysis)({notionalUsd:c,leverage:u,minCorrelation:.6,universeCap:n,enabled:e}),m=(0,t.useMemo)(()=>(0,s.topDistinctPairs)((0,s.byFastestBreakEven)(h),a),[h,a]);return{pairs:m,candidates:h,isLoading:p&&0===m.length}}],390431);let a=(0,e.i(504458).default)("percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);e.s(["Percent",0,a],5364)},727322,e=>{"use strict";e.i(413358);var t=e.i(508947),r=e.i(183023),i=e.i(860991),s=e.i(739835),n=e.i(308146),a=e.i(616861),l=e.i(999069),o=e.i(894771),d=e.i(142298),c=e.i(905843),u=e.i(190459),h=e.i(643459),p=e.i(799227),m=e.i(689384),f=e.i(116082),x=e.i(586569),g=e.i(299959),b=e.i(762745),v=e.i(858007),y=e.i(936548),w=e.i(855600),j=e.i(610021);let S="https://api.imperial.space";class k extends Error{constructor(e){super(e.message)}}async function N(e,t,r,i){let s=await fetch(`${S}${t}`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let e=await (0,y.errorFromResponse)(s);throw 401===s.status?new k(e):e}let n=await s.json();if(!1===n.success)throw(0,y.errorFromPayload)(n,(0,x.message)("trading","orderRejectedFallback"));if("number"==typeof n.adjustedSizeUsd){let e=e=>(e/1e6).toLocaleString(i,{style:"currency",currency:"USD",maximumFractionDigits:2}),t=e(n.adjustedSizeUsd),s="number"==typeof r.sizeUsd?r.sizeUsd:void 0;f.toast.info(void 0!==s&&s>n.adjustedSizeUsd?(0,x.message)("trading","openedReducedFrom",{final:t,requested:e(s)}):(0,x.message)("trading","openedReduced",{final:t}))}return n.signature||null}async function P(e,t){let r=await fetch(`${S}/api/v1/mobile/orders/batch`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let e=await (0,y.errorFromResponse)(r);throw 401===r.status?new k(e):e}return r.json()}function T(e){return+("long"!==e)}function C(e,t=0){return"number"==typeof e?e:"imperial"===e||null==e?t:(0,u.underwriterByteFrom)(e)??t}e.s(["DEFAULT_SLIPPAGE_BPS",0,300,"underwriterToNum",0,C,"useTradeActions",0,function(){let M=(0,g.useFormatters)(),{jwt:_,walletPubkey:A}=(0,a.useMobileAuth)(),{jwt:E,walletPubkey:L,login:F}=(0,l.useSponsorGas)(),{activeProfileIndex:R,activeProfileUnderwriter:D,activeProfileMarginMode:I}=(0,o.useProfile)(),{wallet:U,publicKey:O,signMessage:B,signAndSendTransaction:z,connection:$}=(0,d.useUnifiedWallet)(),V=E||_,H=(L||A)?.toBase58()??"",W=R??0,q=C(D),[K,G]=(0,r.useState)(!1),Y=(0,r.useRef)(null),X=(0,r.useRef)(V);X.current=V;let Q=(0,r.useRef)(H);Q.current=H;let J=O?.toBase58()??U?.publicKey?.toBase58()??H,Z=(0,r.useRef)({wallet:J});Z.current.wallet!==J&&(Z.current={wallet:J});let ee=Z.current,et=(0,r.useRef)(null);(0,r.useLayoutEffect)(()=>(et.current={},()=>{et.current=null}),[]);let er=(0,r.useCallback)((e,t)=>{if(!t.lifetime||et.current!==t.lifetime||Z.current!==t.owner||t.owner.wallet!==e)throw(0,y.userErrorWithCopy)("WalletChanged",(0,x.message)("trading","walletChangedReviewOrder"))},[]),ei=(0,r.useCallback)(async()=>{let t=U?.publicKey??null;
2if(!t||!B)throw(0,y.userErrorWithCopy)("WalletNotConnected",(0,x.message)("trading","connectWalletToTrade"));let r=t.toBase58(),i={owner:ee,lifetime:et.current};er(r,i);let s=Date.now().toString(),n=`imperial:mobile-connect:${r}:${s}`,a=await B(new TextEncoder().encode(n));er(r,i);let l=(await e.A(730276).then(e=>e.default)).encode(a);er(r,i);let o=await fetch(`${S}/api/v1/mobile/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wallet:r,message:n,signature:l})});if(!o.ok)throw await (0,y.errorFromResponse)(o,(0,x.message)("trading","sessionCreateFailed"));let{code:d}=await o.json();er(r,i);let c=await fetch(`${S}/api/v1/mobile/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:d})});if(!c.ok)throw await (0,y.errorFromResponse)(c,(0,x.message)("trading","sessionActivateFailed"));let{jwt:u,expiresAt:h}=await c.json();return er(r,i),F(u,r,h),X.current=u,Q.current=r,u},[U,B,F,er,ee]),es=(0,r.useCallback)(async()=>X.current?X.current:ei(),[ei]),en=(0,r.useCallback)(async(e,t)=>{let r={owner:ee,lifetime:et.current},i="string"==typeof t.wallet&&t.wallet?t.wallet:r.owner.wallet;er(i,r);let s=await es();er(i,r),t.wallet=i;try{return await N(s,e,t,M.intlTag)}catch(n){if(n instanceof k)return er(i,r),X.current=null,s=await ei(),er(i,r),N(s,e,t,M.intlTag);throw n}},[es,ei,M,er,ee]),ea=(0,r.useCallback)(async e=>{let t=async t=>{let r=await fetch(`${S}/api/v1/mobile/orders/preflight`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let e=await (0,y.errorFromResponse)(r);throw 401===r.status?new k(e):e}return await r.json()},r={owner:ee,lifetime:et.current},i="string"==typeof e.wallet&&e.wallet?e.wallet:r.owner.wallet;er(i,r);let s=await es();er(i,r),e.wallet=i;try{return await t(s)}catch(e){if(e instanceof k)return er(i,r),X.current=null,s=await ei(),er(i,r),t(s);throw e}},[es,ei,er,ee]);function el(e){return Math.floor(1e6*e)}function eo(e){return Math.floor(1e9*e)}function ed(e,t){if("number"!=typeof e||e<=0)throw Error(`Missing or invalid ${t}`);return e}async function ec(t,r){if(2===r){let{getGlobalPhoenixRegistry:r}=await e.A(835152),i=r(),s=i?.getMarketBySymbol(t);if(s)return s.orderbook.toBase58();let{JUPITER_MARKETS:n}=await e.A(638110),a=n[t]?.symbol??(0,h.resolveMintSymbol)(t)??null;if(a){let e=i?.getMarketBySymbol(a)??i?.getMarketBySymbol(a.toUpperCase());if(e)return e.orderbook.toBase58()}}if(3===r){let{getGlobalGmTradeRegistry:r}=await e.A(47613),i=r(),s=i?.getMarketBySymbol(t)??i?.getMarketBySymbol(t.toUpperCase());if(s)return s.indexTokenMint.toBase58();let{JUPITER_MARKETS:n}=await e.A(638110),a=n[t]?.symbol??(0,h.resolveMintSymbol)(t)??null;if(a){let e=i?.getMarketBySymbol(a)??i?.getMarketBySymbol(a.toUpperCase());if(e)return e.indexTokenMint.toBase58()}}return 7===r?(0,h.resolveMintSymbol)(t)??t:t}function eu(e,t){return 0===e?0:3===t?eo(e):el(e)}async function eh(e,r,i,s,n,a,l,o,d,c,h,p,m,f,x,g,b){return{wallet:H,marketMint:await ec(e,f),side:r,orderType:i,action:s,triggerCondition:n,sizeUsd:el(a),collateralAmount:el(l),slippageBps:o,triggerPrice:eo(d),marketPrice:eu(c,f),profileIndex:h,priority:p,fundingStatus:m,underwriter:f,requestedHedgeVenue:(0,u.hedgeVenueByteForUnderwriter)(f),extraData:(0,t.sunriseOrderExtra)(f,s,h,R,I,x)??null,...g?{parentOrderPda:g}:{},...b&&b.loanAmountUsd>0?{loanAmountUsd:el(b.loanAmountUsd),...void 0!==b.loanPositionIndex?{loanPositionIndex:b.loanPositionIndex}:{}}:{}}}async function ep(e,t,r,i,s,n,a,l,o,d,c,u,h,p,m,f,x,g){let b=await eh(e,t,r,i,s,n,a,l,o,d,c,u,h,p,m,f,x);return g&&(b.quote=g),en("/api/v1/mobile/orders",b)}function em(e){return e.sizeUsd&&e.sizeUsd>0?e.sizeUsd:(e.collateralAmount??0)*(e.leverage??1)}function ef(e){return void 0!==e.fundingStatus?e.fundingStatus:void 0!==e.deferFunding?+!!e.deferFunding:0}function ex(e,t){if(void 0===e.profileIndex||null===e.profileIndex)throw Error(`${t}: profileIndex is required and must come from the position being closed.`);return e.profileIndex}function eg(e,t){if("string"!=typeof e.underwriter&&"number"!=typeof e.underwriter||""===e.underwriter||Number.isNaN(e.underwriter))throw Error(`${t}: underwriter is required and must come from the position being closed.`);return C(e.underwriter)}function eb(e){return"number"!=typeof e.closeBps?(0,t.sunriseSeatExtra)(e):{closeBps:Math.max(0,Math.min(1e4,Math.round(e.closeBps))),...(0,t.sunriseSeatExtra)(e)}}function ev(e,t,r=!0){return en("/api/v1/mobile/orders/cancel",{wallet:H,orderPda:e,profileIndex:t,cascadeChildren:r})}async function ey(e,t,r,i,s,n,a){let l="long"===r,o=T(r),d=e.sizePercent,u="number"==typeof d&&d>0&&d<100,h=u?Math.max(0,Math.min(1e4,Math.round(100*d))):1e4,p=u?{closeBps:h}:{};switch(e.type){case"tp":return eh(t,o,c.PassthroughOrderType.StopLimit,1,+!l,i,0,a,e.triggerPrice,0,n,0,0,s,{closeBps:h});case"sl":return eh(t,o,c.PassthroughOrderType.StopLimit,1,+!!l,i,0,a,e.triggerPrice,0,n,0,0,s,{closeBps:h});case"ratchet":return eh(t,o,c.PassthroughOrderType.Ratchet,1,+!!l,i,0,a,ed(e.worstPrice,"worstPrice"),0,n,0,0,s,{closeBps:h,worstPrice:eo(ed(e.worstPrice,"worstPrice")),ratchetSize:eo(e.ratchetSize),triggerDelaySeconds:0});case"fib_ratchet":return eh(t,o,c.PassthroughOrderType.FibRatchet,1,+!!l,i,0,a,ed(e.worstPrice,"worstPrice"),0,n,0,0,s,{closeBps:h,worstPrice:eo(ed(e.worstPrice,"worstPrice")),ratchetSize:eo(e.ratchetSize),triggerDelaySeconds:0,reverse:e.reverse});case"dca_close":return eh(t,o,c.PassthroughOrderType.DcaClose,1,+(e.startPrice>e.endPrice),i,0,a,e.startPrice,0,n,0,0,s,{...p,dcaCloseStartPrice
2:eo(e.startPrice),dcaCloseEndPrice:eo(e.endPrice),dcaCloseNumLegs:e.numLegs,dcaCloseWeightingType:e.weightingType??0});case"dca_time_close":return eh(t,o,c.PassthroughOrderType.DcaTimeClose,1,+!l,i,0,a,e.priceLimit??0,0,n,0,0,s,{...p,dcaClosePriceLimit:eo(e.priceLimit??0),dcaCloseIntervalSeconds:e.intervalSeconds,dcaCloseNumLegs:e.numLegs,dcaCloseWeightingType:e.weightingType??0,dcaCloseStartDelaySeconds:e.startDelaySeconds??0});case"dca_ratchet_close":return eh(t,o,c.PassthroughOrderType.DcaRatchetClose,1,+!l,i,0,a,e.priceLimit??0,0,n,0,0,s,{...p,dcaClosePriceLimit:eo(e.priceLimit??0),dcaCloseIntervalSeconds:e.intervalSeconds,dcaCloseNumLegs:e.numLegs,dcaCloseWeightingType:e.weightingType??0,dcaCloseRatchetSize:eo(e.ratchetSize),dcaCloseStartDelaySeconds:e.startDelaySeconds??0});default:return null}}async function ew(e,r){let i;r.forEach(r=>(0,t.inheritSunriseEntrySeat)(e,r));let s={owner:ee,lifetime:et.current},n="string"==typeof e.wallet&&e.wallet?e.wallet:s.owner.wallet;er(n,s);let a=await es();er(n,s),e.wallet=n,r.forEach(e=>{if(e.wallet&&e.wallet!==n)throw Error("Attached order wallet differs from entry");e.wallet=n});try{i=await P(a,{entry:e,closeOrders:r})}catch(t){if(t instanceof k)er(n,s),X.current=null,a=await ei(),er(n,s),i=await P(a,{entry:e,closeOrders:r});else throw t}if(!i.entry.success)throw(0,y.errorFromPayload)(i.entry,(0,x.message)("trading","orderRejectedFallback"));let l=(0,x.message)("trading","closeOrderNotPlaced"),o=[...new Set(i.closeOrders.flatMap((e,t)=>e.success?[]:(console.error(`[batch] close leg ${t} rejected`,e),[(0,w.chainActionError)((0,y.errorFromPayload)(e,l),l,"passthrough")])))];return{entrySignature:i.entry.signature??"",closeFailures:o}}let ej=(0,r.useRef)(null),eS=(0,r.useRef)(null),ek=(0,r.useRef)(null);function eN(e,t){return async r=>{let i=Array.isArray(r)?void 0:r;G(!0),Y.current&&clearTimeout(Y.current),ej.current=null,eS.current=null,ek.current=null;try{let s=await t(r);return null===s||i?.silent||"closePosition"===e&&i?.submissionSound===!1||(0,b.playSound)("orderSubmitted"),s}catch(t){if(ek.current=t,(0,j.isSunriseArriving)(t)||(eS.current=(0,s.isUserRejection)(t),eS.current||(console.error("[trade-action] Failed",{action:e,buildId:"a99c7ad",marketMint:i?.marketMint,underwriter:i?.underwriter,profileIndex:i?.profileIndex??void 0},t),(0,v.reportTradeError)(t,{stage:"trade_action",action:e,wallet:Q.current||U?.publicKey?.toBase58(),positionPda:i?.positionPubkey,marketMint:i?.marketMint,underwriter:i?.underwriter,profileIndex:i?.profileIndex??void 0,sunriseSeat:i?.sunriseSeat,closeBps:i?.closeBps})),i?.silent))throw t;return f.toast.error((0,y.displayClientError)(t)),(0,b.playSound)("orderError"),null}finally{Y.current=setTimeout(()=>G(!1),800)}}}return{...{preflightOpenPosition:eN("preflightOpenPosition",async e=>{let r=em(e),i=C(e.underwriter,q),s=e.profileIndex??W,n=await eh(e.marketMint,T(e.side),c.PassthroughOrderType.Market,0,0,r,e.collateralAmount,e.slippageBps??100,0,e.currentPrice??0,s,0,0,i,(0,t.sunriseSeatExtra)(e),void 0,e.loanLeg);try{return await ea(n)}catch(e){return console.warn("[preflight] check unavailable, proceeding",e),{ok:!0}}}),openPositionViaPassthrough:eN("openPositionViaPassthrough",async e=>{let r=em(e),i=C(e.underwriter,q),s=e.profileIndex??W,n=e.closeSlippageBps??300,a=await eh(e.marketMint,T(e.side),c.PassthroughOrderType.Market,0,0,r,e.collateralAmount,e.slippageBps??100,0,e.currentPrice??0,s,0,0,i,(0,t.sunriseSeatExtra)(e),void 0,e.loanLeg);if(!e.closeOrders?.length)return en("/api/v1/mobile/orders",a);let l=[];for(let t of e.closeOrders){let a=await ey(t,e.marketMint,e.side,r,i,s,n);a&&l.push(a)}let{entrySignature:o,closeFailures:d}=await ew(a,l);return d.length>0&&(ej.current=d,f.toast.error((0,x.message)("trading","openedTpSlAttachFailed",{reasons:d.join(" ")}))),o||null}),closePosition:eN("closePosition",async e=>{if("venue_direct"===e.ownership&&"phoenix"===e.underwriter){if(!U?.publicKey||!e.directVenue)throw Error("Connect the wallet that owns this Phoenix position to close it.");let t=e.entirePosition?1e4:Math.max(1,Math.min(1e4,Math.round(e.closeBps??0))),r=await (0,m.buildPhoenixDirectCloseTransaction)({walletAddress:U.publicKey.toBase58(),symbol:e.asset,pdaIndex:e.directVenue.pdaIndex,subaccountIndex:e.directVenue.subaccountIndex,closeBps:t,slippageBps:e.slippageBps??300}),s=Uint8Array.from(atob(r.serializedTransaction),e=>e.charCodeAt(0)),n=p.Transaction.from(s),a=await z(n);return await (0,i.confirmOrVerifyLanded)($,{signature:a,blockhash:n.recentBlockhash,lastValidBlockHeight:r.lastValidBlockHeight},"confirmed"),a}let r=eg(e,"closePosition"),s=ex(e,"closePosition"),n=e.entirePosition?1e4:"number"==typeof e.closeBps?Math.max(0,Math.min(1e4,Math.round(e.closeBps))):0;return ep(e.marketMint,T(e.side),c.PassthroughOrderType.Market,1,0,e.sizeUsd??0,e.collateralUsd??0,e.slippageBps??100,0,e.currentPrice??0,s,0,0,r,{closeBps:n,...(0,t.sunriseSeatExtra)(e)})}),openLimitOrderViaPassthrough:eN("openLimitOrderViaPassthrough",async e=>{let r=em(e),i=C(e.underwriter,q),s=e.profileIndex??W,n=e.slippageBps??100,a=e.slippageBps??300,l=await eh(e.marketMint,T(e.side),c.PassthroughOrderType.Limit,0,+("long"===e.side),r,e.collateralAmount??0,n,ed(e.triggerPrice,"triggerPrice"),0,s,e.priority??0,ef(e),i,(0,t.sunriseSeatExtra)(e),void 0,e.loanLeg);if(!e.closeOrders?.length)return en("/api/v1/mobile/orders",l);let o=[];for(let t of e.closeOrders){let n=await ey(t,e.marketMint,e.side,r,i,s,a);n&&o.push(n)}let{entrySignature:d,closeFailures:u}=await ew(l,o);return u.length>0&&(ej.current=u,f.toast.error((0,x.message)("trading","limitTpSlAttachFailed",{reasons:u.join(" ")}))),d||null}),createTriggerOrder:eN("createTriggerOrder",async e=>{let t="long"===e.side,r=e.isTakeProfit,i=ex(e,"createTriggerOrder"),s=eg(e,"createTriggerOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.StopLimit,1,t&&r||!t&&!r?0:1,e.sizeUsd??0,0,e.slippageBps??300,ed(e.triggerPrice,"triggerPrice"),0,i,0,0,s,eb(e),e.parentOrderPda,void 0,e.quote)}),createRatchetOrder:eN("createRatchetOrder",async e=>{let t=ex(e,"createRatchetOrder"),r=eg(e,"createRatchetOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.Ratchet,1,+("long"===e.side),e.sizeUsd??0,0,e.slippageBps??300,ed(e.currentPrice??e.triggerPrice,"triggerPrice"),0,t,e.priority??0,0,r,{worstPrice:eo(ed(e.worstPrice,"worstPrice")),ratchetSize:eo(e.ratchetSize),...void 0!==e.stopTriggerPrice&&e.stopTriggerPrice>0?{stopTriggerPrice:eo(e.stopTriggerPrice)}:{},triggerDelaySeconds:0,...eb(e)},e.parentOrderPda)}),createRatchetEntryOrder:eN("createRatchetEntryOrder",async e=>ep(e.marketMint,T(e.side),c.PassthroughOrderType.RatchetEntry,0,+("long"!==e.side),em(e),e.collateralAmount??0,e.slippageBps??100,ed(e.currentPrice??e.triggerPrice,"triggerPrice"),0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{worstPrice:eo(e.worstPrice),ratchetSize:eo(e.ratchetSize),triggerDelaySeconds:0},void 0,e.loanLeg)),createFibRatchetOrder:eN("createFibRatchetOrder",async e=>{let t=ex(e,"createFibRatchetOrder"),r=eg(e,"createFibRatchetOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.FibRatchet,1,+("long"===e.side),e.sizeUsd??0,0,e.slippageBps??300,ed(e.currentPrice??e.triggerPrice,"triggerPrice"),0,t,e.priority??0,0,r,{worstPrice:eo(ed(e.worstPrice,"worstPrice")),ratchetSize:eo(e.ratchetSize),triggerDelaySeconds:0,reverse:e.reverse,...eb(e)},e.parentOrderPda)}),createFibRatchetEntryOrder:eN("createFibRatchetEntryOrder",async e=>ep(e.marketMint,T(e.side),c.PassthroughOrderType.FibRatchetEntry,0,+("long"!==e.side),em(e),e.collateralAmount??0,e.slippageBps??100,ed(e.currentPrice??e.triggerPrice,"triggerPrice"),0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{worstPrice:eo(e.worstPrice),ratchetSize:eo(e.ratchetSize),triggerDelaySeconds:0,reverse:e.reverse},void 0,e.loanLeg)),createLandmineOrder:eN("createLandmineOrder",async e=>ep(e.marketMint,T(e.side),c.PassthroughOrderType.LandMine,0,+("long"===e.side),em(e),e.collateralAmount??0,e.slippageBps??100,ed(e.triggerPrice,"triggerPrice"),0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{waitPrice:eo(e.waitPrice),waitDuration:e.waitDuration,triggerDelaySeconds:0},void 0,e.loanLeg)),createIndicatorOrder:eN("createIndicatorOrder",async e=>{let t=(e.ratchetSize??0)>0?c.PassthroughOrderType.IndicatorRatchet:c.PassthroughOrderType.Indicator;return ep(e.marketMint,T(e.side),t,0,+("long"!==e.side),em(e),e.collateralAmount??0,e.slippageBps??100,0,0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{indicatorType:e.indicatorType??0,timeframeCode:e.timeframeCode,period:e.period,indicatorCondition:e.indicatorCondition,thresholdValue:el(e.thresholdValue),worstPrice:eo(e.worstPrice??0),ratchetSize:el(e.ratchetSize??0),triggerDelaySeconds:0,indicatorAux:e.indicatorAux??0},void 0,e.loanLeg)}),createIndicatorCloseOrder:eN("createIndicatorCloseOrder",async e=>{let t=(e.ratchetSize??0)>0?c.PassthroughOrderType.IndicatorRatchet:c.PassthroughOrderType.Indicator,r=ex(e,"createIndicatorCloseOrder"),i=eg(e,"createIndicatorCloseOrder");return ep(e.marketMint,T(e.side),t,1,+("long"===e.side),e.sizeUsd??0,0,e.slippageBps??300,0,0,r,e.priority??0,0,i,{indicatorType:e.indicatorType??0,timeframeCode:e.timeframeCode,period:e.period,indicatorCondition:e.indicatorCondition,thresholdValue:el(e.thresholdValue),worstPrice:eo(e.worstPrice??0),ratchetSize:el(e.ratchetSize??0),triggerDelaySeconds:0,indicatorAux:e.indicatorAux??0,...eb(e)},e.parentOrderPda)}),createDcaOrder:eN("createDcaOrder",async e=>{let t=ed(e.startPrice,"startPrice"),r=ed(e.endPrice,"endPrice");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.Dca,0,+(t>r),em(e),e.collateralAmount??0,e.slippageBps??100,e.currentPrice??e.triggerPrice??0,0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{dcaStartPrice
2:eo(t),dcaEndPrice:eo(r),dcaNumLegs:ed(e.numLegs,"numLegs"),dcaWeightingType:e.weightingType??0,dcaTriggerType:e.triggerType??0,dcaLeverageWeightingType:0,dcaStartLeverageScaled:0,dcaEndLeverageScaled:0},void 0,e.loanLeg)}),createDcaTimeOrder:eN("createDcaTimeOrder",async e=>ep(e.marketMint,T(e.side),c.PassthroughOrderType.DcaTime,0,+("long"!==e.side),em(e),e.collateralAmount??0,e.slippageBps??100,e.currentPrice??e.triggerPrice??0,0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{dcaPriceLimit:eo(e.priceLimit??0),dcaIntervalSeconds:ed(e.intervalSeconds,"intervalSeconds"),dcaNumLegs:ed(e.numLegs,"numLegs"),dcaWeightingType:e.weightingType??0,dcaLeverageWeightingType:0,dcaStartLeverageScaled:0,dcaEndLeverageScaled:0,dcaStartDelaySeconds:e.startDelaySeconds??0},void 0,e.loanLeg)),createDcaRatchetOrder:eN("createDcaRatchetOrder",async e=>ep(e.marketMint,T(e.side),c.PassthroughOrderType.DcaRatchet,0,+("long"!==e.side),em(e),e.collateralAmount??0,e.slippageBps??100,e.currentPrice??e.triggerPrice??0,0,e.profileIndex??W,e.priority??0,ef(e),C(e.underwriter,q),{dcaPriceLimit:eo(e.priceLimit??0),dcaIntervalSeconds:e.intervalSeconds??0,dcaNumLegs:ed(e.numLegs,"numLegs"),dcaWeightingType:e.weightingType??0,dcaRatchetSize:eo(ed(e.ratchetSize,"ratchetSize")),dcaLeverageWeightingType:0,dcaStartLeverageScaled:0,dcaEndLeverageScaled:0,dcaStartDelaySeconds:e.startDelaySeconds??0},void 0,e.loanLeg)),createDcaCloseOrder:eN("createDcaCloseOrder",async e=>{let r=ed(e.startPrice,"startPrice"),i=ed(e.endPrice,"endPrice"),s=+(r>i),n=ex(e,"createDcaCloseOrder"),a=eg(e,"createDcaCloseOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.DcaClose,1,s,e.sizeUsd??0,0,e.slippageBps??300,r,0,n,e.priority??0,0,a,{...(0,t.sunriseSeatExtra)(e),dcaCloseStartPrice:eo(r),dcaCloseEndPrice:eo(i),dcaCloseNumLegs:ed(e.numLegs,"numLegs"),dcaCloseWeightingType:e.weightingType??0},e.parentOrderPda)}),createDcaTimeCloseOrder:eN("createDcaTimeCloseOrder",async e=>{let r=ex(e,"createDcaTimeCloseOrder"),i=eg(e,"createDcaTimeCloseOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.DcaTimeClose,1,+("long"!==e.side),e.sizeUsd??0,0,e.slippageBps??300,e.priceLimit??0,0,r,e.priority??0,0,i,{...(0,t.sunriseSeatExtra)(e),dcaClosePriceLimit:eo(e.priceLimit??0),dcaCloseIntervalSeconds:ed(e.intervalSeconds,"intervalSeconds"),dcaCloseNumLegs:ed(e.numLegs,"numLegs"),dcaCloseWeightingType:e.weightingType??0,dcaCloseStartDelaySeconds:e.startDelaySeconds??0},e.parentOrderPda)}),createDcaRatchetCloseOrder:eN("createDcaRatchetCloseOrder",async e=>{let r=ex(e,"createDcaRatchetCloseOrder"),i=eg(e,"createDcaRatchetCloseOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.DcaRatchetClose,1,+("long"!==e.side),e.sizeUsd??0,0,e.slippageBps??300,e.priceLimit??0,0,r,e.priority??0,0,i,{...(0,t.sunriseSeatExtra)(e),dcaClosePriceLimit:eo(e.priceLimit??0),dcaCloseIntervalSeconds:e.intervalSeconds??0,dcaCloseNumLegs:ed(e.numLegs,"numLegs"),dcaCloseWeightingType:e.weightingType??0,dcaCloseRatchetSize:eo(ed(e.ratchetSize,"ratchetSize")),dcaCloseStartDelaySeconds:e.startDelaySeconds??0},e.parentOrderPda)}),createPrivateTpSlOrder:eN("createPrivateTpSlOrder",async e=>{let t=ex(e,"createPrivateTpSlOrder"),r=eg(e,"createPrivateTpSlOrder");return ep(e.marketMint,T(e.side),c.PassthroughOrderType.PrivateTpSl,1,0,e.sizeUsd??0,0,e.slippageBps??300,0,0,t,0,0,r,eb(e))}),createPassthroughOrder:eN("createPassthroughOrder",async e=>{let r="string"==typeof e.side?T(e.side):e.side,i=void 0!==e.isTakeProfit||1===e.action,s=i?eg(e,"createPassthroughOrder"):"string"==typeof e.underwriter?C(e.underwriter,q):e.underwriter??q,n=i?ex(e,"createPassthroughOrder"):e.profileIndex??W;if(void 0!==e.isTakeProfit&&void 0===e.orderType){let t=0===r,i=e.isTakeProfit;return ep(e.marketMint,r,c.PassthroughOrderType.StopLimit,1,t&&i||!t&&!i?0:1,e.sizeUsd??0,0,e.slippageBps??300,e.triggerPrice??0,0,n,0,0,s,eb(e),e.parentOrderPda)}return ep(e.marketMint,r,e.orderType,e.action,e.triggerCondition,e.sizeUsd,e.collateralAmount,e.slippageBps,e.triggerPrice,0,n,e.priority??0,e.fundingStatus??0,s,{...e.extraData,...(0,t.sunriseSeatExtra)(e)},e.parentOrderPda)}),cancelPassthroughOrder:eN("cancelPassthroughOrder",async e=>ev(e.orderPda,e.profileIndex)),cancelPassthroughOrders:eN("cancelPassthroughOrders",async e=>{let t=Array.isArray(e)?e:[];for(let e of t)await ev(e.orderPda,e.profileIndex??0);return t.length>0?"batch_cancelled":null}),updatePassthroughOrder:eN("updatePassthroughOrder",async e=>{let t=e.proOrderUpdate,r="number"==typeof e.closeBps?Math.max(0,Math.min(1e4,Math.round(e.closeBps))):void 0;return en("/api/v1/mobile/orders/update",{wallet:H,orderPda:e.orderPda,profileIndex:e.profileIndex,triggerPrice:null!=e.triggerPrice?eo(e.triggerPrice):void 0,sizeUsd:null!=e.sizeUsd?el(e.sizeUsd):void 0,slippageBps:e.slippageBps,priority:e.priority,closeBps:r,proOrderUpdate:t?{type:t.type,worstPrice:null!=t.worstPrice?eo(t.worstPrice):void 0,ratchetSize:null!=t.ratchetSize?eo(t.ratchetSize):void 0,stopTrigger:null!=t.stopTriggerPrice?t.stopTriggerPrice>0?eo(t.stopTriggerPrice):0:void 0,waitPrice:null!=t.waitPrice?eo(t.waitPrice):void 0,waitDurationSeconds:t.waitDurationSeconds}:void 0,quote:e.quote})}),batchUpdatePassthroughPriorities:eN("batchUpdatePassthroughPriorities",async e=>{let t=Array.isArray(e)?e:e.updates??e.orderUpdates??[];for(let r of t)await en("/api/v1/mobile/orders/update",{wallet:H,orderPda:r.orderPda,profileIndex:r.profileIndex??(Array.isArray(e)?void 0:e.profileIndex)??W,priority:r.priority});return t.length>0?"batch_updated":null}),executeOrderAtMarket:eN("executeOrderAtMarket",async e=>{await ev(e.orderPda,e.profileIndex??W,!1);try{return await ep(e.marketMint,T(e.side),c.PassthroughOrderType.Market,0,0,em(e),e.collateralAmount??0,e.slippageBps??100,0,e.currentPrice??0,e.profileIndex??W,0,0,C(e.underwriter,q),{...(0,t.sunriseSeatExtra)(e),...7===C(e.underwriter,q)?{sunriseConversionOrderPda:e.orderPda}:{}},void 0,e.loanLeg)}catch(e){throw new y.ImperialUserError((0,x.message)("trading","restingOrderCanceledNoOpen",{reason:(0,y.displayClientError)(e)}),e instanceof y.ImperialUserError?e.details:void 0)}}),cancelTriggerOrder:eN("cancelTriggerOrder",async e=>{let t=e.orderPda??e.positionRequestPubkey;if("string"!=typeof t||!t.trim())throw Error("Missing order identifier for TP/SL cancellation");return ev(t,e.profileIndex??W)}),updateTriggerOrder:eN("updateTriggerOrder",async e=>en("/api/v1/mobile/orders/update",{wallet:H,orderPda:e.orderPda??e.positionRequestPubkey,profileIndex:e.profileIndex??W,triggerPrice:null!=e.triggerPrice?eo(e.triggerPrice):void 0,sizeUsd:null!=e.sizeUsd?el(e.sizeUsd):void 0,quote:e.quote})),depositCollateral:eN("depositCollateral",async e=>{let t=C(e.underwriter,q);return en("/api/v1/mobile/orders/collateral",{wallet:H,marketMint:await ec(e.marketMint,t),side:T(e.side),action:0,sunriseMarginMode:e.sunriseMarginMode,collateralAmount:el(e.collateralAmount??e.depositAmount??0),slippageBps:e.slippageBps??100,profileIndex:e.profileIndex??W,underwriter:t,price:eu(e.currentPrice??0,t)})}),withdrawCollateral:eN("withdrawCollateral",async e=>{let t=(0,n.floorNumberToBaseUnits)(e.collateralAmount??e.withdrawAmount??0,6
2);if(null===t)throw Error("Invalid withdrawal amount");let r=C(e.underwriter,q);return en("/api/v1/mobile/orders/collateral",{wallet:H,marketMint:await ec(e.marketMint,r),side:T(e.side),action:1,positionPubkey:2===r?e.positionPubkey:void 0,sunriseMarginMode:e.sunriseMarginMode,collateralAmount:Number(t),slippageBps:e.slippageBps??100,profileIndex:e.profileIndex??W,underwriter:r,price:eu(e.currentPrice??0,r)})})},submitting:K,getLastCloseOrderFailures:()=>ej.current,wasLastErrorRejection:()=>eS.current,getLastActionError:()=>ek.current}}])},432313,e=>{"use strict";var t=e.i(183023),r=e.i(21859),i=e.i(214732),s=e.i(653982);e.s(["useUsdcWalletBalance",0,function(e){let n=(0,t.useMemo)(()=>{if(!e)return null;try{return(0,r.getAssociatedTokenAddressSync)(s.USDC_MINT,e)}catch{return null}},[e?.toBase58()]),{data:a,isLoading:l,error:o,refetch:d}=(0,i.useAccountSubscription)({account:n,decoder:e=>(function(e){try{if(e.length<72)return null;return{amount:e.readBigUInt64LE(64)}}catch{return null}})(e.data),commitment:"processed",enabled:!!n}),[c,u]=(0,t.useState)(0),h=n?.toBase58()??null;(0,t.useEffect)(()=>u(0),[h]),(0,t.useEffect)(()=>{if(!o||!h||c>=4)return;let e=setTimeout(()=>{u(e=>e+1),d()},1e3*2**c);return()=>clearTimeout(e)},[h,c,o,d]);let p=a?.amount??BigInt(0),m=Number(p)/1e6;return{rawBalance:p,uiBalance:m,ata:n,isLoading:l,error:o,known:!!n&&!l&&!o,refetch:d}}])},872541,470981,346731,616730,e=>{"use strict";var t=e.i(797699),r=e.i(51314);e.s(["trackOrderSubmitted",0,function(e){let{marketMint:i,venue:s,...n}=e;(0,t.gtagEvent)("order_submitted",{...n,market:(0,r.toUrlSlug)(i),venue:s})}],872541);let i=0,s=null,n=new Set;e.s(["pulseMark",0,{subscribe:function(e){return n.add(e),()=>{n.delete(e)}},getSnapshot:function(){return i},getServerSnapshot:function(){return 0},getLastReason:function(){return s},trigger:function(e){for(let t of(i+=1,s=e,n))try{t()}catch{}}}],470981);let a=new Set(["flash_trade","flash_v2","pairs","touch","sunrise"]),l=e=>Math.round(1e6*e);function o(e){return"deleted"!==e.status&&"increase"===e.action&&!!e.collateralAmount&&!(e.collateralAmount<=0)&&(1===e.fundingStatus||void 0!==e.underwriter&&a.has(e.underwriter))}function d(e,t){return l(e.collateralAmount??0)>l(t)}e.s(["BOT_STATE_INSUFFICIENT_FUNDS",0,"insufficient_funds","fundingShortfallUsd",0,function(e,t){return o(e)?d(e,t)?(e.collateralAmount??0)-t:0:null},"ordersStrandedBySpend",0,function(e,t,r,i){if(i<=0)return[];let s=Math.max(0,r-i);return e.filter(e=>e.profileIndex===t&&o(e)&&!d(e,r)&&d(e,s))}],346731),e.s(["minimumOrderCollateral",0,function({minimumUsd:e,isUnifiedMargin:t,side:r,asset:i,profileIndex:s,positions:n}){let a=n.some(e=>e.asset===i&&e.side===r&&"open"===e.status&&e.profileIndex===s);return t||a?0:e}],616730)},451620,e=>{"use strict";e.i(413358);let t="https://api.imperial.space";async function r(e,i,s=50){let n=new URLSearchParams;e&&n.set("filter",e),i&&n.set("wallet",i),n.set("limit",s.toString());let a=await fetch(`${t}/api/v1/battles?${n}`,{cache:"no-store"});if(!a.ok)throw Error(`Failed to list battles (${a.status})`);return a.json()}async function i(e){let r=await fetch(`${t}/api/v1/battles/${e}`,{cache:"no-store"});if(!r.ok)throw Error(`Failed to fetch battle (${r.status})`);return r.json()}async function s(r,i,s,n,a,l){let o={"Content-Type":"application/json"};if(a)o.Authorization=`Bearer ${a}`;else if(n){let t=`imperial:battle:register:${r}`,s=await n(new TextEncoder().encode(t)),a=await e.A(730276).then(e=>e.default.encode(s));o["x-pubkey"]=i,o["x-signature"]=a}let d={wallet:i,profileIndex:s};l&&(d.clanId=l);let c=await fetch(`${t}/api/v1/battles/${r}/register`,{method:"POST",headers:o,body:JSON.stringify(d)});if(!c.ok)throw Error(await c.text()||`Registration failed (${c.status})`);return c.json()}async function n(e,r){let i=await fetch(`${t}/api/v1/passthrough/users/${e}/profiles/${r}
2/active-battle`,{cache:"no-store"});if(!i.ok)throw Error(`Failed to fetch active battle (${i.status})`);return i.json()}e.s(["getActiveBattleForProfile",0,n,"getBattle",0,i,"listBattles",0,r,"registerForBattle",0,s])},267912,e=>{"use strict";e.i(413358);let t="https://api.imperial.space";async function r(t,r,i,s){let n={"Content-Type":"application/json"};if(s)n.Authorization=`Bearer ${s}`;else if(i){let s=await i(new TextEncoder().encode(r)),a=await e.A(730276).then(e=>e.default);n["x-pubkey"]=t,n["x-signature"]=a.encode(s)}return n}async function i(e,r={}){let s=new URLSearchParams;for(let[e,t]of Object.entries(r))null!=t&&s.set(e,String(t));let n=await fetch(`${t}/api/v1/passthrough/users/${e}/pair-links?${s}`);if(!n.ok)throw Error(`pair-links ${n.status}`);return n.json()}async function s(e,i,s,n,a){let l=await r(e,`imperial:pair-link:${e}`,n,a),o=await fetch(`${t}/api/v1/passthrough/users/${e}/pair-links`,{method:"POST",headers:l,body:JSON.stringify({label:i,legs:s})});if(!o.ok)throw Error(await o.text()||`create pair-link ${o.status}`);return o.json()}e.s(["createPairLink",0,s,"fetchPairLinks",0,i])},702193,148974,e=>{"use strict";function t(e){return e?.openPositions===0&&!(null!=e.initialMarginUsd&&e.initialMarginUsd>0)}e.s(["armadaAccountIsCash",0,t,"armadaOrderPullableUsd",0,function(e,r){return null==e?null:t(r)?e:0},"landedSpendRaw",0,function(e,t){return null===e||e+10000n<t?null:e<t?e:t},"orderAfterArmadaPull",0,function({pulled:e,elapsedMs:t,stillValid:r}){return e?r&&t<=1e4?"submit":"confirm":"submit"},"planArmadaPull",0,function(e,t,r){if(t+10000n>=e)return{kind:"enough"};let i=e-t;return i>BigInt(Math.floor(1e6*Math.max(0,r)))+10000n?{kind:"uncoverable"}:{kind:"pull",pullUsd:Math.min(r,Math.ceil(Number(i)/1e4)/100)}},"spendMayNeedArmadaPull",0,function(e,t,r){return null!=t&&e>t||null!=t&&null!=r&&r>0&&t-e<1},"spendableWithArmadaAccount",0,function(e,t){return null==e?null:e+(t??0)}],702193);var r=e.i(183023),i=e.i(942553),s=e.i(116082),n=e.i(299959),a=e.i(610021);let l=e=>new Promise(t=>setTimeout(t,e));e.s(["useArrivingWithdrawal",0,function(){let e=(0,i.useTranslations)("positions"),t=(0,n.useFormatters)(),[o,d]=(0,r.useState)(!1),c=(0,r.useRef)(!1);return(0,r.useEffect)(()=>(c.current=!1,()=>{c.current=!0}),[]),{awaitingReturn:o,submitWithArrivingWait:(0,r.useCallback)(async({requestedUsd:r,submit:i,readMargin:n,cancelled:o})=>{let u;try{return await i()}catch(e){if(!(0,a.isSunriseArriving)(e)||!n)throw e;u=e}let h=(0,a.arrivingWaitPolicy)((0,a.arrivingEtaSecs)(u)),p=`sunrise-arriving-${Date.now()}`,m=i=>s.toast.loading(e("sunriseWithdrawWaiting",{amount:t.number(r),secs:i}),{id:p,duration:1/0});m(Math.ceil(h.deadlineMs/1e3)),d(!0);try{let t=await (0,a.waitForArrivingWithdrawal)({policy:h,requestedUsd:r,readMargin:n,submit:i,sleep:l,now:()=>Date.now(),onTick:({secsRemaining:e})=>m(e),cancelled:()=>c.current||(o?.()??!1)});switch(s.toast.dismiss(p),t.kind){case"settled":return t.signature;case"reported":return null;case"failed":throw t.error;case"stillArriving":return s.toast.warning(e("sunriseWithdrawStillArriving")),null}}finally{s.toast.dismiss(p),d(!1)}},[e,t])}}],148974)},810661,e=>{"use strict";e.s(["fmtCountdown",0,function(e){if(!isFinite(e)||e<=0)return"expired";let t=Math.floor(e/86400),r=Math.floor(e%86400/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);if(t>=2)return`${t}d ${r}h`;let n=Math.floor(e/3600);return n>0?`${n}h ${i}m`:i>0?`${i}m ${s}s`:`${s}s`}])},37086,777670,718516,e=>{"use strict";function t(e,t,r){return JSON.stringify([e,t,r])}class r{closedSlots=new Map;observedKeys=new Set;slots=new Map;subscriptionSlots=new Map;apply(e,t,r,i="subscription"){return!("unknown"===r||t<(this.slots.get(e)??-1)||"seed"===i&&t<=(this.subscriptionSlots.get(e)??-1))&&(this.slots.set(e,t),"subscription"===i&&this.subscriptionSlots.set(e,t),this.observedKeys.add(e),"closed"===r?this.closedSlots.set(e,t):this.closedSlots.delete(e),!0)}}e.s(["SunrisePositionObservations",0,r,"isSunriseApiPositionClosed",0,function(e,r){if("sunrise"!==e.underwriter)return!1;let i=r.get(t(e.profileIndex??0,e.asset,e.sunriseMarginSeat??null));return void 0!==i&&i>=(e.openingSlot??0)},"sunrisePositionKey",0,t],777670),e.s(["visibleIndexedExits",0,function(e,r){let i=new Set;return{blocked:i,rows:e.filter(e=>{if(e.wallet!==r.wallet||r.closedPdas.has(e.positionPda)||"phoenix"===e.underwriter&&(r.phoenixEmpty.has(e.positionPda)||"venue_direct"!==e.ownership&&r.phoenixCross.has(e.positionPda)))return!1;if("sunrise"===e.underwriter&&null!==e.profileIndex&&"known"===e.sunriseMarginSeat.status){let s=r.sunriseClosed.get(t(e.profileIndex,e.asset,e.sunriseMarginSeat.value));if(void 0!==s){if("known"!==e.openingSlot.status)i.add(e.lifecycleId);else if(BigInt(s)>=BigInt(e.openingSlot.value))return!1}}return!r.full.some(t=>t.wallet===e.wallet&&t.positionPda===e.positionPda&&t.underwriter===e.underwriter&&t.profileIndex===e.profileIndex&&t.side===e.side&&t.asset===e.asset&&(t.apiData?.lifecycleId??t.apiData?.id)===e.lifecycleId)})}}],37086),e.s(["resolvePositionWalletOwner",0,function(e,t,r){if(e&&t)return e===t||e===r?t:void 0}],718516)},795974,e=>{"use strict";function t(e){let{entryPrice:t,sizeUsd:r,collateralUsd:i,isLong:s,accumulatedFees:n=0,maintenanceMarginRatio:a=.00625}=e;if(r<=0||i<=0||t<=0)return 0;let l=i-n-r*a;if(l<=0)return 0;let o=r/t;if(o<=0)return 0;let d=l/o;return s?Math.max(0,t-d):t+d}e.s(["calculateLiquidationInfo",0,function(e,r){let i,s,n=t(e);if(n<=0)return{liquidationPrice:0,distanceToLiquidation:1/0,distancePercent:1/0,isNearLiquidation:!1,isLiquidatable:!1};let{isLong:a}=e;a?(i=r-n,s=r<=n):(i=n-r,s=r>=n);let l=i/r*100;return{liquidationPrice:n,distanceToLiquidation:i,distancePercent:l,isNearLiquidation:l<=1,isLiquidatable:s}},"calculateLiquidationPrice",0,t,"calculateUnrealizedPnl",0,function(e,t,r,i,s=0){if(e<=0||r<=0)return{pnlUsd:0,pnlPercent:0};let n=(i?r*(t-e)/e:r*(e-t)/e)-s;return{pnlUsd:n,pnlPercent:n/r*100}}])},161708,e=>{"use strict";var t=e.i(532906),r=e.i(190459);
2let i=[{upperUsd:1e3,bps:0},{upperUsd:1e4,bps:1},{upperUsd:5e5,bps:5},{upperUsd:2e6,bps:2},{upperUsd:1/0,bps:0}],s=new Set(["GamB1v486nYz1MYnwxwQhEaoHQhYP8ySX9HpJXtcDFaQ","6NSoxTN33GiD7kTHgDnUcSi4dT3FvVhSBVD2mkqER37u"]),n=new Set(["fukcGVbUYoz3VUgq1Qq9opCj4kQi7gKtqaAsrwhAfM7"]),a=new Set(["6bxSMieYskNEFV9jmVssXWdxFxkbB3wusPt1RVweVUW8"]);function l(e){return null!=e&&s.has(e)?"exempt":null!=e&&n.has(e)?"legacy":null!=e&&a.has(e)?"discounted":"standard"}function o(e){return"standard"===e?10:5*("discounted"===e)}function d(e,i,s,n,a,l,o){let d=s*o,{priceUsd:c}=(0,t.estimateLiqPrice)({venue:(0,r.venueFromUnderwriterByte)(l)??"jupiter",isLong:a,entryPrice:e,sizeUsd:s,collateralUsd:i});return{entryPriceUsd:e.toString(),leverage:n.toString(),liquidationPriceUsd:null===c?"":c.toString(),openFeeUsd:d.toString(),outstandingBorrowFeeUsd:"0",priceImpactFeeUsd:"0",priceImpactFeeBps:"0",positionCollateralSizeUsdAfterFees:(i-d).toString(),positionCollateralSizeUsdBeforeFees:i.toString(),positionSizeUsd:s.toString(),positionSizeTokenAmount:(s/e).toString(),sizeUsdDelta:s.toString()}}function c(e,t,r,s,n,a,l,d,c,u,h,p,m,f,x,g){let b,v,y,w,j,S,k,N=2===s;if(N){let e=h?h.takerBps/1e4:35e-5,t=h?h.makerBps/1e4:0;b="limit"===u?t:e,v=0,y=0,w=h?h.takerBps:3.5,j=h?h.makerBps:0}else if(3===s)b=d?(d.openFeePositivePercent+d.openFeeNegativePercent)/200:6e-4,v=d?r?d.longNetRatePerHourPercent:d.shortNetRatePerHourPercent:.003,y=r&&c?7e-4*e:0;else{b=7e-4;let t=r?n?.longBorrowRatePercent:n?.shortBorrowRatePercent;v=t&&parseFloat(t)||0,y=r?.001*e:0}let P=m??f??b;!1===x&&(y=0),void 0!==g&&(v=g);let T=t*P,C=t*(N?h?h.takerBps/1e4:35e-5:f??b),M=0;null!=a&&null!=l&&(M=v/100*l*Math.max(0,(Date.now()/1e3-a)/3600));let _=function(e,t,r){let s=r?e:Math.max(0,e-t),n=r?e+t:e,a=0,l=0;for(let{upperUsd:e,bps:t}of i){if(s>=e){l=e;continue}if(n<=l)break;let r=Math.min(n,e)-Math.max(s,l);if(r>0&&(a+=t/1e4*r),l=e,n<=e)break}return a}(l??0,t,null==l);7===s||"exempt"===p?(S=0,k=0):"standard"===p||"discounted"===p?(S=e*(o(p)/1e4),k=0):(S=y,k=_);let A=v/100*(t+(l??0));return{totalFeesUsd:(S+k+T+M).toString(),platformFeeUsd:S.toString(),slippageUsd:null,interestUsd:M.toString(),openCloseFeeUsd:T.toString(),estCloseFeeUsd:C.toString(),borrowRateHourlyPercent:v.toString(),borrowRateHourlyUsd:A.toString(),phoenixTakerFeeBps:w,phoenixMakerFeeBps:j}}e.s(["FLAT_COLLATERAL_FEE_BPS",0,10,"computeLocalPreview",0,function(e){let{collateralUsd:t,leverage:r,marketPrice:i,underwriter:s,poolInfo:n}=e;if(t<=0||r<=0||!i||i<=0)return null;let a=t*r,o=e.gmTradeLongRequiresSwap??!0,u=e.orderType??"market",h=e.ph
2oenixLiveFees??null,p=l(e.wallet),m=e.openFeeRate??6e-4,{openFeeRate:f,closeFeeRate:x,hasCollateralSwap:g}=e,b=e.borrowRateHourlyPct,v=d(i,t,a,r,!0,s,m),y=d(i,t,a,r,!1,s,m);return{long:{quote:v,fee:c(t,a,!0,s,n,e.existingLongOpenTime,e.existingLongSizeUsd,e.gmTradeFees,o,u,h,p,f,x,g,b)},short:{quote:y,fee:c(t,a,!1,s,n,e.existingShortOpenTime,e.existingShortSizeUsd,e.gmTradeFees,o,u,h,p,f,x,g,b)}}},"feePolicy",0,l,"flatCollateralFeeBps",0,o])},781355,e=>{"use strict";let t="imperial_last_market",r=/^[a-zA-Z0-9-]+$/;e.s(["readLastMarketSlug",0,function(){try{var e;return(e=localStorage.getItem(t))&&r.test(e)?e:"sol"}catch{return"sol"}},"writeLastMarketSlug",0,function(e){if(r.test(e)){try{localStorage.setItem(t,e)}catch{}try{document.cookie=`${t}=${e}; path=/; max-age=31536000; samesite=lax`}catch{}}}])},836758,e=>{"use strict";let t=[25,50,75];function r(e,t){return Math.min(t,Math.max(1.1,Math.round(10*e)/10))}function i(e,t){return t>1.1&&e>0?Math.min(1,Math.max(0,Math.log(e/1.1)/Math.log(t/1.1))):0}function s(e,t){return Math.round(1e3*i(e,t))}e.s(["LEVERAGE_MIN",0,1.1,"LEVERAGE_SLIDER_STEPS",0,1e3,"leverageFraction",0,i,"leverageStops",0,function(e){return t.filter(t=>t<.85*e).concat(e)},"leverageToSliderPos",0,s,"stepLeverageFromSlider",0,function(e,t,i){let n=i>1.1?r(1.1*Math.pow(i/1.1,e/1e3),i):1.1;if(n!==t)return n;let a=s(t,i);return e===a?n:r(e>a?t+.1:t-.1,i)}])},277589,106128,e=>{"use strict";e.s(["estimateArmadaLiq",0,function(e){let{entryPrice:t,sizeUsd:r,collateralUsd:i,debtUsd:s,feesUsd:n}=e,a=e.maintenanceMarginBps/1e4,l=e.reserveBps/1e4;if(![t,r,i,s,n,a,l].every(Number.isFinite)||t<=0||r<=0||i<=0||s<0||a<=0||a>=1||l<0||l>=1)return{priceUsd:null,reason:"invalid"};let o=i-n;if(o<=Math.max(r*a,s+r*l))return{priceUsd:null,reason:"past_maintenance"};let d=(i,s)=>e.isLong?t*(r-o+i)/(r*(1-s)):t*(r+o-i)/(r*(1+s)),c=e.isLong?Math.max(d(0,a),d(s,l)):Math.min(d(0,a),d(s,l));return Number.isFinite(c)&&c>0?{priceUsd:c}:{priceUsd:null,reason:"invalid"}}],277589);var t=e.i(183023);let r="imperial:est-liq-preview",i=null;function s(){return i}function n(e){return window.addEventListener(r,e),()=>window.removeEventListener(r,e)}e.s(["publishDelayMs",0,function(e,t){return Math.max(0,Math.min(150,t+400-e))},"setEstLiqPreview",0,function(e){var t;let s=null!==e&&Number.isFinite(e.price)&&e.price>0?e:null;(null===(t=i)||null===s?t!==s:t.market!==s.market||t.price!==s.price)&&(i=s,window.dispatchEvent(new Event(r)))},"shouldPublishEstLiq",0,function(e){return e.publishChartPreview&&e.active&&e.sizeUsd>0},"useEstLiqPreview",0,function(){return(0,t.useSyncExternalStore)(n,s,()=>null)}],106128)},532906,439507,e=>{"use strict";function t(e){let{entryPrice:t,sizeUsd:r,collateralUsd:i,isLong:s}=e,n=e.phoenix??{};if(n.crossMargin)return{priceUsd:null,reason:"unsupported"};let a=n.maxLeverage??25,l=n.maintenanceRiskFactor??.5;if(a<=0||l<=0||l>=a)return{priceUsd:null,reason:"invalid"};let o=l/a;if(s){let e=r*(1-o);if(e<=0)return{priceUsd:null,reason:"past_maintenance"};let s=(r-i)*t/e;return!Number.isFinite(s)||s<=0||s>=t?{priceUsd:null,reason:"past_maintenance"}:{priceUsd:s}}let d=(r+i)*t/(r*(1+o));return!Number.isFinite(d)||d<=0||d<=t?{priceUsd:null,reason:"past_maintenance"}:{priceUsd:d}}e.s(["estimatePhoenixLiq",0,t],439507),e.s(["estimateLiqPrice",0,function(e){if(!Number.isFinite(e.entryPrice)||!Number.isFinite(e.sizeUsd)||!Number.isFinite(e.collateralUsd)||e.entryPrice<=0||e.sizeUsd<=0||e.collateralUsd<=0)return{priceUsd:null,reason:"invalid"};switch(e.venue){case"jupiter":return function(e){let{entryPrice:t,sizeUsd:r,collateralUsd:i,isLong:s,accruedFeesUsd:n=0}=e,a=e.jupiter??{},l=a.maxLeverageBps??5e6,o=a.closeFeeBps??6,d=a.tradeImpactFeeScalar;if(l<=0)return{priceUsd:null,reason:"invalid"};let c=d&&d>0?Math.ceil(1e4*r/d):0,u=1e4*r/l+r*(o+c)/1e4+n;if(i<u)return{priceUsd:null,reason:"past_maintenance"};let h=(i-u)*t/r,p=s?t-h:t+h;return!Number.isFinite(p)||p<=0?{priceUsd:null,reason:"past_maintenance"}:{priceUsd:p}}(e);case"phoenix":return t(e);case"gmtrade":return function(e){let{entryPrice:t,sizeUsd:r,collateralUsd:i,isLong:s,accruedFeesUsd:n=0}=e,a=e.gmtrade??{},l=a.minCollateralFactor??.005,o=a.minCollateralUsd??1,d=a.positionFeeRate??7e-4,c=a.borrowFeeUsd??0,u=a.fundingFeeUsd??0,h=a.pe
2ndingImpactUsd??0;if(l<=0||l>=1)return{priceUsd:null,reason:"invalid"};let p=r*d+c+u+n,m=Math.min(h,0),f=e=>t*(s?r+e-i-m+p:r-e+i+m-p)/r,x=f(r*l),g=f(o),b=f(0),v=s?Math.max(x,g,b):Math.min(x,g,b);return!Number.isFinite(v)||v<=0||s&&v>=t||!s&&v<=t?{priceUsd:null,reason:"past_maintenance"}:{priceUsd:v}}(e);case"armada":return{priceUsd:null,reason:"unsupported"}}}],532906)},365221,e=>{"use strict";var t=e.i(653982),r=e.i(622463),i=e.i(722732),s=e.i(828047),n=e.i(508947),a=e.i(938425);let l=e=>({status:"unavailable",reason:e}),o=e=>["jupiter","phoenix","gmtrade","sunrise"].includes(e);function d(e,n,a){let l;if(!e||!o(e))return null;let d=n.toUpperCase(),c=[];if("jupiter"===e&&(l=t.ASSET_TO_MINT[d])&&(c=[l]),"phoenix"===e){let e=(0,r.resolvePhoenixSymbol)(n),i=e&&(0,r.getGlobalPhoenixRegistry)()?.getMarketBySymbol(e);i&&(c=[l=i.orderbook.toBase58()],t.ASSET_TO_MINT[d]&&c.push(t.ASSET_TO_MINT[d]))}if("gmtrade"===e){let e=(0,i.getGlobalGmTradeRegistry)()?.getMarketBySymbol(n);e&&(c=[l=e.indexTokenMint.toBase58(),e.marketTokenMint.toBase58()])}return("sunrise"===e&&(l=d,a&&(a===d||(0,s.sunriseSymbolFromAssetMint)(a)===d||t.ASSET_TO_MINT[d]===a)&&c.push(a),c.push(d)),l&&(void 0===a||null!==a&&c.includes(a)))?{underwriter:e,asset:n,rawMarket:a??l,marketMint:l}:null}function c(e,t){if("string"!=typeof e||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let r=Number(e);return Number.isFinite(r)&&r>=0&&Number.isSafeInteger(Math.round(r*t))?r:null}e.s(["closeMarketFor",0,d,"manualCloseIsCurrent",0,function(e,t=Date.now()){return"available"===e.status&&(null===e.expiresAt||t<e.expiresAt)},"manualPriceObservationsFor",0,function(e,t,r={}){let i={};for(let s of e){let e=d(s.underwriter,s.asset,"kind"in s?s.marketMint:void 0),n=t[s.asset],a=r[s.asset];e&&void 0!==n&&Number.isFinite(n)&&n>0&&void 0!==a&&(i[e.marketMint]={marketMint:e.marketMint,value:n,observedAt:a,source:"market_feed"})}return i},"manualTargetIdentity",0,function(e){let t=e.row;return{wallet:t.wallet,positionPda:t.positionPda,asset:t.asset,side:t.side,underwriter:t.underwriter,profileIndex:t.profileIndex,lifecycleId:"partial"===e.kind?e.row.lifecycleId:e.row.apiData?.lifecycleId??e.row.apiData?.id}},"resolveManualClose",0,function(e,t){let r,{row:i}=e;if(!t.current||!t.wallet||i.wallet!==t.wallet||"partial"===e.kind&&"owner"!==t.visibility)return l("owner");if("partial"===e.kind&&"imperial"===i.ownership&&!["imperial","jupiter_via_imperial"].includes(e.row.source))return l("identity");if(t.contradicted)return l("observation");if(!Number.isFinite(t.sizePercent)||t.sizePercent<=0||t.sizePercent>100||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>1e4)return l("intent");let s=Math.round(100*t.sizePercent);if(s<=0||s>1e4)return l("intent");if("full"===e.kind&&"venue_direct"===e.row.ownership&&"phoenix"===e.row.underwriter){let r=e.row.directVenue;return!r||!Number.isSafeInteger(r.pdaIndex)||r.pdaIndex<0||r.pdaIndex>255||!Number.isSafeInteger(r.subaccountIndex)||r.subaccountIndex<0||r.subaccountIndex>255||r.traderAccount!==e.row.positionPda?l("identity"):{status:"available",expiresAt:null,input:{ownership:"venue_direct",underwriter:"phoenix",asset:i.asset,directVenue:r,entirePosition:100===t.sizePercent,closeBps:s,slippageBps:t.slippageBps}}}if("imperial"!==i.ownership||!i.positionPda||!o(i.underwriter??"")||"long"!==i.side&&"short"!==i.side||!Number.isInteger(i.profileIndex)||null==i.profileIndex||i.profileIndex<0||i.profileIndex>=a.MAX_PROFILES)return l("identity");let d=t.market;if(!d||d.underwriter!==i.underwriter||d.asset!==i.asset||"partial"===e.kind&&d.rawMarket!==e.row.marketMint)return l("market");if("sunrise"===i.underwriter){let t="partial"===e.kind?"known"===e.row.sunriseMarginSeat.status?e.row.sunriseMarginSeat.value:void 0:e.row.sunriseMarginSeat;if(void 0===t||null!==t&&(0,n.parseSeatText)(t).symbol!==i.asset)return l("seat");r=(0,n.sunriseSeatFromPosition)(t)}let u="partial"===e.kind?"known"===e.row.closeBasis.sizeUsd.status?e.row.closeBasis.sizeUsd.value:null:e.row.sizeUsd,h="partial"===e.kind?"known"===e.row.closeBasis.collateralUsd.status?e.row.closeBasis.collateralUsd.value:null:e.row.collateralUsd,p=c(u,1e6),m=c(h,1e6);if(null===p||p<=0||null===m)return l("amount");let f=t.price,x=t.now??Date.now(),g="gmtrade"===i.underwriter?1e9:1e6;return!f||"market_feed"!==f.source||!Number.isSafeInteger(f.observedAt)||f.observedAt>x||x-f.observedAt>=3e4||f.marketMint!==d.marketMint||!Number.isFinite(f.value)||f.value<=0||!Number.isSafeInteger(Math.round(f.value*g))||0>=Math.round(f.value*g)?l("price"):0>=Math.round(p*t.sizePercent/100*1e6)?l("amount"):{status:"available",expiresAt:f.observedAt+3e4,input:{ownership:"imperial",underwriter:d.underwriter,profileIndex:i.profileIndex,positionPubkey:i.positionPda,marketMint:d.marketMint,side:i.side,...void 0!==r?{sunriseSeat:r}:{},sizeUsd:p*t.sizePercent/100,collateralUsd:m*t.sizePercent/100,currentPrice:f.value,entirePosition:100===t.sizePercent,closeBps:s,slippageBps:t.slippageBps}}}])},49332,e=>{"use strict";var t=e.i(465217);let r={So11111111111111111111111111111111111111112:{symbol:"SOL",name:"Solana",image:t.TOKEN_ICON_MAP.SOL}
2,"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs":{symbol:"ETH",name:"Ethereum",image:t.TOKEN_ICON_MAP.ETH},"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh":{symbol:"BTC",name:"Bitcoin",image:t.TOKEN_ICON_MAP.BTC}},i=new Set(["USDC","USDT","WSOL"]);e.s(["CORE_SYMBOL_TO_MINT",0,{SOL:"So11111111111111111111111111111111111111112",ETH:"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",BTC:"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh",ZEC:"A7bdiYdS5GjqGFtxf17ppRHtDKPkkRqbKtR27dxvQXaS",HYPE:"98sMhvDwXj1RQi5c5Mndm3vPe9cBqPrbLaufMXFNMh5g",BNB:"BNBXenUbd8ixdDBJWs56yBFEapFvY9LHp8J1mwY3de5",BONK:"DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",WIF:"EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm",JUP:"JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",JTO:"jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL",RAY:"4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R",PENGU:"2zMMhcVQEXDtdE6vsFS7S7D5oUodfJHE8vd1gnBouauv",FARTCOIN:"9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump",PUMP:"pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn",ORE:"oreoU2P8bN6jkk3jbaiVxYnG1dCXcYxwhwyK9jSybcp"},"JUPITER_MARKETS",0,r,"isJupiterMarket",0,function(e){return Object.hasOwn(r,e)},"isNonTradeableQuoteSymbol",0,function(e){return i.has(e.toUpperCase())}])},465217,913451,e=>{"use strict";let t={"0G":"/icons/tokens/0g.png","2Z":"/icons/tokens/2z.png",AAPL:"/icons/tokens/aapl.png",AAVE:"/icons/tokens/aave.png",ADA:"/icons/tokens/ada.svg",AERO:"/icons/tokens/aero.png",AI16Z:"/icons/tokens/ai16z.png",AMD:"/icons/tokens/amd.png",AMZN:"/icons/tokens/amzn.png",ANSEM:"/icons/tokens/ansem.png",ANTHROPIC:"/icons/tokens/anthropic.png",APEX:"/icons/tokens/apex.png",APT:"/icons/tokens/apt.svg",ARB:"/icons/tokens/arb.svg",ARC:"/icons/tokens/arc.png",ASML:"/icons/tokens/asml.svg",ASTER:"/icons/tokens/aster.svg",AUDUSD:"/icons/tokens/audusd.svg",AVAX:"/icons/tokens/avax.svg",AVNT:"/icons/tokens/avnt.png",AXS:"/icons/tokens/axs.png",AZTEC:"/icons/tokens/aztec.png",BABA:"/icons/tokens/baba.png",BB:"/icons/tokens/bb.png",BCH:"/icons/tokens/bch.svg",BERA:"/icons/tokens/bera.svg",BIO:"/icons/tokens/bio.png",BIRB:"/icons/tokens/birb.png",BMNR:"/icons/tokens/bmnr.png",BNB:"/icons/tokens/bnb.png",BOT:"/icons/tokens/bot.png",BOTZ:"/icons/tokens/botz.svg",BRENTOIL:"/icons/tokens/brentoil.png",BTC:"/icons/tokens/btc.png",CAP:"/icons/tokens/cap.png",CASHCAT:"/icons/tokens/cashcat.png",CBRS:"/icons/tokens/cbrs.svg",CC:"/icons/tokens/cc.png",CHIP:"/icons/tokens/chip.svg",COIN:"/icons/tokens/coin.svg",CRCL:"/icons/tokens/crcl.svg",CRO:"/icons/tokens/cro.png",CRV:"/icons/tokens/crv.png",CRWV:"/icons/tokens/crwv.svg",CTR:"/icons/tokens/ctr.png",CXMT:"/icons/tokens/cxmt.png",DASH:"/icons/tokens/dash.png",DATA:"/icons/tokens/data.png",DELL:"/icons/tokens/dell.png",DIA:"/icons/tokens/dia.svg",DOGE:"/icons/tokens/doge.svg",DOLO:"/icons/tokens/dolo.png",DOT:"/icons/tokens/dot.svg",DRAM:"/icons/tokens/dram.png",DUSK:"/icons/tokens/dusk.png",DYDX:"/icons/tokens/dydx.svg",EDEN:"/icons/tokens/eden.png",EDGE:"/icons/tokens/edge.png",EIGEN:"/icons/tokens/eigen.svg",ENA:"/icons/tokens/ena.svg",ETH:"/icons/tokens/eth.png",ETHFI:"/icons/tokens/ethfi.svg",EURUSD:"/icons/tokens/eurusd.svg",EWY:"/icons/tokens/ewy.png",FARTCOIN:"/icons/tokens/fartcoin.png",FF:"/icons/tokens/ff.png",FIL:"/icons/tokens/fil.png",FOGO:"/icons/tokens/fogo.png",FOLKS:"/icons/tokens/folks.png",GBPUSD:"/icons/tokens/gbpusd.svg",GEV:"/icons/tokens/gev.png",GMX:"/icons/tokens/gmx.svg",GOOGL:"/icons/tokens/googl.svg",GRAM:"/icons/tokens/gram.svg",GRASS:"/icons/tokens/grass.svg",H100:"/icons/tokens/h100.png",HANMI:"/icons/tokens/hanmi.svg",HBAR:"/icons/tokens/hbar.svg",HOOD:"/icons/tokens/hood.svg",HYPE:"/icons/tokens/hype.png",HYUNDAI:"/icons/tokens/hyundai.png",HYUNDAIUSD:"/icons/tokens/hyundaiusd.png",IBM:"/icons/tokens/ibm.png",ICP:"/icons/tokens/icp.png",INTC:"/icons/tokens/intc.svg",IP:"/icons/tokens/ip.svg",IWM:"/icons/tokens/iwm.png",JTO:"/icons/tokens/jto.svg",JUP:"/icons/tokens/jup.png",KAITO:"/icons/tokens/kaito.svg",KBONK:"/icons/tokens/kbonk.svg",KFLOKI:"/icons/tokens/kfloki.svg",KNOT:"/icons/tokens/knot.png",KPEPE:"/icons/tokens/kpepe.svg",KRCOMP:"/icons/tokens/krcomp.png",KSHIB:"/icons/tokens/ks
2hib.svg",KTOSHI:"/icons/tokens/ktoshi.png",LAUNCHCOIN:"/icons/tokens/launchcoin.svg",LDO:"/icons/tokens/ldo.svg",LINEA:"/icons/tokens/linea.png",LINK:"/icons/tokens/link.svg",LIT:"/icons/tokens/lit.png",LITE:"/icons/tokens/lite.png",LTC:"/icons/tokens/ltc.svg",MAGS:"/icons/tokens/mags.svg",MEGA:"/icons/tokens/mega.svg",MET:"/icons/tokens/met.png",META:"/icons/tokens/meta.svg",MINIMAX:"/icons/tokens/minimax.png",MKR:"/icons/tokens/mkr.svg",MNT:"/icons/tokens/mnt.svg",MON:"/icons/tokens/mon.png",MORPHO:"/icons/tokens/morpho.svg",MRNA:"/icons/tokens/mrna.svg",MRVL:"/icons/tokens/mrvl.svg",MSFT:"/icons/tokens/msft.svg",MSTR:"/icons/tokens/mstr.svg",MU:"/icons/tokens/mu.svg",MYX:"/icons/tokens/myx.png",NATGAS:"/icons/tokens/natgas.png",NBIS:"/icons/tokens/nbis.png",NEAR:"/icons/tokens/near.svg",NMR:"/icons/tokens/nmr.svg",NOW:"/icons/tokens/now.png",NVDA:"/icons/tokens/nvda.png",NZDUSD:"/icons/tokens/nzdusd.svg",ONDO:"/icons/tokens/ondo.svg",OP:"/icons/tokens/op.svg",OPENAI:"/icons/tokens/openai.png",ORCL:"/icons/tokens/orcl.svg",PAXG:"/icons/tokens/paxg.svg",PENDLE:"/icons/tokens/pendle.svg",PENGU:"/icons/tokens/pengu.png",PIPPIN:"/icons/tokens/pippin.png",PLTR:"/icons/tokens/pltr.png",POL:"/icons/tokens/pol.svg",POPCAT:"/icons/tokens/popcat.svg",PROVE:"/icons/tokens/prove.svg",PUMP:"/icons/tokens/pump.png",PYTH:"/icons/tokens/pyth.png",QQQ:"/icons/tokens/qqq.svg",RAIL:"/icons/tokens/rail.png",RESOLV:"/icons/tokens/resolv.svg",RIVER:"/icons/tokens/river.png",RKLB:"/icons/tokens/rklb.png",ROBO:"/icons/tokens/robo.png",S:"/icons/tokens/s.svg",SAMSUNG:"/icons/tokens/samsung.png",SAMSUNGUSD:"/icons/tokens/samsungusd.png",SEI:"/icons/tokens/sei.svg",SHEIN:"/icons/tokens/shein.png",SKHY:"/icons/tokens/skhy.png",SKHYNIX:"/icons/tokens/skhynix.png",SKHYNIXUSD:"/icons/tokens/skhynixusd.png",SKR:"/icons/tokens/skr.png",SKY:"/icons/tokens/sky.svg",SMIC:"/icons/tokens/smic.png",SNDK:"/icons/tokens/sndk.png",SOL:"/icons/tokens/sol.png",SOXL:"/icons/tokens/soxl.png",SOXX:"/icons/tokens/soxx.png",SPACEX:"/icons/tokens/spacex.png",SPCX:"/icons/tokens/spcx.png",SPX:"/icons/tokens/spx.png",SPY:"/icons/tokens/spy.png",STABLE:"/icons/tokens/stable.png",STABLECOINX:"/icons/tokens/stablecoinx.png",STBL:"/icons/tokens/stbl.svg",STRC:"/icons/tokens/strc.png",STRK:"/icons/tokens/strk.png",SUI:"/icons/tokens/sui.png",SYRUP:"/icons/tokens/syrup.png",TAO:"/icons/tokens/tao.png",TENCENT:"/icons/tokens/tencent.png",TIA:"/icons/tokens/tia.png",TRUMP:"/icons/tokens/trump.svg",TRX:"/icons/tokens/trx.svg",TSLA:"/icons/tokens/tsla.png",TSM:"/icons/tokens/tsm.svg",UNI:"/icons/tokens/uni.svg",UNITREE:"/icons/tokens/unitree.png",URA:"/icons/tokens/ura.svg",US100:"/icons/tokens/us100.png",US10Y:"/icons/tokens/us10y.png",US500:"/icons/tokens/us500.png",USDCAD:"/icons/tokens/usdcad.svg",USDCHF:"/icons/tokens/usdchf.svg",USDJPY:"/icons/tokens/usdjpy.svg",USDKRW:"/icons/tokens/usdkrw.svg",USELESS:"/icons/tokens/useless.png",VIRTUAL:"/icons/tokens/virtual.svg",VVV:"/icons/tokens/vvv.svg",WEN:"/icons/tokens/wen.png",WHEAT:"/icons/tokens/wheat.png",WIF:"/icons/tokens/wif.png",WLD:"/icons/tokens/wld.svg",WLFI:"/icons/tokens/wlfi.svg",WTI:"/icons/tokens/wti.svg",XAG:"/icons/tokens/xag.png",XAU:"/icons/tokens/xau.png",XCU:"/icons/tokens/xcu.png",XIAOMI:"/icons/tokens/xiaomi.png",XLM:"/icons/tokens/xlm.svg",XMR:"/icons/tokens/xmr.png",XPD:"/icons/tokens/xpd.svg",XPL:"/icons/tokens/xpl.svg",XPT:"/icons/tokens/xpt.svg",XRP:"/icons/tokens/xrp.png",YZY:"/icons/tokens/yzy.png",ZEC:"/icons/tokens/zec.png",ZHIPU:"/icons/tokens/zhipu.png",ZK:"/icons/tokens/zk.svg",ZORA:"/icons/tokens/zora.svg",ZRO:"/icons/tokens/zro.png"},r=new Map,i=0,s=new Set;function n(e){if("string"==typeof e)try{let t=new URL(e);if("https:"!==t.protocol||"phoenixcdn.trade"!==t.hostname||t.port||t.username||t.password||!t.pathname.startsWith("/logos/"))return;return t.href}catch{return}}function a(e){return r.get(e.toUpperCase())}e.s(["getPhoenixTokenIcon",0,a,"getPhoenixTokenIconsVersion",0,function(){return i},"getServerPhoenixTokenIconsVersion",0,function(){return 0},"setPhoenixTokenIcons",0,function(e){let t=new Map;for(let i of e){let e=i.symbol.toUpperCase(),s=n(i.logoUri)??r.get(e);s&&(t.set(e,s),t.set(i.phoenixSymbol.toUpperCase(),s))}t.size===r.size&&[...t].every(([e,t])=>
2r.get(e)===t)||(r=t,i++,s.forEach(e=>e()))},"subscribePhoenixTokenIcons",0,function(e){return s.add(e),()=>{s.delete(e)}},"validPhoenixLogoUri",0,n],913451);let l={"1000BONK":"/icons/tokens/kbonk.svg","1000FLOKI":"/icons/tokens/kfloki.svg","1000NOT":"/icons/tokens/knot.png","1000PEPE":"/icons/tokens/kpepe.svg","1000SHIB":"/icons/tokens/kshib.svg","1000TOSHI":"/icons/tokens/ktoshi.png",ADI:"/icons/tokens/adi.png",AI:"/icons/tokens/ai.png",USDC:"/icons/tokens/usdc.png",SOL:"/icons/tokens/sol.png",BTC:"/icons/tokens/btc.png",SOLBTC:"/icons/tokens/solbtc.svg",ANSEM:"/icons/tokens/ansem.png",CASHCAT:"/icons/tokens/cashcat.png",ANSEMCASHCAT:"/icons/tokens/ansemcashcat.svg",SPX6900:"/icons/tokens/spx6900.png",CATE:"/icons/tokens/cate.png",USELESS:"/icons/tokens/useless.png",BVIV:"/icons/tokens/bviv.svg",ETH:"/icons/tokens/eth.png",JUP:"/icons/tokens/jup.png",JTO:"/icons/tokens/jto.svg",RAY:"/icons/tokens/ray.png",HYPE:"/icons/tokens/hype.png",BONK:"/icons/tokens/bonk.png",PENGU:"/icons/tokens/pengu.png",FARTCOIN:"/icons/tokens/fartcoin.png",ZEC:"/icons/tokens/zec.png",WIF:"/icons/tokens/wif.png",ORE:"/icons/tokens/ore.png",PYTH:"/icons/tokens/pyth.png",KMNO:"/icons/tokens/kmno.png",BNB:"/icons/tokens/bnb.png",PUMP:"/icons/tokens/pump.png",MET:"/icons/tokens/met.png",XAU:"/icons/tokens/xau.png",XAUt:"/icons/tokens/xau.png",XAG:"/icons/tokens/xag.png",XAGt:"/icons/tokens/xag.png",XCU:"/icons/tokens/xcu.png",EUR:"/icons/tokens/eur.png",GBP:"/icons/tokens/gbp.png",USDJPY:"/icons/tokens/usdjpy.png",JPY:"/icons/tokens/usdjpy.png",USDCNH:"/icons/tokens/usdcnh.png",CNH:"/icons/tokens/usdcnh.png",CRUDEOIL:"/icons/tokens/crudeoil.png","CRUDE-OIL":"/icons/tokens/crudeoil.png",WTIOIL:"/icons/tokens/wti.svg",NATGAS:"/icons/tokens/natgas.png",JitoSOL:"/icons/tokens/jitosol.png",SPY:"/icons/tokens/spy.png",NVDA:"/icons/tokens/nvda.png",TSLA:"/icons/tokens/tsla.png",AAPL:"/icons/tokens/aapl.png",ADBE:"/icons/tokens/adbe.svg",AMD:"/icons/tokens/amd.png",AMZN:"/icons/tokens/amzn.png",PLTR:"/icons/tokens/pltr.png",TXN:"/icons/tokens/txn.png",TS
2M:"/icons/tokens/tsm.png",LLY:"/icons/tokens/lly.png",SNDK:"/icons/tokens/sndk.png",QCOM:"/icons/tokens/qcom.png",IREN:"/icons/tokens/iren.png",IWM:"/icons/tokens/iwm.png",SPCX:"/icons/tokens/spcx.png",SONY:"/icons/tokens/sony.svg",SAMO:"/icons/tokens/samo.png",TRUMP:"/icons/tokens/trump.png",DOGE:"/icons/tokens/doge.png",XRP:"/icons/tokens/xrp.png",AAVE:"/icons/tokens/aave.png",SUI:"/icons/tokens/sui.png",SKR:"/icons/tokens/skr.png",TAO:"/icons/tokens/tao.png",LIT:"/icons/tokens/lit.png",CHIP:"/icons/tokens/chip.svg",MON:"/icons/tokens/mon.png",NEAR:"/icons/tokens/near.png",ENA:"/icons/tokens/ena.png",XPL:"/icons/tokens/xpl.png",MEGA:"/icons/tokens/mega.svg",MEGAETH:"/icons/tokens/mega.svg",BP:"/icons/tokens/bp.png",GRAM:"/icons/tokens/gram.svg",HOOD:"/icons/tokens/hood.svg",MSTR:"/icons/tokens/mstr.svg",COIN:"/icons/tokens/coin.svg",CRCL:"/icons/tokens/crcl.svg",CRWD:"/icons/tokens/crwd.svg",MRNA:"/icons/tokens/mrna.svg",MRVL:"/icons/tokens/mrvl.svg",NET:"/icons/tokens/net.svg",NFLX:"/icons/tokens/nflx.svg"},o="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32'%3E%3Ccircle cx='16' cy='16' r='16' fill='%23374151'/%3E%3Ctext x='16' y='21' text-anchor='middle' fill='white' font-size='14' font-family='sans-serif'%3E%3F%3C/text%3E%3C/svg%3E";function d(e){if(n(e)){let r=new URL(e).pathname.split("/")[2];return/^[a-zA-Z0-9_-]+$/.test(r??"")?t[r.toUpperCase()]??`/icons/tokens/${r.toLowerCase()}.svg`:null}return/(?:^|\/)icons\/tokens\/[^/]+\.svg$/.test(e)?e.replace(/\.svg$/,".png"):null}e.s(["TOKEN_ICON_MAP",0,l,"getFlashTokenImage",0,function(e,r){return l[e]??l[e.toUpperCase()]??n(r)??a(e)??t[e.toUpperCase()]??`/icons/tokens/${e.toLowerCase()}.svg`},"handleTokenImageError",0,function(e){e.currentTarget.getAttribute("src")!==o&&(e.currentTarget.src=d(e.currentTarget.src)??o)},"nextTokenIconSrc",0,d],465217)},308146,e=>{"use strict";let t=/^(\d*)(?:\.(\d*))?$/;function r(e,t){return!Number.isFinite(e)||e<0?null:BigInt(Math.round(e*10**t))}function i(e,t){let i=r(e,t);return null===i?null:Number(i)/10**t>e?i-1n:i}function s(e,t){let r=e<BigInt(0),i=(r?-e:e).toString().padStart(t+1,"0"),s=i.slice(0,i.length-t),n=i.slice(i.length-t).replace(/0+$/,"");return`${r?"-":""}${s}${n?`.${n}`:""}`}e.s(["baseUnitsToDecimalString",0,s,"decimalStringToBaseUnits",0,function(e,r){let i=t.exec(e.trim());if(!i)return null;let s=i[1]??"",n=i[2]??"";if(""===s&&""===n||n.length>r)return null;let a=BigInt(10)**BigInt(r);return BigInt(s||"0")*a+BigInt(n.padEnd(r,"0")||"0")},"floorNumberToBaseUnits",0,i,"numberToBaseUnits",0,r,"numberToDecimalString",0,function(e,t){let i=r(e,t);return null===i?"":s(i,t)},"percentToDecimalString",0,function(e,t,r){let n=i(e,r);return null===n||!Number.isInteger(t)||t<0||t>100?"":s(n*BigInt(t)/100n,r)}])},601852,e=>{"use strict";var t=e.i(972015),r=e.i(161708),i=e.i(360525);let s=new Set(["phoenix","armada"]);function n(e,t,r){let i="phoenix"===t?e?.phoenix:"armada"===t?e?.sunrise:void 0;if(!i)return null;let s="long"===r,n=s?i.longFundingRatePerHourPercent:i.shortFundingRatePerHourPercent,a=s?i.longBorrowRatePerHourPercent:i.shortBorrowRatePerHourPercent;return(null!=n||null!=a)&&Number.isFinite(n??0)&&Number.isFinite(a??0)?-((n??0)+(a??0)):null}e.s(["selectCarryVenue",0,function(e,a,l,o,d,c,u){let h=null,p=-1/0;for(let m of e){let e=m.venue;if(!m.supported||!s.has(e)||!Number.isFinite(m.maxLeverage)||u>m.maxLeverage)continue;let f=n(l,e,o);if(null===f)continue;let x=f/100*24*d,{breakdown:g,costExBorrowUsd:b}=function(e,s,n,a,l,o){let d=(0,t.computeCost)(e,s,n,a,l),c=d.total-d.borrow;return{breakdown:d,costExBorrowUsd:c+("armada"===e.venue?0:(0,i.imperialRoundTripFeeUsd)(a,o,r.FLAT_COLLATERAL_FEE_BPS))}}(m,a[e],o,d,c,u),v=c/24*x-b;v>p&&(p=v,h={underwriter:e,side:o,notionalUsd:d,carryPerDayUsd:x,carryPctPerHour:f,costExBorrowUsd:b,breakdown:g})}return h},"signedCarryPctPerHour",0,n])},375290,e=>{"use strict";e.s(["formatBreakEven",0,function(e){return null===e||!Number.isFinite(e)||e<0?"never":e<1?`${Math.round(60*e)}m`:e<48?e<10?`${e.toFixed(1)}h`:`${Math.round(e)}h`:`${Math.round(e/24)}d`}])},360525,e=>{"use strict";e.s(["betaDrift",0,function(e,t){return null!=t&&Number.isFinite(t)&&e>0?Math.abs(t/e-1):null},"breakEvenHours",0,function(e,t){return e>0&&t>=0?t/e*24:null},"byFastestBreakEven",0,function(e){return e.filter(e=>null!==e.breakEvenHours).sort((e,t)=>
2e.breakEvenHours-t.breakEvenHours)},"carryDominanceDays",0,function(e,t){if(!(e>0)||!(t>0))return null;let r=t/e;return r*r},"hedgeQuality",0,function(e){if(!Number.isFinite(e))return 0;let t=Math.min(1,Math.abs(e));return 1-Math.sqrt(1-t*t)},"imperialRoundTripFeeUsd",0,function(e,t,r){return e>0&&t>0&&r>0?e/t*2*(r/1e4):0},"probProfitAt",0,function(e,t,r,i){var s;let n,a;return i>0&&r>0&&Number.isFinite(e)?(a=1/(1+.3275911*(n=Math.abs(s=(e*i-t)/(r*Math.sqrt(i)))/Math.SQRT2)),.5*(1+(s<0?-1:1)*(1-((((1.061405429*a-1.453152027)*a+1.421413741)*a-.284496736)*a+.254829592)*a*Math.exp(-n*n)))):null},"recommendedMaxLeverage",0,function(e,t,r=2){if(!(e>0)||!(t>0)||!(r>0))return null;let i=r*e*Math.sqrt(t);return i>0?Math.max(1,1/i):null},"scorePair",0,function(e,t){return t>0?e/t:null},"topDistinctPairs",0,function(e,t){let r=new Set,i=[];for(let s of e)if(!(r.has(s.longSymbol)||r.has(s.shortSymbol))&&(r.add(s.longSymbol),r.add(s.shortSymbol),i.push(s),i.length>=t))break;return i}])},232024,e=>{"use strict";e.s(["pairRepayment",0,function(e,t){let r=e.reduce((e,t)=>e+t.feesPaidUsd+t.closeFeesUsd,0),i=e.reduce((e,t)=>e-t.accruedFundingUsd,0)+t,s=Math.max(0,r-i),n=r>0?Math.min(1,Math.max(0,i/r)):0,a=e.map(e=>e.fundingRateHourlyUsd),l=a.every(e=>null===e)?null:a.reduce((e,t)=>e+(t??0),0),o=null===l?0:-l;return{totalFeesUsd:r,fundingEarnedUsd:i,progress:n,remainingUsd:s,hoursToRepay:s>0&&o>0?s/o:null,netRateHourlyUsd:l}}])},519527,e=>{"use strict";e.s(["buildPairLegs",0,function(e){let{underwriter:t,profileIndex:r,long:i,short:s}=e;return[{underwriter:i.underwriter??t,profileIndex:r,marketMint:i.legMarket,assetSymbol:i.symbol,side:0},{underwriter:s.underwriter??t,profileIndex:r,marketMint:s.legMarket,assetSymbol:s.symbol,side:1}]}])},613448,e=>{"use strict";let t=[{symbol:"SOLBTC",mint:"2XPaUSz89iZMjAWPeMAVFumuPAPCpPCLorWsucxZfyAM",marketId:0},{symbol:"ANSEM",mint:"J6qsBCE6nHyNqEtx9r3gTAa1n62rq3hpeS6ndQU7Fm7x",marketId:1},{symbol:"CASHCAT",mint:"EAXXcwBbzgU4qJDHx7EgZg7eka4MALurp99GJNMdU7vT",marketId:2},{symbol:"ANSEMCASHCAT",mint:"HZ4jtJ88BWXXYMoSv8FTvcB1KcYhgUA341XDLtcpkYbq",marketId:3},{symbol:"SPX6900",mint:"AHzJ59shdLavXxKhcE5992VtsVTMueaKbPLcy6UnPgac",marketId:4},{symbol:"USELESS",mint:"H5Cozuj6GQqzsEjXWMmQuZ7S1etVz21cDYab1ERmX24z",marketId:5},{symbol:"BVIV",mint:"4qg7PBiFVpeXAVCTf7yhXjLSopuLdUo7vjqRc5XdUcg4",marketId:12},{symbol:"CATE",mint:"7pWLTGKGcruiwAhTuXX15MGHECgMpUt11obVauH3KxJ8",marketId:13}],r={SOLBTC:"SOL/BTC Spread",ANSEMCASHCAT:"ANSEM/CASHCAT Spread",BVIV:"BTC 30-Day Implied Vol"},i=new Map(t.map(e=>[e.symbol,e])),s=new Map(t.map(e=>[e.mint,e]));function n(e){return i.get(e.toUpperCase())}function a(e){return n(e)?.mint??null}e.s(["pairsDisplayName",0,function(e){return r[e.toUpperCase()]??e},"pairsMarketByMint",0,function(e){return s.get(e)},"pairsMarketBySymbol",0,n,"pairsMintBySymbol",0,a,"pairsMintForPosition",0,function(e,t){return"pairs"!==t?null:a(e)}])},555381,477303,976125,341833,e=>{"use strict";e.s(["matchesPhoenixApiPosition",0,function(e,t,r){return"phoenix"===e.underwriter&&"venue_direct"!==e.ownership&&e.positionPda===t.positionPda&&e.side===t.side&&(!t.isPhoenixCrossSeat||r===t.asset)},"phoenixPositionKey",0,function(e){return`phoenix:${e.positionPda}:${e.asset}:${e.side}`}],555381);var t=e.i(183023),r=e.i(111526),i=e.i(717421),s=e.i(799227);let n="296149696ed67009",a=56,l=88,o=224,d=240,c=0,u=8,h=16;function p(e,t){let r=Number(e.readBigUInt64LE(o)),i=new Set,s=new Set;for(let n=0;n<Math.min(r,t);n++){let t=d+40*n;if(t+40>e.length)break;if(0===Number(e.readBigInt64LE(t+u)))continue;let r=65535&Number(e.readBigUInt64LE(t+c));s.has(r)||(s.add(r),i.add(n))}return i}var m=e.i(622463),f=e.i(938425);async function x(e,t,r){if(t.length<=100)return e.getMultipleAccountsInfoAndContext(t,r);let i=[];for(let e=0;e<t.length;e+=100)i.push(t.slice(e,e+100));let s=await Promise.all(i.map(t=>e.getMultipleAccountsInfoAndContext(t,r)));return{context:s.reduce((e,t)=>t.context.slot<e.context.slot?t:e).context,value:s.flatMap(e=>e.value)}}e.s(["usePhoenixRealtimePositions",0,function(e,x,g,b){let{accounts:v,isConnected:y,lastUpdate:w,subscribe:j,unsubscribe:S}=(0,i.useAccountSubscriptionContext)(),k=(0,t.useRef)([]),N=(0,t.useRef)(new Map),P=(0,t.useRef)(null),[T,C]=(0,t.useState)(0);(0,t.useEffect)(()=>(0,m.subscribePhoenixRegistry)(()=>C(e=>e+1)),[]);let M=(0,t.useMemo)(()=>{let e=(0,m.getGlobalPhoenixRegistry)(),t=new Map;for(let r of e?.getAllMarkets()??[]){let e=r.subaccountIndex-1>>1&65535;t.set(e,{symbol:r.symbol,baseLotsDecimals:r.baseLotsDecimals})}return e=>t.get(65535&e)},[T]),_=(0,t.useMemo)(()=>
2{if(!e)return[];let t=(0,m.getGlobalPhoenixRegistry)(),r=t?.getAllMarkets()??[];return x.flatMap(t=>{let[i]=(0,f.getProfilePda)(e,t);return[...r.flatMap(e=>[{pda:(0,m.derivePhoenixTraderAccount)(i,0,e.subaccountIndex),profileIndex:t,symbol:e.symbol},{pda:(0,m.derivePhoenixTraderAccount)(i,0,e.subaccountIndex+1),profileIndex:t,symbol:e.symbol}]),{pda:(0,m.derivePhoenixTraderAccount)(i,0,m.CROSS_MARGIN_SUBACCOUNT_IDX),profileIndex:t,symbol:null}]})},[e,x,T]);(0,t.useEffect)(()=>{let e=_.map(e=>e.pda.toBase58()),t=new Set(k.current),r=new Set(e),i=e.filter(e=>!t.has(e)),s=k.current.filter(e=>!r.has(e));i.length>0&&(console.debug("[PHX-WS] subscribing to trader PDAs",i.map(e=>e.slice(0,8))),j(i)),s.length>0&&(console.debug("[PHX-WS] unsubscribing from trader PDAs",s.map(e=>e.slice(0,8))),S(s)),k.current=e},[_,j,S]);let{positions:A,emptyTraderPdas:E,observedCrossSeats:L,observedSeats:F}=(0,t.useMemo)(()=>{let e=[],t=new Set,i=new Set,m=new Set;for(let f of _){let x=f.pda.toBase58(),g=v.get(x);if(!g)continue;let b=null===f.symbol;if(g.isDeleted){t.add(x),m.add(x),b&&i.add(x);continue}if(!g.data)continue;let y=r.Buffer.from(g.data,"base64");if(!function(e,t){if(e.length<280||(e.length-240)%40!=0||e.subarray(0,8).toString("hex")!==n)return!1;let r=(e.length-240)/40;if(e.readBigUInt64LE(o)>BigInt(r))return!1;for(let i of p(e,r))if(!t(Number(e.readBigUInt64LE(240+40*i))))return!1;return!0}(y,M))continue;m.add(x),b&&i.add(x);let w=function(e,t){if(e.length<280||e.subarray(0,8).toString("hex")!==n)return[];let r=Math.floor((e.length-240)/40),i=p(e,r);if(0===i.size)return[];let o=new s.PublicKey(e.subarray(a,a+32)),m=Number(e.readBigInt64LE(l))/1e6,f=[];for(let s=0;s<r;s++){let r=d+40*s;if(r+40>e.length)break;if(!i.has(s))continue;let n=Number(e.readBigInt64LE(r+u)),a=Number(e.readBigInt64LE(r+h));if(0===n)continue;let l=Number(e.readBigUInt64LE(r+c)),p=t(l);if(!p)continue;let x=n>0?"long":"short",g=Math.abs(a),b=g/1e6,v=g/Math.abs(n)/Math.pow(10,6-p.baseLotsDecimals),y=m>0?b/m:0;f.push({slotIndex:s,assetId:l,owner:o.toBase58(),pool:"",custody:"",collateralCustody:"",openTime:0,updateTime:0,side:x,priceUsd:v,sizeUsd:b,collateralUsd:m,realisedPnlUsd:0,leverageX:y,isEmpty:!1})}return f}(y,M);if(0===w.length){t.add(x);continue}for(let t of w){if("none"===t.side)continue;let r=t.side,i=M(t.assetId)?.symbol??f.symbol;i&&(console.debug("[PHX-WS] position found",{symbol:i,side:r,sizeUsd:t.sizeUsd,collateralUsd:t.collateralUsd,priceUsd:t.priceUsd,slotIndex:t.slotIndex}),e.push({positionPda:x,asset:i,side:r,marketMint:"",custody:"",collateralCustody:"",owner:t.owner,openTime:0,updateTime:0,priceUsd:t.priceUsd,sizeUsd:t.sizeUsd,collateralUsd:t.collateralUsd,realisedPnlUsd:0,leverageX:t.leverageX,lastWsUpdate:g.lastUpdate,profileIndex:f.profileIndex,isPhoenix:!0,isPhoenixCrossSeat:b}))}}return{positions:e,emptyTraderPdas:t,observedCrossSeats:i,observedSeats:m}},[_,v,M]);return(0,t.useEffect)(()=>{let t=e?.toBase58()??null;t!==P.current&&(N.current.clear(),P.current=t);let r=new Map(A.map(e=>[`${e.positionPda}:${e.asset}:${e.side}`,e])),i=new Set(_.map(e=>e.pda.toBase58()));N.current.forEach((e,t)=>{!r.has(t)&&i.has(e.positionPda)&&(F.has(e.positionPda)?b?.(e.positionPda,e):r.set(t,e))}),N.current=r},[A,F,_,e,b]),{positions:A,emptyTraderPdas:E,observedCrossSeats:L,isConnected:y,lastUpdate:w}}],477303);var g=e.i(653982),b=e.i(326702),v=e.i(508947),y=e.i(777670),w=e.i(562955);e.s(["useSunrisePositions",0,function(e,r,i){let[s,n]=(0,t.useState)([]),[a,l]=(0,t.useState)(new Set),[o,d]=(0,t.useState)(new Map),[c,u]=(0,t.useState)(null),[h,p]=(0,t.useState)(!1),m=(0,t.useRef)(async()=>!1),j=(0,t.useCallback)(e=>m.current(e),[]),S=(0,t.useRef)(new Map),k=(0,t.useRef)(new Map),N=(0,t.useRef)({wallet:null,slot:0}),P=e?.toBase58()??null,T=r.slice().sort((e,t)=>e-t).join(","),C=i.slice().sort().join(","),M=JSON.stringify([P,T,C]);return(0,t.useEffect)(()=>{let t;if(!e||!b.SUNRISE_PROGRAM_ID||0===r.length||0===i.length){S.current=new Map,k.current=new Map,n([]),l(new Set),d(new Map),u(M),p(!1);return}let s=!1,a=(0,b.getSunriseConnection)(),o=[],c=new y.SunrisePositionObservations,h=new Map,j=new Map;N.current.wallet!==P&&(N.current={wallet:P,slot:0});let T=N.current.slot,C=new Map;n([]),l(new Set),d(new Map),u(M);let _=new Map,A=new Map,E=(e,t,r)=>"cross"===t?`${e}|cross`:`${e}
2|iso|${(0,v.seatText)(r,t)}`,L=()=>{if(s)return;let e=[];for(let[t,{profileIndex:r,position:i}]of S.current){let s=k.current.get(E(i.profile,i.seat,i.symbol)),n=s?.collateralUsd??0,a=void 0===s;e.push({positionPda:t,asset:i.symbol,side:i.side,marketMint:g.ASSET_TO_MINT[i.symbol]??i.symbol,custody:"",collateralCustody:"",owner:i.user,openTime:0,updateTime:Date.now(),priceUsd:i.entryPrice,sizeUsd:i.sizeUsd,collateralUsd:n,collateralUnknown:a,realisedPnlUsd:0,leverageX:n>0?i.sizeUsd/n:0,lastWsUpdate:Date.now(),profileIndex:r,isSunrise:!0,sunriseMarginSeat:(0,v.seatText)(i.symbol,i.seat),isSunriseCrossMargin:"cross"===i.seat,sunrisePrimeBound:s?.primeBound})}n(e),d(new Map(c.closedSlots)),l(new Set(r.filter(e=>Array.from(_).filter(([,t])=>t===e).every(([e])=>c.observedKeys.has(C.get(e))))))},F=(e,t,r,i="subscription")=>{if(s||r<T)return;let n=(0,b.decodePosition)(t),a=_.get(e),l=C.get(e);if(!l)return;let o=n?"open":(0,b.isClosedPositionAccount)(t)?"closed":"unknown";c.apply(l,r,o,i)&&(n&&void 0!==a?S.current.set(e,{profileIndex:a,position:n}):S.current.delete(e),L())},R=(e,t,r,i="subscription")=>{if(s||r<T||r<(h.get(e)??-1)||"seed"===i&&r<=(j.get(e)??-1))return;let n=A.get(e);if(!n)return;let a=(0,b.decodeMargin)(t);(!t||0===t.length||a)&&(h.set(e,r),"subscription"===i&&j.set(e,r),a?k.current.set(n,a):k.current.delete(n),L())},D=["cross","isolated","isolated_2"],I=[];for(let t of r){let r=(0,f.getProfilePda)(e,t)[0],s=r.toBase58();for(let e of D)for(let n of i){let i=(0,b.getPositionPda)(r,n,e);_.set(i.toBase58(),t),C.set(i.toBase58(),(0,y.sunrisePositionKey)(t,n,(0,v.seatText)(n,e))),I.push({pda:i,kind:"position"});let a=(0,b.getMarginPdaForSeat)(r,n,e),l=a.toBase58();A.has(l)||(A.set(l,E(s,e,n)),I.push({pda:a,kind:"margin"}))}}p(!0);let U=null,O=async e=>{if(e){if(!r.includes(e.profileIndex)||!i.includes(e.symbol))return!1;T=Math.max(T,e.minContextSlot),N.current.slot=T}if(!e&&U)return U;for(;U;)await U;if(s)return!1;let t=(async()=>{try{let{value:e,context:t}=await x(a,I.map(e=>e.pda),{commitment:"confirmed",minContextSlot:T});if(s||t.slot<T||e.length!==I.length)return!1;let r=!0;return e.forEach((e,i)=>{let{pda:s,kind:n}=I[i],a=e?.data??null;"margin"===n?(a&&0!==a.length&&!(0,b.decodeMargin)(a)&&(r=!1),R(s.toBase58(),a,t.slot,"seed")):((0,b.decodePosition)(a)||(0,b.isClosedPositionAccount)(a)||(r=!1),F(s.toBase58(),a,t.slot,"seed"))}),r}catch{return!1}finally{s||p(!1)}})();U=t;try{return await t}finally{U===t&&(U=null)}};m.current=O,O();let B=()=>{clearTimeout(t),O().then(e=>{s||e||(t=setTimeout(B,1e3))})},z=(0,w.onSunriseRpcOpen)(a,B);for(let{pda:e,kind:t}of I){let r=e.toBase58(),i=a.onAccountChange(e,(e,i)=>"margin"===t?R(r,e.data,i.slot):F(r,e.data,i.slot),"confirmed");o.push(i)}return()=>{for(let e of(s=!0,clearTimeout(t),z(),m.current=async()=>!1,o))a.removeAccountChangeListener(e).catch(()=>{});S.current=new Map,k.current=new Map}},[P,T,C]),c===M?{positions:s,observedProfiles:a,closedPositionSlots:o,isInitialLoading:h,refresh:j}:{positions:[],observedProfiles:new Set,closedPositionSlots:new Map,isInitialLoading:h,refresh:j}}],976125);var j=e.i(401673),S=e.i(47280);let k={},N=()=>k;e.s(["usePhoenixMarkPrices",0,function(e){let r=JSON.stringify([...new Set(e)].sort()),i=(0,t.useMemo)(()=>{let e,t,i;return e=new Set(JSON.parse(r)),t=k,i=new Set,{wanted:e,getSnapshot:()=>t,subscribe:e=>(i.add(e),()=>{i.delete(e)}),set:(r,s)=>{if(e.has(r)&&Number.isFinite(s)&&!(s<=0)&&t[r]!==s)for(let e of(t={...t,[r]:s},i))e()}}},[r]),s=(0,j.useThrottledStore)(i,N,500);return(0,t.useEffect)(()=>{if(0===i.wanted.size)return;let e=new Map,t=(0,m.subscribePhoenixRegistry)(function(){let t=(0,m.getGlobalPhoenixRegistry)();if(t)for(let r of i.wanted){let s=t.getMarketBySymbol(r),n=e.get(r),a=s?.phoenixSymbol??(s?r:void 0);n?.raw!==a&&(n?.release(),e.delete(r),a&&e.set(r,{raw:a,release:(0,S.retainPhoenixMarket)(a,{connection:()=>{},message:e=>i.set(r,Number(e.markPx))})}))}});return()=>
2{for(let r of(t(),e.values()))r.release();e.clear()}},[i]),s}],341833)},259048,e=>{"use strict";e.s(["pnlColor",0,function(e){return null!=e&&0!==e&&Number.isFinite(e)?e>0?"text-side-long":"text-side-short":"text-muted-foreground"},"pnlColorDim",0,function(e){return null!=e&&0!==e&&Number.isFinite(e)?e>0?"text-side-long/85":"text-side-short/85":"text-muted-foreground"}])},265724,e=>{"use strict";function t(e){if(!e)return null;let t=parseFloat(e);return Number.isFinite(t)&&t>0?t:null}e.s(["consistentLeverageX",0,function(e){let r=t(e.apiLeverageXRaw);if(null!==r)return r;let i=t(e.apiSizeUsdRaw),s=t(e.apiCollateralUsdRaw);return null!==i&&null!==s?i/s:e.wsCollateralUsd>0?e.wsSizeUsd/e.wsCollateralUsd:0},"displayPositionLeverage",0,function(e){if(null!==t(e.effectiveLeverageX))return e.effectiveLeverageX;if("closed"===e.status||"liquidated"===e.status)return e.maxLeverageX??e.leverageX??null;if(null!==t(e.leverageX))return e.leverageX;let r=t(e.sizeUsd),i=t(e.collateralUsd);return null!==r&&null!==i?String(r/i):null}])},856255,e=>{"use strict";var t=e.i(799227),r=e.i(308146),i=e.i(860991),s=e.i(21859),n=e.i(653982),a=e.i(739835),l=e.i(858007),o=e.i(801637);async function d(e,t){try{let r=(0,s.getAssociatedTokenAddressSync)(n.USDC_MINT,t),i=await e.getTokenAccountBalance(r);return parseFloat(i.value.uiAmountString??"0")}catch{return 0}}async function c({connection:e,publicKey:s,signTransaction:d,sendTransaction:u,profileIndex:h,amountUsdc:p}){let m=(0,r.numberToBaseUnits)(p,6);if(null===m)throw Error(`fundProfileWithUsdc: invalid amount ${p}`);if(m<=BigInt(0))return;let f=await (0,o.planSelfPaidProfileTx)({connection:e,publicKey:s,profileIndex:h,mint:n.USDC_MINT,amount:m,mode:"deposit"});if(f.canSelfPay){let r=new t.Transaction;f.instructions.forEach(e=>r.add(e));let{blockhash:n,lastValidBlockHeight:a}=await e.getLatestBlockhash();r.recentBlockhash=n,r.feePayer=s;let l=await u(r);await (0,i.confirmOrVerifyLanded)(e,{signature:l,blockhash:n,lastValidBlockHeight:a});return}try{await (0,o.sendSponsoredProfileTx)({publicKey:s,signTransaction:d,profileIndex:h,amount:m,mode:"deposit"})}catch(e){if((0,a.isUserRejection)(e))throw e;throw(0,l.logErrorToServer)({type:"profile_autofund_failed",wallet:s.toBase58(),profileIndex:h,amount:Number(m),lamportsAvailable:f.lamportsAvailable,lamportsRequired:f.lamportsRequired,errorName:e?.name,errorMessage:e?.message??String(e),status:e?.
2status,body:e?.body}),e}}e.s(["fundProfileWithUsdc",0,c,"getWalletUsdcBalance",0,d])},156777,e=>{"use strict";var t=e.i(938425);e.s(["collectKnownProfileIndices",0,function(e,r,i=[]){let s=new Set([0]),n=e=>{"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<t.MAX_PROFILES&&s.add(e)};return n(e),r.forEach(e=>n(e.profileIndex)),i.forEach(e=>n(e.profileIndex)),Array.from(s).sort((e,t)=>e-t)}])},801637,e=>{"use strict";e.i(413358);var t=e.i(799227);e.i(943353);var r=e.i(356534),i=e.i(21859),s=e.i(568801),n=e.i(327139),a=e.i(985604),l=e.i(596331),o=e.i(938425),d=e.i(936548);let c="https://api.imperial.space";class u extends Error{constructor(){super("Profile transaction context changed"),this.name="ProfileTxCancelledError"}}async function h({connection:e,publicKey:t,profileIndex:d,mint:c,amount:u,mode:p}){let[m]=(0,o.getProfilePda)(t,d),[f]=(0,o.getUserAccountPda)(t),x=(0,i.getAssociatedTokenAddressSync)(c,t),g=(0,i.getAssociatedTokenAddressSync)(c,m,!0),b="deposit"===p?g:x,[v,y,w]=await e.getMultipleAccountsInfo([t,f,b]),j=[],S=0;y||(j.push(new l.PassthroughClient(e).createUserAccountIx(t,t)),S+=2115840),w||(S+=2039280),"deposit"===p?(j.push((0,s.createAssociatedTokenAccountIdempotentInstruction)(t,g,m,c)),j.push((0,n.createTransferInstruction)(x,g,t,u,[],a.TOKEN_PROGRAM_ID))):(j.push((0,s.createAssociatedTokenAccountIdempotentInstruction)(t,x,t,c)),j.push(new l.PassthroughClient(e).withdrawFromProfileIx({wallet:t,profileIndex:d,mint:c,amount:new r.BN(u.toString())})));let k=S+5e3+1e6,N=v?.lamports??0;return{instructions:j,lamportsRequired:k,rentLamports:S,lamportsAvailable:N,canSelfPay:N>=k}}class p extends d.ImperialUserError{step;status;body;constructor(e,t,r,i,s){super(e,s),this.step=t,this.status=r,this.body=i,this.name="SponsoredProfileTxError"}}async function m(e,t){let r=await t.text().catch(()=>null),i=null;if(t.status<500&&r)try{i=(0,d.errorFromPayload)(JSON.parse(r))}catch{}let s=i??(0,d.userErrorForCode)("Generic");return new p(s.message,e,t.status,r,s.details)}async function f({publicKey:e,signTransaction:r,profileIndex:i,amount:s,mode:n,onSigning:a,onSubmitting:l,isCurrent:o}){let d,h=()=>{if(o&&!o())throw new u};h();let p={wallet:e.toBase58(),profileIndex:i,amount:Number(s),mode:n},x=new AbortController,g=setTimeout(()=>x.abort(),8e3);try{d=await fetch(`${c}/api/v1/deposit/build-tx`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...p,deferOperatorSignature:!0}),signal:x.signal})}finally{clearTimeout(g)}if(!d.ok)throw await m("build-tx",d);let{transaction:b}=await d.json();h(),a?.();let v=function(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}((await r(t.Transaction.from(Uint8Array.from(atob(b),e=>e.charCodeAt(0))))).serialize({requireAllSignatures:!1}));h(),l?.();let y=await fetch(`${c}/api/v1/deposit/cosign-tx`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...p,transaction:v})});if(!y.ok)throw await m("cosign-tx",y);let{signature:w}=await y.json();return w}e.s(["ProfileTxCancelledError",0,u,"planSelfPaidProfileTx",0,h,"sendSponsoredProfileTx",0,f])},965155,541043,798526,401673,250672,22156,e=>{"use strict";var t=e.i(799227);new t.PublicKey("FYq2BWQ1V5P1WFBqr3qB2Kb5yHVvSv7upzKodgQE5zXh"),new t.PublicKey("hUqAT1KQ7eW1i6Csp9CXYtpPfSAvi835V7wKi5fRfmC"),new t.PublicKey("AFZnHPzy4mvVCffrVwhewHbFc93uTHvDSFrVH7GtfXF1");let r={So11111111111111111111111111111111111111112:"SOL","3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh":"BTC","7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs":"ETH"},i=new Set;function s(e){return i.add(e),()=>{i.delete(e)}}e.s(["MINT_TO_PYTH_SYMBOL",0,r,"subscribeMintSymbol",0,s],541043);var n=e.i(183023),a=e.i(142910),l=e.i(177194);let o=new Map,d=new Map,c=new Map,u=!1;function h(e){if(e!==u)for(let t of(u=e,c.values()))t(e)}let p=null,m=[],f=null,x=0,g=null,b=0,v=new Map,y=null;function w(){if("u"<typeof EventSource)return;let e=Array.from(d.keys()).sort((e,t)=>e-t);if(0===e.length)return void k();if(p&&function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(m,e))return;k(),m=e;let t=new EventSource(`https://api.imperial.space/api/v1/pyth/lazer-stream?${e.map(e=>`price_feed_ids=${e}`).join("&")}`);p=t;let r=Date.now();for(let t of(b=r,e))v.set(t,r);t.onopen=()=>{h(!0)},t.addEventListener("price_update",e=>{b=Date.now(),x=0,h(!0),function(e){try{let t=JSON.parse(e);if(!t.priceFeeds||!Array.isArray(t.priceFeeds))return;let r=Math.floor(Number(t.timestampUs)/1e3);for(let e of t.priceFeeds){let t=Number(e.priceFeedId);if(!Number.isFinite(t))continue;
2let i=e.price,s=Number(e.exponent);if(!i||!Number.isFinite(s))continue;let n=parseInt(i,10)*Math.pow(10,s);Number.isFinite(n)&&!(n<=0)&&function(e,t,r){v.set(e,Date.now());let i=d.get(e);if(!i||0===i.size)return;let s={symbol:(0,a.getSymbolByLazerId)(e)??"",price:t,timestamp:r,volume:0};for(let e of i){let t=o.get(e);t&&t.callback(s)}}(t,n,r)}}catch{}}(e.data)}),t.onerror=()=>{p===t&&(k(),j())},S(),y=setInterval(()=>{if(!p)return;let e=Date.now();if(e-b>1e4){k(),j();return}for(let t of d.keys())if(e-(v.get(t)??0)>15e3){k(),j();return}},5e3)}function j(){f&&clearTimeout(f),0!==o.size&&(f=setTimeout(()=>{f=null,w()},(0,l.reconnectDelayMs)(x++)))}function S(){y&&(clearInterval(y),y=null)}function k(){p&&(p.close(),p=null),S(),m=[],h(!1)}function N(){g=null,w()}function P(){g||(g=setTimeout(N,50))}function T(e,t){o.delete(e);let r=d.get(t);r&&(r.delete(e),0===r.size&&(d.delete(t),v.delete(t))),0===o.size?(f&&(clearTimeout(f),f=null),g&&(clearTimeout(g),g=null),k()):P()}"u">typeof document&&document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&o.size>0&&(p&&p.readyState===EventSource.OPEN&&Date.now()-b<5e3||(x=0,f&&(clearTimeout(f),f=null),k(),w())
2)});let C={So11111111111111111111111111111111111111112:"SOL","3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh":"BTC","7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs":"ETH"},M=new Map,_=new Map,A=null;function E(e,t,r){let i=(0,a.getLazerIdBySymbol)(t);if(void 0!==i){let s;return o.set(e,{feedId:i,symbol:t,callback:r}),(s=d.get(i))||(s=new Set,d.set(i,s)),s.add(e),P(),_.set(e,()=>T(e,i)),!0}return!1}function L(){if(0===M.size&&A){let e=A;A=null,e()}}function F(){for(let[e,t]of[...M])E(e,t.symbol,t.listener)&&M.delete(e);L()}function R(e,t,r){return(_.get(e)?.(),_.delete(e),E(e,t,r))?(M.delete(e),L(),!0):(M.set(e,{symbol:t,listener:r}),A||(A=(0,a.subscribeFeedRegistry)(F)),!1)}function D(e,t){let r=_.get(e);if(r){_.delete(e),r();return}if(M.delete(e))return void L();let i=(0,a.getLazerIdBySymbol)(t);void 0!==i&&T(e,i)}let I=new Map,U=!1,O=!1,B="__oracle_feed_agg";function z(e,t){if(!O){var r;O=!0,r=e=>{if(e!==U)for(let t of(U=e,I.values()))t(e)},c.set(B,r),r(u)}I.set(e,t),t(U)}function $(e){(I.delete(e),!(I.size>0)&&O)&&(O=!1,c.delete(B),U=!1)}e.s(["addConnectionListener",0,z,"addListener",0,R,"getFeedSymbol",0,function(e){let t=C[e];return t||(0,a.getFeedInfo)(e)?.symbol},"removeConnectionListener",0,$,"removeListener",0,D],798526);var V=e.i(394390);function H(e,t,r){let i=(0,n.useMemo)(()=>(function(e,t){let r,i,s=e.getSnapshot(),n=-1/0,a=new Set;function l(){clearTimeout(r),r=void 0;let t=e.getSnapshot();if(!Object.is(s,t))for(let e of(s=t,n=Date.now(),a))e()}function o(){if(Object.is(s,e.getSnapshot()))return;let i=t-(Date.now()-n);i<=0?l():void 0===r&&(r=setTimeout(l,i))}return{getSnapshot:()=>(0===a.size&&(s=e.getSnapshot()),s),subscribe:t=>(a.add(t),1===a.size&&(i=e.subscribe(o),l()),()=>{a.delete(t),0===a.size&&(i?.(),i=void 0,clearTimeout(r),r=void 0,n=-1/0)})}})(e,r),[e,r]),s=r>0?i:e;return(0,n.useSyncExternalStore)(s.subscribe,s.getSnapshot,t)}e.s(["useThrottledStore",0,H],401673);let W={price:void 0,isConnected:!1,lastUpdate:void 0},q=()=>W;function K(){let e=W,t=new Set;return{getSnapshot:()=>e,subscribe:e=>(t.add(e),()=>{t.delete(e)}),set:r=>{if(e.price!==r.price||e.isConnected!==r.isConnected||e.lastUpdate!==r.lastUpdate)for(let i of(e=r,t))i()}}}let G=(0,n.createContext)(K());e.s(["PythPriceProvider",0,function({marketMint:e,children:t}){let i=(0,n.useMemo)(()=>K(),[e]);return(0,n.useEffect)(()=>{let t,n,a,l=`pyth-price-${Math.random().toString(36).slice(2)}`,o=!0,d=()=>{let s=r[e]??e;s!==t&&(t&&D(l,t),void 0!==n&&cancelAnimationFrame(n),n=void 0,a=void 0,t=s,i.set({...W,isConnected:i.getSnapshot().isConnected}),R(l,s,e=>{o&&t===s&&(a={price:e.price,receivedAt:Date.now()},void 0===n&&(n=requestAnimationFrame(()=>{if(n=void 0,!a||!o)return;let e=i.getSnapshot();i.set({price:a.price,isConnected:e.isConnected,lastUpdate:void 0!==e.lastUpdate&&a.receivedAt-e.lastUpdate<1e3?e.lastUpdate:a.receivedAt})})))}))};d();let c=s(d);return z(l,e=>{o&&i.set({...i.getSnapshot(),isConnected:e})}),()=>{o=!1,c(),void 0!==n&&cancelAnimationFrame(n),t&&D(l,t),$(l)}},[e,i]),(0,V.jsx)(G.Provider,{value:i,children:t})},"usePythPriceContext",0,function(e=0){return H((0,n.useContext)(G),q,e)}],250672);var Y=e.i(622463),X=e.i(47280);let Q={SOL:void 0,BTC:void 0,ETH:void 0},J={},Z={},ee={},et={prices:Q,timestamps:J,sourceTimestamps:Z,prevDayPrices:ee},er=new Set;function ei(e){return er.add(e),()=>{er.delete(e)}}let es=!1;function en(){if(es)return;es=!0;let e=()=>{for(let e of(es=!1,et={prices:Q,timestamps:J,sourceTimestamps:Z,prevDayPrices:ee},er))e()};"u">typeof requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,16)}function ea(e,t,r,i){let s=!1,n=Number.isFinite(t)&&t>0;if(n){Q[e]!==t&&(Q={...Q,[e]:t},s=!0);let i=1e3*Math.floor((Number.isFinite(r)?r:Date.now())/1e3);J[e]!==i&&(J={...J,[e]:i},s=!0)}let a=n&&void 0!==i&&Number.isSafeInteger(i)&&i>0&&i<=Date.now()?i:void 0;Z[e]!==a&&(Z={...Z,[e]:a},s=!0),s&&en()}let el={prices:{},timestamps:{},sourceTimestamps:{},prevDayPrices:{}},eo={subscribe:ei,getSnapshot:()=>et},ed=()=>el,ec=["SOL","BTC","ETH"];e.s(["AllMarketsPriceProvider",0,function({children:e}){let t=`all-markets-${(0,n.useId)()}`;return(0,n.useEffect)(()=>{let e=new Map,r=new Map;function i(){let i=(0,Y.getGlobalPhoenixRegistry)(),s=new Set([...ec,...i?.getSymbols()??[]]);for(let r of e.keys())s.has(r)||(D(`${t}-${r}`,r),e.delete(r));for(let[e,t]of r)s.has(e)||(t.release(),r.delete(e));for(let n of s){let s=(0,a.getLazerIdBySymbol)(n);e.has(n)&&e.get(n)===s||(D(`${t}-${n}`,n),R(`${t}-${n}`,n,e=>
2ea(n,e.price,ec.includes(n)?Date.now():e.timestamp,e.timestamp)),e.set(n,s));let l=r.get(n),o=i?.getMarketBySymbol(n),d=void 0===s&&o?o.phoenixSymbol??n:void 0;l?.raw!==d&&(l?.release(),r.delete(n),d&&r.set(n,{raw:d,release:(0,X.retainPhoenixMarket)(d,{connection:()=>{},message:e=>{ea(n,Number(e.markPx),Date.now());let t=Number(e.prevDayPx);Number.isFinite(t)&&t>0&&ee[n]!==t&&(ee={...ee,[n]:t},en())}})}))}}i();let s=(0,Y.subscribePhoenixRegistry)(i),n=(0,a.subscribeFeedRegistry)(i);return()=>{for(let r of(s(),n(),e.keys()))D(`${t}-${r}`,r);for(let e of r.values())e.release();e.clear(),r.clear()}},[t]),(0,V.jsx)(V.Fragment,{children:e})},"useAllMarketsPricesThrottled",0,function(e=500){return H(eo,ed,e)},"usePriceForSymbol",0,function(e){return(0,n.useSyncExternalStore)(ei,()=>void 0===e?void 0:Q[e],()=>void 0)},"useTimestampForSymbol",0,function(e){return(0,n.useSyncExternalStore)(ei,()=>void 0===e?void 0:J[e],()=>void 0)}],22156),e.s([],965155)},872501,e=>{"use strict";e.i(413358);let t={"collector-crypt":!1,slabz:!0,beezie:!1,imperial:!1};e.s(["LAMPORTS_PER_SOL",0,1e9,"LOAN_OPEN_LTV_BPS",0,9e3,"MIN_SOL_LAMPORTS",0,3e6,"PROTOCOL_FLOOR_BPS",0,5500,"RIP_NAV_VISIBLE",0,!0,"VENUE_BROADCASTS",0,{"collector-crypt":!1,slabz:!0,beezie:!1,imperial:!1},"VENUE_PAYS_POSITIONS",0,{"collector-crypt":!1,slabz:!1,beezie:!1,imperial:!0},"VENUE_SELF_SETTLES",0,{"collector-crypt":!1,slabz:!1,beezie:!1,imperial:!0},"VENUE_USER_PAYS_NETWORK_FEE",0,{"collector-crypt":!1,slabz:!0,beezie:!0,imperial:!1},"publishesTopHits",0,function(e){return null!==e&&!0===t[e]},"solReadiness",0,function(e,t){return e?null===t?"unknown":t<3e6?"short":"ok":"notRequired"},"venueRipCopy",0,function(e){let t=e.unavailableReason??"";return e.canEverBeRipped?"beezie"===e.slug?{reasonKey:"notRippableBeezie",serverReason:t,shortKey:"notRippableShortNotYet"}:"imperial"===e.slug?{reasonKey:"notRippableImperial",serverReason:t,shortKey:"notRippableShortNotBuilt"}:{reasonKey:null,serverReason:t,shortKey:"notRippableShortNotYet"}:{reasonKey:"collector-crypt"===e.slug?"notRippableCollectorCrypt":null,serverReason:t,shortKey:"notRippableShortNotSold"}}])},162388,e=>{"use strict";var t=e.i(183023);e.s(["useReducedMotion",0,function(){let[e,r]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=()=>r(e.matches);return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),e}])},915402,e=>{"use strict";var t=e.i(275683);let r=e=>e.isLong?"long":"short";function i(e,t){return null===t?null:e/100+t}function s(e){if(null!=e.storyCollateralCents)return e.storyCollateralCents;if(null==e.stakeCents)return null;let t=e.stakeCents-(e.ripFeeCents??0);return t>0?t:null}e.s(["leverageXOf",0,e=>e/1e4,"liquidationPriceOf",0,e=>Number.isFinite(e)&&e>0?e:null,"packCapitalUsd",0,function(e,t,r){return e+Math.max(0,r-t)},"packReturnUsd",0,function(e,t,r){return e+t-r},"perpDeskHref",0,function(e){let i=`/perps/${e.market.toLowerCase()}?tab=positions`,s=e.positionRef?(0,t.unifiedPositionRowId)(e.positionRef,e.market,r(e)):null;return s?`${i}&close=${encodeURIComponent(s)}`:i},"perpEntryPrice",0,function(e){let t=e.backdatedEntryPriceMicros;return null!=t?t/1e6:null===e.entryPriceMicros?null:e.entryPriceMicros/1e6},"perpHasIssueReceipt",0,function(e){return null!=e.storyCollateralCents||(e.ripFeeCents??0)>0},"perpPnlNow",0,function(e,t){let r=s(e);if(null==r)return null;let n=i(e.collateralCents,t);return null===n?null:n-r/100},"perpSideOf",0,r,"perpStartingBasisCents",0,s,"perpValueNow",0,i])},972015,e=>{"use strict";e.s(["bookWalkPriceImpactBps",0,function(e,t,r){if(r<=0||t<=0||0===e.length)return 0;let i=[...e].sort((e,r)=>Math.abs(e.price-t)-Math.abs(r.price-t)),s=r,n=0,a=0;for(let e of i){let t=Math.min(s,e.sizeBase*e.price),r=t/e.price;if(n+=t,a+=r,(s-=t)<=0)break}return s>0?1/0:(n/a-t)/t*1e4},"computeCost",0,function(e,t,r,i,s){let n=i*e.openFeeBps/1e4,a=i*e.closeFeeBps/1e4,l=t?.priceImpactBps(i,r,"open")??0,o=t?.priceImpactBps(i,r,"close")??0,d=i*Math.abs(l)/1e4,c=i*Math.abs(o)/1e4,u=i*Math.max(0,e.borrowHourlyPctBySide?"long"===r?e.borrowHourlyPctBySide.long:e.borrowHourlyPctBySide.short:e.borrowHourlyPct??0)*s/100;return{openFee:n,closeFee:a,openSlip:d,closeSlip:c,borrow:u,total:n+a+d+c+u}},"gmtradePositionImpactBps",0,function(e,t,r,i,s,n,a,l){let o;if(r<=0||!isFinite(r)||n<=0)return 0;let d="long"===i?e+r:e,c="short"===i?t+r:t,[u,h,p,m]="open"===s?[e,t,d,c]:[d,c,e,t],f=u-h,x=p-m;if(Math.sign(f)*Math.sign(x)<0){let e=a*Math.pow(Math.abs(f),n);o=Math.abs(l*Math.pow(Math.abs(x),n)-e)}else{let e=Math.pow(Math.abs(f),n),t=Math.pow(Math.abs(x),n);o=(e>=t?a:l)*Math.abs(e-t)}return o/r*1e4}])},107481,e=>{"use strict";e.s(["CARD_BACKGROUNDS",0,["/king_retro.png","/cyber-king.png","/hapsburg-cyber.png","/ancient-bust-cyber.png"],"CARD_EXPORT_SCALE",0,2,"CARD_HEIGHT",0,400,"CARD_PAD",0,40,"CARD_WIDTH",0,800,"IMPERIAL_LOGO",0,"/[email protected]","dataUrlToPngBlob",0,function(e){let t=atob(e.split(",")[1]),r=new 
2Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return new Blob([r],{type:"image/png"})},"drawCardBackground",0,function(e,t,r,i,s=.25){e.globalAlpha=s,e.imageSmoothingEnabled=!0;let n=Math.max(r/t.naturalWidth,i/t.naturalHeight),a=t.naturalWidth*n,l=t.naturalHeight*n;e.drawImage(t,(r-a)/2,(i-l)/2,a,l),e.globalAlpha=1},"isWalletInAppBrowser",0,function(){return/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)&&!!window.solana},"resizeImageForBackground",0,function(e){return new Promise((t,r)=>{let i=new window.Image;i.onload=()=>{let e=Math.min(1,1200/Math.max(i.width,i.height)),s=Math.round(i.width*e),n=Math.round(i.height*e),a=document.createElement("canvas");a.width=s,a.height=n,a.getContext("2d").drawImage(i,0,0,s,n),a.toBlob(e=>e?t(e):r(Error("Failed to compress image")),"image/jpeg",.85)},i.onerror=()=>r(Error("Failed to load image")),i.src=URL.createObjectURL(e)})}])},610021,e=>{"use strict";var t=e.i(936548);function r(e){return e instanceof t.ImperialUserError&&["SunriseArriving","ArmadaArriving"].includes(e.details?.code??"")}async function i(e){let{policy:t,requestedUsd:i,readMargin:s,submit:n,sleep:a,now:l,onTick:o,cancelled:d}=e,c=l(),u=()=>l()-c,h=1;for(;;){let e=t.deadlineMs-u();if(e<=0||d?.()||(await a(Math.min(t.pollMs,e)),d?.()))return{kind:"stillArriving",waitedMs:u()};let l=null;try{l=function(e,t){let r=e?.withdrawableNowUsd;if("number"!=typeof r||!Number.isFinite(r))return null;let i=e?.withdrawableTotalUsd;return r+.005>=("number"==typeof i&&Number.isFinite(i)?Math.min(t,i):t)}(await s(),i)}catch{l=null}if(o?.({secsRemaining:Math.max(0,Math.ceil((t.deadlineMs-u())/1e3)),ready:!0===l}),!0===l){if(d?.()||h>=t.maxSubmits)return{kind:"stillArriving",waitedMs:u()};h+=1;try{let e=await n();return e?{kind:"settled",signature:e}:{kind:"reported"}}catch(e){if(!r(e))return{kind:"failed",error:e}}}}}e.s(["arrivingEtaSecs",0,function(e){if(!(e instanceof t.ImperialUserError))return null;let r=e.details?.retryAfterSecs;return"number"==typeof r&&Number.isFinite(r)&&r>0?r:null},"arrivingWaitPolicy",0,function(e){return{pollMs:3e3,deadlineMs:Math.min(12e4,Math.max(3e4,3*("number"==typeof e&&Number.isFinite(e)&&e>0?e:10)*1e3)),maxSubmits:3}},"isSunriseArriving",0,r,"waitForArrivingWithdrawal",0,i])},326702,e=>{"use strict";var t=e.i(591318),r=e.i(799227),i=e.i(444080),s=e.i(861646),n=e.i(508947);let a=new r.PublicKey("ARmavNtb6xs7SpH3geahw434fwTrVw5BSvJf36CAbWKB"),l=t.Buffer.from("sunpos"),o=t.Buffer.from("sunmargin"),d=t.Buffer.from("iso"),c=null;function u(e,t,i){return"cross"===i?function(e){if(!a)throw Error("NEXT_PUBLIC_SUNRISE_PROGRAM_ID is unset");return r.PublicKey.findProgramAddressSync([o,e.toBuffer()],a)[0]}(e):function(e,t,i="isolated"){if(!a)throw Error("NEXT_PUBLIC_SUNRISE_PROGRAM_ID is unset");return r.PublicKey.findProgramAddressSync([o,e.toBuffer(),p(t,i)],a)[0]}(e,t,i)}function h(e){let r=t.Buffer.alloc(16);return t.Buffer.from(e.toUpperCase(),"ascii").copy(r),r}function p(e,t){let r=h(e);return"isolated_2"===t&&(r[15]|=128),r}function m(e,t){return Number(new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!0))}let f={0:"cross",1:"isolated",2:"isolated_2"};e.s(["SUNRISE_PROGRAM_ID",0,a,"decodeMargin",0,function(e){var i;let s,a,l;if(!e)return null;let o=t.Buffer.from(e);return o.length<128||5!==o[0]?null:{profile:new r.PublicKey(o.subarray(8,40)).toBase58(),user:new r.PublicKey(o.subarray(40,72)).toBase58(),collateralUsd:m(o,72)/1e6,grossNotionalUsd:m(o,80)/1e6,openPositions:m(o,88),seatAsset:(i=o,a=(128&(s=t.Buffer.from(i.subarray(96,112)))[15])!=0,s[15]&=-129,0===(l=s.toString("ascii").replace(/\0+$/,"")).length?null:(0,n.seatText)(l,a?"isolated_2":"isolated")),primeBound:(4&o[112])!=0,retainsCollateral:(1&o[112])!=0,...o.length>=184&&{depositBasisUsd:m(o,128)/1e6,heldProfit:[{amountUsd:m(o,136)/1e6,until:m(o,144)},{amountUsd:m(o,168)/1e6,until:m(o,176)}]}}},"decodePosition",0,function(e){if(!e)return null;let i=t.Buffer.from(e);if(i.length<144||4!==i[0])return null;let s=i.subarray(72,88).toString("ascii").replace(/\0+$/,""),n=m(i,88)/1e6;return n<=0?null:{side:0===i[2]?"long":"short",hedgeVenue:i[3],seat:f[i[4]]??"isolated",profile:new r.PublicKey(i.subarray(8,40)).toBase58(),user:new r.PublicKey(i.subarray(40,72)).toBase58(),symbol:s,sizeUsd:n,entryPrice:m(i,96)/1e9,openedAtSlot:m(i,104)}},"getMarginPdaForSeat",0,u,"getMarginPdaForSeatText",0,function(e,t){let{symbol:r,seat:i}=(0,n.parseSeatText)(t);return u(e,r??"",i)},"getPositionPda",0,function(e,t,i="cross"){if(!a)throw Error("NEXT_PUBLIC_SUNRISE_PROGRAM_ID is unset");let s="cross"===i?[l,e.toBuffer(),h(t)]:[l,e.toBuffer(),p(t,i),d];return r.PublicKey.findProgramAddressSync(s,a)[0]},"getSunriseConnection",0,function(){return c||(c=function(e,t="confirmed"){return new r.Connection(e,{commitment:t,fetchMiddleware:(0,s.createRateLimitedFetchMiddleware)()})}("https://imperial-maind4b-5715.mainnet.rpcpool.com","confirmed")),c},"isClosedPositionAccount",0,function(e){if(!e||0===e.length)return!0;let r=t.Buffer.from(e);return r.length>=144&&4===r[0]&&0===m(r,88)},"marginAccountFilters",0,function(e){return[{memcmp:{offset:0,bytes:i.default.encode(Uint8Array.of(5))}},{memcmp:{offset:40,bytes:e}}]}],326702)},828047,e=>{"use strict";e.i(413358);var t=e.i(799227);let r=null,i=new Map,s=0,n=!1,a=new Set;function l(){r||n||(n=!0,fetch("https://api.imperial.space/api/v1/armada/markets").then(e=>e.ok?e.json():null).then(e=>{e&&o(e)}).catch(()=>{}).finally(()=>{n=!1}))}function o(e){0!==e.length&&(r=new Set(e.map(e=>e.symbol.toUpperCase())),i=new Map(e.filter(e=>"number"==typeof e.listedAt).map(e=>
2[e.symbol.toUpperCase(),e.listedAt])),s++,a.forEach(e=>e()))}e.s(["clampHistoryWindow",0,function(e,t,r){return null===e?{from:t,to:r}:void 0!==r&&r<=e?null:{from:void 0===t?void 0:Math.max(t,e),to:r}},"getGlobalSunriseMarkets",0,function(){return l(),r},"setGlobalSunriseMarkets",0,o,"subscribeSunriseMarkets",0,function(e){return l(),a.add(e),r&&e(),()=>{a.delete(e)}},"sunriseHistoryFloor",0,function(e){l();let t=i.get(e.toUpperCase());return void 0===t?null:t-604800},"sunriseListsSymbol",0,function(e){return l(),r?.has(e.toUpperCase())??!1},"sunriseSymbolFromAssetMint",0,function(e){let r;try{r=new t.PublicKey(e).toBytes()}catch{return null}for(let e=0;e<16;e++)if(r[e]!=="imperial-sunrise".charCodeAt(e))return null;let i=r.subarray(16),s=i.indexOf(0),n=-1===s?16:s;if(0===n||i.subarray(n).some(e=>0!==e))return null;let a=String.fromCharCode(...i.subarray(0,n));return/^[A-Z0-9.-]+$/.test(a)?a:null}])},508947,e=>{"use strict";function t(e){return null===e?{symbol:null,seat:"cross"}:e.endsWith("#2")?{symbol:e.slice(0,-2),seat:"isolated_2"}:{symbol:e,seat:"isolated"}}e.s(["inheritSunriseEntrySeat",0,function(e,t){if(7!==e.underwriter||7!==t.underwriter)return;let r=e.extraData?.sunriseSeat;(0===r||1===r||2===r)&&(t.extraData={...t.extraData,sunriseSeat:r})},"parseSeatText",0,t,"seatText",0,function(e,t){return"cross"===t?null:"isolated_2"===t?`${e}#2`:e},"sunriseOrderExtra",0,function(e,t,r,i,s,n){return"unified"!==s&&"isolated"!==s||7!==e||0!==t||n?.sunriseSeat!==void 0||n?.sunriseConversionOrderPda!==void 0||r!==i?n:{...n,sunriseSeat:+("unified"!==s)}},"sunriseSeatExtra",0,function(e){return void 0===e.sunriseSeat?{}:{sunriseSeat:e.sunriseSeat}},"sunriseSeatFromPosition",0,function(e){if(void 0!==e)return({cross:0,isolated:1,isolated_2:2})[t(e).seat]}])},68409,e=>{"use strict";var t=e.i(795974);e.s(["hasSunriseChainPosition",0,function(e,t){return"sunrise"===e.underwriter&&t.some(t=>t.asset===e.asset&&(t.profileIndex??0)===(e.profileIndex??0)&&(t.sunriseMarginSeat??null)===(e.sunriseMarginSeat??null))},"mergeSunrisePositions",0,function(e,r=[],i){return Array.from(new Map(e.map(e=>[e.positionPda,e])).values()).map(e=>{let s=r.find(t=>t.wallet===e.owner&&"sunrise"===t.underwriter&&t.asset===e.asset&&t.side===e.side&&(t.profileIndex??0)===(e.profileIndex??0)&&(t.sunriseMarginSeat??null)===(e.sunriseMarginSeat??null)),n=i?.[e.asset]||parseFloat(s?.markPrice||"0")||e.priceUsd,a=(0,t.calculateUnrealizedPnl)(e.priceUsd,n,e.sizeUsd,"long"===e.side),l=s?.borrowedCollateralUsd!=null?Number(s.borrowedCollateralUsd):null,o=e.sunrisePrimeBound?null!=l&&Number.isFinite(l)&&!e.collateralUnknown?Math.max(0,e.collateralUsd-l):null:void 0;return{positionPda:e.positionPda,wallet:e.owner,asset:e.asset,side:e.side,sizeUsd:e.sizeUsd.toString(),collateralUsd:e.sunrisePrimeBound?o?.toString()??null:e.collateralUnknown?s?.collateralUsd??null:e.collateralUsd.toString(),entryPrice:e.priceUsd.toString(),markPrice:n.toString(),liquidationPrice:e.sunrisePrimeBound?"0":s?.liquidationPrice||"0",unrealizedPnl:a.pnlUsd.toFixed(2),unrealizedPnlPercent:a.pnlPercent.toFixed(2),leverageX:e.sunrisePrimeBound?null!=o&&o>0?(e.sizeUsd/o).toFixed(2):null:e.collateralUnknown?s?.leverageX??null:e.leverageX.toFixed(2),depositedAmount:s?.collateralUsd||null,estimatedFees:s?.totalFeesUsd||null,status:"open",dataSource:s?"merged":"ws",isStale:!1,lastWsUpdate:e.lastWsUpdate,openTime:e.openTime,tpslOrders:[],apiData:s||null,profileIndex:e.profileIndex,underwriter:"sunrise",ownership:e.owner&&null!=e.profileIndex?"imperial":void 0,sunriseMarginSeat:e.sunriseMarginSeat,isSunriseCrossMargin:e.isSunriseCrossMargin}})}])}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.