@liberfi.io/ui-predict 0.1.50 → 0.1.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var react=require('react'),reactQuery=require('@tanstack/react-query'),i18n=require('@liberfi.io/i18n'),ui=require('@liberfi.io/ui'),jsxRuntime=require('react/jsx-runtime'),reactWindow=require('react-window'),reactWindowInfiniteLoader=require('react-window-infinite-loader'),hooks=require('@liberfi.io/hooks'),utils=require('@liberfi.io/utils'),walletConnector=require('@liberfi.io/wallet-connector'),Nt=require('canvas-confetti'),types=require('@liberfi.io/types'),react$1=require('@liberfi.io/react'),recharts=require('recharts');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Nt__default=/*#__PURE__*/_interopDefault(Nt);typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.50");var us="0.1.50";var Oe=react.createContext({});var me=react.createContext(null);function Zt(){let e=react.useContext(Oe);if(!e)throw new Error("usePredictContext must be used within a PredictProvider");return e}function h(){let{client:e}=Zt();return e}function fs(e){return ["predict","events",e??{}]}async function pt(e,t){return await e.getEvents(t)}function Uc(e,t={}){let r=h();return reactQuery.useQuery({queryKey:fs(e),queryFn:async()=>pt(r,e),...t})}function xs(e){return ["predict","events","infinite",e??{}]}function Jt(e={},t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:xs(e),queryFn:async({pageParam:n})=>pt(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.cursor??void 0,...t})}function hs(e){return ["predict","event","byId",e.id,e.withNestedMarkets]}async function vs(e,t){return await e.getEventById(t.id,t.withNestedMarkets)}function ze(e,t={}){let r=h();return reactQuery.useQuery({queryKey:hs(e),queryFn:async()=>vs(r,e),...t})}function Ps(e){return ["predict","markets",e??{}]}async function Cs(e,t){return await e.getMarkets(t)}function zc(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ps(e),queryFn:async()=>Cs(r,e),...t})}function Ts(e){return ["predict","market","byId",e.id]}async function Ms(e,t){return await e.getMarketById(t.id)}function Xc(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ts(e),queryFn:async()=>Ms(r,e),...t})}function Os(e){return ["predict","market","byMint",e]}async function Rs(e,t){return await e.getMarketByMint(t)}function tu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Os(e),queryFn:async()=>Rs(r,e),...t})}function Es(e){return ["predict","markets","batch",e]}async function Is(e,t){return await e.getMarketsBatch(t)}function ou(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Es(e),queryFn:async()=>Is(r,e),enabled:!!(e.tickers?.length||e.mints?.length),...t})}function Qs(e){return ["predict","orderBook",e]}async function Bs(e,t){return await e.getOrderbook(t)}function Re(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Qs(e),queryFn:async()=>Bs(r,e),...t})}function Ls(e){return ["predict","orderBook","byMint",e]}async function Us(e,t){return await e.getOrderbookByMint(t)}function cu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ls(e),queryFn:async()=>Us(r,e),...t})}function As(e){return ["predict","trades",e??{}]}async function Ds(e,t){return await e.getTrades(t)}function rr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:As(e),queryFn:async()=>Ds(r,e),...t})}function Ws(e){return ["predict","trades","byMint",e]}async function _s(e,t){return await e.getTradesByMint(t)}function mu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ws(e),queryFn:async()=>_s(r,e),...t})}function Fs(e){return ["predict","onchainTrades","byWallet",e]}async function yt(e,t){return await e.getOnchainTradesByWallet(t)}function nr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Fs(e),queryFn:async()=>yt(r,e),...t})}function qs(e){return ["predict","onchainTrades","byEvent",e]}async function ft(e,t){return await e.getOnchainTradesByEvent(t)}function xu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:qs(e),queryFn:async()=>ft(r,e),...t})}function Ks(e){return ["predict","onchainTrades","byMarket",e]}async function gt(e,t){return await e.getOnchainTradesByMarket(t)}function bu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ks(e),queryFn:async()=>gt(r,e),...t})}function bt(e){return e.cursor??void 0}function Hs(e){return ["predict","onchainTrades","byWallet","infinite",e]}function Cu(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:Hs(e),queryFn:async({pageParam:n})=>yt(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:bt,...t})}function $s(e){return ["predict","onchainTrades","byEvent","infinite",e]}function Su(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:$s(e),queryFn:async({pageParam:n})=>ft(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:bt,...t})}function Vs(e){return ["predict","onchainTrades","byMarket","infinite",e]}function Tu(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:Vs(e),queryFn:async({pageParam:n})=>gt(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:bt,...t})}function zs(e){return ["predict","candlesticks","event",e]}async function Ys(e,t){let{ticker:r,...n}=t;return await e.getEventCandlesticks(r,n)}function Ru(e,t={}){let r=h();return reactQuery.useQuery({queryKey:zs(e),queryFn:async()=>Ys(r,e),...t})}function vt(e){return ["predict","candlesticks","market",e]}async function kt(e,t){let{ticker:r,...n}=t;return await e.getMarketCandlesticks(r,n)}function Pt(e,t={}){let r=h();return reactQuery.useQuery({queryKey:vt(e),queryFn:async()=>kt(r,e),...t})}function Gs(e){return ["predict","candlesticks","market","byMint",e]}async function js(e,t){let{mintAddress:r,...n}=t;return await e.getMarketCandlesticksByMint(r,n)}function Nu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Gs(e),queryFn:async()=>js(r,e),...t})}var Eu=Pt;function Xs(e){return ["predict","forecast","percentileHistory",e]}async function Zs(e,t){return await e.getEventForecastPercentileHistory(t)}function Lu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Xs(e),queryFn:async()=>Zs(r,e),...t})}function Js(e){return ["predict","forecast","percentileHistory","byMint",e]}async function eo(e,t){return await e.getEventForecastPercentileHistoryByMint(t)}function Uu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Js(e),queryFn:async()=>eo(r,e),...t})}function to(e){return ["predict","liveData",e]}async function ro(e,t){return await e.getLiveData(t)}function _u(e,t={}){let r=h();return reactQuery.useQuery({queryKey:to(e),queryFn:async()=>ro(r,e),enabled:e.milestoneIds.length>0,...t})}function no(e){return ["predict","liveData","byEvent",e]}async function so(e,t){return await e.getLiveDataByEvent(t)}function Fu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:no(e),queryFn:async()=>so(r,e),enabled:!!e.eventTicker,...t})}function oo(e){return ["predict","liveData","byMint",e]}async function ao(e,t){return await e.getLiveDataByMint(t)}function qu(e,t={}){let r=h();return reactQuery.useQuery({queryKey:oo(e),queryFn:async()=>ao(r,e),enabled:!!e.mintAddress,...t})}function io(e){return ["predict","series",e??{}]}async function lo(e,t){return await e.getSeries(t)}function ar(e,t={}){let r=h();return reactQuery.useQuery({queryKey:io(e),queryFn:async()=>lo(r,e),...t})}function co(e){return ["predict","series","byTicker",e]}async function uo(e,t){return await e.getSeriesByTicker(t)}function ir(e,t={}){let r=h();return reactQuery.useQuery({queryKey:co(e),queryFn:async()=>uo(r,e),...t})}function po(){return ["predict","tags","byCategories"]}async function mo(e){return await e.getTagsByCategories()}function St(e={}){let t=h();return reactQuery.useQuery({queryKey:po(),queryFn:async()=>mo(t),...e})}function yo(){return ["predict","filters","bySports"]}async function fo(e){return await e.getFiltersBySports()}function Gu(e={}){let t=h();return reactQuery.useQuery({queryKey:yo(),queryFn:async()=>fo(t),...e})}var ju=St;function xo(e){return ["predict","search",e]}async function bo(e,t){return await e.search(t)}function ed(e,t={}){let r=h();return reactQuery.useQuery({queryKey:xo(e),queryFn:async()=>bo(r,e),...t})}function vo(e){return ["predict","positions","byWallet",e]}async function ko(e,t){return await e.getPositionsByWallet(t)}function cr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:vo(e),queryFn:async()=>ko(r,e),...t})}function id(){let e=react.useContext(me);if(!e)throw new Error("useUserPredictContext must be used within a UserPredictProvider");return e}function ur(e){let t=react.useContext(me);return react.useMemo(()=>t?{positions:t.positions.filter(n=>n.market?.ticker===e.ticker),isLoading:t.isLoading,isAvailable:true}:{positions:[],isLoading:false,isAvailable:false},[t,e.ticker])}function wo(e){return ["predict","outcomeMints",e??{}]}async function Oo(e,t){return await e.getOutcomeMints(t)}function yd(e,t={}){let r=h();return reactQuery.useQuery({queryKey:wo(e),queryFn:async()=>Oo(r,e),...t})}async function Ro(e,t){return await e.filterOutcomeMints(t)}function fd(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>Ro(t,r),...e})}function Eo(e){return ["predict","quote",e]}async function Io(e,t){return await e.getQuote(t)}function hd(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Eo(e),queryFn:async()=>Io(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Qo(e,t){return await e.createSwap(t)}function Cd(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>Qo(t,r),...e})}async function Bo(e,t){return await e.createSwapInstructions(t)}function Sd(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>Bo(t,r),...e})}function Lo(e){return ["predict","order",e]}async function Uo(e,t){return await e.getOrder(t)}function mr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Lo(e),queryFn:async()=>Uo(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}function Ao(e){return ["predict","order","status",e.signature]}async function Do(e,t){return await e.getOrderStatus(t)}function yr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ao(e),queryFn:async()=>Do(r,e),enabled:!!e.signature,refetchInterval:t.refetchInterval??3e3,retry:false,...t})}function Fo(e){return ["predict","intent","quote",e]}async function qo(e,t){return await e.getIntentQuote(t)}function Ed(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Fo(e),queryFn:async()=>qo(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Ko(e,t){return await e.submitIntentSwap(t)}function Id(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>Ko(t,r),...e})}async function $o(e,t){return await e.initPredictionMarket(t)}function Ud(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>$o(t,r),...e})}function Vo(){return ["predict","tokens"]}async function zo(e){return await e.getTokens()}function _d(e={}){let t=h();return reactQuery.useQuery({queryKey:Vo(),queryFn:async()=>zo(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Yo(){return ["predict","tokens","decimals"]}async function Go(e){return await e.getTokensWithDecimals()}function Fd(e={}){let t=h();return reactQuery.useQuery({queryKey:Yo(),queryFn:async()=>Go(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Xo(){return ["predict","venues"]}async function Zo(e){return await e.getVenues()}function $d(e={}){let t=h();return reactQuery.useQuery({queryKey:Xo(),queryFn:async()=>Zo(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}var Le=class{ws=null;wsUrl;autoReconnect;reconnectIntervalBase;reconnectMaxInterval;pingInterval;status="disconnected";reconnectAttempts=0;reconnectTimeout=null;pingIntervalId=null;shouldReconnect=true;listeners={connect:[],disconnect:[],reconnecting:[],error:[],price:[],trade:[],orderbook:[],status:[],subscribed:[],unsubscribed:[]};subscriptions={prices:{all:false,tickers:new Set},trades:{all:false,tickers:new Set},orderbook:{all:false,tickers:new Set}};constructor(t){this.wsUrl=t.wsUrl,this.autoReconnect=t.autoReconnect??true,this.reconnectIntervalBase=t.reconnectIntervalBase??1e3,this.reconnectMaxInterval=t.reconnectMaxInterval??3e4,this.pingInterval=t.pingInterval??3e4,t.autoConnect!==false&&this.connect();}connect(){if(!(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))){this.shouldReconnect=true,this.setStatus("connecting");try{this.ws=new WebSocket(this.wsUrl),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus("connected"),this.emit("connect",void 0),this.restoreSubscriptions(),this.startPingInterval();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onerror=t=>{let r=new Error("WebSocket error");this.emit("error",r);},this.ws.onclose=t=>{this.stopPingInterval(),this.setStatus("disconnected"),this.emit("disconnect",{code:t.code,reason:t.reason}),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();};}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();}}}disconnect(){this.shouldReconnect=false,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus("disconnected");}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getStatus(){return this.status}subscribePrices(t,r){this.subscribeChannel("prices",t);let n=this.on("price",r);return ()=>{n(),this.unsubscribeChannel("prices",t);}}subscribeTrades(t,r){this.subscribeChannel("trades",t);let n=this.on("trade",r);return ()=>{n(),this.unsubscribeChannel("trades",t);}}subscribeOrderbook(t,r){this.subscribeChannel("orderbook",t);let n=this.on("orderbook",r);return ()=>{n(),this.unsubscribeChannel("orderbook",t);}}onStatusChange(t){return this.on("status",t)}on(t,r){return this.listeners[t].push(r),()=>{this.off(t,r);}}off(t,r){let n=this.listeners[t],s=n.indexOf(r);s!==-1&&n.splice(s,1);}removeAllListeners(t){if(t)this.listeners[t].length=0;else for(let r of Object.keys(this.listeners))this.listeners[r].length=0;}subscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=true,n.tickers.clear();else if(r.tickers&&r.tickers.length>0){n.all=false;for(let s of r.tickers)n.tickers.add(s);}this.sendSubscription("subscribe",t,r);}unsubscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=false,n.tickers.clear();else if(r.tickers&&r.tickers.length>0)for(let s of r.tickers)n.tickers.delete(s);this.sendSubscription("unsubscribe",t,r);}setStatus(t){this.status!==t&&(this.status=t,this.emit("status",t));}emit(t,r){let n=this.listeners[t];for(let s of n)try{s(r);}catch{}}send(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return false;try{return this.ws.send(JSON.stringify(t)),!0}catch{return false}}sendSubscription(t,r,n){this.send({type:t,channel:r,all:n.all,tickers:n.tickers});}handleMessage(t){try{let r=JSON.parse(t);switch(r.type){case "ticker":this.emit("price",r);break;case "trade":this.emit("trade",r);break;case "orderbook":this.emit("orderbook",r);break;case "status":break;case "subscribed":this.emit("subscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "unsubscribed":this.emit("unsubscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "pong":break;case "error":this.emit("error",new Error(r.message));break;default:if("channel"in r){let n=r;switch(n.channel){case "prices":this.emit("price",n);break;case "trades":this.emit("trade",n);break;case "orderbook":this.emit("orderbook",n);break}}}}catch{}}scheduleReconnect(){if(this.reconnectTimeout)return;let t=Math.min(this.reconnectIntervalBase*Math.pow(2,this.reconnectAttempts),this.reconnectMaxInterval);this.setStatus("reconnecting"),this.emit("reconnecting",{attempt:this.reconnectAttempts+1,delay:t}),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts++,this.connect();},t);}restoreSubscriptions(){for(let t of ["prices","trades","orderbook"]){let r=this.subscriptions[t];r.all?this.sendSubscription("subscribe",t,{all:true}):r.tickers.size>0&&this.sendSubscription("subscribe",t,{tickers:Array.from(r.tickers)});}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.send({type:"ping"});},this.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}};function Ye(e){return new Le(e)}function Xd({wsEndpoint:e,autoConnect:t=true,autoReconnect:r=true,enabled:n=true}){let[s,a]=react.useState("disconnected"),[o,l]=react.useState(null),i=react.useRef(null);react.useEffect(()=>{if(!n){i.current&&(i.current.disconnect(),i.current=null),a("disconnected");return}let p=Ye({wsUrl:e,autoConnect:t,autoReconnect:r});i.current=p;let f=p.on("status",b=>{a(b);}),m=p.on("error",b=>{l(b);}),y=p.on("connect",()=>{l(null);});return ()=>{f(),m(),y(),p.disconnect(),i.current=null;}},[e,t,r,n]);let c=react.useCallback(()=>{i.current?.connect();},[]),d=react.useCallback(()=>{i.current?.disconnect();},[]);return {client:i.current,status:s,isConnected:s==="connected",connect:c,disconnect:d,error:o}}function tp(){let e=react.useContext(Oe);if(!e)throw new Error("useWsClient must be used within a PredictProvider");let{wsClient:t}=e,[r,n]=react.useState(t?.getStatus()??"disconnected");return react.useEffect(()=>{if(!t){n("disconnected");return}return n(t.getStatus()),t.onStatusChange(n)},[t]),{wsClient:t,wsStatus:r,isWsConnected:r==="connected"}}function sp({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=react.useState(new Map),[l,i]=react.useState(false),c=react.useRef(s);return react.useEffect(()=>{c.current=s;},[s]),react.useEffect(()=>{if(!e||!n){i(false);return}if(!t&&r.length===0)return;let d=t?{all:true}:{tickers:r},u=e.subscribePrices(d,p=>{o(f=>{let m=new Map(f);return m.set(p.market_ticker,{yesBid:p.yes_bid,yesAsk:p.yes_ask,noBid:p.no_bid,noAsk:p.no_ask,updatedAt:Date.now()}),m}),c.current?.(p);});return i(true),()=>{u(),i(false);}},[e,t,r.join(","),n]),{prices:a,isSubscribed:l}}function ip({client:e,all:t=false,tickers:r=[],enabled:n=true,maxHistory:s=100,onUpdate:a}){let[o,l]=react.useState([]),[i,c]=react.useState(false),d=react.useRef(a);react.useEffect(()=>{d.current=a;},[a]),react.useEffect(()=>{if(!e||!n){c(false);return}if(!t&&r.length===0)return;let p=t?{all:true}:{tickers:r},f=e.subscribeTrades(p,m=>{let y={tradeId:m.trade_id,marketTicker:m.market_ticker,price:m.price,count:m.count,yesPrice:m.yes_price,noPrice:m.no_price,takerSide:m.taker_side,createdTime:m.created_time};l(b=>{let x=[y,...b];return x.length>s?x.slice(0,s):x}),d.current?.(m);});return c(true),()=>{f(),c(false);}},[e,t,r.join(","),n,s]);let u=react.useCallback(()=>{l([]);},[]);return {trades:o,isSubscribed:i,clearHistory:u}}function up({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=react.useState(new Map),[l,i]=react.useState(false),c=react.useRef(s);react.useEffect(()=>{c.current=s;},[s]),react.useEffect(()=>{if(!e||!n){i(false);return}if(!t&&r.length===0)return;let u=t?{all:true}:{tickers:r},p=e.subscribeOrderbook(u,f=>{o(m=>{let y=new Map(m);return y.set(f.market_ticker,{yesBids:f.yes_bids,yesAsks:f.yes_asks,noBids:f.no_bids,noAsks:f.no_asks,updatedAt:Date.now()}),y}),c.current?.(f);});return i(true),()=>{p(),i(false);}},[e,t,r.join(","),n]);let d=react.useCallback(u=>a.get(u),[a]);return {orderbooks:a,isSubscribed:l,getOrderbook:d}}var Sr=["Politics","Sports","Culture","Crypto","Climate","Economics","Mentions","Companies","Financials","Tech & Science"];function Tr(){let{data:e,isLoading:t,isError:r,error:n}=St();return {data:react.useMemo(()=>{if(!e?.tagsByCategories)return [];let a=o=>{let l=Sr.indexOf(o);return l===-1?Sr.length:l};return Object.entries(e.tagsByCategories).map(([o,l])=>({category:o,tags:l})).sort((o,l)=>a(o.category)-a(l.category))},[e]),isLoading:t,isError:r,error:n??null}}function Or({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:s,onTagSelect:a,className:o}){let{t:l}=i18n.useTranslation(),i=react.useCallback(()=>{s(null);},[s]);return jsxRuntime.jsxs("div",{className:ui.cn("flex w-full flex-col gap-2",o),children:[jsxRuntime.jsx(ui.HorizontalScrollContainer,{children:jsxRuntime.jsxs("div",{className:"flex items-center gap-2 px-0.5 py-1",children:[jsxRuntime.jsx(Ge,{label:l("predict.categories.trending"),isSelected:t===null,onPress:i}),e.map(c=>jsxRuntime.jsx(Ge,{label:c.category,isSelected:t===c.category,onPress:()=>s(c.category)},c.category))]})}),t&&n.length>0&&jsxRuntime.jsx(ui.HorizontalScrollContainer,{children:jsxRuntime.jsxs("div",{className:"flex items-center gap-2 px-0.5 py-1",children:[jsxRuntime.jsx(Ge,{label:l("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>a(null),variant:"secondary"}),n.map(c=>jsxRuntime.jsx(Ge,{label:c,isSelected:r===c,onPress:()=>a(c),variant:"secondary"},c))]})})]})}function Ge({label:e,isSelected:t,onPress:r,variant:n="primary"}){return jsxRuntime.jsx("button",{type:"button",onClick:r,className:ui.cn("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition-colors duration-150 cursor-pointer","border whitespace-nowrap",n==="primary"?t?"bg-foreground text-background border-foreground":"bg-content1 text-foreground/70 border-default-200 hover:bg-default-100 hover:text-foreground":t?"bg-primary/15 text-primary border-primary/40":"bg-content1 text-foreground/50 border-default-100 hover:bg-default-50 hover:text-foreground/70"),children:e})}function Rr({count:e=6}){return jsxRuntime.jsx("div",{className:"flex items-center gap-2 px-0.5 py-1",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(ui.Skeleton,{className:"h-8 shrink-0 rounded-full",style:{width:`${60+Math.random()*40}px`}},r))})}function Qr({onSelect:e,className:t}){let{data:r,isLoading:n}=Tr(),[s,a]=react.useState(null),[o,l]=react.useState(null),i=react.useCallback(u=>{if(a(u),l(null),!u)e?.({category:null,tags:null});else {let p=r.find(f=>f.category===u);e?.({category:u,tags:p?.tags??null});}},[r,e]),c=react.useCallback(u=>{if(l(u),u)e?.({category:s,tags:[u]});else {let p=r.find(f=>f.category===s);e?.({category:s,tags:p?.tags??null});}},[r,s,e]);if(n)return jsxRuntime.jsx(Rr,{});let d=r.find(u=>u.category===s)?.tags??[];return jsxRuntime.jsx(Or,{categories:r,selectedCategory:s,selectedTag:o,activeTags:d,onCategorySelect:i,onTagSelect:c,className:t})}var Pe=48,ye=4,je={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},T={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},fe=T.ALL,Xe={[T.ONE_DAY]:je.ONE_MINUTE,[T.ONE_WEEK]:je.ONE_HOUR,[T.ONE_MONTH]:je.ONE_HOUR,[T.ALL]:je.ONE_DAY},Ze={[T.ONE_DAY]:300,[T.ONE_WEEK]:3600,[T.ONE_MONTH]:10800,[T.ALL]:1440*60},Je={[T.ONE_DAY]:1440*60,[T.ONE_WEEK]:10080*60,[T.ONE_MONTH]:720*60*60,[T.ALL]:null},Mt=1,im=1,lm=1,cm=99,Ne={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},um=Ne.ONE_WEEK,dm={[Ne.ONE_HOUR]:60,[Ne.SIX_HOURS]:60,[Ne.ONE_DAY]:300,[Ne.ONE_WEEK]:1800,[Ne.MAX]:1800};function Br(e={}){let{category:t,tags:r,...n}=e,s=!!t||!!r&&r.length>0,{data:a,isFetching:o,isError:l,error:i}=ar({...t?{category:t}:{},...r&&r.length>0?{tags:r.join(",")}:{},isInitialized:true,status:"active"},{enabled:s}),c=react.useMemo(()=>{if(!s||!a?.series)return;let N=a.series.map(P=>P.ticker).slice(0,25);return N.length>0?N.join(","):void 0},[s,a]),d=react.useMemo(()=>({status:"active",withNestedMarkets:true,sort:"volume24h",order:"desc",limit:48,...n,...c!==void 0?{seriesTickers:c}:{}}),[n,c]),{data:u,isLoading:p,isFetching:f,isFetchingNextPage:m,isError:y,error:b,hasNextPage:x,fetchNextPage:v,refetch:k}=Jt(d),g=react.useMemo(()=>u?.pages.flatMap(N=>N.events)??[],[u]),C=s&&!a&&!l;return {data:g,isLoading:C||p,isFetching:o||C||f&&!m,isFetchingMore:m,isError:l||y,error:i??b,hasMore:x,fetchMore:v,refetch:k}}function ma({className:e}){return jsxRuntime.jsxs("div",{className:`flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 @5xl:gap-y-3 @5xl:p-4 ${e??""}`,children:[jsxRuntime.jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-8 flex-shrink-0 rounded-lg @5xl:h-12 @5xl:w-12"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-md @5xl:h-12"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-12 flex-shrink-0 rounded-lg @5xl:h-10 @5xl:w-14"})]}),jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-0.5 @5xl:gap-y-1",children:[jsxRuntime.jsxs("div",{className:"flex min-h-8 w-full items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-2/3 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-8 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-16 rounded-lg"})]})]}),jsxRuntime.jsxs("div",{className:"flex min-h-8 w-full items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-1/2 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-8 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-16 rounded-lg"})]})]})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-16 rounded-md @5xl:h-4"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded-md @5xl:h-4"})]})]})}function Lr({count:e=8}){return jsxRuntime.jsx("div",{className:"@container w-full h-full",children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 gap-4 @[640px]:grid-cols-2 @[1024px]:grid-cols-3 @[1280px]:grid-cols-4",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(ma,{className:"min-h-44 @5xl:min-h-56"},r))})})}function Ur({value:e,showLabel:t=true}){let r=e/100;return jsxRuntime.jsx("div",{className:"flex-shrink-0 flex flex-col items-center",children:jsxRuntime.jsxs("div",{className:"relative w-16 h-12 lg:w-20 lg:h-14",children:[jsxRuntime.jsxs("svg",{className:"w-full h-full",viewBox:"0 0 100 70",children:[jsxRuntime.jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-default-200",strokeWidth:"6",strokeLinecap:"round"}),jsxRuntime.jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-primary",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:`${r*125.6} 125.6`,style:{transition:"stroke-dasharray 0.5s ease-in-out"}})]}),t&&jsxRuntime.jsx("div",{className:"absolute inset-0 flex items-center justify-center pt-3 lg:pt-4",children:jsxRuntime.jsxs("span",{className:"text-sm font-bold text-foreground lg:text-base leading-none",children:[e.toFixed(0),"%"]})})]})})}function Wr({event:e,onSelect:t,onSelectOutcome:r}){let{t:n}=i18n.useTranslation(),[s,a]=react.useState(null),o=e.markets||[],l=o.length>2?[...o].sort((P,Q)=>Number(Q.yesAsk??0)-Number(P.yesAsk??0)):o,i=l.filter(P=>P.status==="active"),c=l.length===1,d=c?l[0]:s,u=react.useMemo(()=>utils.formatAmountUSDCompact((e.volume??0)/100),[e.volume]),p=P=>P.yesAsk?parseFloat(P.yesAsk)*100:null,f=P=>P.noAsk?parseFloat(P.noAsk)*100:null,m=P=>{let Q=p(P),U=f(P);return Q!=null?U==null&&Q<=1?"< 1%":b(Q):U!=null?U<=1?"> 99%":b(100-U):"0%"},y=P=>{let Q=p(P),U=f(P);return U!=null?Q==null&&U<=1?"< 1%":b(U):Q!=null?Q<=1?"> 99%":b(100-Q):"0%"},b=P=>P!=null?`${P.toFixed(0)}%`:"--",x=react.useMemo(()=>{let P=l.some(U=>U.status==="active");return l.every(U=>U.status==="closed"||U.status==="determined")?{label:n("predict.event.status.closed"),color:"bg-danger-100/50 text-danger"}:P?{label:n("predict.event.status.live"),color:"bg-primary-100/50 text-primary"}:{label:n("predict.event.status.pending"),color:"bg-warning-100/50 text-warning"}},[l,n]),v=P=>{a(P);},k=()=>{a(null);},g=()=>{d&&r&&r(e,d,"yes");},C=()=>{d&&r&&r(e,d,"no");},M=()=>{t&&t(e);},R=i.slice(0,2),N=i.length>2;return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 transition-all duration-300 cursor-pointer hover:border-primary hover:ring-2 hover:ring-primary/20 focus-within:border-primary focus-within:bg-content2 focus-within:ring-2 focus-within:ring-primary/20 @5xl:gap-y-3 @5xl:p-4",onClick:M,children:[jsxRuntime.jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntime.jsx(ui.Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"md",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover:scale-110 @5xl:h-12 @5xl:w-12"}),jsxRuntime.jsx(ui.StyledTooltip,{content:e.title,placement:"bottom",children:jsxRuntime.jsx("p",{className:"flex-1 min-w-0 h-10 @5xl:h-12 text-sm font-semibold @5xl:text-base line-clamp-2",children:e.title})}),c?jsxRuntime.jsx(Ur,{value:p(l[0])??50}):x.label!==n("predict.event.status.live")&&jsxRuntime.jsx("div",{className:`flex-shrink-0 flex items-center gap-x-2 rounded-lg px-2 py-1 text-sm @5xl:px-4 @5xl:py-2 ${x.color}`,children:jsxRuntime.jsx("span",{children:x.label})})]}),d&&!c&&jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:P=>{P.stopPropagation(),k();},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:d.yesSubTitle}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-sm font-semibold text-foreground @5xl:text-lg",children:m(d)}),jsxRuntime.jsx(ui.ChevronUpIcon,{className:"w-3 h-3 text-default-500 @5xl:w-4 @5xl:h-4"})]})]}),!d&&!c&&R.length>0&&jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-0.5 text-xs @5xl:gap-y-1 @5xl:text-sm",children:[R.map(P=>jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:Q=>{Q.stopPropagation(),v(P);},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:P.yesSubTitle}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-xs text-foreground @5xl:text-base",children:m(P)}),jsxRuntime.jsxs("div",{className:"flex h-full items-center gap-x-3 rounded-lg p-1 @5xl:p-1.5 bg-gradient-to-r from-primary-50/20 via-primary-50/20 to-secondary-50/20",children:[jsxRuntime.jsx("span",{className:"text-primary",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"text-default-400",children:"/"}),jsxRuntime.jsx("span",{className:"text-secondary",children:n("predict.market.no")})]})]})]},P.ticker)),N&&jsxRuntime.jsx("span",{className:"text-xxs text-default-500 @5xl:text-xs",children:n("predict.event.moreMarkets",{count:i.length-2})})]}),d&&jsxRuntime.jsxs("div",{className:`flex items-center gap-x-2 text-sm @5xl:text-base ${c?"mt-3":""}`,children:[jsxRuntime.jsxs(ui.Button,{color:"primary",fullWidth:true,className:"group/yes bg-primary-100 text-primary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:g,children:[jsxRuntime.jsx("span",{className:"group-hover/yes:hidden",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"hidden group-hover/yes:inline",children:m(d)})]}),jsxRuntime.jsxs(ui.Button,{color:"secondary",fullWidth:true,className:"group/no bg-secondary-100 text-secondary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:C,children:[jsxRuntime.jsx("span",{className:"group-hover/no:hidden",children:n("predict.market.no")}),jsxRuntime.jsx("span",{className:"hidden group-hover/no:inline",children:y(d)})]})]})]}),!d||c?jsxRuntime.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:P=>{P.stopPropagation(),M();},children:[jsxRuntime.jsx("span",{children:n("predict.event.showMore")}),jsxRuntime.jsx(ui.ChevronRightIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"})]}),jsxRuntime.jsxs("span",{className:"text-xxs text-default-600 @5xl:text-xs",children:[u," ",n("predict.event.volume")]})]}):jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:P=>{P.stopPropagation(),k();},children:[jsxRuntime.jsx(ui.ChevronLeftIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"}),jsxRuntime.jsx("span",{children:n("predict.event.back")})]})]})}var wa=640,Oa=768,Fr=1024,Ra=1280,Na=16,Ea=192,Ia=228,Qa=244;function Ba(e){return e>=Ra?4:e>=Fr?3:e>=wa?2:1}function La(e){return e>=Fr?Qa:e>=Oa?Ia:Ea}function qr({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s}){let a=react.useRef(null),{width:o=0,height:l=0}=hooks.useResizeObserver({ref:a}),i=Ba(o),c=La(o),d=Math.ceil(e.length/i)||0,u=t?d+1:d,p=react.useCallback(y=>y<d,[d]),f=react.useCallback(async()=>{r?.();},[r]),m=reactWindowInfiniteLoader.useInfiniteLoader({isRowLoaded:p,loadMoreRows:f,rowCount:u,threshold:3});return jsxRuntime.jsx("div",{ref:a,className:"@container w-full h-full",children:l>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:l},onRowsRendered:m,rowComponent:Ua,rowCount:u,rowHeight:c,rowProps:{events:e,columnCount:i,dataRowCount:d,gap:Na,onSelect:n,onSelectOutcome:s}})})}function Ua({index:e,style:t,events:r,columnCount:n,dataRowCount:s,gap:a,onSelect:o,onSelectOutcome:l}){if(e>=s)return jsxRuntime.jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsxRuntime.jsx(ui.Spinner,{size:"sm"})});let i=e*n,c=r.slice(i,i+n),d=n-c.length,u={display:"flex",gap:a,height:`calc(100% - ${a}px)`};return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:u,children:[c.map(p=>jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsx(Wr,{event:p,onSelect:o,onSelectOutcome:l})},p.ticker)),d>0&&Array.from({length:d}).map((p,f)=>jsxRuntime.jsx("div",{style:{flex:1,minWidth:0}},`spacer-${f}`))]})})}function Hr({onSelect:e,onSelectOutcome:t,...r}){let{data:n,hasMore:s,fetchMore:a,isFetching:o}=Br({limit:48,...r});return o?jsxRuntime.jsx(Lr,{count:48}):jsxRuntime.jsx(qr,{events:n,hasMore:s,onFetchMore:a,onSelect:e,onSelectOutcome:t})}function Vm({onSelect:e,onSelectOutcome:t}){let[r,n]=react.useState({category:null,tags:null}),s=react.useCallback(a=>{n(a);},[]);return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsxRuntime.jsx(Qr,{onSelect:s}),jsxRuntime.jsx("div",{className:"min-h-0 flex-1",children:jsxRuntime.jsx(Hr,{category:r.category,tags:r.tags,onSelect:e,onSelectOutcome:t})})]})}function It(e,t,r){let n=e[t];return n?r==="yes"?n.yesMint:n.noMint:null}var Ue=utils.SOLANA_TOKENS.stablecoins.USDC.address;function za(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Nt__default.default({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Nt__default.default({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Nt__default.default({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function Vr({market:e,chain:t="solana",initialOutcome:r="yes",initialSide:n="buy"}){let{t:s}=i18n.useTranslation(),a=react.useContext(me),{status:o}=walletConnector.useAuth(),i=walletConnector.useWallets().find(S=>S.chainNamespace===types.ChainNamespace.SOLANA&&S.isConnected),c=o==="authenticated",d=i?.address,[u,p]=react.useState(r),[f,m]=react.useState(n),[y,b]=react.useState(NaN),x=react.useMemo(()=>It(e.accounts,Ue,u),[e.accounts,u]),{inputMint:v,outputMint:k}=react.useMemo(()=>f==="buy"?{inputMint:Ue,outputMint:x}:{inputMint:x,outputMint:Ue},[f,x]),g=!!v&&!!k&&y>0,C=react.useMemo(()=>Number(u==="yes"?e.yesAsk??.5:e.noAsk??.5),[u,e.yesAsk,e.noAsk]),M=react.useMemo(()=>isNaN(y)||y<=0?0:f==="buy"?C>0?y/C:0:y,[f,y,C]),R=react.useMemo(()=>isNaN(y)||y<=0?0:Math.round(y*1e6),[y]),{data:N,isLoading:P,error:Q,refetch:U}=mr({userPublicKey:d??void 0,inputMint:v??"",outputMint:k??"",amount:R,slippageBps:100},{enabled:g}),ke=a?.usdcBalance??null,pe=a?.isLoading??false,Gt=a?.refetch,oe=a?.positions,qe=react.useMemo(()=>{if(!oe||!x)return null;let S=oe.find(te=>te.mint===x);return S?S.balance:0},[oe,x]),lt=react.useMemo(()=>It(e.accounts,Ue,"yes"),[e.accounts]),ct=react.useMemo(()=>It(e.accounts,Ue,"no"),[e.accounts]),Zn=react.useMemo(()=>{if(!oe||!lt)return null;let S=oe.find(te=>te.mint===lt);return S?S.balance:0},[oe,lt]),Jn=react.useMemo(()=>{if(!oe||!ct)return null;let S=oe.find(te=>te.mint===ct);return S?S.balance:0},[oe,ct]),{data:Me}=Re(e.ticker,{refetchInterval:5e3}),es=react.useMemo(()=>(u==="yes"?Me?.yesBids:Me?.noBids)?.[0]?.price??null,[Me,u]),ts=react.useMemo(()=>(u==="yes"?Me?.yesAsks:Me?.noAsks)?.[0]?.price??null,[Me,u]),rs=react.useMemo(()=>N?.priceImpactPct?parseFloat(N.priceImpactPct):null,[N]),Ke=react.useMemo(()=>{if(isNaN(y)||y<=0)return 0;if(N)return parseInt(N.inAmount)/1e6;if(f==="buy")return y;let S=Number(u==="yes"?e.yesBid??0:e.noBid??0);return y*S},[N,f,u,y,e.yesBid,e.noBid]),jt=react.useMemo(()=>isNaN(y)||y<=0?0:f==="buy"?M*1:Ke,[f,M,Ke,y]),ns=jt-Ke,ss=react.useCallback(S=>{m(S),b(NaN);},[]),os=react.useCallback(S=>{if(isNaN(S)){b(NaN);return}let te=Math.max(0,S),Ve=f==="buy"?Math.round(te*100)/100:Math.round(te);b(Ve);},[f]);react.useEffect(()=>{g&&U();},[y,u,f,g,U]);let ut=react.useMemo(()=>{let S=[];return (isNaN(y)||y<Mt)&&S.push(`Minimum quantity is ${Mt}`),e.status!=="active"&&S.push("Market is not active"),f==="buy"&&ke!=null&&!isNaN(y)&&y>0&&y>ke&&S.push("Insufficient USDC balance"),f==="sell"&&qe!=null&&!isNaN(y)&&y>0&&y>qe&&S.push("Insufficient shares"),{isValid:S.length===0,errors:S}},[y,e.status,f,ke,qe]),[as,dt]=react.useState(null),[is,we]=react.useState(false),[He,Be]=react.useState(null),{data:$e}=yr({signature:He??""},{enabled:!!He});react.useEffect(()=>{if(!$e||!He)return;let{status:S}=$e;S==="closed"?(we(false),Be(null),ui.toast.success(s("predict.trade.submitSuccess")),za(),b(NaN),Gt?.()):(S==="failed"||S==="expired")&&(we(false),Be(null),ui.toast.error(s("predict.trade.submitError")));},[$e,He,Gt,s]);let ls=react.useCallback(async()=>{if(!(!ut.isValid||!c||!d||!i||pe)){dt(null),Be(null),we(true);try{let S=N;if(S?.transaction||(S=(await U()).data),!S?.transaction){we(!1);return}let te=Uint8Array.from(atob(S.transaction),Xt=>Xt.charCodeAt(0)),Ve=await i.sendTransaction(te);dt(Ve),Be(Ve);}catch{ui.toast.error(s("predict.trade.submitError")),we(false);}}},[ut.isValid,c,d,i,N,pe,U,s]),cs=react.useCallback(()=>{p(r),m(n),b(NaN),dt(null),Be(null),we(false);},[r,n]);return {outcome:u,side:f,quantity:y,shares:M,estimatedCost:Ke,potentialPayout:jt,potentialProfit:ns,isAuthenticated:c,bestBid:es,bestAsk:ts,order:N??null,priceImpact:rs,usdcBalance:ke,outcomeTokenBalance:qe,yesTokenBalance:Zn,noTokenBalance:Jn,isBalanceLoading:pe,isQuoteLoading:P,isSubmitting:is,quoteError:Q??null,txHash:as,orderStatus:$e??null,validation:ut,setOutcome:p,setSide:ss,setQuantity:os,submit:ls,reset:cs}}var Ja=`https://s1.chainstream.io/chains/sol/tokens/${utils.SOLANA_TOKENS.stablecoins.USDC.address}/image.png`;function jr({event:e,market:t,outcome:r,side:n,quantity:s,potentialProfit:a,estimatedCost:o,usdcBalance:l,yesTokenBalance:i,noTokenBalance:c,isBalanceLoading:d,isSubmitting:u,isValid:p,onOutcomeChange:f,onSideChange:m,onQuantityChange:y,onSubmit:b}){let{t:x}=i18n.useTranslation(),v=react.useMemo(()=>{if(u)return x("predict.trade.submitting");let g=x(n==="buy"?"predict.trade.buy":"predict.trade.sell"),C=x(r==="yes"?"predict.trade.yes":"predict.trade.no");return `${g} ${C}`},[u,n,r,x]),k=react.useMemo(()=>r==="yes"?"primary":"secondary",[r]);return jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4",children:[e&&jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsxRuntime.jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxRuntime.jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsxRuntime.jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxRuntime.jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxRuntime.jsxs("span",{className:r==="yes"?"text-bullish":"text-bearish",children:[x(n==="buy"?"predict.trade.buy":"predict.trade.sell")," ",x(r==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxRuntime.jsxs("span",{className:"text-foreground",children:[" \xB7 ",r==="yes"?t.yesSubTitle:t.noSubTitle]})]})]})]}),jsxRuntime.jsxs(ui.Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:g=>m(g),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsxRuntime.jsx(ui.Tab,{title:x("predict.trade.buy")},"buy"),jsxRuntime.jsx(ui.Tab,{title:x("predict.trade.sell")},"sell")]}),jsxRuntime.jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(g=>{let C=g==="yes"?i:c;return jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col gap-y-1",children:[jsxRuntime.jsxs("button",{type:"button",onClick:()=>f(g),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${r===g?g==="yes"?"border-primary bg-primary-50 text-primary":"border-secondary bg-secondary-50 text-secondary":"border-default-400 text-foreground hover:border-default-500"}`,children:[jsxRuntime.jsx("span",{children:x(g==="yes"?"predict.trade.yes":"predict.trade.no")}),(()=>{let M=n==="buy"?g==="yes"?t.yesAsk:t.noAsk:g==="yes"?t.yesBid:t.noBid;return M!=null?jsxRuntime.jsxs("span",{className:"ml-1 opacity-70",children:[Math.round(Number(M)*100),"\xA2"]}):null})()]}),n==="sell"&&r===g&&jsxRuntime.jsx("span",{className:"text-center text-xs text-foreground",children:d?"\u2013":`${C??0} shares`})]},g)})}),n==="buy"&&jsxRuntime.jsxs("div",{className:"flex items-center justify-end gap-x-1 text-xs text-default-500",children:[jsxRuntime.jsx("img",{src:Ja,alt:"USDC",className:"h-4 w-4 rounded-full object-cover"}),jsxRuntime.jsxs("span",{children:[x("predict.trade.balance"),":"]}),jsxRuntime.jsx("span",{className:"font-medium text-foreground",children:l!=null?`$${l.toFixed(2)}`:"\u2013"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:x(n==="buy"?"predict.trade.amount":"predict.trade.contracts")}),jsxRuntime.jsx(ui.StyledNumberInput,{fullWidth:true,placeholder:"0",radius:"lg",size:"lg",value:isNaN(s)?void 0:s,onValueChange:g=>{y(g);},minValue:0,step:n==="buy"?.01:1,formatOptions:n==="buy"?{maximumFractionDigits:2}:{maximumFractionDigits:0},startContent:n==="buy"?jsxRuntime.jsx("span",{className:"text-default-600 text-xl",children:"$"}):void 0,classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}},n),jsxRuntime.jsx("div",{className:"flex gap-x-2 justify-end",children:n==="buy"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[[1,5,10,100].map(g=>jsxRuntime.jsxs("button",{type:"button",onClick:()=>y(Math.round(((isNaN(s)?0:s)+g)*100)/100),className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:["+",g,"$"]},g)),jsxRuntime.jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:x("common.all")})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[[25,50].map(g=>jsxRuntime.jsxs("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:[g,"%"]},g)),jsxRuntime.jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:x("common.all")})]})})]}),!isNaN(s)&&s>0&&jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-y-0.5",children:[jsxRuntime.jsx("span",{className:"text-sm text-foreground",children:x(n==="buy"?"predict.trade.potentialWin":"predict.trade.estimatedReceive")}),jsxRuntime.jsxs("span",{className:"text-xl font-semibold text-bullish",children:["$",(n==="buy"?a:o).toFixed(2)]})]}),jsxRuntime.jsx(ui.Button,{color:k,fullWidth:true,radius:"lg",size:"lg",isDisabled:!p||u,isLoading:u,onPress:b,children:v})]})}function Qt({event:e,market:t,initialSide:r,initialOutcome:n,chain:s}){let{outcome:a,side:o,quantity:l,estimatedCost:i,potentialPayout:c,potentialProfit:d,usdcBalance:u,yesTokenBalance:p,noTokenBalance:f,isBalanceLoading:m,isSubmitting:y,validation:b,setOutcome:x,setSide:v,setQuantity:k,submit:g}=Vr({market:t,initialSide:r,initialOutcome:n,chain:s}),C=walletConnector.useAuthCallback(g);return jsxRuntime.jsx(jr,{event:e,market:t,outcome:a,side:o,quantity:l,estimatedCost:i,potentialPayout:c,potentialProfit:d,usdcBalance:u,yesTokenBalance:p,noTokenBalance:f,isBalanceLoading:m,isSubmitting:y,isValid:b.isValid,validationErrors:b.errors,onOutcomeChange:x,onSideChange:v,onQuantityChange:k,onSubmit:C})}function ri(){return jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 lg:gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 flex-1 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-10 shrink-0 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-16 rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-16 rounded-lg"})]})]})}function Ae({marketCount:e=4}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 lg:px-4 lg:max-w-3xl animate-pulse",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 lg:gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-14 w-14 shrink-0 rounded-lg lg:h-18 lg:w-18"}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1.5 min-w-0 flex-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-24 rounded-md lg:w-32"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-48 rounded-md lg:h-6 lg:w-72"})]})]}),jsxRuntime.jsx(ui.Skeleton,{className:"h-[200px] w-full rounded-xl lg:h-[280px]"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-32 rounded-md"}),jsxRuntime.jsx("div",{className:"flex gap-x-1",children:Array.from({length:4}).map((t,r)=>jsxRuntime.jsx(ui.Skeleton,{className:"h-7 w-10 rounded-md"},r))})]}),jsxRuntime.jsx("div",{className:"flex flex-col divide-y divide-default-200",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(ri,{},r))})]})}function Xr(){return jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4 animate-pulse",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-10 w-10 shrink-0 rounded-lg"}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1 flex-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-28 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-40 rounded-md"})]})]}),jsxRuntime.jsxs("div",{className:"flex gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-12 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-12 rounded-md"})]}),jsxRuntime.jsxs("div",{className:"flex gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-lg"})]}),jsxRuntime.jsx(ui.Skeleton,{className:"h-14 w-full rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-12 w-full rounded-lg"})]})}var Zr=e=>{let{candlestickMarketTickers:t,chartRange:r=fe}=e,n=Xe[r],s=Je[r],a=react.useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=h(),{data:l,isLoading:i,error:c}=ze({id:e.eventId,withNestedMarkets:true}),d=react.useMemo(()=>{if(s!=null)return a-s;let k=l?.markets;return k?.length?Math.min(...k.map(g=>g.openTime)):a},[a,s,l?.markets]),{data:u,isLoading:p,error:f}=ir(l?.seriesTicker??"",{enabled:!!l?.seriesTicker}),m=react.useMemo(()=>l?.markets?(t&&t.length>0?t.slice(0,4).map(g=>l.markets.find(C=>C.ticker===g)).filter(g=>g!==void 0):[...l.markets].sort((g,C)=>Number(C.yesAsk??0)-Number(g.yesAsk??0)).slice(0,4)).map(g=>g.ticker):[],[t,l?.markets]),y=reactQuery.useQueries({queries:m.map(k=>({queryKey:vt({ticker:k,startTs:d,endTs:a,periodInterval:n}),queryFn:()=>kt(o,{ticker:k,startTs:d,endTs:a,periodInterval:n}),enabled:m.length>0}))}),b=y.some(k=>k.isLoading),x=react.useMemo(()=>{let k=new Map;return m.forEach((g,C)=>{let M=y[C]?.error;M&&k.set(g,M);}),k},[m,y]),v=react.useMemo(()=>{let k=new Map;return m.forEach((g,C)=>{let M=y[C]?.data;M&&k.set(g,M);}),k},[m,y]);return {event:l,isEventLoading:i,eventError:c,series:u,isSeriesLoading:p,seriesError:f,periodInterval:n,candlesticks:v,isCandlesticksLoading:b,candlestickErrors:x}};var di=utils.SOLANA_TOKENS.stablecoins.USDC.address;function Jr(e){let{status:t}=walletConnector.useAuth(),n=walletConnector.useWallets().find(c=>c.chainNamespace===types.ChainNamespace.SOLANA&&c.isConnected),s=t==="authenticated",a=n?.address,{data:o,isLoading:l}=react$1.useWalletPortfoliosQuery({chain:types.Chain.SOLANA,address:a??""},{enabled:s&&!!a,refetchInterval:1e4});return {holdings:react.useMemo(()=>{let c=new Map;if(!o?.portfolios||e.length===0)return c;let d=new Map;for(let u of o.portfolios)d.set(u.address,parseFloat(u.amount));for(let u of e){let p=u.accounts[di];if(!p)continue;let f=d.get(p.yesMint)??0,m=d.get(p.noMint)??0;(f>0||m>0)&&c.set(u.ticker,{yesShares:f,noShares:m});}return c},[o,e]),isLoading:l}}function ki(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxRuntime.jsxs("g",{children:[jsxRuntime.jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsxRuntime.jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsxRuntime.jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsxRuntime.jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}var rt=[{stroke:"hsl(var(--heroui-primary))",id:"colorMarket0"},{stroke:"hsl(var(--heroui-secondary))",id:"colorMarket1"},{stroke:"hsl(var(--heroui-success))",id:"colorMarket2"},{stroke:"hsl(var(--heroui-warning))",id:"colorMarket3"}];function en(e,t){let r=new Date(e*1e3);switch(t){case T.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case T.ONE_WEEK:case T.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case T.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function Pi(e,t,r){let n=Ze[r],s=new Map;e.forEach((i,c)=>{let d=new Map;(i.candlesticks??[]).forEach(p=>{let f=p.end_period_ts-p.end_period_ts%n;d.set(f,p.yes_ask.close);}),s.set(c,d);});let a=new Set;for(let i of s.values())for(let c of i.keys())a.add(c);let o=Array.from(a).sort((i,c)=>i-c),l=new Map;return o.map(i=>{let d={date:new Date(i*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),timestamp:i};return t.forEach(u=>{let p=s.get(u)?.get(i);if(p!==void 0)d[u]=Math.round(p*100)/100,l.set(u,d[u]);else {let f=l.get(u);f!==void 0&&(d[u]=f);}}),d})}function tn({candlesticks:e,markets:t=[],isLoading:r,chartRange:n=T.ALL,onDataChange:s}){let[a,o]=react.useState(null),l=react.useRef(s);react.useEffect(()=>{l.current=s;});let i=react.useMemo(()=>e?Array.from(e.keys()).slice(0,4):[],[e]),c=react.useMemo(()=>!e||e.size===0?[]:Pi(e,i,n),[e,i,n]),d=react.useMemo(()=>{if(c.length===0||i.length===0)return [0,100];let m=1/0,y=-1/0;if(c.forEach(g=>{i.forEach(C=>{let M=g[C];M!==void 0&&(m=Math.min(m,M),y=Math.max(y,M));});}),m===1/0||y===-1/0)return [0,100];let b=y-m,x=Math.max(b*.2,5),v=Math.max(0,Math.floor(m-x)),k=Math.min(100,Math.ceil(y+x));return [v,k]},[c,i]),u=react.useCallback(m=>{if(c.length===0)return null;let y=m!==null?c[m]:c[c.length-1];return y?{timestamp:y.timestamp,date:y.date,markets:i.map((b,x)=>{let v=t.find(k=>k.ticker===b);return {id:b,label:v?.yesSubTitle||`Market ${x+1}`,value:y[b]??0,color:rt[x%rt.length].stroke}})}:null},[c,i,t]);react.useEffect(()=>{l.current&&c.length>0&&l.current(u(null));},[c,u]),react.useEffect(()=>{l.current&&l.current(u(a));},[a,u]);let p=react.useCallback(m=>{typeof m?.activeTooltipIndex=="number"&&o(m.activeTooltipIndex);},[]),f=react.useCallback(()=>{o(null);},[]);return r?jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-default-400 text-sm",children:"Loading chart..."})}):c.length===0?jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-default-400 text-sm",children:"No price history data"})}):jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px]",children:jsxRuntime.jsx(recharts.ResponsiveContainer,{width:"100%",height:"100%",children:jsxRuntime.jsxs(recharts.LineChart,{data:c,margin:{top:10,right:16,left:16,bottom:0},onMouseMove:p,onMouseLeave:f,children:[jsxRuntime.jsx(recharts.XAxis,{dataKey:"timestamp",tick:m=>{let{x:y,y:b,payload:x,index:v}=m,k=c.length,C=Math.max(1,Math.ceil(k/6)),M=v===0,R=v===k-1,N=v%C===0;return !M&&!R&&!N?null:jsxRuntime.jsx("text",{x:y,y:b+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:en(x.value,n)})},tickLine:false,axisLine:false,interval:0}),jsxRuntime.jsx(recharts.CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsxRuntime.jsx(recharts.YAxis,{domain:d,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:m=>`${m}%`,width:40}),jsxRuntime.jsx(recharts.Tooltip,{contentStyle:{backgroundColor:"hsl(var(--heroui-content1))",border:"1px solid hsl(var(--heroui-default-200))",borderRadius:"8px",fontSize:"12px"},labelFormatter:m=>en(m,n),formatter:(m,y)=>{let x=t.find(v=>v.ticker===y)?.yesSubTitle||y;return [`${m.toFixed(2)}%`,x]}}),i.map((m,y)=>jsxRuntime.jsx(recharts.Line,{type:"monotone",dataKey:m,stroke:rt[y%rt.length].stroke,strokeWidth:2,isAnimationActive:false,dot:b=>jsxRuntime.jsx(ki,{...b,dataLength:c.length},`dot-${m}-${b.index}`),activeDot:false},m))]})})})}function rn(){return {timestamp:Date.now()/1e3,date:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"}),markets:[]}}function sn({marketTicker:e,openTime:t,chartRange:r=fe}){let n=Xe[r],s=Je[r],a=react.useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=react.useMemo(()=>s!=null?a-s:t??a,[a,s,t]),{data:l,isLoading:i,isFetching:c,error:d}=Pt({ticker:e,startTs:o,endTs:a,periodInterval:n},{enabled:!!e});return {candlesticks:l,isLoading:i,isFetching:c,error:d,periodInterval:n}}var Ni="hsl(var(--heroui-primary))",Ei=[{value:T.ONE_DAY,label:"1D"},{value:T.ONE_WEEK,label:"1W"},{value:T.ONE_MONTH,label:"1M"},{value:T.ALL,label:"ALL"}];function Ii(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxRuntime.jsxs("g",{children:[jsxRuntime.jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsxRuntime.jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsxRuntime.jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsxRuntime.jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}function an(e,t){let r=new Date(e*1e3);switch(t){case T.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case T.ONE_WEEK:case T.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case T.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function Qi(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(0)}function Bi(e,t){let r=Ze[t],n=e.candlesticks??[],s=new Map;for(let o of n){let l=o.end_period_ts-o.end_period_ts%r,i=s.get(l);s.set(l,{close:o.yes_ask.close,volume:(i?.volume??0)+(o.volume??0)});}return Array.from(s.entries()).sort((o,l)=>o[0]-l[0]).map(([o,{close:l,volume:i}])=>({timestamp:o,date:new Date(o*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:Math.round(l*100)/100,volume:i}))}function ln({candlesticks:e,isLoading:t,chartRange:r,onRangeChange:n}){let s=react.useMemo(()=>e?Bi(e,r):[],[e,r]),a=react.useMemo(()=>{if(s.length===0)return [0,100];let o=1/0,l=-1/0;for(let p of s)p.value<o&&(o=p.value),p.value>l&&(l=p.value);if(o===1/0||l===-1/0)return [0,100];let i=l-o,c=Math.max(i*.2,5),d=Math.max(0,Math.floor(o-c)),u=Math.min(100,Math.ceil(l+c));return [d,u]},[s]);return t?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-neutral text-sm",children:"Loading chart..."})}),jsxRuntime.jsx(Dt,{chartRange:r,onRangeChange:n})]}):s.length===0?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-neutral text-sm",children:"No price history data"})}),jsxRuntime.jsx(Dt,{chartRange:r,onRangeChange:n})]}):jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full",children:jsxRuntime.jsx(recharts.ResponsiveContainer,{width:"100%",height:"100%",children:jsxRuntime.jsxs(recharts.LineChart,{data:s,margin:{top:10,right:16,left:16,bottom:0},children:[jsxRuntime.jsx(recharts.XAxis,{dataKey:"timestamp",tick:o=>{let{x:l,y:i,payload:c,index:d}=o,u=s.length,f=Math.max(1,Math.ceil(u/6)),m=d===0,y=d===u-1,b=d%f===0;return !m&&!y&&!b?null:jsxRuntime.jsx("text",{x:l,y:i+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:an(c.value,r)})},tickLine:false,axisLine:false,interval:0}),jsxRuntime.jsx(recharts.CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsxRuntime.jsx(recharts.YAxis,{domain:a,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:o=>`${o}%`,width:40}),jsxRuntime.jsx(recharts.Tooltip,{cursor:{stroke:"hsl(var(--heroui-default-300))"},content:({active:o,payload:l})=>{if(!o||!l?.length)return null;let i=l[0].payload,c=Math.round(i.value);return jsxRuntime.jsxs("div",{className:"rounded-lg border border-default-200 bg-content1 px-3 py-2 shadow-md",children:[jsxRuntime.jsxs("div",{className:"text-lg font-semibold text-primary",children:["Yes ",c,"\xA2"]}),jsxRuntime.jsxs("div",{className:"text-sm text-neutral",children:["Vol ",Qi(i.volume)," \xB7"," ",an(i.timestamp,r)]})]})}}),jsxRuntime.jsx(recharts.Line,{type:"monotone",dataKey:"value",stroke:Ni,strokeWidth:2,isAnimationActive:false,dot:o=>jsxRuntime.jsx(Ii,{...o,dataLength:s.length},`dot-${o.index}`),activeDot:false})]})})}),jsxRuntime.jsx(Dt,{chartRange:r,onRangeChange:n})]})}function Dt({chartRange:e,onRangeChange:t}){return jsxRuntime.jsx("div",{className:"flex items-center justify-end gap-x-1",children:Ei.map(r=>{let n=e===r.value;return jsxRuntime.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,onClick:()=>t?.(r.value),children:r.label},r.value)})})}function cn({marketTicker:e}){let{data:t,isLoading:r,error:n}=Re(e,{enabled:!!e});return {orderbook:react.useMemo(()=>{if(!t)return null;let{yesBids:a,yesAsks:o,noBids:l,noAsks:i}=t;return {yesBids:a,yesAsks:o,noBids:l,noAsks:i,bestYesBid:a.length>0?a[0].price:null,bestYesAsk:o.length>0?o[0].price:null,bestNoBid:l.length>0?l[0].price:null,bestNoAsk:i.length>0?i[0].price:null,sequence:t.sequence??null}},[t]),isOrderbookLoading:r,orderbookError:n}}function un(e,t){let r=e.slice(0,t),n=0;return r.map(s=>(n+=s.quantity,{...s,cumulative:n,depth:0,total:s.price*s.quantity}))}function dn(e,t){for(let r of e)r.depth=t>0?r.cumulative/t:0;}function fn(e){return `${Math.round(e*100)}\xA2`}function Ai(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Di(e){return e>=1e6?`$${(e/1e6).toFixed(2)}M`:e>=1e3?`$${(e/1e3).toFixed(2)}K`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function pn({row:e,side:t,showType:r=false,onClick:n}){let{t:s}=i18n.useTranslation(),a=t==="ask",o=a?"bg-bullish/10":"bg-bearish/10",l=a?"text-bullish":"text-bearish";return jsxRuntime.jsxs("button",{type:"button",className:"relative grid w-full grid-cols-4 px-2 py-2.5 text-xs cursor-pointer hover:bg-default-100 transition-colors",onClick:()=>n?.(e.price,t),children:[jsxRuntime.jsx("div",{className:`absolute inset-y-0 left-0 ${o} transition-[width] duration-200`,style:{width:`${e.depth*100}%`}}),jsxRuntime.jsx("span",{className:`relative z-10 font-mono font-medium ${l} text-left`,children:r?s(a?"predict.trade.bestAsk":"predict.trade.bestBid"):""}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:fn(e.price)}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Ai(e.quantity)}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Di(e.total)})]})}function mn({index:e}){let t=["60%","45%","75%","55%","65%","50%","70%","40%"];return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function Wi(){return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"})]}),Array.from({length:Wt}).map((e,t)=>jsxRuntime.jsx(mn,{index:t},`ask-${t}`)),jsxRuntime.jsx("div",{className:"flex justify-center border-y border-default-200 px-2 py-2.5",children:jsxRuntime.jsx("div",{className:"h-4 w-24 animate-pulse rounded bg-default-100"})}),Array.from({length:Wt}).map((e,t)=>jsxRuntime.jsx(mn,{index:t+3},`bid-${t}`))]})}var Wt=8;function _t({bids:e,asks:t,isLoading:r=false,maxLevels:n=Wt,onPriceClick:s}){let{t:a}=i18n.useTranslation(),{bidRows:o,askRows:l,spread:i,spreadPercent:c}=react.useMemo(()=>{let u=un(e,n),p=un(t,n),f=Math.max(u[u.length-1]?.cumulative??0,p[p.length-1]?.cumulative??0);dn(u,f),dn(p,f);let m=u[0]?.price??null,y=p[0]?.price??null,b=null,x=null;if(m!=null&&y!=null){b=y-m;let v=(m+y)/2;v>0&&(x=Math.round(b/v*1e4)/100);}return {bidRows:u,askRows:p,spread:b,spreadPercent:x}},[e,t,n]);return r?jsxRuntime.jsx(Wi,{}):o.length===0&&l.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:a("predict.orderBook.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.price")}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.contracts")}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.total")})]}),jsxRuntime.jsx("div",{className:"flex flex-col-reverse",children:l.map((u,p)=>jsxRuntime.jsx(pn,{row:u,side:"ask",showType:p===0,onClick:s},u.price))}),i!=null&&jsxRuntime.jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 px-2 py-2.5 text-xs text-default-500",children:[jsxRuntime.jsxs("span",{children:[a("predict.orderBook.spread"),": ",fn(i)]}),c!=null&&jsxRuntime.jsxs("span",{className:"text-default-400",children:["(",c,"%)"]})]}),jsxRuntime.jsx("div",{className:"flex flex-col",children:o.map((u,p)=>jsxRuntime.jsx(pn,{row:u,side:"bid",showType:p===0,onClick:s},u.price))})]})}function qi(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function Ki(e){let t=Math.abs(e),r=e>=0?"+":"-";return t>=1e3?`${r}$${(t/1e3).toFixed(1)}K`:t>=1?`${r}$${t.toFixed(2)}`:`${r}$${t.toFixed(4)}`}function gn({positions:e,isLoading:t=false}){let{t:r}=i18n.useTranslation();return t?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx(ui.Spinner,{size:"sm"})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.positions.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{children:r("predict.positions.outcome")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.qty")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.avgCost")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.currentPrice")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.pnl")})]}),e.map(n=>{let s=n.position==="YES",a=s?"text-bullish":"text-bearish",o=r(s?"predict.market.yes":"predict.market.no"),l=n.avgCost!=null?`${Math.round(n.avgCost*100)}\xA2`:"\u2014",i=n.currentPrice!=null?`${Math.round(n.currentPrice*100)}\xA2`:"\u2014",c=n.pnl!=null&&n.pnlPercent!=null,d=c&&n.pnl>0?"text-bullish":c&&n.pnl<0?"text-bearish":"text-foreground";return jsxRuntime.jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsxRuntime.jsx("span",{className:`font-medium ${a}`,children:o}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:qi(n.balance)}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:l}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:i}),jsxRuntime.jsx("span",{className:`text-right font-mono ${d}`,children:c?jsxRuntime.jsxs("span",{className:"flex flex-col items-end",children:[jsxRuntime.jsx("span",{children:Ki(n.pnl)}),jsxRuntime.jsxs("span",{className:"text-[10px] opacity-70",children:[n.pnlPercent>=0?"+":"",n.pnlPercent.toFixed(1),"%"]})]}):"\u2014"})]},n.mint)})]})}function $i(e){let t=e/1e6;return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(2)}K`:t.toLocaleString(void 0,{maximumFractionDigits:2})}function Vi(e){return e==null?"\u2014":`${Math.round(e*100)}\xA2`}function zi(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return `${r} ${n} ${s}:${a}`}function Yi({index:e}){let t=["60%","45%","75%","55%","65%"];return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function xn({trades:e,isLoading:t=false}){let{t:r}=i18n.useTranslation();return t?jsxRuntime.jsx("div",{className:"flex flex-col",children:Array.from({length:6}).map((n,s)=>jsxRuntime.jsx(Yi,{index:s},s))}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.tradeHistory.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{children:r("predict.tradeHistory.side")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.price")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.qty")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.time")})]}),e.map(n=>{let s=n.side==="yes",a=s?"text-bullish":"text-bearish",o=n.side?r(s?"predict.trade.yes":"predict.trade.no"):"\u2014";return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsxRuntime.jsx("span",{className:`font-medium ${a}`,children:o}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:Vi(n.usdPricePerContract)}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:$i(n.outputAmount)}),jsxRuntime.jsx("span",{className:"text-right text-default-500",children:zi(n.createdAt)})]},n.id)})]})}function kn({market:e,onTradeAction:t}){let{t:r}=i18n.useTranslation(),[n,s]=react.useState("trade-yes"),[a,o]=react.useState(fe),{orderbook:l,isOrderbookLoading:i}=cn({marketTicker:e.ticker}),{candlesticks:c,isFetching:d}=sn({marketTicker:e.ticker,openTime:e.openTime,chartRange:a}),{positions:u,isLoading:p}=ur(e),{status:f}=walletConnector.useAuth(),b=walletConnector.useWallets().find(R=>R.chainNamespace===types.ChainNamespace.SOLANA&&R.isConnected)?.address,{data:x,isLoading:v}=nr({walletAddress:b??""},{enabled:(n==="trade-history"||n==="positions")&&f==="authenticated"&&!!b}),k=(x?.trades??[]).filter(R=>R.marketTicker===e.ticker),g=react.useMemo(()=>u.map(R=>{let N=k.filter(pe=>pe.outputMint===R.mint&&pe.usdPricePerContract!=null&&pe.contracts!=null&&pe.contracts>0),P=tl(N),Q=R.position==="YES"?vn(R.market?.yesAsk):vn(R.market?.noAsk),U=null,ke=null;return P!=null&&Q!=null&&(U=(Q-P)*R.balance,ke=P>0?(Q-P)/P*100:null),{...R,avgCost:P,currentPrice:Q,pnl:U,pnlPercent:ke}}),[u,k]),C=react.useCallback((R,N)=>{t?.(e,"yes",N==="ask"?"buy":"sell");},[e,t]),M=react.useCallback((R,N)=>{t?.(e,"no",N==="ask"?"buy":"sell");},[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-3",children:[jsxRuntime.jsxs(ui.Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:R=>s(R),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsxRuntime.jsx(ui.Tab,{title:r("predict.market.tradeYes")},"trade-yes"),jsxRuntime.jsx(ui.Tab,{title:r("predict.market.tradeNo")},"trade-no"),jsxRuntime.jsx(ui.Tab,{title:r("predict.market.graph")},"graph"),jsxRuntime.jsx(ui.Tab,{title:r("predict.positions.title")},"positions"),jsxRuntime.jsx(ui.Tab,{title:r("predict.tradeHistory.title")},"trade-history")]}),jsxRuntime.jsxs("div",{className:"min-h-[120px]",children:[n==="trade-yes"&&jsxRuntime.jsx(_t,{bids:l?.yesBids??[],asks:l?.yesAsks??[],isLoading:i,onPriceClick:C}),n==="trade-no"&&jsxRuntime.jsx(_t,{bids:l?.noBids??[],asks:l?.noAsks??[],isLoading:i,onPriceClick:M}),n==="graph"&&jsxRuntime.jsx(ln,{candlesticks:c,isLoading:d,chartRange:a,onRangeChange:o}),n==="positions"&&jsxRuntime.jsx(gn,{positions:g,isLoading:p}),n==="trade-history"&&jsxRuntime.jsx(xn,{trades:k,isLoading:v})]})]})}function tl(e){if(e.length===0)return null;let t=0,r=0;for(let n of e)t+=n.contracts,r+=n.usdPricePerContract*n.contracts;return t>0?r/t:null}function vn(e){if(e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}var qt=4;function nl(e){let t=e.yesAsk?Math.round(parseFloat(e.yesAsk)*100):null,r=e.noAsk?Math.round(parseFloat(e.noAsk)*100):null;return {yesCents:t,noCents:r}}function On({markets:e,renderMarketDetail:t,onTradeAction:r,marketHoldings:n}){let{t:s}=i18n.useTranslation(),[a,o]=react.useState(false),[l,i]=react.useState(null);if(e.length===0)return null;let c=e.length>qt,d=a?e:e.slice(0,qt),u=p=>{i(f=>f===p?null:p);};return jsxRuntime.jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[d.map(p=>{let{yesCents:f,noCents:m}=nl(p),y=l===p.ticker;return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>u(p.ticker),role:"button",tabIndex:0,onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u(p.ticker));},children:[jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:p.yesSubTitle}),(()=>{let b=n?.get(p.ticker);if(!b)return null;let{yesShares:x,noShares:v}=b;return x<=0&&v<=0?null:jsxRuntime.jsxs("div",{className:"flex items-center gap-x-1.5",children:[x>0&&jsxRuntime.jsx(ui.Chip,{size:"sm",variant:"flat",color:"primary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesYes",{shares:x%1===0?x:x.toFixed(2)})}),v>0&&jsxRuntime.jsx(ui.Chip,{size:"sm",variant:"flat",color:"secondary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesNo",{shares:v%1===0?v:v.toFixed(2)})})]})})()]}),(()=>{let b=f!=null,x=m!=null;return b&&!x&&f<=1?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"< 1%"}):x&&!b&&m<=1?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"> 99%"}):!b&&!x?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"0%"}):jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:`${f}%`})})(),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsxRuntime.jsx(ui.Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>r?.(p,"yes","buy"),children:f!=null?s("predict.market.action.yes",{price:f}):s("predict.market.yes")}),jsxRuntime.jsx(ui.Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>r?.(p,"no","buy"),children:m!=null?s("predict.market.action.no",{price:m}):s("predict.market.no")})]}),y?jsxRuntime.jsx(ui.ChevronUpIcon,{className:"h-4 w-4 shrink-0 text-default-400"}):jsxRuntime.jsx(ui.ChevronDownIcon,{className:"h-4 w-4 shrink-0 text-default-400"})]}),y&&t&&jsxRuntime.jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:t(p)})]},p.ticker)}),c&&jsxRuntime.jsx("button",{type:"button",onClick:()=>o(p=>!p),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:a?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{children:s("predict.event.rules.collapse")}),jsxRuntime.jsx(ui.ChevronUpIcon,{className:"h-4 w-4"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{children:s("predict.event.moreMarkets",{count:e.length-qt})}),jsxRuntime.jsx(ui.ChevronDownIcon,{className:"h-4 w-4"})]})})]})}var ll=new Set(["closed","determined","finalized"]);function st(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function cl({market:e}){let t=ll.has(e.status),r=react.useMemo(()=>{let s={label:"Market Open",value:st(e.openTime),isActive:true},a={label:"Market Closes",value:t?st(e.closeTime):"After the outcome occurs",isActive:t},o={label:"Projected Payout",value:"30 minutes after closing",isActive:e.status==="finalized"};return [s,a,o]},[e.openTime,e.closeTime,e.status,t]),n=react.useMemo(()=>t?null:e.canCloseEarly&&e.earlyCloseCondition?`${e.earlyCloseCondition} Otherwise, it closes by ${st(e.expirationTime)}.`:`This market closes by ${st(e.expirationTime)}.`,[t,e.canCloseEarly,e.earlyCloseCondition,e.expirationTime]);return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[r.map((s,a)=>jsxRuntime.jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-col items-center w-3",children:[jsxRuntime.jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${s.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),a<r.length-1&&jsxRuntime.jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxRuntime.jsxs("div",{className:`flex flex-col ${a<r.length-1?"pb-4":""}`,children:[jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:s.label}),jsxRuntime.jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:s.value})]})]},s.label)),n&&jsxRuntime.jsx("p",{className:"text-xs text-default-500 mt-3 lg:text-sm",children:n})]})}function Nn({markets:e,event:t,series:r}){let{t:n}=i18n.useTranslation(),[s,a]=react.useState(null),o=e.filter(i=>i.rulesPrimary);if(o.length===0)return null;let l=o.find(i=>i.ticker===s)??o[0];return l?.rulesPrimary?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium lg:text-base",children:n("predict.event.rules")}),o.length>1&&jsxRuntime.jsx(ui.Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([l.ticker]),onSelectionChange:i=>{if(i==="all")return;let c=Array.from(i);c.length>0&&a(c[0]);},children:o.map(i=>jsxRuntime.jsx(ui.SelectItem,{textValue:i.yesSubTitle,children:jsxRuntime.jsx("span",{className:"text-xs truncate",children:i.yesSubTitle})},i.ticker))}),jsxRuntime.jsx("div",{className:"text-xs text-foreground lg:text-sm",children:l.rulesPrimary}),jsxRuntime.jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline and payout"}),jsxRuntime.jsx(cl,{market:l}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[r?.ticker&&jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Series:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:r.ticker})]}),t.ticker&&jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Event:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:t.ticker})]}),jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Market:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:l.ticker})]})]})]}):null}var bl=[{value:T.ONE_DAY,label:"1D"},{value:T.ONE_WEEK,label:"1W"},{value:T.ONE_MONTH,label:"1M"},{value:T.ALL,label:"ALL"}];function In({event:e,series:t,candlesticks:r,chartRange:n=T.ONE_DAY,periodInterval:s,isCandlesticksLoading:a,onRangeChange:o,selectedMarketTickers:l,onMarketSelectionChange:i,onTradeAction:c}){let{t:d}=i18n.useTranslation(),[u,p]=react.useState(rn()),[f,m]=react.useState(false),y=react.useRef(null);react.useEffect(()=>{let g=y.current;if(!g)return;let C=false,M=0,R=()=>{let{bottom:P}=g.getBoundingClientRect(),Q=C?P<0:P<-20;Q!==C&&(C=Q,m(Q));},N=()=>{cancelAnimationFrame(M),M=requestAnimationFrame(R);};return window.addEventListener("scroll",N,{passive:true,capture:true}),R(),()=>{cancelAnimationFrame(M),window.removeEventListener("scroll",N,{capture:true});}},[]);let b=react.useMemo(()=>[...e.markets||[]].sort((g,C)=>Number(C.yesAsk??0)-Number(g.yesAsk??0)),[e.markets]),{holdings:x}=Jr(b),v=react.useMemo(()=>utils.formatAmountUSDCompact((e.volume??0)/100),[e.volume]),k=react.useMemo(()=>{if(!e.strikeDate)return null;let g=new Date(e.strikeDate*1e3),C=g.toLocaleString("default",{month:"short"}),M=g.getDate(),R=g.getFullYear();return `${C} ${M}, ${R}`},[e.strikeDate]);return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsxRuntime.jsx("div",{ref:y,className:"h-0 w-0"}),jsxRuntime.jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${f?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsxRuntime.jsx(ui.Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${f?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[!f&&(t?.category||t?.tags&&t.tags.length>0)&&jsxRuntime.jsxs("span",{className:"text-xs text-default-500 lg:text-sm truncate",children:[t.category,t.category&&t.tags?.length>0&&" \xB7 ",t.tags?.join(", ")]}),jsxRuntime.jsx("span",{className:`font-semibold truncate transition-all duration-300 ${f?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-4",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[u&&u.markets.length>0&&jsxRuntime.jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:u.markets.map(g=>jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:g.color}}),jsxRuntime.jsx("span",{className:"text-default-600",children:g.label})]},g.id))}),jsxRuntime.jsx(tn,{candlesticks:r,chartRange:n,markets:b,isLoading:a,onDataChange:g=>p(g)}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxRuntime.jsxs("span",{children:[v," ",d("predict.event.volume")]}),k&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"text-default-300",children:"\xB7"}),jsxRuntime.jsx("span",{children:d("predict.event.endDate",{date:k})})]})]}),jsxRuntime.jsx("div",{className:"flex items-center gap-x-1",children:bl.map(g=>jsxRuntime.jsx("button",{type:"button",onClick:()=>o?.(g.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n===g.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:g.label},g.value))}),b.length>1&&jsxRuntime.jsx(ui.Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:l?new Set(l):void 0,onSelectionChange:g=>{if(g==="all")return;let C=Array.from(g);C.length<=4&&i?.(C);},children:jsxRuntime.jsx(ui.SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:b.map(g=>jsxRuntime.jsx(ui.SelectItem,{textValue:g.yesSubTitle,children:jsxRuntime.jsx("span",{className:"text-xs truncate",children:g.yesSubTitle})},g.ticker))})})]})]})}),jsxRuntime.jsx(On,{markets:b,onTradeAction:c,marketHoldings:x,renderMarketDetail:g=>jsxRuntime.jsx(kn,{market:g,onTradeAction:c})}),jsxRuntime.jsx(Nn,{markets:b,event:e,series:t})]})}function $t({eventId:e,initialMarketTickers:t,initialChartRange:r=fe,onTradeAction:n}){let[s,a]=react.useState(r),[o,l]=react.useState(t),{event:i,isEventLoading:c,eventError:d,series:u,isSeriesLoading:p,periodInterval:f,candlesticks:m,isCandlesticksLoading:y,candlestickErrors:b}=Zr({eventId:e,candlestickMarketTickers:o,chartRange:s}),x=react.useRef(!!t);react.useEffect(()=>{if(i?.markets&&!x.current){x.current=true;let g=[...i.markets].sort((C,M)=>Number(M.yesAsk??0)-Number(C.yesAsk??0)).slice(0,4).map(C=>C.ticker);l(g);}},[i?.markets]);let v=react.useMemo(()=>g=>{a(g);},[]),k=react.useMemo(()=>g=>{l(g);},[]);return c||p?jsxRuntime.jsx(Ae,{}):d||!i?jsxRuntime.jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:d?.message||"Event not found"}):jsxRuntime.jsx(In,{event:i,series:u,candlesticks:m,chartRange:s,periodInterval:f,isCandlesticksLoading:y,candlestickErrors:b,onRangeChange:v,selectedMarketTickers:o,onMarketSelectionChange:k,onTradeAction:n})}function fg({eventId:e,chain:t,...r}){let{t:n}=i18n.useTranslation(),{isMobile:s}=ui.useScreen(),{isOpen:a,onOpen:o,onClose:l}=ui.useDisclosure(),{data:i,isLoading:c}=ze({id:e,withNestedMarkets:true}),d=react.useMemo(()=>[...i?.markets||[]].sort((b,x)=>Number(x.yesAsk??0)-Number(b.yesAsk??0)),[i?.markets]),[u,p]=react.useState(null),f=react.useCallback((b,x,v)=>{p(k=>({market:b,outcome:x,side:v,version:(k?.version??0)+1})),s&&o();},[s,o]),m=u?.market??d[0];if(c)return s?jsxRuntime.jsx(Ae,{}):jsxRuntime.jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsxRuntime.jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsxRuntime.jsx(Ae,{})}),jsxRuntime.jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsxRuntime.jsx("div",{className:"sticky top-4",children:jsxRuntime.jsx(Xr,{})})})]});let y=u?`${u.market.ticker}-${u.version}`:m?.ticker??"default";return s?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full pb-20",children:jsxRuntime.jsx($t,{eventId:e,onTradeAction:f,...r})}),m&&jsxRuntime.jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsxRuntime.jsx(ui.Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:o,children:n("predict.trade.action")})}),jsxRuntime.jsx(ui.Drawer,{isOpen:a,onClose:l,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsxRuntime.jsx(ui.DrawerContent,{children:jsxRuntime.jsx(ui.DrawerBody,{children:m&&jsxRuntime.jsx(Qt,{event:i,market:m,initialSide:u?.side,initialOutcome:u?.outcome,chain:t},y)})})})]}):jsxRuntime.jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsxRuntime.jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsxRuntime.jsx($t,{eventId:e,onTradeAction:f,...r})}),m&&jsxRuntime.jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsxRuntime.jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsxRuntime.jsx(Qt,{event:i,market:m,initialSide:u?.side,initialOutcome:u?.outcome,chain:t},y)})})]})}function Ln(e,t){if(!e)return [];let r=e.slice(0,t),n=0,s=r.map(o=>(n+=o.quantity,{...o,cumulative:n,depth:0})),a=s[s.length-1]?.cumulative??1;for(let o of s)o.depth=o.cumulative/a;return s}function Un({marketTicker:e,maxLevels:t=10,refetchInterval:r=5e3,outcome:n="yes"}){let{data:s,isLoading:a,isFetching:o}=Re(e,{refetchInterval:r||void 0}),l=react.useMemo(()=>n==="yes"?s?.yesBids:s?.noBids,[s,n]),i=react.useMemo(()=>n==="yes"?s?.yesAsks:s?.noAsks,[s,n]),c=react.useMemo(()=>Ln(l,t),[l,t]),d=react.useMemo(()=>Ln(i,t),[i,t]),u=react.useMemo(()=>c.length===0||d.length===0?null:d[0].price-c[0].price,[c,d]),p=react.useMemo(()=>c.length===0||d.length===0?null:(c[0].price+d[0].price)/2,[c,d]),f=react.useMemo(()=>u===null||p===null||p===0?null:Math.round(u/p*1e4)/100,[u,p]);return {bids:c,asks:d,spread:u,spreadPercent:f,midpoint:p,isLoading:a,isFetching:o}}function An({row:e,side:t,onClick:r}){let n=t==="bid",s=n?"bg-primary/10":"bg-danger/10",a=n?"text-primary":"text-danger";return jsxRuntime.jsxs("button",{type:"button",className:"relative flex w-full items-center justify-between px-3 py-1 text-xs hover:bg-default-100 cursor-pointer",onClick:()=>r?.(e.price),children:[jsxRuntime.jsx("div",{className:`absolute inset-y-0 ${n?"right-0":"left-0"} ${s}`,style:{width:`${e.depth*100}%`}}),jsxRuntime.jsxs("span",{className:`relative z-10 font-medium ${a}`,children:[e.price,"\xA2"]}),jsxRuntime.jsx("span",{className:"relative z-10 text-default-600",children:e.quantity}),jsxRuntime.jsx("span",{className:"relative z-10 text-default-400",children:e.cumulative})]})}function Dn(){return jsxRuntime.jsx("div",{className:"flex flex-col gap-y-1 py-2",children:Array.from({length:5}).map((e,t)=>jsxRuntime.jsx("div",{className:"mx-3 h-4 animate-pulse rounded bg-default-100"},t))})}function Wn({bids:e,asks:t,spread:r,spreadPercent:n,isLoading:s,onPriceClick:a}){let{t:o}=i18n.useTranslation();if(s)return jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:o("predict.orderBook.title")}),jsxRuntime.jsx(Dn,{}),jsxRuntime.jsx(Dn,{})]});let l=e.length===0&&t.length===0;return jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxRuntime.jsx("span",{className:"text-sm font-medium",children:o("predict.orderBook.title")})}),l?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:o("predict.orderBook.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between px-3 py-1 text-xxs text-default-400",children:[jsxRuntime.jsx("span",{children:o("predict.orderBook.price")}),jsxRuntime.jsx("span",{children:o("predict.orderBook.qty")}),jsxRuntime.jsx("span",{children:o("predict.orderBook.total")})]}),jsxRuntime.jsx("div",{className:"flex flex-col-reverse",children:t.map(i=>jsxRuntime.jsx(An,{row:i,side:"ask",onClick:a},i.price))}),r!==null&&jsxRuntime.jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 py-1.5 text-xs text-default-500",children:[jsxRuntime.jsxs("span",{children:[o("predict.orderBook.spread"),": ",r,"\xA2"]}),n!==null&&jsxRuntime.jsxs("span",{className:"text-default-400",children:["(",n,"%)"]})]}),jsxRuntime.jsx("div",{className:"flex flex-col",children:e.map(i=>jsxRuntime.jsx(An,{row:i,side:"bid",onClick:a},i.price))})]})]})}function Ag({marketTicker:e,maxLevels:t,refetchInterval:r,onPriceClick:n,outcome:s}){let{bids:a,asks:o,spread:l,spreadPercent:i,isLoading:c}=Un({marketTicker:e,maxLevels:t,refetchInterval:r,outcome:s});return jsxRuntime.jsx(Wn,{bids:a,asks:o,spread:l,spreadPercent:i,isLoading:c,onPriceClick:n})}function Fn(e={}){let[t,r]=react.useState(null),[n]=react.useState(null),s=react.useCallback(a=>{r(null);},[]);return {orders:[],isLoading:false,isFetching:false,cancellingOrderId:t,cancelOrder:s,cancelError:n}}function Hl(e){return new Date(e).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qn({orders:e,isLoading:t,cancellingOrderId:r,onCancel:n}){let{t:s}=i18n.useTranslation(),a=react.useMemo(()=>e.map(o=>({key:o.id,side:o.side,outcome:o.outcome,type:o.type,price:o.price,filled:`${o.filledQuantity}/${o.quantity}`,status:o.status,createdAt:Hl(o.createdAt),isCancelling:o.id===r,id:o.id})),[e,r]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.openOrders.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,l)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},l))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsxs("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:[s("predict.openOrders.title"),e.length>0&&jsxRuntime.jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.openOrders.empty")}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto",children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Open orders",className:"min-w-[600px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Side",width:60,children:s("predict.openOrders.side")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Outcome",width:60,children:s("predict.openOrders.outcome")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Type",width:60,children:s("predict.openOrders.type")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:60,children:s("predict.openOrders.price")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Filled",width:80,children:s("predict.openOrders.filled")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Status",width:70,children:s("predict.openOrders.status")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Time",width:120,children:s("predict.openOrders.time")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Action",width:80,align:"end",children:" "})]}),jsxRuntime.jsx(ui.TableBody,{children:a.map(o=>jsxRuntime.jsxs(ui.TableRow,{children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${o.side==="buy"?"text-primary":"text-danger"}`,children:o.side==="buy"?s("predict.trade.buy"):s("predict.trade.sell")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs capitalize",children:o.type})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.price,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:o.filled})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs capitalize",children:o.status})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:o.createdAt})}),jsxRuntime.jsx(ui.TableCell,{className:"text-right",children:jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"danger",isLoading:o.isCancelling,onPress:()=>n(o.id),children:s("predict.openOrders.cancel")})})]},o.key))})]})})]})}function Jg({refetchInterval:e}={}){let{orders:t,isLoading:r,cancellingOrderId:n,cancelOrder:s}=Fn({});return jsxRuntime.jsx(qn,{orders:t,isLoading:r,cancellingOrderId:n,onCancel:s})}function Hn({ticker:e,pageSize:t=48}={}){let[r,n]=react.useState(1),[s,a]=react.useState([void 0]),o=s[r-1],l=react.useMemo(()=>({...e?{ticker:e}:{},limit:t,...o?{cursor:o}:{}}),[e,t,o]),{data:i,isLoading:c,isFetching:d}=rr(l),u=i,p=u?.trades??[],f=!!u?.cursor,m=r>1,y=react.useCallback(v=>{v>=1&&v<=s.length&&n(v);},[s.length]),b=react.useCallback(()=>{f&&u?.cursor&&(a(v=>{let k=[...v];return k.length===r&&k.push(u.cursor),k}),n(v=>v+1));},[f,u?.cursor,r]),x=react.useCallback(()=>{m&&n(v=>v-1);},[m]);return {trades:p,isLoading:c,isFetching:d,page:r,pageSize:t,hasNextPage:f,hasPrevPage:m,goToPage:y,nextPage:b,prevPage:x}}function tc(e){return new Date(e*1e3).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Vn({trades:e,isLoading:t,isFetching:r,page:n,hasNextPage:s,hasPrevPage:a,onNextPage:o,onPrevPage:l}){let{t:i}=i18n.useTranslation(),c=react.useMemo(()=>e.map(d=>({key:d.tradeId,ticker:d.ticker,takerSide:d.takerSide,price:d.price,yesPrice:d.yesPrice,noPrice:d.noPrice,count:d.count,createdAt:tc(d.createdTime)})),[e]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:i("predict.tradeHistory.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((d,u)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},u))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:i("predict.tradeHistory.title")}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:i("predict.tradeHistory.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:`w-full overflow-x-auto ${r?"opacity-60":""}`,children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Trade history",className:"min-w-[480px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Side",width:60,children:i("predict.tradeHistory.side")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:80,children:i("predict.tradeHistory.price")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Yes",width:60,children:i("predict.trade.yes")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"No",width:60,children:i("predict.trade.no")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Qty",width:60,children:i("predict.tradeHistory.qty")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Time",width:120,children:i("predict.tradeHistory.time")})]}),jsxRuntime.jsx(ui.TableBody,{children:c.map(d=>jsxRuntime.jsxs(ui.TableRow,{children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${d.takerSide==="yes"?"text-primary":"text-secondary"}`,children:d.takerSide==="yes"?i("predict.trade.yes"):i("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[d.price,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs text-primary",children:[d.yesPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs text-secondary",children:[d.noPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:d.count})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:d.createdAt})})]},d.key))})]})}),(a||s)&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2",children:[jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",isDisabled:!a,onPress:l,startContent:jsxRuntime.jsx(ui.ChevronLeftIcon,{className:"h-3 w-3"}),children:i("predict.pagination.prev")}),jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:i("predict.pagination.page",{page:n})}),jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",isDisabled:!s,onPress:o,endContent:jsxRuntime.jsx(ui.ChevronRightIcon,{className:"h-3 w-3"}),children:i("predict.pagination.next")})]})]})]})}function xx({ticker:e,pageSize:t}={}){let{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:l,nextPage:i,prevPage:c}=Hn({ticker:e,pageSize:t});return jsxRuntime.jsx(Vn,{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:l,onNextPage:i,onPrevPage:c})}function zn(e={}){let t=react.useMemo(()=>({totalValue:0,totalUnrealizedPnl:0,totalRealizedPnl:0,count:0}),[]);return {positions:[],isLoading:false,isFetching:false,summary:t}}var ot=e=>utils.formatAmountUSDCompact(e/100);function Yt({value:e}){if(e===0)return jsxRuntime.jsx("span",{className:"text-default-500",children:ot(0)});let t=e>0;return jsxRuntime.jsxs("span",{className:t?"text-success":"text-danger",children:[t?"+":"",ot(e)]})}function Yn({positions:e,isLoading:t,summary:r,onSell:n}){let{t:s}=i18n.useTranslation(),a=react.useMemo(()=>e.map(o=>({key:`${o.marketId}-${o.outcome}`,marketTitle:o.marketTitle,outcome:o.outcome,quantity:o.quantity,avgCost:o.avgCostBasis,currentPrice:o.currentPrice,value:o.currentPrice*o.quantity,unrealizedPnl:o.unrealizedPnl,position:o})),[e]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.positions.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,l)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},l))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxRuntime.jsxs("span",{className:"text-sm font-medium",children:[s("predict.positions.title"),e.length>0&&jsxRuntime.jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]})}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.positions.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto",children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Positions",className:"min-w-[640px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Market",width:200,children:s("predict.positions.market")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Outcome",width:60,children:s("predict.positions.outcome")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Qty",width:50,children:s("predict.positions.qty")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Avg Cost",width:70,children:s("predict.positions.avgCost")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:60,children:s("predict.positions.currentPrice")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Value",width:80,children:s("predict.positions.value")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"PnL",width:80,children:s("predict.positions.pnl")})]}),jsxRuntime.jsx(ui.TableBody,{children:a.map(o=>jsxRuntime.jsxs(ui.TableRow,{className:n?"cursor-pointer hover:bg-default-50":"",onClick:()=>n?.(o.position),children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs font-medium line-clamp-1",children:o.marketTitle})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:o.quantity})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.avgCost,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.currentPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:ot(o.value)})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:jsxRuntime.jsx(Yt,{value:o.unrealizedPnl})})})]},o.key))})]})}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2 text-xs",children:[jsxRuntime.jsx("div",{className:"flex items-center gap-x-4",children:jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.totalValue"),":"," ",jsxRuntime.jsx("span",{className:"font-medium text-foreground",children:ot(r.totalValue)})]})}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-4",children:[jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.unrealizedPnl"),":"," ",jsxRuntime.jsx(Yt,{value:r.totalUnrealizedPnl})]}),jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.realizedPnl"),":"," ",jsxRuntime.jsx(Yt,{value:r.totalRealizedPnl})]})]})]})]})]})}function Bx({refetchInterval:e,onSell:t}={}){let{positions:r,isLoading:n,summary:s}=zn({});return jsxRuntime.jsx(Yn,{positions:r,isLoading:n,summary:s,onSell:t})}function rb({client:e,wsClient:t=null,children:r}){let n=react.useMemo(()=>({client:e,wsClient:t}),[e,t]);return jsxRuntime.jsx(Oe.Provider,{value:n,children:r})}var xc=3e4;function lb({walletAddress:e,pollingInterval:t=xc,enabled:r=true,children:n}){let{data:s,isLoading:a,error:o,refetch:l}=cr({walletAddress:e},{enabled:r&&!!e,refetchInterval:t}),i=react.useMemo(()=>({positions:s?.positions??[],usdcBalance:s?.usdcBalance??0,isLoading:a,error:o??null,refetch:l}),[s?.positions,s?.usdcBalance,a,o,l]);return jsxRuntime.jsx(me.Provider,{value:i,children:n})}function Gn(e,t){let r=new URLSearchParams;t&&r.set("provider",t);for(let[s,a]of Object.entries(e))a!=null&&(typeof a=="object"?r.set(s,JSON.stringify(a)):r.set(s,String(a)));let n=r.toString();return n?`?${n}`:""}function jn(e){return e}var Fe=class{constructor(t,r){this.endpoint=t;this.provider=r;}buildUrl(t,r){let n=Gn(r??{},this.provider);return `${this.endpoint}${t}${n}`}async fetch(t,r){let n=this.buildUrl(t,r);return await utils.httpGet(n)}async postRequest(t,r,n){let s=this.buildUrl(t,n);return await utils.httpPost(s,r)}};function at(e,t){if(!e)return [];let r=Object.entries(e).map(([n,s])=>({price:parseFloat(n),quantity:s}));return r.sort((n,s)=>t==="desc"?s.price-n.price:n.price-s.price),r}function Xn(e){return {yesBids:at(e.yes_bids,"desc"),yesAsks:at(e.yes_asks,"asc"),noBids:at(e.no_bids,"desc"),noAsks:at(e.no_asks,"asc"),sequence:e.sequence}}var it=class extends Fe{constructor(t){super(t,"dflow");}async getEvents(t){return await this.fetch("/v2/event",t??{})}async getEventById(t,r){return await this.fetch(`/v2/event/${t}`,{withNestedMarkets:r})}async getEventCandlesticks(t,r){return await this.fetch(`/v2/event/${t}/candlesticks`,r)}async getEventForecastPercentileHistory(t){let{seriesTicker:r,eventId:n,...s}=t;return await this.fetch(`/v2/event/${r}/${n}/forecast_percentile_history`,s)}async getEventForecastPercentileHistoryByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/event/by-mint/${r}/forecast_percentile_history`,n)}async getMarkets(t){return await this.fetch("/v2/market",t??{})}async getMarketById(t){return await this.fetch(`/v2/market/${t}`)}async getMarketByMint(t){return await this.fetch(`/v2/market/by-mint/${t}`)}async getMarketsBatch(t){return await this.postRequest("/v2/market/batch",t)}async getMarketCandlesticks(t,r){return await this.fetch(`/v2/market/${t}/candlesticks`,r)}async getMarketCandlesticksByMint(t,r){return await this.fetch(`/v2/market/by-mint/${t}/candlesticks`,r)}async getOrderbook(t){let r=await this.fetch(`/v2/orderbook/${t}`);return Xn(r)}async getOrderbookByMint(t){let r=await this.fetch(`/v2/orderbook/by-mint/${t}`);return Xn(r)}async getTrades(t){return await this.fetch("/v2/trades",t??{})}async getTradesByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/trades/by-mint/${r}`,n)}async getOnchainTradesByWallet(t){let{walletAddress:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-wallet/${r}`,n)}async getOnchainTradesByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-event/${r}`,n)}async getOnchainTradesByMarket(t){let{marketTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-market/${r}`,n)}async getLiveData(t){return await this.fetch("/v2/live",{milestoneIds:t.milestoneIds.join(",")})}async getLiveDataByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/live/event/${r}`,n)}async getLiveDataByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/live/by-mint/${r}`,n)}async getSeries(t){return await this.fetch("/v2/series",t??{})}async getSeriesByTicker(t){return await this.fetch(`/v2/series/${t}`)}async getTagsByCategories(){return await this.fetch("/v2/tags/by_categories")}async getFiltersBySports(){return await this.fetch("/v2/sports/filters")}async search(t){return await this.fetch("/v2/search",t)}async getPositionsByWallet(t){let{walletAddress:r}=t;return await this.fetch(`/v2/positions/by-wallet/${r}`)}async getOutcomeMints(t){return await this.fetch("/v2/outcome_mints",t??{})}async filterOutcomeMints(t){return await this.postRequest("/v2/filter_outcome_mints",t)}async getQuote(t){return await this.fetch("/v2/swap/quote",t)}async createSwap(t){return await this.postRequest("/v2/swap",t)}async createSwapInstructions(t){return await this.postRequest("/v2/swap/instructions",t)}async getOrder(t){return await this.fetch("/v2/order",t)}async getOrderStatus(t){try{return await this.fetch("/v2/order/status",t)}catch(r){if(r instanceof Error&&/\b404\b/.test(r.message))return {status:"pending",inAmount:"0",outAmount:"0"};throw r}}async getIntentQuote(t){return await this.fetch("/v2/intent/quote",t)}async submitIntentSwap(t){return await this.postRequest("/v2/intent/swap",t)}async initPredictionMarket(t){return await this.fetch("/v2/prediction-market/init",t)}async getTokens(){return await this.fetch("/v2/tokens")}async getTokensWithDecimals(){return await this.fetch("/v2/tokens/decimals")}async getVenues(){return await this.fetch("/v2/venues")}};
2
- exports.BasePredictClient=Fe;exports.CHART_RANGE_DURATION=Je;exports.CHART_RANGE_PERIOD=Xe;exports.CHART_RANGE_SAMPLE_INTERVAL=Ze;exports.CandlestickPeriod=je;exports.CategoriesSkeleton=Rr;exports.CategoriesUI=Or;exports.CategoriesWidget=Qr;exports.ChartRange=T;exports.DEFAULT_CHART_RANGE=fe;exports.DEFAULT_PAGE_SIZE=Pe;exports.DEFAULT_PRICE_HISTORY_INTERVAL=um;exports.DflowPredictClient=it;exports.DflowPredictWsClient=Le;exports.EventDetailPage=fg;exports.EventDetailSkeleton=Ae;exports.EventDetailUI=In;exports.EventDetailWidget=$t;exports.EventItemSkeleton=ma;exports.EventItemUI=Wr;exports.EventMarketDetailWidget=kn;exports.EventsPage=Vm;exports.EventsSkeleton=Lr;exports.EventsUI=qr;exports.EventsWidget=Hr;exports.MAX_PRICE_HISTORY_MARKETS=ye;exports.ORDER_MAX_PRICE=cm;exports.ORDER_MIN_PRICE=lm;exports.ORDER_MIN_QUANTITY=Mt;exports.ORDER_PRICE_STEP=im;exports.OpenOrdersUI=qn;exports.OpenOrdersWidget=Jg;exports.OrderBookUI=Wn;exports.OrderBookWidget=Ag;exports.PRICE_HISTORY_SAMPLE_INTERVAL=dm;exports.PositionsUI=Yn;exports.PositionsWidget=Bx;exports.PredictClient=it;exports.PredictContext=Oe;exports.PredictProvider=rb;exports.PredictWsClient=Le;exports.PriceHistoryInterval=Ne;exports.TradeFormSkeleton=Xr;exports.TradeFormUI=jr;exports.TradeFormWidget=Qt;exports.TradeHistoryUI=Vn;exports.TradeHistoryWidget=xx;exports.UserPredictContext=me;exports.UserPredictProvider=lb;exports.buildQuery=Gn;exports.createDflowPredictWsClient=Ye;exports.createPredictWsClient=Ye;exports.createSwap=Qo;exports.createSwapInstructions=Bo;exports.eventByIdQueryKey=hs;exports.eventCandlesticksQueryKey=zs;exports.eventsInfiniteQueryKey=xs;exports.eventsQueryKey=fs;exports.fetchEventById=vs;exports.fetchEventCandlesticks=Ys;exports.fetchEvents=pt;exports.fetchFiltersBySports=fo;exports.fetchForecastPercentileHistory=Zs;exports.fetchForecastPercentileHistoryByMint=eo;exports.fetchIntentQuote=qo;exports.fetchLiveData=ro;exports.fetchLiveDataByEvent=so;exports.fetchLiveDataByMint=ao;exports.fetchMarketById=Ms;exports.fetchMarketByMint=Rs;exports.fetchMarketCandlesticks=kt;exports.fetchMarketCandlesticksByMint=js;exports.fetchMarkets=Cs;exports.fetchMarketsBatch=Is;exports.fetchOnchainTradesByEvent=ft;exports.fetchOnchainTradesByMarket=gt;exports.fetchOnchainTradesByWallet=yt;exports.fetchOrder=Uo;exports.fetchOrderBook=Bs;exports.fetchOrderBookByMint=Us;exports.fetchOrderStatus=Do;exports.fetchOutcomeMints=Oo;exports.fetchPositionsByWallet=ko;exports.fetchQuote=Io;exports.fetchSearch=bo;exports.fetchSeries=lo;exports.fetchSeriesByTicker=uo;exports.fetchTagsByCategories=mo;exports.fetchTokens=zo;exports.fetchTokensWithDecimals=Go;exports.fetchTrades=Ds;exports.fetchTradesByMint=_s;exports.fetchVenues=Zo;exports.filterOutcomeMints=Ro;exports.filtersBySportsQueryKey=yo;exports.forecastPercentileHistoryByMintQueryKey=Js;exports.forecastPercentileHistoryQueryKey=Xs;exports.initPredictionMarket=$o;exports.intentQuoteQueryKey=Fo;exports.liveDataByEventQueryKey=no;exports.liveDataByMintQueryKey=oo;exports.liveDataQueryKey=to;exports.marketByIdQueryKey=Ts;exports.marketByMintQueryKey=Os;exports.marketCandlesticksByMintQueryKey=Gs;exports.marketCandlesticksQueryKey=vt;exports.marketsBatchQueryKey=Es;exports.marketsQueryKey=Ps;exports.onchainTradesByEventInfiniteQueryKey=$s;exports.onchainTradesByEventQueryKey=qs;exports.onchainTradesByMarketInfiniteQueryKey=Vs;exports.onchainTradesByMarketQueryKey=Ks;exports.onchainTradesByWalletInfiniteQueryKey=Hs;exports.onchainTradesByWalletQueryKey=Fs;exports.orderBookByMintQueryKey=Ls;exports.orderBookQueryKey=Qs;exports.orderQueryKey=Lo;exports.orderStatusQueryKey=Ao;exports.outcomeMintsQueryKey=wo;exports.positionsByWalletQueryKey=vo;exports.quoteQueryKey=Eo;exports.searchQueryKey=xo;exports.seriesByTickerQueryKey=co;exports.seriesQueryKey=io;exports.submitIntentSwap=Ko;exports.tagsByCategoriesQueryKey=po;exports.toRecord=jn;exports.tokensQueryKey=Vo;exports.tokensWithDecimalsQueryKey=Yo;exports.tradesByMintQueryKey=Ws;exports.tradesQueryKey=As;exports.useCategoriesQuery=ju;exports.useCreateSwapInstructionsMutation=Sd;exports.useCreateSwapMutation=Cd;exports.useEventByIdQuery=ze;exports.useEventCandlesticksQuery=Ru;exports.useEventDetail=Zr;exports.useEvents=Br;exports.useEventsCategories=Tr;exports.useEventsInfiniteQuery=Jt;exports.useEventsQuery=Uc;exports.useFilterOutcomeMintsMutation=fd;exports.useFiltersBySportsQuery=Gu;exports.useForecastPercentileHistoryByMintQuery=Uu;exports.useForecastPercentileHistoryQuery=Lu;exports.useInitPredictionMarketMutation=Ud;exports.useIntentQuoteQuery=Ed;exports.useLiveDataByEventQuery=Fu;exports.useLiveDataByMintQuery=qu;exports.useLiveDataQuery=_u;exports.useMarketByIdQuery=Xc;exports.useMarketByMintQuery=tu;exports.useMarketCandlesticksByMintQuery=Nu;exports.useMarketCandlesticksQuery=Pt;exports.useMarketPositions=ur;exports.useMarketsBatchQuery=ou;exports.useMarketsQuery=zc;exports.useOnchainTradesByEventInfiniteQuery=Su;exports.useOnchainTradesByEventQuery=xu;exports.useOnchainTradesByMarketInfiniteQuery=Tu;exports.useOnchainTradesByMarketQuery=bu;exports.useOnchainTradesByWalletInfiniteQuery=Cu;exports.useOnchainTradesByWalletQuery=nr;exports.useOpenOrders=Fn;exports.useOrderBook=Un;exports.useOrderBookByMintQuery=cu;exports.useOrderBookQuery=Re;exports.useOrderQuery=mr;exports.useOrderStatusQuery=yr;exports.useOrderbookSubscription=up;exports.useOutcomeMintsQuery=yd;exports.usePositions=zn;exports.usePositionsByWalletQuery=cr;exports.usePredictClient=h;exports.usePredictContext=Zt;exports.usePriceHistoryQuery=Eu;exports.usePricesSubscription=sp;exports.useQuoteQuery=hd;exports.useSearchQuery=ed;exports.useSeriesByTickerQuery=ir;exports.useSeriesQuery=ar;exports.useSubmitIntentSwapMutation=Id;exports.useTagsByCategoriesQuery=St;exports.useTokensQuery=_d;exports.useTokensWithDecimalsQuery=Fd;exports.useTradeForm=Vr;exports.useTradeHistory=Hn;exports.useTradesByMintQuery=mu;exports.useTradesQuery=rr;exports.useTradesSubscription=ip;exports.useUserPredictContext=id;exports.useVenuesQuery=$d;exports.useWsClient=tp;exports.useWsConnection=Xd;exports.venuesQueryKey=Xo;exports.version=us;//# sourceMappingURL=index.js.map
1
+ 'use strict';var react=require('react'),reactQuery=require('@tanstack/react-query'),i18n=require('@liberfi.io/i18n'),ui=require('@liberfi.io/ui'),jsxRuntime=require('react/jsx-runtime'),reactWindow=require('react-window'),reactWindowInfiniteLoader=require('react-window-infinite-loader'),hooks=require('@liberfi.io/hooks'),utils=require('@liberfi.io/utils'),walletConnector=require('@liberfi.io/wallet-connector'),Kt=require('canvas-confetti'),types=require('@liberfi.io/types'),react$1=require('@liberfi.io/react'),recharts=require('recharts');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Kt__default=/*#__PURE__*/_interopDefault(Kt);typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.51");var Fs="0.1.51";var et=react.createContext(null);function mr(){let e=react.useContext(et);if(!e)throw new Error("usePredictV2Context must be used within a PredictV2Provider");return e}function Ne(){let{client:e}=mr();return e}function Ks(e){return ["predict-v2","events",e??{}]}async function $s(e,t){return e.listEvents(t)}function td(e,t={}){let r=Ne();return reactQuery.useQuery({queryKey:Ks(e),queryFn:()=>$s(r,e),...t})}function Gs(e){return ["predict-v2","event",e]}async function Ys(e,t){return e.getEvent(t)}function od(e,t={}){let r=Ne();return reactQuery.useQuery({queryKey:Gs(e.slug),queryFn:()=>Ys(r,e.slug),enabled:!!e.slug,...t})}var Ie=react.createContext({});var ge=react.createContext(null);function yr(){let e=react.useContext(Ie);if(!e)throw new Error("usePredictContext must be used within a PredictProvider");return e}function h(){let{client:e}=yr();return e}function eo(e){return ["predict","events",e??{}]}async function St(e,t){return await e.getEvents(t)}function Ed(e,t={}){let r=h();return reactQuery.useQuery({queryKey:eo(e),queryFn:async()=>St(r,e),...t})}function ro(e){return ["predict","events","infinite",e??{}]}function fr(e={},t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:ro(e),queryFn:async({pageParam:n})=>St(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.cursor??void 0,...t})}function so(e){return ["predict","event","byId",e.id,e.withNestedMarkets]}async function oo(e,t){return await e.getEventById(t.id,t.withNestedMarkets)}function tt(e,t={}){let r=h();return reactQuery.useQuery({queryKey:so(e),queryFn:async()=>oo(r,e),...t})}function io(e){return ["predict","markets",e??{}]}async function lo(e,t){return await e.getMarkets(t)}function Wd(e,t={}){let r=h();return reactQuery.useQuery({queryKey:io(e),queryFn:async()=>lo(r,e),...t})}function uo(e){return ["predict","market","byId",e.id]}async function po(e,t){return await e.getMarketById(t.id)}function Vd(e,t={}){let r=h();return reactQuery.useQuery({queryKey:uo(e),queryFn:async()=>po(r,e),...t})}function yo(e){return ["predict","market","byMint",e]}async function fo(e,t){return await e.getMarketByMint(t)}function $d(e,t={}){let r=h();return reactQuery.useQuery({queryKey:yo(e),queryFn:async()=>fo(r,e),...t})}function xo(e){return ["predict","markets","batch",e]}async function vo(e,t){return await e.getMarketsBatch(t)}function jd(e,t={}){let r=h();return reactQuery.useQuery({queryKey:xo(e),queryFn:async()=>vo(r,e),enabled:!!(e.tickers?.length||e.mints?.length),...t})}function ho(e){return ["predict","orderBook",e]}async function bo(e,t){return await e.getOrderbook(t)}function Qe(e,t={}){let r=h();return reactQuery.useQuery({queryKey:ho(e),queryFn:async()=>bo(r,e),...t})}function ko(e){return ["predict","orderBook","byMint",e]}async function Po(e,t){return await e.getOrderbookByMint(t)}function ep(e,t={}){let r=h();return reactQuery.useQuery({queryKey:ko(e),queryFn:async()=>Po(r,e),...t})}function Co(e){return ["predict","trades",e??{}]}async function So(e,t){return await e.getTrades(t)}function vr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Co(e),queryFn:async()=>So(r,e),...t})}function To(e){return ["predict","trades","byMint",e]}async function Mo(e,t){return await e.getTradesByMint(t)}function sp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:To(e),queryFn:async()=>Mo(r,e),...t})}function Eo(e){return ["predict","onchainTrades","byWallet",e]}async function Mt(e,t){return await e.getOnchainTradesByWallet(t)}function hr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Eo(e),queryFn:async()=>Mt(r,e),...t})}function wo(e){return ["predict","onchainTrades","byEvent",e]}async function Et(e,t){return await e.getOnchainTradesByEvent(t)}function lp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:wo(e),queryFn:async()=>Et(r,e),...t})}function Ro(e){return ["predict","onchainTrades","byMarket",e]}async function wt(e,t){return await e.getOnchainTradesByMarket(t)}function cp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ro(e),queryFn:async()=>wt(r,e),...t})}function Ot(e){return e.cursor??void 0}function Oo(e){return ["predict","onchainTrades","byWallet","infinite",e]}function yp(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:Oo(e),queryFn:async({pageParam:n})=>Mt(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:Ot,...t})}function No(e){return ["predict","onchainTrades","byEvent","infinite",e]}function fp(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:No(e),queryFn:async({pageParam:n})=>Et(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:Ot,...t})}function Io(e){return ["predict","onchainTrades","byMarket","infinite",e]}function gp(e,t={}){let r=h();return reactQuery.useInfiniteQuery({queryKey:Io(e),queryFn:async({pageParam:n})=>wt(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:Ot,...t})}function Qo(e){return ["predict","candlesticks","event",e]}async function Bo(e,t){let{ticker:r,...n}=t;return await e.getEventCandlesticks(r,n)}function bp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Qo(e),queryFn:async()=>Bo(r,e),...t})}function It(e){return ["predict","candlesticks","market",e]}async function Qt(e,t){let{ticker:r,...n}=t;return await e.getMarketCandlesticks(r,n)}function Bt(e,t={}){let r=h();return reactQuery.useQuery({queryKey:It(e),queryFn:async()=>Qt(r,e),...t})}function Lo(e){return ["predict","candlesticks","market","byMint",e]}async function Uo(e,t){let{mintAddress:r,...n}=t;return await e.getMarketCandlesticksByMint(r,n)}function kp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Lo(e),queryFn:async()=>Uo(r,e),...t})}var Pp=Bt;function Ao(e){return ["predict","forecast","percentileHistory",e]}async function Wo(e,t){return await e.getEventForecastPercentileHistory(t)}function Mp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ao(e),queryFn:async()=>Wo(r,e),...t})}function Do(e){return ["predict","forecast","percentileHistory","byMint",e]}async function _o(e,t){return await e.getEventForecastPercentileHistoryByMint(t)}function Ep(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Do(e),queryFn:async()=>_o(r,e),...t})}function Fo(e){return ["predict","liveData",e]}async function Vo(e,t){return await e.getLiveData(t)}function Np(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Fo(e),queryFn:async()=>Vo(r,e),enabled:e.milestoneIds.length>0,...t})}function qo(e){return ["predict","liveData","byEvent",e]}async function Ho(e,t){return await e.getLiveDataByEvent(t)}function Ip(e,t={}){let r=h();return reactQuery.useQuery({queryKey:qo(e),queryFn:async()=>Ho(r,e),enabled:!!e.eventTicker,...t})}function Ko(e){return ["predict","liveData","byMint",e]}async function $o(e,t){return await e.getLiveDataByMint(t)}function Qp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ko(e),queryFn:async()=>$o(r,e),enabled:!!e.mintAddress,...t})}function zo(e){return ["predict","series",e??{}]}async function Go(e,t){return await e.getSeries(t)}function Pr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:zo(e),queryFn:async()=>Go(r,e),...t})}function Yo(e){return ["predict","series","byTicker",e]}async function jo(e,t){return await e.getSeriesByTicker(t)}function Cr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Yo(e),queryFn:async()=>jo(r,e),...t})}function Xo(){return ["predict","tags","byCategories"]}async function Zo(e){return await e.getTagsByCategories()}function Ut(e={}){let t=h();return reactQuery.useQuery({queryKey:Xo(),queryFn:async()=>Zo(t),...e})}function Jo(){return ["predict","filters","bySports"]}async function ea(e){return await e.getFiltersBySports()}function _p(e={}){let t=h();return reactQuery.useQuery({queryKey:Jo(),queryFn:async()=>ea(t),...e})}var Fp=Ut;function ra(e){return ["predict","search",e]}async function na(e,t){return await e.search(t)}function Kp(e,t={}){let r=h();return reactQuery.useQuery({queryKey:ra(e),queryFn:async()=>na(r,e),...t})}function oa(e){return ["predict","positions","byWallet",e]}async function aa(e,t){return await e.getPositionsByWallet(t)}function Tr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:oa(e),queryFn:async()=>aa(r,e),...t})}function Zp(){let e=react.useContext(ge);if(!e)throw new Error("useUserPredictContext must be used within a UserPredictProvider");return e}function Mr(e){let t=react.useContext(ge);return react.useMemo(()=>t?{positions:t.positions.filter(n=>n.market?.ticker===e.ticker),isLoading:t.isLoading,isAvailable:true}:{positions:[],isLoading:false,isAvailable:false},[t,e.ticker])}function pa(e){return ["predict","outcomeMints",e??{}]}async function ma(e,t){return await e.getOutcomeMints(t)}function om(e,t={}){let r=h();return reactQuery.useQuery({queryKey:pa(e),queryFn:async()=>ma(r,e),...t})}async function ya(e,t){return await e.filterOutcomeMints(t)}function am(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>ya(t,r),...e})}function ga(e){return ["predict","quote",e]}async function xa(e,t){return await e.getQuote(t)}function um(e,t={}){let r=h();return reactQuery.useQuery({queryKey:ga(e),queryFn:async()=>xa(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function va(e,t){return await e.createSwap(t)}function ym(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>va(t,r),...e})}async function ha(e,t){return await e.createSwapInstructions(t)}function fm(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>ha(t,r),...e})}function ba(e){return ["predict","order",e]}async function ka(e,t){return await e.getOrder(t)}function Rr(e,t={}){let r=h();return reactQuery.useQuery({queryKey:ba(e),queryFn:async()=>ka(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}function Pa(e){return ["predict","order","status",e.signature]}async function Ca(e,t){return await e.getOrderStatus(t)}function Or(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Pa(e),queryFn:async()=>Ca(r,e),enabled:!!e.signature,refetchInterval:t.refetchInterval??3e3,retry:false,...t})}function Ma(e){return ["predict","intent","quote",e]}async function Ea(e,t){return await e.getIntentQuote(t)}function Pm(e,t={}){let r=h();return reactQuery.useQuery({queryKey:Ma(e),queryFn:async()=>Ea(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function wa(e,t){return await e.submitIntentSwap(t)}function Cm(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>wa(t,r),...e})}async function Oa(e,t){return await e.initPredictionMarket(t)}function Em(e={}){let t=h();return reactQuery.useMutation({mutationFn:async r=>Oa(t,r),...e})}function Na(){return ["predict","tokens"]}async function Ia(e){return await e.getTokens()}function Nm(e={}){let t=h();return reactQuery.useQuery({queryKey:Na(),queryFn:async()=>Ia(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Qa(){return ["predict","tokens","decimals"]}async function Ba(e){return await e.getTokensWithDecimals()}function Im(e={}){let t=h();return reactQuery.useQuery({queryKey:Qa(),queryFn:async()=>Ba(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Ua(){return ["predict","venues"]}async function Aa(e){return await e.getVenues()}function Um(e={}){let t=h();return reactQuery.useQuery({queryKey:Ua(),queryFn:async()=>Aa(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}var De=class{ws=null;wsUrl;autoReconnect;reconnectIntervalBase;reconnectMaxInterval;pingInterval;status="disconnected";reconnectAttempts=0;reconnectTimeout=null;pingIntervalId=null;shouldReconnect=true;listeners={connect:[],disconnect:[],reconnecting:[],error:[],price:[],trade:[],orderbook:[],status:[],subscribed:[],unsubscribed:[]};subscriptions={prices:{all:false,tickers:new Set},trades:{all:false,tickers:new Set},orderbook:{all:false,tickers:new Set}};constructor(t){this.wsUrl=t.wsUrl,this.autoReconnect=t.autoReconnect??true,this.reconnectIntervalBase=t.reconnectIntervalBase??1e3,this.reconnectMaxInterval=t.reconnectMaxInterval??3e4,this.pingInterval=t.pingInterval??3e4,t.autoConnect!==false&&this.connect();}connect(){if(!(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))){this.shouldReconnect=true,this.setStatus("connecting");try{this.ws=new WebSocket(this.wsUrl),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus("connected"),this.emit("connect",void 0),this.restoreSubscriptions(),this.startPingInterval();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onerror=t=>{let r=new Error("WebSocket error");this.emit("error",r);},this.ws.onclose=t=>{this.stopPingInterval(),this.setStatus("disconnected"),this.emit("disconnect",{code:t.code,reason:t.reason}),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();};}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();}}}disconnect(){this.shouldReconnect=false,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus("disconnected");}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getStatus(){return this.status}subscribePrices(t,r){this.subscribeChannel("prices",t);let n=this.on("price",r);return ()=>{n(),this.unsubscribeChannel("prices",t);}}subscribeTrades(t,r){this.subscribeChannel("trades",t);let n=this.on("trade",r);return ()=>{n(),this.unsubscribeChannel("trades",t);}}subscribeOrderbook(t,r){this.subscribeChannel("orderbook",t);let n=this.on("orderbook",r);return ()=>{n(),this.unsubscribeChannel("orderbook",t);}}onStatusChange(t){return this.on("status",t)}on(t,r){return this.listeners[t].push(r),()=>{this.off(t,r);}}off(t,r){let n=this.listeners[t],s=n.indexOf(r);s!==-1&&n.splice(s,1);}removeAllListeners(t){if(t)this.listeners[t].length=0;else for(let r of Object.keys(this.listeners))this.listeners[r].length=0;}subscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=true,n.tickers.clear();else if(r.tickers&&r.tickers.length>0){n.all=false;for(let s of r.tickers)n.tickers.add(s);}this.sendSubscription("subscribe",t,r);}unsubscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=false,n.tickers.clear();else if(r.tickers&&r.tickers.length>0)for(let s of r.tickers)n.tickers.delete(s);this.sendSubscription("unsubscribe",t,r);}setStatus(t){this.status!==t&&(this.status=t,this.emit("status",t));}emit(t,r){let n=this.listeners[t];for(let s of n)try{s(r);}catch{}}send(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return false;try{return this.ws.send(JSON.stringify(t)),!0}catch{return false}}sendSubscription(t,r,n){this.send({type:t,channel:r,all:n.all,tickers:n.tickers});}handleMessage(t){try{let r=JSON.parse(t);switch(r.type){case "ticker":this.emit("price",r);break;case "trade":this.emit("trade",r);break;case "orderbook":this.emit("orderbook",r);break;case "status":break;case "subscribed":this.emit("subscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "unsubscribed":this.emit("unsubscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "pong":break;case "error":this.emit("error",new Error(r.message));break;default:if("channel"in r){let n=r;switch(n.channel){case "prices":this.emit("price",n);break;case "trades":this.emit("trade",n);break;case "orderbook":this.emit("orderbook",n);break}}}}catch{}}scheduleReconnect(){if(this.reconnectTimeout)return;let t=Math.min(this.reconnectIntervalBase*Math.pow(2,this.reconnectAttempts),this.reconnectMaxInterval);this.setStatus("reconnecting"),this.emit("reconnecting",{attempt:this.reconnectAttempts+1,delay:t}),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts++,this.connect();},t);}restoreSubscriptions(){for(let t of ["prices","trades","orderbook"]){let r=this.subscriptions[t];r.all?this.sendSubscription("subscribe",t,{all:true}):r.tickers.size>0&&this.sendSubscription("subscribe",t,{tickers:Array.from(r.tickers)});}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.send({type:"ping"});},this.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}};function rt(e){return new De(e)}function Vm({wsEndpoint:e,autoConnect:t=true,autoReconnect:r=true,enabled:n=true}){let[s,a]=react.useState("disconnected"),[o,l]=react.useState(null),i=react.useRef(null);react.useEffect(()=>{if(!n){i.current&&(i.current.disconnect(),i.current=null),a("disconnected");return}let p=rt({wsUrl:e,autoConnect:t,autoReconnect:r});i.current=p;let g=p.on("status",v=>{a(v);}),y=p.on("error",v=>{l(v);}),f=p.on("connect",()=>{l(null);});return ()=>{g(),y(),f(),p.disconnect(),i.current=null;}},[e,t,r,n]);let u=react.useCallback(()=>{i.current?.connect();},[]),c=react.useCallback(()=>{i.current?.disconnect();},[]);return {client:i.current,status:s,isConnected:s==="connected",connect:u,disconnect:c,error:o}}function $m(){let e=react.useContext(Ie);if(!e)throw new Error("useWsClient must be used within a PredictProvider");let{wsClient:t}=e,[r,n]=react.useState(t?.getStatus()??"disconnected");return react.useEffect(()=>{if(!t){n("disconnected");return}return n(t.getStatus()),t.onStatusChange(n)},[t]),{wsClient:t,wsStatus:r,isWsConnected:r==="connected"}}function Ym({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=react.useState(new Map),[l,i]=react.useState(false),u=react.useRef(s);return react.useEffect(()=>{u.current=s;},[s]),react.useEffect(()=>{if(!e||!n){i(false);return}if(!t&&r.length===0)return;let c=t?{all:true}:{tickers:r},d=e.subscribePrices(c,p=>{o(g=>{let y=new Map(g);return y.set(p.market_ticker,{yesBid:p.yes_bid,yesAsk:p.yes_ask,noBid:p.no_bid,noAsk:p.no_ask,updatedAt:Date.now()}),y}),u.current?.(p);});return i(true),()=>{d(),i(false);}},[e,t,r.join(","),n]),{prices:a,isSubscribed:l}}function Zm({client:e,all:t=false,tickers:r=[],enabled:n=true,maxHistory:s=100,onUpdate:a}){let[o,l]=react.useState([]),[i,u]=react.useState(false),c=react.useRef(a);react.useEffect(()=>{c.current=a;},[a]),react.useEffect(()=>{if(!e||!n){u(false);return}if(!t&&r.length===0)return;let p=t?{all:true}:{tickers:r},g=e.subscribeTrades(p,y=>{let f={tradeId:y.trade_id,marketTicker:y.market_ticker,price:y.price,count:y.count,yesPrice:y.yes_price,noPrice:y.no_price,takerSide:y.taker_side,createdTime:y.created_time};l(v=>{let x=[f,...v];return x.length>s?x.slice(0,s):x}),c.current?.(y);});return u(true),()=>{g(),u(false);}},[e,t,r.join(","),n,s]);let d=react.useCallback(()=>{l([]);},[]);return {trades:o,isSubscribed:i,clearHistory:d}}function ty({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=react.useState(new Map),[l,i]=react.useState(false),u=react.useRef(s);react.useEffect(()=>{u.current=s;},[s]),react.useEffect(()=>{if(!e||!n){i(false);return}if(!t&&r.length===0)return;let d=t?{all:true}:{tickers:r},p=e.subscribeOrderbook(d,g=>{o(y=>{let f=new Map(y);return f.set(g.market_ticker,{yesBids:g.yes_bids,yesAsks:g.yes_asks,noBids:g.no_bids,noAsks:g.no_asks,updatedAt:Date.now()}),f}),u.current?.(g);});return i(true),()=>{p(),i(false);}},[e,t,r.join(","),n]);let c=react.useCallback(d=>a.get(d),[a]);return {orderbooks:a,isSubscribed:l,getOrderbook:c}}var _r=["Politics","Sports","Culture","Crypto","Climate","Economics","Mentions","Companies","Financials","Tech & Science"];function Fr(){let{data:e,isLoading:t,isError:r,error:n}=Ut();return {data:react.useMemo(()=>{if(!e?.tagsByCategories)return [];let a=o=>{let l=_r.indexOf(o);return l===-1?_r.length:l};return Object.entries(e.tagsByCategories).map(([o,l])=>({category:o,tags:l})).sort((o,l)=>a(o.category)-a(l.category))},[e]),isLoading:t,isError:r,error:n??null}}function st({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:s,onTagSelect:a,className:o}){let{t:l}=i18n.useTranslation(),i=react.useCallback(()=>{s(null);},[s]);return jsxRuntime.jsxs("div",{className:ui.cn("flex w-full flex-col gap-2",o),children:[jsxRuntime.jsx(ui.HorizontalScrollContainer,{children:jsxRuntime.jsxs("div",{className:"flex items-center gap-2 px-0.5 py-1",children:[jsxRuntime.jsx(nt,{label:l("predict.categories.trending"),isSelected:t===null,onPress:i}),e.map(u=>jsxRuntime.jsx(nt,{label:u.category,isSelected:t===u.category,onPress:()=>s(u.category)},u.category))]})}),t&&n.length>0&&jsxRuntime.jsx(ui.HorizontalScrollContainer,{children:jsxRuntime.jsxs("div",{className:"flex items-center gap-2 px-0.5 py-1",children:[jsxRuntime.jsx(nt,{label:l("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>a(null),variant:"secondary"}),n.map(u=>jsxRuntime.jsx(nt,{label:u,isSelected:r===u,onPress:()=>a(u),variant:"secondary"},u))]})})]})}function nt({label:e,isSelected:t,onPress:r,variant:n="primary"}){return jsxRuntime.jsx("button",{type:"button",onClick:r,className:ui.cn("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition-colors duration-150 cursor-pointer","border whitespace-nowrap",n==="primary"?t?"bg-foreground text-background border-foreground":"bg-content1 text-foreground/70 border-default-200 hover:bg-default-100 hover:text-foreground":t?"bg-primary/15 text-primary border-primary/40":"bg-content1 text-foreground/50 border-default-100 hover:bg-default-50 hover:text-foreground/70"),children:e})}function Hr({count:e=6}){return jsxRuntime.jsx("div",{className:"flex items-center gap-2 px-0.5 py-1",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(ui.Skeleton,{className:"h-8 shrink-0 rounded-full",style:{width:`${60+Math.random()*40}px`}},r))})}function Gr({onSelect:e,className:t}){let{data:r,isLoading:n}=Fr(),[s,a]=react.useState(null),[o,l]=react.useState(null),i=react.useCallback(d=>{if(a(d),l(null),!d)e?.({category:null,tags:null});else {let p=r.find(g=>g.category===d);e?.({category:d,tags:p?.tags??null});}},[r,e]),u=react.useCallback(d=>{if(l(d),d)e?.({category:s,tags:[d]});else {let p=r.find(g=>g.category===s);e?.({category:s,tags:p?.tags??null});}},[r,s,e]);if(n)return jsxRuntime.jsx(Hr,{});let c=r.find(d=>d.category===s)?.tags??[];return jsxRuntime.jsx(st,{categories:r,selectedCategory:s,selectedTag:o,activeTags:c,onCategorySelect:i,onTagSelect:u,className:t})}var te=48,xe=4,ot={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},M={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},ve=M.ALL,at={[M.ONE_DAY]:ot.ONE_MINUTE,[M.ONE_WEEK]:ot.ONE_HOUR,[M.ONE_MONTH]:ot.ONE_HOUR,[M.ALL]:ot.ONE_DAY},it={[M.ONE_DAY]:300,[M.ONE_WEEK]:3600,[M.ONE_MONTH]:10800,[M.ALL]:1440*60},lt={[M.ONE_DAY]:1440*60,[M.ONE_WEEK]:10080*60,[M.ONE_MONTH]:720*60*60,[M.ALL]:null},Wt=1,Jy=1,ef=1,tf=99,Be={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},rf=Be.ONE_WEEK,nf={[Be.ONE_HOUR]:60,[Be.SIX_HOURS]:60,[Be.ONE_DAY]:300,[Be.ONE_WEEK]:1800,[Be.MAX]:1800};function Yr(e={}){let{category:t,tags:r,...n}=e,s=!!t||!!r&&r.length>0,{data:a,isFetching:o,isError:l,error:i}=Pr({...t?{category:t}:{},...r&&r.length>0?{tags:r.join(",")}:{},isInitialized:true,status:"active"},{enabled:s}),u=react.useMemo(()=>{if(!s||!a?.series)return;let O=a.series.map(C=>C.ticker).slice(0,25);return O.length>0?O.join(","):void 0},[s,a]),c=react.useMemo(()=>({status:"active",withNestedMarkets:true,sort:"volume24h",order:"desc",limit:48,...n,...u!==void 0?{seriesTickers:u}:{}}),[n,u]),{data:d,isLoading:p,isFetching:g,isFetchingNextPage:y,isError:f,error:v,hasNextPage:x,fetchNextPage:k,refetch:P}=fr(c),m=react.useMemo(()=>d?.pages.flatMap(O=>O.events)??[],[d]),b=s&&!a&&!l;return {data:m,isLoading:b||p,isFetching:o||b||g&&!y,isFetchingMore:y,isError:l||f,error:i??v,hasMore:x,fetchMore:k,refetch:P}}function Za({className:e}){return jsxRuntime.jsxs("div",{className:`flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 @5xl:gap-y-3 @5xl:p-4 ${e??""}`,children:[jsxRuntime.jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-8 flex-shrink-0 rounded-lg @5xl:h-12 @5xl:w-12"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-md @5xl:h-12"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-12 flex-shrink-0 rounded-lg @5xl:h-10 @5xl:w-14"})]}),jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-0.5 @5xl:gap-y-1",children:[jsxRuntime.jsxs("div",{className:"flex min-h-8 w-full items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-2/3 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-8 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-16 rounded-lg"})]})]}),jsxRuntime.jsxs("div",{className:"flex min-h-8 w-full items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-1/2 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-8 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-16 rounded-lg"})]})]})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-16 rounded-md @5xl:h-4"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded-md @5xl:h-4"})]})]})}function ct({count:e=8}){return jsxRuntime.jsx("div",{className:"@container w-full h-full",children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 gap-4 @[640px]:grid-cols-2 @[1024px]:grid-cols-3 @[1280px]:grid-cols-4",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(Za,{className:"min-h-44 @5xl:min-h-56"},r))})})}function dt({value:e,showLabel:t=true}){let r=e/100;return jsxRuntime.jsx("div",{className:"flex-shrink-0 flex flex-col items-center",children:jsxRuntime.jsxs("div",{className:"relative w-16 h-12 lg:w-20 lg:h-14",children:[jsxRuntime.jsxs("svg",{className:"w-full h-full",viewBox:"0 0 100 70",children:[jsxRuntime.jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-default-200",strokeWidth:"6",strokeLinecap:"round"}),jsxRuntime.jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-primary",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:`${r*125.6} 125.6`,style:{transition:"stroke-dasharray 0.5s ease-in-out"}})]}),t&&jsxRuntime.jsx("div",{className:"absolute inset-0 flex items-center justify-center pt-3 lg:pt-4",children:jsxRuntime.jsxs("span",{className:"text-sm font-bold text-foreground lg:text-base leading-none",children:[e.toFixed(0),"%"]})})]})})}function Zr({event:e,onSelect:t,onSelectOutcome:r}){let{t:n}=i18n.useTranslation(),[s,a]=react.useState(null),o=e.markets||[],l=o.length>2?[...o].sort((C,Q)=>Number(Q.yesAsk??0)-Number(C.yesAsk??0)):o,i=l.filter(C=>C.status==="active"),u=l.length===1,c=u?l[0]:s,d=react.useMemo(()=>utils.formatAmountUSDCompact((e.volume??0)/100),[e.volume]),p=C=>C.yesAsk?parseFloat(C.yesAsk)*100:null,g=C=>C.noAsk?parseFloat(C.noAsk)*100:null,y=C=>{let Q=p(C),A=g(C);return Q!=null?A==null&&Q<=1?"< 1%":v(Q):A!=null?A<=1?"> 99%":v(100-A):"0%"},f=C=>{let Q=p(C),A=g(C);return A!=null?Q==null&&A<=1?"< 1%":v(A):Q!=null?Q<=1?"> 99%":v(100-Q):"0%"},v=C=>C!=null?`${C.toFixed(0)}%`:"--",x=react.useMemo(()=>{let C=l.some(A=>A.status==="active");return l.every(A=>A.status==="closed"||A.status==="determined")?{label:n("predict.event.status.closed"),color:"bg-danger-100/50 text-danger"}:C?{label:n("predict.event.status.live"),color:"bg-primary-100/50 text-primary"}:{label:n("predict.event.status.pending"),color:"bg-warning-100/50 text-warning"}},[l,n]),k=C=>{a(C);},P=()=>{a(null);},m=()=>{c&&r&&r(e,c,"yes");},b=()=>{c&&r&&r(e,c,"no");},S=()=>{t&&t(e);},R=i.slice(0,2),O=i.length>2;return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 transition-all duration-300 cursor-pointer hover:border-primary hover:ring-2 hover:ring-primary/20 focus-within:border-primary focus-within:bg-content2 focus-within:ring-2 focus-within:ring-primary/20 @5xl:gap-y-3 @5xl:p-4",onClick:S,children:[jsxRuntime.jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntime.jsx(ui.Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"md",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover:scale-110 @5xl:h-12 @5xl:w-12"}),jsxRuntime.jsx(ui.StyledTooltip,{content:e.title,placement:"bottom",children:jsxRuntime.jsx("p",{className:"flex-1 min-w-0 h-10 @5xl:h-12 text-sm font-semibold @5xl:text-base line-clamp-2",children:e.title})}),u?jsxRuntime.jsx(dt,{value:p(l[0])??50}):x.label!==n("predict.event.status.live")&&jsxRuntime.jsx("div",{className:`flex-shrink-0 flex items-center gap-x-2 rounded-lg px-2 py-1 text-sm @5xl:px-4 @5xl:py-2 ${x.color}`,children:jsxRuntime.jsx("span",{children:x.label})})]}),c&&!u&&jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:C=>{C.stopPropagation(),P();},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:c.yesSubTitle}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-sm font-semibold text-foreground @5xl:text-lg",children:y(c)}),jsxRuntime.jsx(ui.ChevronUpIcon,{className:"w-3 h-3 text-default-500 @5xl:w-4 @5xl:h-4"})]})]}),!c&&!u&&R.length>0&&jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-0.5 text-xs @5xl:gap-y-1 @5xl:text-sm",children:[R.map(C=>jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:Q=>{Q.stopPropagation(),k(C);},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:C.yesSubTitle}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-xs text-foreground @5xl:text-base",children:y(C)}),jsxRuntime.jsxs("div",{className:"flex h-full items-center gap-x-3 rounded-lg p-1 @5xl:p-1.5 bg-gradient-to-r from-primary-50/20 via-primary-50/20 to-secondary-50/20",children:[jsxRuntime.jsx("span",{className:"text-primary",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"text-default-400",children:"/"}),jsxRuntime.jsx("span",{className:"text-secondary",children:n("predict.market.no")})]})]})]},C.ticker)),O&&jsxRuntime.jsx("span",{className:"text-xxs text-default-500 @5xl:text-xs",children:n("predict.event.moreMarkets",{count:i.length-2})})]}),c&&jsxRuntime.jsxs("div",{className:`flex items-center gap-x-2 text-sm @5xl:text-base ${u?"mt-3":""}`,children:[jsxRuntime.jsxs(ui.Button,{color:"primary",fullWidth:true,className:"group/yes bg-primary-100 text-primary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:m,children:[jsxRuntime.jsx("span",{className:"group-hover/yes:hidden",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"hidden group-hover/yes:inline",children:y(c)})]}),jsxRuntime.jsxs(ui.Button,{color:"secondary",fullWidth:true,className:"group/no bg-secondary-100 text-secondary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:b,children:[jsxRuntime.jsx("span",{className:"group-hover/no:hidden",children:n("predict.market.no")}),jsxRuntime.jsx("span",{className:"hidden group-hover/no:inline",children:f(c)})]})]})]}),!c||u?jsxRuntime.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),S();},children:[jsxRuntime.jsx("span",{children:n("predict.event.showMore")}),jsxRuntime.jsx(ui.ChevronRightIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"})]}),jsxRuntime.jsxs("span",{className:"text-xxs text-default-600 @5xl:text-xs",children:[d," ",n("predict.event.volume")]})]}):jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),P();},children:[jsxRuntime.jsx(ui.ChevronLeftIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"}),jsxRuntime.jsx("span",{children:n("predict.event.back")})]})]})}var pi=640,mi=768,en=1024,yi=1280,fi=16,gi=192,xi=228,vi=244;function hi(e){return e>=yi?4:e>=en?3:e>=pi?2:1}function bi(e){return e>=en?vi:e>=mi?xi:gi}function tn({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s}){let a=react.useRef(null),{width:o=0,height:l=0}=hooks.useResizeObserver({ref:a}),i=hi(o),u=bi(o),c=Math.ceil(e.length/i)||0,d=t?c+1:c,p=react.useCallback(f=>f<c,[c]),g=react.useCallback(async()=>{r?.();},[r]),y=reactWindowInfiniteLoader.useInfiniteLoader({isRowLoaded:p,loadMoreRows:g,rowCount:d,threshold:3});return jsxRuntime.jsx("div",{ref:a,className:"@container w-full h-full",children:l>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:l},onRowsRendered:y,rowComponent:ki,rowCount:d,rowHeight:u,rowProps:{events:e,columnCount:i,dataRowCount:c,gap:fi,onSelect:n,onSelectOutcome:s}})})}function ki({index:e,style:t,events:r,columnCount:n,dataRowCount:s,gap:a,onSelect:o,onSelectOutcome:l}){if(e>=s)return jsxRuntime.jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsxRuntime.jsx(ui.Spinner,{size:"sm"})});let i=e*n,u=r.slice(i,i+n),c=n-u.length,d={display:"flex",gap:a,height:`calc(100% - ${a}px)`};return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:d,children:[u.map(p=>jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsx(Zr,{event:p,onSelect:o,onSelectOutcome:l})},p.ticker)),c>0&&Array.from({length:c}).map((p,g)=>jsxRuntime.jsx("div",{style:{flex:1,minWidth:0}},`spacer-${g}`))]})})}function nn({onSelect:e,onSelectOutcome:t,...r}){let{data:n,hasMore:s,fetchMore:a,isFetching:o}=Yr({limit:48,...r});return o?jsxRuntime.jsx(ct,{count:48}):jsxRuntime.jsx(tn,{events:n,hasMore:s,onFetchMore:a,onSelect:e,onSelectOutcome:t})}function Df({onSelect:e,onSelectOutcome:t}){let[r,n]=react.useState({category:null,tags:null}),s=react.useCallback(a=>{n(a);},[]);return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsxRuntime.jsx(Gr,{onSelect:s}),jsxRuntime.jsx("div",{className:"min-h-0 flex-1",children:jsxRuntime.jsx(nn,{category:r.category,tags:r.tags,onSelect:e,onSelectOutcome:t})})]})}var Mi={"Climate and Weather":["Daily temperature","Snow and rain","Climate change","Natural disasters","Hurricanes"],Companies:["IPOs","Product launches","KPIs","Elon Musk","CEOs","Layoffs"],Crypto:["BTC","15 min","Hourly","ETH","SOL","DOGE","Pre-Market","XRP","BNB","HYPE"],Economics:["Growth","Fed","Inflation","Oil and energy","Employment","Housing","Jobs & Economy","Bankruptcy & Defaults","GDP","Global Central Banks"],Elections:["Primaries","International elections"],Entertainment:["Music","Movies","Music charts","Television","Awards","Video games","Oscars","Rotten Tomatoes"],Financials:["S&P","Nasdaq","Daily","Metals","Treasuries","Oil","EUR/USD","USD/JPY","WTI"],Mentions:["Politicians","Earnings","Entertainment"],Politics:["Trump","Congress","International","SCOTUS & courts","Local","Recurring","Iran","House"],"Science and Technology":["AI","Energy","Space"],Social:null,Sports:["Soccer","Basketball","Baseball","Football","Hockey","Golf","Tennis","Motorsport","Esports","Boxing","MMA","Rugby","Lacrosse","Mentions","Chess","Cricket","Aussie Rules","Darts"],World:null},sn=["Politics","Sports","Crypto","Economics","Financials","Elections","Entertainment","Companies","Science and Technology","Climate and Weather","Mentions","Social","World"],Vt=(()=>{let e=t=>{let r=sn.indexOf(t);return r===-1?sn.length:r};return Object.entries(Mi).map(([t,r])=>({slug:t,label:t,tags:(r??[]).map(n=>({slug:n,label:n}))})).sort((t,r)=>e(t.slug)-e(r.slug))})();function Ei(e){return e.map(t=>({category:t.label,tags:t.tags.map(r=>r.label)}))}function ln({onSelect:e,className:t}){let[r,n]=react.useState(null),[s,a]=react.useState(null),o=react.useCallback(c=>{n(c),a(null),e?.({categorySlug:c,tagSlug:null});},[e]),l=react.useCallback(c=>{a(c),e?.({categorySlug:r,tagSlug:c});},[r,e]),i=Ei(Vt),u=Vt.find(c=>c.slug===r)?.tags.map(c=>c.label)??[];return jsxRuntime.jsx(st,{categories:i,selectedCategory:r,selectedTag:s,activeTags:u,onCategorySelect:o,onTagSelect:l,className:t})}function Oi(e){if(e)return e.tagSlug??e.categorySlug??void 0}function Ni(e){return ["predict-v2","events-infinite",e]}function dn(e={}){let{tagSlugSelection:t,limit:r=48,status:n="open",sort_by:s,sort_asc:a,with_markets:o=true}=e,l=Ne(),i=react.useMemo(()=>{let b=Oi(t);return {limit:r,status:n,with_markets:o,...b?{tag_slug:b}:{},...s?{sort_by:s}:{},...a!==void 0?{sort_asc:a}:{}}},[t,r,n,s,a,o]),{data:u,isLoading:c,isFetching:d,isFetchingNextPage:p,isError:g,error:y,hasNextPage:f,fetchNextPage:v,refetch:x}=reactQuery.useInfiniteQuery({queryKey:Ni(i),queryFn:({pageParam:b})=>l.listEvents({...i,...b!==void 0?{cursor:b}:{}}),initialPageParam:void 0,getNextPageParam:b=>b.has_more&&b.next_cursor?b.next_cursor:void 0}),k=react.useMemo(()=>u?.pages.flatMap(b=>b.items).filter(b=>b!=null)??[],[u]),P=react.useCallback(()=>{v();},[v]),m=react.useCallback(()=>{x();},[x]);return {data:k,isLoading:c,isFetching:d&&!p,isFetchingMore:p,isError:g,error:y??null,hasMore:f??false,fetchMore:P,refetch:m}}function _e(e){let t=e.outcomes?.[0];return t?t.best_ask??t.price??null:null}function yn(e){let t=e.outcomes?.[1];return t?t.best_ask??t.price??null:null}function Fe(e){return e!=null?e*100:null}function pt(e){return e!=null?`${e.toFixed(0)}%`:"--"}function qt(e){let t=Fe(_e(e)),r=Fe(yn(e));return t!=null?r==null&&t<=1?"< 1%":pt(t):r!=null?r<=1?"> 99%":pt(100-r):"0%"}function _i(e){let t=Fe(_e(e)),r=Fe(yn(e));return r!=null?t==null&&r<=1?"< 1%":pt(r):t!=null?t<=1?"> 99%":pt(100-t):"0%"}function fn({event:e,onSelect:t,onSelectOutcome:r}){let{t:n}=i18n.useTranslation(),[s,a]=react.useState(null),o=e.markets??[],l=o.length>2?[...o].sort((m,b)=>(_e(b)??0)-(_e(m)??0)):o,i=l.filter(m=>m.status==="open"),u=l.length===1,c=u?l[0]:s,d=react.useMemo(()=>utils.formatAmountUSDCompact(e.volume??0),[e.volume]),p=react.useMemo(()=>{let m=l.some(S=>S.status==="open");return l.every(S=>S.status==="closed"||S.status==="voided")?{label:n("predict.event.status.closed"),color:"bg-danger-100/50 text-danger"}:m?{label:n("predict.event.status.live"),color:"bg-primary-100/50 text-primary"}:{label:n("predict.event.status.pending"),color:"bg-warning-100/50 text-warning"}},[l,n]),g=m=>{a(m);},y=()=>{a(null);},f=()=>{c&&r&&r(e,c,"yes");},v=()=>{c&&r&&r(e,c,"no");},x=()=>{t?.(e);},k=i.slice(0,2),P=i.length>2;return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 transition-all duration-300 cursor-pointer hover:border-primary hover:ring-2 hover:ring-primary/20 focus-within:border-primary focus-within:bg-content2 focus-within:ring-2 focus-within:ring-primary/20 @5xl:gap-y-3 @5xl:p-4",onClick:x,children:[jsxRuntime.jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntime.jsx(ui.Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"md",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover:scale-110 @5xl:h-12 @5xl:w-12"}),jsxRuntime.jsx(ui.StyledTooltip,{content:e.title,placement:"bottom",children:jsxRuntime.jsx("p",{className:"flex-1 min-w-0 h-10 @5xl:h-12 text-sm font-semibold @5xl:text-base line-clamp-2",children:e.title})}),u?jsxRuntime.jsx(dt,{value:Fe(_e(l[0]))??50}):p.label!==n("predict.event.status.live")&&jsxRuntime.jsx("div",{className:`flex-shrink-0 flex items-center gap-x-2 rounded-lg px-2 py-1 text-sm @5xl:px-4 @5xl:py-2 ${p.color}`,children:jsxRuntime.jsx("span",{children:p.label})})]}),c&&!u&&jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:m=>{m.stopPropagation(),y();},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:c.question}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-sm font-semibold text-foreground @5xl:text-lg",children:qt(c)}),jsxRuntime.jsx(ui.ChevronUpIcon,{className:"w-3 h-3 text-default-500 @5xl:w-4 @5xl:h-4"})]})]}),!c&&!u&&k.length>0&&jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-0.5 text-xs @5xl:gap-y-1 @5xl:text-sm",children:[k.map(m=>jsxRuntime.jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:b=>{b.stopPropagation(),g(m);},children:[jsxRuntime.jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:m.question}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("span",{className:"text-xs text-foreground @5xl:text-base",children:qt(m)}),jsxRuntime.jsxs("div",{className:"flex h-full items-center gap-x-3 rounded-lg p-1 @5xl:p-1.5 bg-gradient-to-r from-primary-50/20 via-primary-50/20 to-secondary-50/20",children:[jsxRuntime.jsx("span",{className:"text-primary",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"text-default-400",children:"/"}),jsxRuntime.jsx("span",{className:"text-secondary",children:n("predict.market.no")})]})]})]},m.slug)),P&&jsxRuntime.jsx("span",{className:"text-xxs text-default-500 @5xl:text-xs",children:n("predict.event.moreMarkets",{count:i.length-2})})]}),c&&jsxRuntime.jsxs("div",{className:`flex items-center gap-x-2 text-sm @5xl:text-base ${u?"mt-3":""}`,children:[jsxRuntime.jsxs(ui.Button,{color:"primary",fullWidth:true,className:"group/yes bg-primary-100 text-primary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:f,children:[jsxRuntime.jsx("span",{className:"group-hover/yes:hidden",children:n("predict.market.yes")}),jsxRuntime.jsx("span",{className:"hidden group-hover/yes:inline",children:qt(c)})]}),jsxRuntime.jsxs(ui.Button,{color:"secondary",fullWidth:true,className:"group/no bg-secondary-100 text-secondary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:v,children:[jsxRuntime.jsx("span",{className:"group-hover/no:hidden",children:n("predict.market.no")}),jsxRuntime.jsx("span",{className:"hidden group-hover/no:inline",children:_i(c)})]})]})]}),!c||u?jsxRuntime.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:m=>{m.stopPropagation(),x();},children:[jsxRuntime.jsx("span",{children:n("predict.event.showMore")}),jsxRuntime.jsx(ui.ChevronRightIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"})]}),jsxRuntime.jsxs("span",{className:"text-xxs text-default-600 @5xl:text-xs",children:[d," ",n("predict.event.volume")]})]}):jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:m=>{m.stopPropagation(),y();},children:[jsxRuntime.jsx(ui.ChevronLeftIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"}),jsxRuntime.jsx("span",{children:n("predict.event.back")})]})]})}var $i=640,zi=768,xn=1024,Gi=1280,Yi=16,ji=192,Xi=228,Zi=244;function Ji(e){return e>=Gi?4:e>=xn?3:e>=$i?2:1}function el(e){return e>=xn?Zi:e>=zi?Xi:ji}function vn({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s}){let a=react.useRef(null),{width:o=0,height:l=0}=hooks.useResizeObserver({ref:a}),i=Ji(o),u=el(o),c=Math.ceil(e.length/i)||0,d=t?c+1:c,p=react.useCallback(f=>f<c,[c]),g=react.useCallback(async()=>{r?.();},[r]),y=reactWindowInfiniteLoader.useInfiniteLoader({isRowLoaded:p,loadMoreRows:g,rowCount:d,threshold:3});return jsxRuntime.jsx("div",{ref:a,className:"@container w-full h-full",children:l>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:l},onRowsRendered:y,rowComponent:tl,rowCount:d,rowHeight:u,rowProps:{events:e,columnCount:i,dataRowCount:c,gap:Yi,onSelect:n,onSelectOutcome:s}})})}function tl({index:e,style:t,events:r,columnCount:n,dataRowCount:s,gap:a,onSelect:o,onSelectOutcome:l}){if(e>=s)return jsxRuntime.jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsxRuntime.jsx(ui.Spinner,{size:"sm"})});let i=e*n,u=r.slice(i,i+n),c=n-u.length,d={display:"flex",gap:a,height:`calc(100% - ${a}px)`};return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:d,children:[u.map(p=>p==null?null:jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsx(fn,{event:p,onSelect:o,onSelectOutcome:l})},p.slug)),c>0&&Array.from({length:c}).map((p,g)=>jsxRuntime.jsx("div",{style:{flex:1,minWidth:0}},`spacer-${g}`))]})})}function bn({tagSlugSelection:e,limit:t=48,status:r,sort_by:n,sort_asc:s,with_markets:a,onSelect:o,onSelectOutcome:l}){let{data:i,hasMore:u,fetchMore:c,isFetching:d}=dn({tagSlugSelection:e,limit:t,status:r,sort_by:n,sort_asc:s,with_markets:a});return d?jsxRuntime.jsx(ct,{count:48}):jsxRuntime.jsx(vn,{events:i,hasMore:u,onFetchMore:c,onSelect:o,onSelectOutcome:l})}function Cg({onSelect:e,onSelectOutcome:t}){let[r,n]=react.useState({categorySlug:null,tagSlug:null}),s=react.useCallback(a=>{n(a);},[]);return jsxRuntime.jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsxRuntime.jsx(ln,{onSelect:s}),jsxRuntime.jsx("div",{className:"min-h-0 flex-1",children:jsxRuntime.jsx(bn,{tagSlugSelection:r,onSelect:e,onSelectOutcome:t})})]})}function zt(e,t,r){let n=e[t];return n?r==="yes"?n.yesMint:n.noMint:null}var Ve=utils.SOLANA_TOKENS.stablecoins.USDC.address;function pl(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Kt__default.default({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Kt__default.default({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Kt__default.default({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function Pn({market:e,chain:t="solana",initialOutcome:r="yes",initialSide:n="buy"}){let{t:s}=i18n.useTranslation(),a=react.useContext(ge),{status:o}=walletConnector.useAuth(),i=walletConnector.useWallets().find(T=>T.chainNamespace===types.ChainNamespace.SOLANA&&T.isConnected),u=o==="authenticated",c=i?.address,[d,p]=react.useState(r),[g,y]=react.useState(n),[f,v]=react.useState(NaN),x=react.useMemo(()=>zt(e.accounts,Ve,d),[e.accounts,d]),{inputMint:k,outputMint:P}=react.useMemo(()=>g==="buy"?{inputMint:Ve,outputMint:x}:{inputMint:x,outputMint:Ve},[g,x]),m=!!k&&!!P&&f>0,b=react.useMemo(()=>Number(d==="yes"?e.yesAsk??.5:e.noAsk??.5),[d,e.yesAsk,e.noAsk]),S=react.useMemo(()=>isNaN(f)||f<=0?0:g==="buy"?b>0?f/b:0:f,[g,f,b]),R=react.useMemo(()=>isNaN(f)||f<=0?0:Math.round(f*1e6),[f]),{data:O,isLoading:C,error:Q,refetch:A}=Rr({userPublicKey:c??void 0,inputMint:k??"",outputMint:P??"",amount:R,slippageBps:100},{enabled:m}),Te=a?.usdcBalance??null,fe=a?.isLoading??false,ur=a?.refetch,le=a?.positions,Ye=react.useMemo(()=>{if(!le||!x)return null;let T=le.find(se=>se.mint===x);return T?T.balance:0},[le,x]),bt=react.useMemo(()=>zt(e.accounts,Ve,"yes"),[e.accounts]),kt=react.useMemo(()=>zt(e.accounts,Ve,"no"),[e.accounts]),Rs=react.useMemo(()=>{if(!le||!bt)return null;let T=le.find(se=>se.mint===bt);return T?T.balance:0},[le,bt]),Os=react.useMemo(()=>{if(!le||!kt)return null;let T=le.find(se=>se.mint===kt);return T?T.balance:0},[le,kt]),{data:Re}=Qe(e.ticker,{refetchInterval:5e3}),Ns=react.useMemo(()=>(d==="yes"?Re?.yesBids:Re?.noBids)?.[0]?.price??null,[Re,d]),Is=react.useMemo(()=>(d==="yes"?Re?.yesAsks:Re?.noAsks)?.[0]?.price??null,[Re,d]),Qs=react.useMemo(()=>O?.priceImpactPct?parseFloat(O.priceImpactPct):null,[O]),je=react.useMemo(()=>{if(isNaN(f)||f<=0)return 0;if(O)return parseInt(O.inAmount)/1e6;if(g==="buy")return f;let T=Number(d==="yes"?e.yesBid??0:e.noBid??0);return f*T},[O,g,d,f,e.yesBid,e.noBid]),dr=react.useMemo(()=>isNaN(f)||f<=0?0:g==="buy"?S*1:je,[g,S,je,f]),Bs=dr-je,Ls=react.useCallback(T=>{y(T),v(NaN);},[]),Us=react.useCallback(T=>{if(isNaN(T)){v(NaN);return}let se=Math.max(0,T),Je=g==="buy"?Math.round(se*100)/100:Math.round(se);v(Je);},[g]);react.useEffect(()=>{m&&A();},[f,d,g,m,A]);let Pt=react.useMemo(()=>{let T=[];return (isNaN(f)||f<Wt)&&T.push(`Minimum quantity is ${Wt}`),e.status!=="active"&&T.push("Market is not active"),g==="buy"&&Te!=null&&!isNaN(f)&&f>0&&f>Te&&T.push("Insufficient USDC balance"),g==="sell"&&Ye!=null&&!isNaN(f)&&f>0&&f>Ye&&T.push("Insufficient shares"),{isValid:T.length===0,errors:T}},[f,e.status,g,Te,Ye]),[As,Ct]=react.useState(null),[Ws,Oe]=react.useState(false),[Xe,We]=react.useState(null),{data:Ze}=Or({signature:Xe??""},{enabled:!!Xe});react.useEffect(()=>{if(!Ze||!Xe)return;let{status:T}=Ze;T==="closed"?(Oe(false),We(null),ui.toast.success(s("predict.trade.submitSuccess")),pl(),v(NaN),ur?.()):(T==="failed"||T==="expired")&&(Oe(false),We(null),ui.toast.error(s("predict.trade.submitError")));},[Ze,Xe,ur,s]);let Ds=react.useCallback(async()=>{if(!(!Pt.isValid||!u||!c||!i||fe)){Ct(null),We(null),Oe(true);try{let T=O;if(T?.transaction||(T=(await A()).data),!T?.transaction){Oe(!1);return}let se=Uint8Array.from(atob(T.transaction),pr=>pr.charCodeAt(0)),Je=await i.sendTransaction(se);Ct(Je),We(Je);}catch{ui.toast.error(s("predict.trade.submitError")),Oe(false);}}},[Pt.isValid,u,c,i,O,fe,A,s]),_s=react.useCallback(()=>{p(r),y(n),v(NaN),Ct(null),We(null),Oe(false);},[r,n]);return {outcome:d,side:g,quantity:f,shares:S,estimatedCost:je,potentialPayout:dr,potentialProfit:Bs,isAuthenticated:u,bestBid:Ns,bestAsk:Is,order:O??null,priceImpact:Qs,usdcBalance:Te,outcomeTokenBalance:Ye,yesTokenBalance:Rs,noTokenBalance:Os,isBalanceLoading:fe,isQuoteLoading:C,isSubmitting:Ws,quoteError:Q??null,txHash:As,orderStatus:Ze??null,validation:Pt,setOutcome:p,setSide:Ls,setQuantity:Us,submit:Ds,reset:_s}}var vl=`https://s1.chainstream.io/chains/sol/tokens/${utils.SOLANA_TOKENS.stablecoins.USDC.address}/image.png`;function Mn({event:e,market:t,outcome:r,side:n,quantity:s,potentialProfit:a,estimatedCost:o,usdcBalance:l,yesTokenBalance:i,noTokenBalance:u,isBalanceLoading:c,isSubmitting:d,isValid:p,onOutcomeChange:g,onSideChange:y,onQuantityChange:f,onSubmit:v}){let{t:x}=i18n.useTranslation(),k=react.useMemo(()=>{if(d)return x("predict.trade.submitting");let m=x(n==="buy"?"predict.trade.buy":"predict.trade.sell"),b=x(r==="yes"?"predict.trade.yes":"predict.trade.no");return `${m} ${b}`},[d,n,r,x]),P=react.useMemo(()=>r==="yes"?"primary":"secondary",[r]);return jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4",children:[e&&jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsxRuntime.jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxRuntime.jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsxRuntime.jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxRuntime.jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxRuntime.jsxs("span",{className:r==="yes"?"text-bullish":"text-bearish",children:[x(n==="buy"?"predict.trade.buy":"predict.trade.sell")," ",x(r==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxRuntime.jsxs("span",{className:"text-foreground",children:[" \xB7 ",r==="yes"?t.yesSubTitle:t.noSubTitle]})]})]})]}),jsxRuntime.jsxs(ui.Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:m=>y(m),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsxRuntime.jsx(ui.Tab,{title:x("predict.trade.buy")},"buy"),jsxRuntime.jsx(ui.Tab,{title:x("predict.trade.sell")},"sell")]}),jsxRuntime.jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(m=>{let b=m==="yes"?i:u;return jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col gap-y-1",children:[jsxRuntime.jsxs("button",{type:"button",onClick:()=>g(m),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${r===m?m==="yes"?"border-primary bg-primary-50 text-primary":"border-secondary bg-secondary-50 text-secondary":"border-default-400 text-foreground hover:border-default-500"}`,children:[jsxRuntime.jsx("span",{children:x(m==="yes"?"predict.trade.yes":"predict.trade.no")}),(()=>{let S=n==="buy"?m==="yes"?t.yesAsk:t.noAsk:m==="yes"?t.yesBid:t.noBid;return S!=null?jsxRuntime.jsxs("span",{className:"ml-1 opacity-70",children:[Math.round(Number(S)*100),"\xA2"]}):null})()]}),n==="sell"&&r===m&&jsxRuntime.jsx("span",{className:"text-center text-xs text-foreground",children:c?"\u2013":`${b??0} shares`})]},m)})}),n==="buy"&&jsxRuntime.jsxs("div",{className:"flex items-center justify-end gap-x-1 text-xs text-default-500",children:[jsxRuntime.jsx("img",{src:vl,alt:"USDC",className:"h-4 w-4 rounded-full object-cover"}),jsxRuntime.jsxs("span",{children:[x("predict.trade.balance"),":"]}),jsxRuntime.jsx("span",{className:"font-medium text-foreground",children:l!=null?`$${l.toFixed(2)}`:"\u2013"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:x(n==="buy"?"predict.trade.amount":"predict.trade.contracts")}),jsxRuntime.jsx(ui.StyledNumberInput,{fullWidth:true,placeholder:"0",radius:"lg",size:"lg",value:isNaN(s)?void 0:s,onValueChange:m=>{f(m);},minValue:0,step:n==="buy"?.01:1,formatOptions:n==="buy"?{maximumFractionDigits:2}:{maximumFractionDigits:0},startContent:n==="buy"?jsxRuntime.jsx("span",{className:"text-default-600 text-xl",children:"$"}):void 0,classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}},n),jsxRuntime.jsx("div",{className:"flex gap-x-2 justify-end",children:n==="buy"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[[1,5,10,100].map(m=>jsxRuntime.jsxs("button",{type:"button",onClick:()=>f(Math.round(((isNaN(s)?0:s)+m)*100)/100),className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:["+",m,"$"]},m)),jsxRuntime.jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:x("common.all")})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[[25,50].map(m=>jsxRuntime.jsxs("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:[m,"%"]},m)),jsxRuntime.jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:x("common.all")})]})})]}),!isNaN(s)&&s>0&&jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-y-0.5",children:[jsxRuntime.jsx("span",{className:"text-sm text-foreground",children:x(n==="buy"?"predict.trade.potentialWin":"predict.trade.estimatedReceive")}),jsxRuntime.jsxs("span",{className:"text-xl font-semibold text-bullish",children:["$",(n==="buy"?a:o).toFixed(2)]})]}),jsxRuntime.jsx(ui.Button,{color:P,fullWidth:true,radius:"lg",size:"lg",isDisabled:!p||d,isLoading:d,onPress:v,children:k})]})}function Gt({event:e,market:t,initialSide:r,initialOutcome:n,chain:s}){let{outcome:a,side:o,quantity:l,estimatedCost:i,potentialPayout:u,potentialProfit:c,usdcBalance:d,yesTokenBalance:p,noTokenBalance:g,isBalanceLoading:y,isSubmitting:f,validation:v,setOutcome:x,setSide:k,setQuantity:P,submit:m}=Pn({market:t,initialSide:r,initialOutcome:n,chain:s}),b=walletConnector.useAuthCallback(m);return jsxRuntime.jsx(Mn,{event:e,market:t,outcome:a,side:o,quantity:l,estimatedCost:i,potentialPayout:u,potentialProfit:c,usdcBalance:d,yesTokenBalance:p,noTokenBalance:g,isBalanceLoading:y,isSubmitting:f,isValid:v.isValid,validationErrors:v.errors,onOutcomeChange:x,onSideChange:k,onQuantityChange:P,onSubmit:b})}function kl(){return jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 lg:gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 flex-1 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-10 shrink-0 rounded-md"}),jsxRuntime.jsxs("div",{className:"flex gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-16 rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-16 rounded-lg"})]})]})}function qe({marketCount:e=4}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 lg:px-4 lg:max-w-3xl animate-pulse",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 lg:gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-14 w-14 shrink-0 rounded-lg lg:h-18 lg:w-18"}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1.5 min-w-0 flex-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-24 rounded-md lg:w-32"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-48 rounded-md lg:h-6 lg:w-72"})]})]}),jsxRuntime.jsx(ui.Skeleton,{className:"h-[200px] w-full rounded-xl lg:h-[280px]"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-32 rounded-md"}),jsxRuntime.jsx("div",{className:"flex gap-x-1",children:Array.from({length:4}).map((t,r)=>jsxRuntime.jsx(ui.Skeleton,{className:"h-7 w-10 rounded-md"},r))})]}),jsxRuntime.jsx("div",{className:"flex flex-col divide-y divide-default-200",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsx(kl,{},r))})]})}function En(){return jsxRuntime.jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4 animate-pulse",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-10 w-10 shrink-0 rounded-lg"}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1 flex-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-28 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-40 rounded-md"})]})]}),jsxRuntime.jsxs("div",{className:"flex gap-x-4",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-12 rounded-md"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-12 rounded-md"})]}),jsxRuntime.jsxs("div",{className:"flex gap-x-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-10 flex-1 rounded-lg"})]}),jsxRuntime.jsx(ui.Skeleton,{className:"h-14 w-full rounded-lg"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-12 w-full rounded-lg"})]})}var wn=e=>{let{candlestickMarketTickers:t,chartRange:r=ve}=e,n=at[r],s=lt[r],a=react.useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=h(),{data:l,isLoading:i,error:u}=tt({id:e.eventId,withNestedMarkets:true}),c=react.useMemo(()=>{if(s!=null)return a-s;let P=l?.markets;return P?.length?Math.min(...P.map(m=>m.openTime)):a},[a,s,l?.markets]),{data:d,isLoading:p,error:g}=Cr(l?.seriesTicker??"",{enabled:!!l?.seriesTicker}),y=react.useMemo(()=>l?.markets?(t&&t.length>0?t.slice(0,4).map(m=>l.markets.find(b=>b.ticker===m)).filter(m=>m!==void 0):[...l.markets].sort((m,b)=>Number(b.yesAsk??0)-Number(m.yesAsk??0)).slice(0,4)).map(m=>m.ticker):[],[t,l?.markets]),f=reactQuery.useQueries({queries:y.map(P=>({queryKey:It({ticker:P,startTs:c,endTs:a,periodInterval:n}),queryFn:()=>Qt(o,{ticker:P,startTs:c,endTs:a,periodInterval:n}),enabled:y.length>0}))}),v=f.some(P=>P.isLoading),x=react.useMemo(()=>{let P=new Map;return y.forEach((m,b)=>{let S=f[b]?.error;S&&P.set(m,S);}),P},[y,f]),k=react.useMemo(()=>{let P=new Map;return y.forEach((m,b)=>{let S=f[b]?.data;S&&P.set(m,S);}),P},[y,f]);return {event:l,isEventLoading:i,eventError:u,series:d,isSeriesLoading:p,seriesError:g,periodInterval:n,candlesticks:k,isCandlesticksLoading:v,candlestickErrors:x}};var Ol=utils.SOLANA_TOKENS.stablecoins.USDC.address;function Rn(e){let{status:t}=walletConnector.useAuth(),n=walletConnector.useWallets().find(u=>u.chainNamespace===types.ChainNamespace.SOLANA&&u.isConnected),s=t==="authenticated",a=n?.address,{data:o,isLoading:l}=react$1.useWalletPortfoliosQuery({chain:types.Chain.SOLANA,address:a??""},{enabled:s&&!!a,refetchInterval:1e4});return {holdings:react.useMemo(()=>{let u=new Map;if(!o?.portfolios||e.length===0)return u;let c=new Map;for(let d of o.portfolios)c.set(d.address,parseFloat(d.amount));for(let d of e){let p=d.accounts[Ol];if(!p)continue;let g=c.get(p.yesMint)??0,y=c.get(p.noMint)??0;(g>0||y>0)&&u.set(d.ticker,{yesShares:g,noShares:y});}return u},[o,e]),isLoading:l}}function _l(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxRuntime.jsxs("g",{children:[jsxRuntime.jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsxRuntime.jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsxRuntime.jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsxRuntime.jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}var yt=[{stroke:"hsl(var(--heroui-primary))",id:"colorMarket0"},{stroke:"hsl(var(--heroui-secondary))",id:"colorMarket1"},{stroke:"hsl(var(--heroui-success))",id:"colorMarket2"},{stroke:"hsl(var(--heroui-warning))",id:"colorMarket3"}];function On(e,t){let r=new Date(e*1e3);switch(t){case M.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case M.ONE_WEEK:case M.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case M.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function Fl(e,t,r){let n=it[r],s=new Map;e.forEach((i,u)=>{let c=new Map;(i.candlesticks??[]).forEach(p=>{let g=p.end_period_ts-p.end_period_ts%n;c.set(g,p.yes_ask.close);}),s.set(u,c);});let a=new Set;for(let i of s.values())for(let u of i.keys())a.add(u);let o=Array.from(a).sort((i,u)=>i-u),l=new Map;return o.map(i=>{let c={date:new Date(i*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),timestamp:i};return t.forEach(d=>{let p=s.get(d)?.get(i);if(p!==void 0)c[d]=Math.round(p*100)/100,l.set(d,c[d]);else {let g=l.get(d);g!==void 0&&(c[d]=g);}}),c})}function Nn({candlesticks:e,markets:t=[],isLoading:r,chartRange:n=M.ALL,onDataChange:s}){let[a,o]=react.useState(null),l=react.useRef(s);react.useEffect(()=>{l.current=s;});let i=react.useMemo(()=>e?Array.from(e.keys()).slice(0,4):[],[e]),u=react.useMemo(()=>!e||e.size===0?[]:Fl(e,i,n),[e,i,n]),c=react.useMemo(()=>{if(u.length===0||i.length===0)return [0,100];let y=1/0,f=-1/0;if(u.forEach(m=>{i.forEach(b=>{let S=m[b];S!==void 0&&(y=Math.min(y,S),f=Math.max(f,S));});}),y===1/0||f===-1/0)return [0,100];let v=f-y,x=Math.max(v*.2,5),k=Math.max(0,Math.floor(y-x)),P=Math.min(100,Math.ceil(f+x));return [k,P]},[u,i]),d=react.useCallback(y=>{if(u.length===0)return null;let f=y!==null?u[y]:u[u.length-1];return f?{timestamp:f.timestamp,date:f.date,markets:i.map((v,x)=>{let k=t.find(P=>P.ticker===v);return {id:v,label:k?.yesSubTitle||`Market ${x+1}`,value:f[v]??0,color:yt[x%yt.length].stroke}})}:null},[u,i,t]);react.useEffect(()=>{l.current&&u.length>0&&l.current(d(null));},[u,d]),react.useEffect(()=>{l.current&&l.current(d(a));},[a,d]);let p=react.useCallback(y=>{typeof y?.activeTooltipIndex=="number"&&o(y.activeTooltipIndex);},[]),g=react.useCallback(()=>{o(null);},[]);return r?jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-default-400 text-sm",children:"Loading chart..."})}):u.length===0?jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-default-400 text-sm",children:"No price history data"})}):jsxRuntime.jsx("div",{className:"h-[200px] w-full lg:h-[300px]",children:jsxRuntime.jsx(recharts.ResponsiveContainer,{width:"100%",height:"100%",children:jsxRuntime.jsxs(recharts.LineChart,{data:u,margin:{top:10,right:16,left:16,bottom:0},onMouseMove:p,onMouseLeave:g,children:[jsxRuntime.jsx(recharts.XAxis,{dataKey:"timestamp",tick:y=>{let{x:f,y:v,payload:x,index:k}=y,P=u.length,b=Math.max(1,Math.ceil(P/6)),S=k===0,R=k===P-1,O=k%b===0;return !S&&!R&&!O?null:jsxRuntime.jsx("text",{x:f,y:v+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:On(x.value,n)})},tickLine:false,axisLine:false,interval:0}),jsxRuntime.jsx(recharts.CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsxRuntime.jsx(recharts.YAxis,{domain:c,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:y=>`${y}%`,width:40}),jsxRuntime.jsx(recharts.Tooltip,{contentStyle:{backgroundColor:"hsl(var(--heroui-content1))",border:"1px solid hsl(var(--heroui-default-200))",borderRadius:"8px",fontSize:"12px"},labelFormatter:y=>On(y,n),formatter:(y,f)=>{let x=t.find(k=>k.ticker===f)?.yesSubTitle||f;return [`${y.toFixed(2)}%`,x]}}),i.map((y,f)=>jsxRuntime.jsx(recharts.Line,{type:"monotone",dataKey:y,stroke:yt[f%yt.length].stroke,strokeWidth:2,isAnimationActive:false,dot:v=>jsxRuntime.jsx(_l,{...v,dataLength:u.length},`dot-${y}-${v.index}`),activeDot:false},y))]})})})}function In(){return {timestamp:Date.now()/1e3,date:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"}),markets:[]}}function Bn({marketTicker:e,openTime:t,chartRange:r=ve}){let n=at[r],s=lt[r],a=react.useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=react.useMemo(()=>s!=null?a-s:t??a,[a,s,t]),{data:l,isLoading:i,isFetching:u,error:c}=Bt({ticker:e,startTs:o,endTs:a,periodInterval:n},{enabled:!!e});return {candlesticks:l,isLoading:i,isFetching:u,error:c,periodInterval:n}}var Yl="hsl(var(--heroui-primary))",jl=[{value:M.ONE_DAY,label:"1D"},{value:M.ONE_WEEK,label:"1W"},{value:M.ONE_MONTH,label:"1M"},{value:M.ALL,label:"ALL"}];function Xl(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxRuntime.jsxs("g",{children:[jsxRuntime.jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsxRuntime.jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsxRuntime.jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsxRuntime.jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}function Un(e,t){let r=new Date(e*1e3);switch(t){case M.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case M.ONE_WEEK:case M.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case M.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function Zl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(0)}function Jl(e,t){let r=it[t],n=e.candlesticks??[],s=new Map;for(let o of n){let l=o.end_period_ts-o.end_period_ts%r,i=s.get(l);s.set(l,{close:o.yes_ask.close,volume:(i?.volume??0)+(o.volume??0)});}return Array.from(s.entries()).sort((o,l)=>o[0]-l[0]).map(([o,{close:l,volume:i}])=>({timestamp:o,date:new Date(o*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:Math.round(l*100)/100,volume:i}))}function An({candlesticks:e,isLoading:t,chartRange:r,onRangeChange:n}){let s=react.useMemo(()=>e?Jl(e,r):[],[e,r]),a=react.useMemo(()=>{if(s.length===0)return [0,100];let o=1/0,l=-1/0;for(let p of s)p.value<o&&(o=p.value),p.value>l&&(l=p.value);if(o===1/0||l===-1/0)return [0,100];let i=l-o,u=Math.max(i*.2,5),c=Math.max(0,Math.floor(o-u)),d=Math.min(100,Math.ceil(l+u));return [c,d]},[s]);return t?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-neutral text-sm",children:"Loading chart..."})}),jsxRuntime.jsx(Jt,{chartRange:r,onRangeChange:n})]}):s.length===0?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsxRuntime.jsx("div",{className:"text-neutral text-sm",children:"No price history data"})}),jsxRuntime.jsx(Jt,{chartRange:r,onRangeChange:n})]}):jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("div",{className:"h-[200px] w-full",children:jsxRuntime.jsx(recharts.ResponsiveContainer,{width:"100%",height:"100%",children:jsxRuntime.jsxs(recharts.LineChart,{data:s,margin:{top:10,right:16,left:16,bottom:0},children:[jsxRuntime.jsx(recharts.XAxis,{dataKey:"timestamp",tick:o=>{let{x:l,y:i,payload:u,index:c}=o,d=s.length,g=Math.max(1,Math.ceil(d/6)),y=c===0,f=c===d-1,v=c%g===0;return !y&&!f&&!v?null:jsxRuntime.jsx("text",{x:l,y:i+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:Un(u.value,r)})},tickLine:false,axisLine:false,interval:0}),jsxRuntime.jsx(recharts.CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsxRuntime.jsx(recharts.YAxis,{domain:a,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:o=>`${o}%`,width:40}),jsxRuntime.jsx(recharts.Tooltip,{cursor:{stroke:"hsl(var(--heroui-default-300))"},content:({active:o,payload:l})=>{if(!o||!l?.length)return null;let i=l[0].payload,u=Math.round(i.value);return jsxRuntime.jsxs("div",{className:"rounded-lg border border-default-200 bg-content1 px-3 py-2 shadow-md",children:[jsxRuntime.jsxs("div",{className:"text-lg font-semibold text-primary",children:["Yes ",u,"\xA2"]}),jsxRuntime.jsxs("div",{className:"text-sm text-neutral",children:["Vol ",Zl(i.volume)," \xB7"," ",Un(i.timestamp,r)]})]})}}),jsxRuntime.jsx(recharts.Line,{type:"monotone",dataKey:"value",stroke:Yl,strokeWidth:2,isAnimationActive:false,dot:o=>jsxRuntime.jsx(Xl,{...o,dataLength:s.length},`dot-${o.index}`),activeDot:false})]})})}),jsxRuntime.jsx(Jt,{chartRange:r,onRangeChange:n})]})}function Jt({chartRange:e,onRangeChange:t}){return jsxRuntime.jsx("div",{className:"flex items-center justify-end gap-x-1",children:jl.map(r=>{let n=e===r.value;return jsxRuntime.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,onClick:()=>t?.(r.value),children:r.label},r.value)})})}function Wn({marketTicker:e}){let{data:t,isLoading:r,error:n}=Qe(e,{enabled:!!e});return {orderbook:react.useMemo(()=>{if(!t)return null;let{yesBids:a,yesAsks:o,noBids:l,noAsks:i}=t;return {yesBids:a,yesAsks:o,noBids:l,noAsks:i,bestYesBid:a.length>0?a[0].price:null,bestYesAsk:o.length>0?o[0].price:null,bestNoBid:l.length>0?l[0].price:null,bestNoAsk:i.length>0?i[0].price:null,sequence:t.sequence??null}},[t]),isOrderbookLoading:r,orderbookError:n}}function Dn(e,t){let r=e.slice(0,t),n=0;return r.map(s=>(n+=s.quantity,{...s,cumulative:n,depth:0,total:s.price*s.quantity}))}function _n(e,t){for(let r of e)r.depth=t>0?r.cumulative/t:0;}function Hn(e){return `${Math.round(e*100)}\xA2`}function rc(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function nc(e){return e>=1e6?`$${(e/1e6).toFixed(2)}M`:e>=1e3?`$${(e/1e3).toFixed(2)}K`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function Fn({row:e,side:t,showType:r=false,onClick:n}){let{t:s}=i18n.useTranslation(),a=t==="ask",o=a?"bg-bullish/10":"bg-bearish/10",l=a?"text-bullish":"text-bearish";return jsxRuntime.jsxs("button",{type:"button",className:"relative grid w-full grid-cols-4 px-2 py-2.5 text-xs cursor-pointer hover:bg-default-100 transition-colors",onClick:()=>n?.(e.price,t),children:[jsxRuntime.jsx("div",{className:`absolute inset-y-0 left-0 ${o} transition-[width] duration-200`,style:{width:`${e.depth*100}%`}}),jsxRuntime.jsx("span",{className:`relative z-10 font-mono font-medium ${l} text-left`,children:r?s(a?"predict.trade.bestAsk":"predict.trade.bestBid"):""}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Hn(e.price)}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:rc(e.quantity)}),jsxRuntime.jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:nc(e.total)})]})}function Vn({index:e}){let t=["60%","45%","75%","55%","65%","50%","70%","40%"];return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function sc(){return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"})]}),Array.from({length:er}).map((e,t)=>jsxRuntime.jsx(Vn,{index:t},`ask-${t}`)),jsxRuntime.jsx("div",{className:"flex justify-center border-y border-default-200 px-2 py-2.5",children:jsxRuntime.jsx("div",{className:"h-4 w-24 animate-pulse rounded bg-default-100"})}),Array.from({length:er}).map((e,t)=>jsxRuntime.jsx(Vn,{index:t+3},`bid-${t}`))]})}var er=8;function tr({bids:e,asks:t,isLoading:r=false,maxLevels:n=er,onPriceClick:s}){let{t:a}=i18n.useTranslation(),{bidRows:o,askRows:l,spread:i,spreadPercent:u}=react.useMemo(()=>{let d=Dn(e,n),p=Dn(t,n),g=Math.max(d[d.length-1]?.cumulative??0,p[p.length-1]?.cumulative??0);_n(d,g),_n(p,g);let y=d[0]?.price??null,f=p[0]?.price??null,v=null,x=null;if(y!=null&&f!=null){v=f-y;let k=(y+f)/2;k>0&&(x=Math.round(v/k*1e4)/100);}return {bidRows:d,askRows:p,spread:v,spreadPercent:x}},[e,t,n]);return r?jsxRuntime.jsx(sc,{}):o.length===0&&l.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:a("predict.orderBook.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.price")}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.contracts")}),jsxRuntime.jsx("span",{className:"text-right",children:a("predict.orderBook.total")})]}),jsxRuntime.jsx("div",{className:"flex flex-col-reverse",children:l.map((d,p)=>jsxRuntime.jsx(Fn,{row:d,side:"ask",showType:p===0,onClick:s},d.price))}),i!=null&&jsxRuntime.jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 px-2 py-2.5 text-xs text-default-500",children:[jsxRuntime.jsxs("span",{children:[a("predict.orderBook.spread"),": ",Hn(i)]}),u!=null&&jsxRuntime.jsxs("span",{className:"text-default-400",children:["(",u,"%)"]})]}),jsxRuntime.jsx("div",{className:"flex flex-col",children:o.map((d,p)=>jsxRuntime.jsx(Fn,{row:d,side:"bid",showType:p===0,onClick:s},d.price))})]})}function ic(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function lc(e){let t=Math.abs(e),r=e>=0?"+":"-";return t>=1e3?`${r}$${(t/1e3).toFixed(1)}K`:t>=1?`${r}$${t.toFixed(2)}`:`${r}$${t.toFixed(4)}`}function Kn({positions:e,isLoading:t=false}){let{t:r}=i18n.useTranslation();return t?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx(ui.Spinner,{size:"sm"})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.positions.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{children:r("predict.positions.outcome")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.qty")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.avgCost")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.currentPrice")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.positions.pnl")})]}),e.map(n=>{let s=n.position==="YES",a=s?"text-bullish":"text-bearish",o=r(s?"predict.market.yes":"predict.market.no"),l=n.avgCost!=null?`${Math.round(n.avgCost*100)}\xA2`:"\u2014",i=n.currentPrice!=null?`${Math.round(n.currentPrice*100)}\xA2`:"\u2014",u=n.pnl!=null&&n.pnlPercent!=null,c=u&&n.pnl>0?"text-bullish":u&&n.pnl<0?"text-bearish":"text-foreground";return jsxRuntime.jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsxRuntime.jsx("span",{className:`font-medium ${a}`,children:o}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:ic(n.balance)}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:l}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:i}),jsxRuntime.jsx("span",{className:`text-right font-mono ${c}`,children:u?jsxRuntime.jsxs("span",{className:"flex flex-col items-end",children:[jsxRuntime.jsx("span",{children:lc(n.pnl)}),jsxRuntime.jsxs("span",{className:"text-[10px] opacity-70",children:[n.pnlPercent>=0?"+":"",n.pnlPercent.toFixed(1),"%"]})]}):"\u2014"})]},n.mint)})]})}function uc(e){let t=e/1e6;return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(2)}K`:t.toLocaleString(void 0,{maximumFractionDigits:2})}function dc(e){return e==null?"\u2014":`${Math.round(e*100)}\xA2`}function pc(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return `${r} ${n} ${s}:${a}`}function mc({index:e}){let t=["60%","45%","75%","55%","65%"];return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsxRuntime.jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function $n({trades:e,isLoading:t=false}){let{t:r}=i18n.useTranslation();return t?jsxRuntime.jsx("div",{className:"flex flex-col",children:Array.from({length:6}).map((n,s)=>jsxRuntime.jsx(mc,{index:s},s))}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.tradeHistory.empty")}):jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsxRuntime.jsx("span",{children:r("predict.tradeHistory.side")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.price")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.qty")}),jsxRuntime.jsx("span",{className:"text-right",children:r("predict.tradeHistory.time")})]}),e.map(n=>{let s=n.side==="yes",a=s?"text-bullish":"text-bearish",o=n.side?r(s?"predict.trade.yes":"predict.trade.no"):"\u2014";return jsxRuntime.jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsxRuntime.jsx("span",{className:`font-medium ${a}`,children:o}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:dc(n.usdPricePerContract)}),jsxRuntime.jsx("span",{className:"text-right font-mono text-foreground",children:uc(n.outputAmount)}),jsxRuntime.jsx("span",{className:"text-right text-default-500",children:pc(n.createdAt)})]},n.id)})]})}function jn({market:e,onTradeAction:t}){let{t:r}=i18n.useTranslation(),[n,s]=react.useState("trade-yes"),[a,o]=react.useState(ve),{orderbook:l,isOrderbookLoading:i}=Wn({marketTicker:e.ticker}),{candlesticks:u,isFetching:c}=Bn({marketTicker:e.ticker,openTime:e.openTime,chartRange:a}),{positions:d,isLoading:p}=Mr(e),{status:g}=walletConnector.useAuth(),v=walletConnector.useWallets().find(R=>R.chainNamespace===types.ChainNamespace.SOLANA&&R.isConnected)?.address,{data:x,isLoading:k}=hr({walletAddress:v??""},{enabled:(n==="trade-history"||n==="positions")&&g==="authenticated"&&!!v}),P=(x?.trades??[]).filter(R=>R.marketTicker===e.ticker),m=react.useMemo(()=>d.map(R=>{let O=P.filter(fe=>fe.outputMint===R.mint&&fe.usdPricePerContract!=null&&fe.contracts!=null&&fe.contracts>0),C=bc(O),Q=R.position==="YES"?Yn(R.market?.yesAsk):Yn(R.market?.noAsk),A=null,Te=null;return C!=null&&Q!=null&&(A=(Q-C)*R.balance,Te=C>0?(Q-C)/C*100:null),{...R,avgCost:C,currentPrice:Q,pnl:A,pnlPercent:Te}}),[d,P]),b=react.useCallback((R,O)=>{t?.(e,"yes",O==="ask"?"buy":"sell");},[e,t]),S=react.useCallback((R,O)=>{t?.(e,"no",O==="ask"?"buy":"sell");},[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-3",children:[jsxRuntime.jsxs(ui.Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:R=>s(R),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsxRuntime.jsx(ui.Tab,{title:r("predict.market.tradeYes")},"trade-yes"),jsxRuntime.jsx(ui.Tab,{title:r("predict.market.tradeNo")},"trade-no"),jsxRuntime.jsx(ui.Tab,{title:r("predict.market.graph")},"graph"),jsxRuntime.jsx(ui.Tab,{title:r("predict.positions.title")},"positions"),jsxRuntime.jsx(ui.Tab,{title:r("predict.tradeHistory.title")},"trade-history")]}),jsxRuntime.jsxs("div",{className:"min-h-[120px]",children:[n==="trade-yes"&&jsxRuntime.jsx(tr,{bids:l?.yesBids??[],asks:l?.yesAsks??[],isLoading:i,onPriceClick:b}),n==="trade-no"&&jsxRuntime.jsx(tr,{bids:l?.noBids??[],asks:l?.noAsks??[],isLoading:i,onPriceClick:S}),n==="graph"&&jsxRuntime.jsx(An,{candlesticks:u,isLoading:c,chartRange:a,onRangeChange:o}),n==="positions"&&jsxRuntime.jsx(Kn,{positions:m,isLoading:p}),n==="trade-history"&&jsxRuntime.jsx($n,{trades:P,isLoading:k})]})]})}function bc(e){if(e.length===0)return null;let t=0,r=0;for(let n of e)t+=n.contracts,r+=n.usdPricePerContract*n.contracts;return t>0?r/t:null}function Yn(e){if(e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}var nr=4;function Pc(e){let t=e.yesAsk?Math.round(parseFloat(e.yesAsk)*100):null,r=e.noAsk?Math.round(parseFloat(e.noAsk)*100):null;return {yesCents:t,noCents:r}}function ns({markets:e,renderMarketDetail:t,onTradeAction:r,marketHoldings:n}){let{t:s}=i18n.useTranslation(),[a,o]=react.useState(false),[l,i]=react.useState(null);if(e.length===0)return null;let u=e.length>nr,c=a?e:e.slice(0,nr),d=p=>{i(g=>g===p?null:p);};return jsxRuntime.jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[c.map(p=>{let{yesCents:g,noCents:y}=Pc(p),f=l===p.ticker;return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>d(p.ticker),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(p.ticker));},children:[jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:p.yesSubTitle}),(()=>{let v=n?.get(p.ticker);if(!v)return null;let{yesShares:x,noShares:k}=v;return x<=0&&k<=0?null:jsxRuntime.jsxs("div",{className:"flex items-center gap-x-1.5",children:[x>0&&jsxRuntime.jsx(ui.Chip,{size:"sm",variant:"flat",color:"primary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesYes",{shares:x%1===0?x:x.toFixed(2)})}),k>0&&jsxRuntime.jsx(ui.Chip,{size:"sm",variant:"flat",color:"secondary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesNo",{shares:k%1===0?k:k.toFixed(2)})})]})})()]}),(()=>{let v=g!=null,x=y!=null;return v&&!x&&g<=1?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"< 1%"}):x&&!v&&y<=1?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"> 99%"}):!v&&!x?jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"0%"}):jsxRuntime.jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:`${g}%`})})(),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsxRuntime.jsx(ui.Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>r?.(p,"yes","buy"),children:g!=null?s("predict.market.action.yes",{price:g}):s("predict.market.yes")}),jsxRuntime.jsx(ui.Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>r?.(p,"no","buy"),children:y!=null?s("predict.market.action.no",{price:y}):s("predict.market.no")})]}),f?jsxRuntime.jsx(ui.ChevronUpIcon,{className:"h-4 w-4 shrink-0 text-default-400"}):jsxRuntime.jsx(ui.ChevronDownIcon,{className:"h-4 w-4 shrink-0 text-default-400"})]}),f&&t&&jsxRuntime.jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:t(p)})]},p.ticker)}),u&&jsxRuntime.jsx("button",{type:"button",onClick:()=>o(p=>!p),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:a?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{children:s("predict.event.rules.collapse")}),jsxRuntime.jsx(ui.ChevronUpIcon,{className:"h-4 w-4"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{children:s("predict.event.moreMarkets",{count:e.length-nr})}),jsxRuntime.jsx(ui.ChevronDownIcon,{className:"h-4 w-4"})]})})]})}var Ec=new Set(["closed","determined","finalized"]);function gt(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function wc({market:e}){let t=Ec.has(e.status),r=react.useMemo(()=>{let s={label:"Market Open",value:gt(e.openTime),isActive:true},a={label:"Market Closes",value:t?gt(e.closeTime):"After the outcome occurs",isActive:t},o={label:"Projected Payout",value:"30 minutes after closing",isActive:e.status==="finalized"};return [s,a,o]},[e.openTime,e.closeTime,e.status,t]),n=react.useMemo(()=>t?null:e.canCloseEarly&&e.earlyCloseCondition?`${e.earlyCloseCondition} Otherwise, it closes by ${gt(e.expirationTime)}.`:`This market closes by ${gt(e.expirationTime)}.`,[t,e.canCloseEarly,e.earlyCloseCondition,e.expirationTime]);return jsxRuntime.jsxs("div",{className:"flex flex-col",children:[r.map((s,a)=>jsxRuntime.jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-col items-center w-3",children:[jsxRuntime.jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${s.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),a<r.length-1&&jsxRuntime.jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxRuntime.jsxs("div",{className:`flex flex-col ${a<r.length-1?"pb-4":""}`,children:[jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:s.label}),jsxRuntime.jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:s.value})]})]},s.label)),n&&jsxRuntime.jsx("p",{className:"text-xs text-default-500 mt-3 lg:text-sm",children:n})]})}function os({markets:e,event:t,series:r}){let{t:n}=i18n.useTranslation(),[s,a]=react.useState(null),o=e.filter(i=>i.rulesPrimary);if(o.length===0)return null;let l=o.find(i=>i.ticker===s)??o[0];return l?.rulesPrimary?jsxRuntime.jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium lg:text-base",children:n("predict.event.rules")}),o.length>1&&jsxRuntime.jsx(ui.Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([l.ticker]),onSelectionChange:i=>{if(i==="all")return;let u=Array.from(i);u.length>0&&a(u[0]);},children:o.map(i=>jsxRuntime.jsx(ui.SelectItem,{textValue:i.yesSubTitle,children:jsxRuntime.jsx("span",{className:"text-xs truncate",children:i.yesSubTitle})},i.ticker))}),jsxRuntime.jsx("div",{className:"text-xs text-foreground lg:text-sm",children:l.rulesPrimary}),jsxRuntime.jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline and payout"}),jsxRuntime.jsx(wc,{market:l}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[r?.ticker&&jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Series:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:r.ticker})]}),t.ticker&&jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Event:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:t.ticker})]}),jsxRuntime.jsxs("span",{children:[jsxRuntime.jsx("span",{className:"text-default-500",children:"Market:"})," ",jsxRuntime.jsx("span",{className:"text-foreground",children:l.ticker})]})]})]}):null}var Ac=[{value:M.ONE_DAY,label:"1D"},{value:M.ONE_WEEK,label:"1W"},{value:M.ONE_MONTH,label:"1M"},{value:M.ALL,label:"ALL"}];function is({event:e,series:t,candlesticks:r,chartRange:n=M.ONE_DAY,periodInterval:s,isCandlesticksLoading:a,onRangeChange:o,selectedMarketTickers:l,onMarketSelectionChange:i,onTradeAction:u}){let{t:c}=i18n.useTranslation(),[d,p]=react.useState(In()),[g,y]=react.useState(false),f=react.useRef(null);react.useEffect(()=>{let m=f.current;if(!m)return;let b=false,S=0,R=()=>{let{bottom:C}=m.getBoundingClientRect(),Q=b?C<0:C<-20;Q!==b&&(b=Q,y(Q));},O=()=>{cancelAnimationFrame(S),S=requestAnimationFrame(R);};return window.addEventListener("scroll",O,{passive:true,capture:true}),R(),()=>{cancelAnimationFrame(S),window.removeEventListener("scroll",O,{capture:true});}},[]);let v=react.useMemo(()=>[...e.markets||[]].sort((m,b)=>Number(b.yesAsk??0)-Number(m.yesAsk??0)),[e.markets]),{holdings:x}=Rn(v),k=react.useMemo(()=>utils.formatAmountUSDCompact((e.volume??0)/100),[e.volume]),P=react.useMemo(()=>{if(!e.strikeDate)return null;let m=new Date(e.strikeDate*1e3),b=m.toLocaleString("default",{month:"short"}),S=m.getDate(),R=m.getFullYear();return `${b} ${S}, ${R}`},[e.strikeDate]);return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsxRuntime.jsx("div",{ref:f,className:"h-0 w-0"}),jsxRuntime.jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${g?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsxRuntime.jsx(ui.Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${g?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[!g&&(t?.category||t?.tags&&t.tags.length>0)&&jsxRuntime.jsxs("span",{className:"text-xs text-default-500 lg:text-sm truncate",children:[t.category,t.category&&t.tags?.length>0&&" \xB7 ",t.tags?.join(", ")]}),jsxRuntime.jsx("span",{className:`font-semibold truncate transition-all duration-300 ${g?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-4",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[d&&d.markets.length>0&&jsxRuntime.jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:d.markets.map(m=>jsxRuntime.jsxs("div",{className:"flex items-center gap-x-2",children:[jsxRuntime.jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:m.color}}),jsxRuntime.jsx("span",{className:"text-default-600",children:m.label})]},m.id))}),jsxRuntime.jsx(Nn,{candlesticks:r,chartRange:n,markets:v,isLoading:a,onDataChange:m=>p(m)}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxRuntime.jsxs("span",{children:[k," ",c("predict.event.volume")]}),P&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"text-default-300",children:"\xB7"}),jsxRuntime.jsx("span",{children:c("predict.event.endDate",{date:P})})]})]}),jsxRuntime.jsx("div",{className:"flex items-center gap-x-1",children:Ac.map(m=>jsxRuntime.jsx("button",{type:"button",onClick:()=>o?.(m.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n===m.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:m.label},m.value))}),v.length>1&&jsxRuntime.jsx(ui.Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:l?new Set(l):void 0,onSelectionChange:m=>{if(m==="all")return;let b=Array.from(m);b.length<=4&&i?.(b);},children:jsxRuntime.jsx(ui.SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:v.map(m=>jsxRuntime.jsx(ui.SelectItem,{textValue:m.yesSubTitle,children:jsxRuntime.jsx("span",{className:"text-xs truncate",children:m.yesSubTitle})},m.ticker))})})]})]})}),jsxRuntime.jsx(ns,{markets:v,onTradeAction:u,marketHoldings:x,renderMarketDetail:m=>jsxRuntime.jsx(jn,{market:m,onTradeAction:u})}),jsxRuntime.jsx(os,{markets:v,event:e,series:t})]})}function ar({eventId:e,initialMarketTickers:t,initialChartRange:r=ve,onTradeAction:n}){let[s,a]=react.useState(r),[o,l]=react.useState(t),{event:i,isEventLoading:u,eventError:c,series:d,isSeriesLoading:p,periodInterval:g,candlesticks:y,isCandlesticksLoading:f,candlestickErrors:v}=wn({eventId:e,candlestickMarketTickers:o,chartRange:s}),x=react.useRef(!!t);react.useEffect(()=>{if(i?.markets&&!x.current){x.current=true;let m=[...i.markets].sort((b,S)=>Number(S.yesAsk??0)-Number(b.yesAsk??0)).slice(0,4).map(b=>b.ticker);l(m);}},[i?.markets]);let k=react.useMemo(()=>m=>{a(m);},[]),P=react.useMemo(()=>m=>{l(m);},[]);return u||p?jsxRuntime.jsx(qe,{}):c||!i?jsxRuntime.jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:c?.message||"Event not found"}):jsxRuntime.jsx(is,{event:i,series:d,candlesticks:y,chartRange:s,periodInterval:g,isCandlesticksLoading:f,candlestickErrors:v,onRangeChange:k,selectedMarketTickers:o,onMarketSelectionChange:P,onTradeAction:n})}function jv({eventId:e,chain:t,...r}){let{t:n}=i18n.useTranslation(),{isMobile:s}=ui.useScreen(),{isOpen:a,onOpen:o,onClose:l}=ui.useDisclosure(),{data:i,isLoading:u}=tt({id:e,withNestedMarkets:true}),c=react.useMemo(()=>[...i?.markets||[]].sort((v,x)=>Number(x.yesAsk??0)-Number(v.yesAsk??0)),[i?.markets]),[d,p]=react.useState(null),g=react.useCallback((v,x,k)=>{p(P=>({market:v,outcome:x,side:k,version:(P?.version??0)+1})),s&&o();},[s,o]),y=d?.market??c[0];if(u)return s?jsxRuntime.jsx(qe,{}):jsxRuntime.jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsxRuntime.jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsxRuntime.jsx(qe,{})}),jsxRuntime.jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsxRuntime.jsx("div",{className:"sticky top-4",children:jsxRuntime.jsx(En,{})})})]});let f=d?`${d.market.ticker}-${d.version}`:y?.ticker??"default";return s?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full pb-20",children:jsxRuntime.jsx(ar,{eventId:e,onTradeAction:g,...r})}),y&&jsxRuntime.jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsxRuntime.jsx(ui.Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:o,children:n("predict.trade.action")})}),jsxRuntime.jsx(ui.Drawer,{isOpen:a,onClose:l,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsxRuntime.jsx(ui.DrawerContent,{children:jsxRuntime.jsx(ui.DrawerBody,{children:y&&jsxRuntime.jsx(Gt,{event:i,market:y,initialSide:d?.side,initialOutcome:d?.outcome,chain:t},f)})})})]}):jsxRuntime.jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsxRuntime.jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsxRuntime.jsx(ar,{eventId:e,onTradeAction:g,...r})}),y&&jsxRuntime.jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsxRuntime.jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsxRuntime.jsx(Gt,{event:i,market:y,initialSide:d?.side,initialOutcome:d?.outcome,chain:t},f)})})]})}function us(e,t){if(!e)return [];let r=e.slice(0,t),n=0,s=r.map(o=>(n+=o.quantity,{...o,cumulative:n,depth:0})),a=s[s.length-1]?.cumulative??1;for(let o of s)o.depth=o.cumulative/a;return s}function ds({marketTicker:e,maxLevels:t=10,refetchInterval:r=5e3,outcome:n="yes"}){let{data:s,isLoading:a,isFetching:o}=Qe(e,{refetchInterval:r||void 0}),l=react.useMemo(()=>n==="yes"?s?.yesBids:s?.noBids,[s,n]),i=react.useMemo(()=>n==="yes"?s?.yesAsks:s?.noAsks,[s,n]),u=react.useMemo(()=>us(l,t),[l,t]),c=react.useMemo(()=>us(i,t),[i,t]),d=react.useMemo(()=>u.length===0||c.length===0?null:c[0].price-u[0].price,[u,c]),p=react.useMemo(()=>u.length===0||c.length===0?null:(u[0].price+c[0].price)/2,[u,c]),g=react.useMemo(()=>d===null||p===null||p===0?null:Math.round(d/p*1e4)/100,[d,p]);return {bids:u,asks:c,spread:d,spreadPercent:g,midpoint:p,isLoading:a,isFetching:o}}function ps({row:e,side:t,onClick:r}){let n=t==="bid",s=n?"bg-primary/10":"bg-danger/10",a=n?"text-primary":"text-danger";return jsxRuntime.jsxs("button",{type:"button",className:"relative flex w-full items-center justify-between px-3 py-1 text-xs hover:bg-default-100 cursor-pointer",onClick:()=>r?.(e.price),children:[jsxRuntime.jsx("div",{className:`absolute inset-y-0 ${n?"right-0":"left-0"} ${s}`,style:{width:`${e.depth*100}%`}}),jsxRuntime.jsxs("span",{className:`relative z-10 font-medium ${a}`,children:[e.price,"\xA2"]}),jsxRuntime.jsx("span",{className:"relative z-10 text-default-600",children:e.quantity}),jsxRuntime.jsx("span",{className:"relative z-10 text-default-400",children:e.cumulative})]})}function ms(){return jsxRuntime.jsx("div",{className:"flex flex-col gap-y-1 py-2",children:Array.from({length:5}).map((e,t)=>jsxRuntime.jsx("div",{className:"mx-3 h-4 animate-pulse rounded bg-default-100"},t))})}function ys({bids:e,asks:t,spread:r,spreadPercent:n,isLoading:s,onPriceClick:a}){let{t:o}=i18n.useTranslation();if(s)return jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:o("predict.orderBook.title")}),jsxRuntime.jsx(ms,{}),jsxRuntime.jsx(ms,{})]});let l=e.length===0&&t.length===0;return jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxRuntime.jsx("span",{className:"text-sm font-medium",children:o("predict.orderBook.title")})}),l?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:o("predict.orderBook.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between px-3 py-1 text-xxs text-default-400",children:[jsxRuntime.jsx("span",{children:o("predict.orderBook.price")}),jsxRuntime.jsx("span",{children:o("predict.orderBook.qty")}),jsxRuntime.jsx("span",{children:o("predict.orderBook.total")})]}),jsxRuntime.jsx("div",{className:"flex flex-col-reverse",children:t.map(i=>jsxRuntime.jsx(ps,{row:i,side:"ask",onClick:a},i.price))}),r!==null&&jsxRuntime.jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 py-1.5 text-xs text-default-500",children:[jsxRuntime.jsxs("span",{children:[o("predict.orderBook.spread"),": ",r,"\xA2"]}),n!==null&&jsxRuntime.jsxs("span",{className:"text-default-400",children:["(",n,"%)"]})]}),jsxRuntime.jsx("div",{className:"flex flex-col",children:e.map(i=>jsxRuntime.jsx(ps,{row:i,side:"bid",onClick:a},i.price))})]})]})}function vh({marketTicker:e,maxLevels:t,refetchInterval:r,onPriceClick:n,outcome:s}){let{bids:a,asks:o,spread:l,spreadPercent:i,isLoading:u}=ds({marketTicker:e,maxLevels:t,refetchInterval:r,outcome:s});return jsxRuntime.jsx(ys,{bids:a,asks:o,spread:l,spreadPercent:i,isLoading:u,onPriceClick:n})}function gs(e={}){let[t,r]=react.useState(null),[n]=react.useState(null),s=react.useCallback(a=>{r(null);},[]);return {orders:[],isLoading:false,isFetching:false,cancellingOrderId:t,cancelOrder:s,cancelError:n}}function cu(e){return new Date(e).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function xs({orders:e,isLoading:t,cancellingOrderId:r,onCancel:n}){let{t:s}=i18n.useTranslation(),a=react.useMemo(()=>e.map(o=>({key:o.id,side:o.side,outcome:o.outcome,type:o.type,price:o.price,filled:`${o.filledQuantity}/${o.quantity}`,status:o.status,createdAt:cu(o.createdAt),isCancelling:o.id===r,id:o.id})),[e,r]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.openOrders.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,l)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},l))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsxs("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:[s("predict.openOrders.title"),e.length>0&&jsxRuntime.jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.openOrders.empty")}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto",children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Open orders",className:"min-w-[600px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Side",width:60,children:s("predict.openOrders.side")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Outcome",width:60,children:s("predict.openOrders.outcome")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Type",width:60,children:s("predict.openOrders.type")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:60,children:s("predict.openOrders.price")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Filled",width:80,children:s("predict.openOrders.filled")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Status",width:70,children:s("predict.openOrders.status")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Time",width:120,children:s("predict.openOrders.time")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Action",width:80,align:"end",children:" "})]}),jsxRuntime.jsx(ui.TableBody,{children:a.map(o=>jsxRuntime.jsxs(ui.TableRow,{children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${o.side==="buy"?"text-primary":"text-danger"}`,children:o.side==="buy"?s("predict.trade.buy"):s("predict.trade.sell")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs capitalize",children:o.type})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.price,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:o.filled})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs capitalize",children:o.status})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:o.createdAt})}),jsxRuntime.jsx(ui.TableCell,{className:"text-right",children:jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"danger",isLoading:o.isCancelling,onPress:()=>n(o.id),children:s("predict.openOrders.cancel")})})]},o.key))})]})})]})}function Bh({refetchInterval:e}={}){let{orders:t,isLoading:r,cancellingOrderId:n,cancelOrder:s}=gs({});return jsxRuntime.jsx(xs,{orders:t,isLoading:r,cancellingOrderId:n,onCancel:s})}function hs({ticker:e,pageSize:t=48}={}){let[r,n]=react.useState(1),[s,a]=react.useState([void 0]),o=s[r-1],l=react.useMemo(()=>({...e?{ticker:e}:{},limit:t,...o?{cursor:o}:{}}),[e,t,o]),{data:i,isLoading:u,isFetching:c}=vr(l),d=i,p=d?.trades??[],g=!!d?.cursor,y=r>1,f=react.useCallback(k=>{k>=1&&k<=s.length&&n(k);},[s.length]),v=react.useCallback(()=>{g&&d?.cursor&&(a(k=>{let P=[...k];return P.length===r&&P.push(d.cursor),P}),n(k=>k+1));},[g,d?.cursor,r]),x=react.useCallback(()=>{y&&n(k=>k-1);},[y]);return {trades:p,isLoading:u,isFetching:c,page:r,pageSize:t,hasNextPage:g,hasPrevPage:y,goToPage:f,nextPage:v,prevPage:x}}function bu(e){return new Date(e*1e3).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ks({trades:e,isLoading:t,isFetching:r,page:n,hasNextPage:s,hasPrevPage:a,onNextPage:o,onPrevPage:l}){let{t:i}=i18n.useTranslation(),u=react.useMemo(()=>e.map(c=>({key:c.tradeId,ticker:c.ticker,takerSide:c.takerSide,price:c.price,yesPrice:c.yesPrice,noPrice:c.noPrice,count:c.count,createdAt:bu(c.createdTime)})),[e]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:i("predict.tradeHistory.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((c,d)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},d))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:i("predict.tradeHistory.title")}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:i("predict.tradeHistory.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:`w-full overflow-x-auto ${r?"opacity-60":""}`,children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Trade history",className:"min-w-[480px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Side",width:60,children:i("predict.tradeHistory.side")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:80,children:i("predict.tradeHistory.price")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Yes",width:60,children:i("predict.trade.yes")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"No",width:60,children:i("predict.trade.no")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Qty",width:60,children:i("predict.tradeHistory.qty")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Time",width:120,children:i("predict.tradeHistory.time")})]}),jsxRuntime.jsx(ui.TableBody,{children:u.map(c=>jsxRuntime.jsxs(ui.TableRow,{children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${c.takerSide==="yes"?"text-primary":"text-secondary"}`,children:c.takerSide==="yes"?i("predict.trade.yes"):i("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[c.price,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs text-primary",children:[c.yesPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs text-secondary",children:[c.noPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:c.count})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:c.createdAt})})]},c.key))})]})}),(a||s)&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2",children:[jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",isDisabled:!a,onPress:l,startContent:jsxRuntime.jsx(ui.ChevronLeftIcon,{className:"h-3 w-3"}),children:i("predict.pagination.prev")}),jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:i("predict.pagination.page",{page:n})}),jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",isDisabled:!s,onPress:o,endContent:jsxRuntime.jsx(ui.ChevronRightIcon,{className:"h-3 w-3"}),children:i("predict.pagination.next")})]})]})]})}function Zh({ticker:e,pageSize:t}={}){let{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:l,nextPage:i,prevPage:u}=hs({ticker:e,pageSize:t});return jsxRuntime.jsx(ks,{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:l,onNextPage:i,onPrevPage:u})}function Ps(e={}){let t=react.useMemo(()=>({totalValue:0,totalUnrealizedPnl:0,totalRealizedPnl:0,count:0}),[]);return {positions:[],isLoading:false,isFetching:false,summary:t}}var xt=e=>utils.formatAmountUSDCompact(e/100);function cr({value:e}){if(e===0)return jsxRuntime.jsx("span",{className:"text-default-500",children:xt(0)});let t=e>0;return jsxRuntime.jsxs("span",{className:t?"text-success":"text-danger",children:[t?"+":"",xt(e)]})}function Cs({positions:e,isLoading:t,summary:r,onSell:n}){let{t:s}=i18n.useTranslation(),a=react.useMemo(()=>e.map(o=>({key:`${o.marketId}-${o.outcome}`,marketTitle:o.marketTitle,outcome:o.outcome,quantity:o.quantity,avgCost:o.avgCostBasis,currentPrice:o.currentPrice,value:o.currentPrice*o.quantity,unrealizedPnl:o.unrealizedPnl,position:o})),[e]);return t?jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.positions.title")}),jsxRuntime.jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,l)=>jsxRuntime.jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},l))})]}):jsxRuntime.jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxRuntime.jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxRuntime.jsxs("span",{className:"text-sm font-medium",children:[s("predict.positions.title"),e.length>0&&jsxRuntime.jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]})}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.positions.empty")}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto",children:jsxRuntime.jsxs(ui.StyledTable,{radius:"none","aria-label":"Positions",className:"min-w-[640px]",children:[jsxRuntime.jsxs(ui.TableHeader,{children:[jsxRuntime.jsx(ui.TableColumn,{textValue:"Market",width:200,children:s("predict.positions.market")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Outcome",width:60,children:s("predict.positions.outcome")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Qty",width:50,children:s("predict.positions.qty")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Avg Cost",width:70,children:s("predict.positions.avgCost")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Price",width:60,children:s("predict.positions.currentPrice")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"Value",width:80,children:s("predict.positions.value")}),jsxRuntime.jsx(ui.TableColumn,{textValue:"PnL",width:80,children:s("predict.positions.pnl")})]}),jsxRuntime.jsx(ui.TableBody,{children:a.map(o=>jsxRuntime.jsxs(ui.TableRow,{className:n?"cursor-pointer hover:bg-default-50":"",onClick:()=>n?.(o.position),children:[jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs font-medium line-clamp-1",children:o.marketTitle})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:`text-xs font-medium ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:o.quantity})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.avgCost,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsxs("span",{className:"text-xs",children:[o.currentPrice,"\xA2"]})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:xt(o.value)})}),jsxRuntime.jsx(ui.TableCell,{children:jsxRuntime.jsx("span",{className:"text-xs",children:jsxRuntime.jsx(cr,{value:o.unrealizedPnl})})})]},o.key))})]})}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2 text-xs",children:[jsxRuntime.jsx("div",{className:"flex items-center gap-x-4",children:jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.totalValue"),":"," ",jsxRuntime.jsx("span",{className:"font-medium text-foreground",children:xt(r.totalValue)})]})}),jsxRuntime.jsxs("div",{className:"flex items-center gap-x-4",children:[jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.unrealizedPnl"),":"," ",jsxRuntime.jsx(cr,{value:r.totalUnrealizedPnl})]}),jsxRuntime.jsxs("span",{className:"text-default-500",children:[s("predict.positions.realizedPnl"),":"," ",jsxRuntime.jsx(cr,{value:r.totalRealizedPnl})]})]})]})]})]})}function fb({refetchInterval:e,onSell:t}={}){let{positions:r,isLoading:n,summary:s}=Ps({});return jsxRuntime.jsx(Cs,{positions:r,isLoading:n,summary:s,onSell:t})}function Db({client:e,wsClient:t=null,children:r}){let n=react.useMemo(()=>({client:e,wsClient:t}),[e,t]);return jsxRuntime.jsx(Ie.Provider,{value:n,children:r})}var Uu=3e4;function Kb({walletAddress:e,pollingInterval:t=Uu,enabled:r=true,children:n}){let{data:s,isLoading:a,error:o,refetch:l}=Tr({walletAddress:e},{enabled:r&&!!e,refetchInterval:t}),i=react.useMemo(()=>({positions:s?.positions??[],usdcBalance:s?.usdcBalance??0,isLoading:a,error:o??null,refetch:l}),[s?.positions,s?.usdcBalance,a,o,l]);return jsxRuntime.jsx(ge.Provider,{value:i,children:n})}function jb({client:e,children:t}){let r=react.useMemo(()=>({client:e}),[e]);return jsxRuntime.jsx(et.Provider,{value:r,children:t})}function Ss(e,t){let r=new URLSearchParams;t&&r.set("provider",t);for(let[s,a]of Object.entries(e))a!=null&&(typeof a=="object"?r.set(s,JSON.stringify(a)):r.set(s,String(a)));let n=r.toString();return n?`?${n}`:""}function Ts(e){return e}var ze=class{constructor(t,r){this.endpoint=t;this.provider=r;}buildUrl(t,r){let n=Ss(r??{},this.provider);return `${this.endpoint}${t}${n}`}async fetch(t,r){let n=this.buildUrl(t,r);return await utils.httpGet(n)}async postRequest(t,r,n){let s=this.buildUrl(t,n);return await utils.httpPost(s,r)}};function vt(e,t){if(!e)return [];let r=Object.entries(e).map(([n,s])=>({price:parseFloat(n),quantity:s}));return r.sort((n,s)=>t==="desc"?s.price-n.price:n.price-s.price),r}function Ms(e){return {yesBids:vt(e.yes_bids,"desc"),yesAsks:vt(e.yes_asks,"asc"),noBids:vt(e.no_bids,"desc"),noAsks:vt(e.no_asks,"asc"),sequence:e.sequence}}var ht=class extends ze{constructor(t){super(t,"dflow");}async getEvents(t){return await this.fetch("/v2/event",t??{})}async getEventById(t,r){return await this.fetch(`/v2/event/${t}`,{withNestedMarkets:r})}async getEventCandlesticks(t,r){return await this.fetch(`/v2/event/${t}/candlesticks`,r)}async getEventForecastPercentileHistory(t){let{seriesTicker:r,eventId:n,...s}=t;return await this.fetch(`/v2/event/${r}/${n}/forecast_percentile_history`,s)}async getEventForecastPercentileHistoryByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/event/by-mint/${r}/forecast_percentile_history`,n)}async getMarkets(t){return await this.fetch("/v2/market",t??{})}async getMarketById(t){return await this.fetch(`/v2/market/${t}`)}async getMarketByMint(t){return await this.fetch(`/v2/market/by-mint/${t}`)}async getMarketsBatch(t){return await this.postRequest("/v2/market/batch",t)}async getMarketCandlesticks(t,r){return await this.fetch(`/v2/market/${t}/candlesticks`,r)}async getMarketCandlesticksByMint(t,r){return await this.fetch(`/v2/market/by-mint/${t}/candlesticks`,r)}async getOrderbook(t){let r=await this.fetch(`/v2/orderbook/${t}`);return Ms(r)}async getOrderbookByMint(t){let r=await this.fetch(`/v2/orderbook/by-mint/${t}`);return Ms(r)}async getTrades(t){return await this.fetch("/v2/trades",t??{})}async getTradesByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/trades/by-mint/${r}`,n)}async getOnchainTradesByWallet(t){let{walletAddress:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-wallet/${r}`,n)}async getOnchainTradesByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-event/${r}`,n)}async getOnchainTradesByMarket(t){let{marketTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-market/${r}`,n)}async getLiveData(t){return await this.fetch("/v2/live",{milestoneIds:t.milestoneIds.join(",")})}async getLiveDataByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/live/event/${r}`,n)}async getLiveDataByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/live/by-mint/${r}`,n)}async getSeries(t){return await this.fetch("/v2/series",t??{})}async getSeriesByTicker(t){return await this.fetch(`/v2/series/${t}`)}async getTagsByCategories(){return await this.fetch("/v2/tags/by_categories")}async getFiltersBySports(){return await this.fetch("/v2/sports/filters")}async search(t){return await this.fetch("/v2/search",t)}async getPositionsByWallet(t){let{walletAddress:r}=t;return await this.fetch(`/v2/positions/by-wallet/${r}`)}async getOutcomeMints(t){return await this.fetch("/v2/outcome_mints",t??{})}async filterOutcomeMints(t){return await this.postRequest("/v2/filter_outcome_mints",t)}async getQuote(t){return await this.fetch("/v2/swap/quote",t)}async createSwap(t){return await this.postRequest("/v2/swap",t)}async createSwapInstructions(t){return await this.postRequest("/v2/swap/instructions",t)}async getOrder(t){return await this.fetch("/v2/order",t)}async getOrderStatus(t){try{return await this.fetch("/v2/order/status",t)}catch(r){if(r instanceof Error&&/\b404\b/.test(r.message))return {status:"pending",inAmount:"0",outAmount:"0"};throw r}}async getIntentQuote(t){return await this.fetch("/v2/intent/quote",t)}async submitIntentSwap(t){return await this.postRequest("/v2/intent/swap",t)}async initPredictionMarket(t){return await this.fetch("/v2/prediction-market/init",t)}async getTokens(){return await this.fetch("/v2/tokens")}async getTokensWithDecimals(){return await this.fetch("/v2/tokens/decimals")}async getVenues(){return await this.fetch("/v2/venues")}};function Vu(e){let t=new URLSearchParams;for(let[n,s]of Object.entries(e))s!=null&&t.set(n,String(s));let r=t.toString();return r?`?${r}`:""}var Ge=class{constructor(t){this.endpoint=t;}async listEvents(t){let r=Vu(t??{}),n=`${this.endpoint}/api/v1/events${r}`;return await utils.httpGet(n)}async getEvent(t){let r=`${this.endpoint}/api/v1/events/${encodeURIComponent(t)}`;return await utils.httpGet(r)}};function ws(e){return new Ge(e)}
2
+ exports.BasePredictClient=ze;exports.CATEGORIES_V2=Vt;exports.CHART_RANGE_DURATION=lt;exports.CHART_RANGE_PERIOD=at;exports.CHART_RANGE_SAMPLE_INTERVAL=it;exports.CandlestickPeriod=ot;exports.CategoriesSkeleton=Hr;exports.CategoriesUI=st;exports.CategoriesWidget=Gr;exports.CategoriesWidgetV2=ln;exports.ChartRange=M;exports.DEFAULT_CHART_RANGE=ve;exports.DEFAULT_PAGE_SIZE=te;exports.DEFAULT_PRICE_HISTORY_INTERVAL=rf;exports.DflowPredictClient=ht;exports.DflowPredictWsClient=De;exports.EventDetailPage=jv;exports.EventDetailSkeleton=qe;exports.EventDetailUI=is;exports.EventDetailWidget=ar;exports.EventItemSkeleton=Za;exports.EventItemUI=Zr;exports.EventItemV2UI=fn;exports.EventMarketDetailWidget=jn;exports.EventsPage=Df;exports.EventsPageV2=Cg;exports.EventsSkeleton=ct;exports.EventsUI=tn;exports.EventsV2UI=vn;exports.EventsWidget=nn;exports.EventsWidgetV2=bn;exports.MAX_PRICE_HISTORY_MARKETS=xe;exports.ORDER_MAX_PRICE=tf;exports.ORDER_MIN_PRICE=ef;exports.ORDER_MIN_QUANTITY=Wt;exports.ORDER_PRICE_STEP=Jy;exports.OpenOrdersUI=xs;exports.OpenOrdersWidget=Bh;exports.OrderBookUI=ys;exports.OrderBookWidget=vh;exports.PRICE_HISTORY_SAMPLE_INTERVAL=nf;exports.PositionsUI=Cs;exports.PositionsWidget=fb;exports.PredictClient=ht;exports.PredictClientV2=Ge;exports.PredictContext=Ie;exports.PredictProvider=Db;exports.PredictV2Context=et;exports.PredictV2Provider=jb;exports.PredictWsClient=De;exports.PriceHistoryInterval=Be;exports.TradeFormSkeleton=En;exports.TradeFormUI=Mn;exports.TradeFormWidget=Gt;exports.TradeHistoryUI=ks;exports.TradeHistoryWidget=Zh;exports.UserPredictContext=ge;exports.UserPredictProvider=Kb;exports.buildQuery=Ss;exports.createDflowPredictWsClient=rt;exports.createPredictClientV2=ws;exports.createPredictWsClient=rt;exports.createSwap=va;exports.createSwapInstructions=ha;exports.eventByIdQueryKey=so;exports.eventCandlesticksQueryKey=Qo;exports.eventV2QueryKey=Gs;exports.eventsInfiniteQueryKey=ro;exports.eventsQueryKey=eo;exports.eventsV2QueryKey=Ks;exports.fetchEventById=oo;exports.fetchEventCandlesticks=Bo;exports.fetchEventV2=Ys;exports.fetchEvents=St;exports.fetchEventsV2=$s;exports.fetchFiltersBySports=ea;exports.fetchForecastPercentileHistory=Wo;exports.fetchForecastPercentileHistoryByMint=_o;exports.fetchIntentQuote=Ea;exports.fetchLiveData=Vo;exports.fetchLiveDataByEvent=Ho;exports.fetchLiveDataByMint=$o;exports.fetchMarketById=po;exports.fetchMarketByMint=fo;exports.fetchMarketCandlesticks=Qt;exports.fetchMarketCandlesticksByMint=Uo;exports.fetchMarkets=lo;exports.fetchMarketsBatch=vo;exports.fetchOnchainTradesByEvent=Et;exports.fetchOnchainTradesByMarket=wt;exports.fetchOnchainTradesByWallet=Mt;exports.fetchOrder=ka;exports.fetchOrderBook=bo;exports.fetchOrderBookByMint=Po;exports.fetchOrderStatus=Ca;exports.fetchOutcomeMints=ma;exports.fetchPositionsByWallet=aa;exports.fetchQuote=xa;exports.fetchSearch=na;exports.fetchSeries=Go;exports.fetchSeriesByTicker=jo;exports.fetchTagsByCategories=Zo;exports.fetchTokens=Ia;exports.fetchTokensWithDecimals=Ba;exports.fetchTrades=So;exports.fetchTradesByMint=Mo;exports.fetchVenues=Aa;exports.filterOutcomeMints=ya;exports.filtersBySportsQueryKey=Jo;exports.forecastPercentileHistoryByMintQueryKey=Do;exports.forecastPercentileHistoryQueryKey=Ao;exports.initPredictionMarket=Oa;exports.intentQuoteQueryKey=Ma;exports.liveDataByEventQueryKey=qo;exports.liveDataByMintQueryKey=Ko;exports.liveDataQueryKey=Fo;exports.marketByIdQueryKey=uo;exports.marketByMintQueryKey=yo;exports.marketCandlesticksByMintQueryKey=Lo;exports.marketCandlesticksQueryKey=It;exports.marketsBatchQueryKey=xo;exports.marketsQueryKey=io;exports.onchainTradesByEventInfiniteQueryKey=No;exports.onchainTradesByEventQueryKey=wo;exports.onchainTradesByMarketInfiniteQueryKey=Io;exports.onchainTradesByMarketQueryKey=Ro;exports.onchainTradesByWalletInfiniteQueryKey=Oo;exports.onchainTradesByWalletQueryKey=Eo;exports.orderBookByMintQueryKey=ko;exports.orderBookQueryKey=ho;exports.orderQueryKey=ba;exports.orderStatusQueryKey=Pa;exports.outcomeMintsQueryKey=pa;exports.positionsByWalletQueryKey=oa;exports.quoteQueryKey=ga;exports.searchQueryKey=ra;exports.seriesByTickerQueryKey=Yo;exports.seriesQueryKey=zo;exports.submitIntentSwap=wa;exports.tagsByCategoriesQueryKey=Xo;exports.toRecord=Ts;exports.tokensQueryKey=Na;exports.tokensWithDecimalsQueryKey=Qa;exports.tradesByMintQueryKey=To;exports.tradesQueryKey=Co;exports.useCategoriesQuery=Fp;exports.useCreateSwapInstructionsMutation=fm;exports.useCreateSwapMutation=ym;exports.useEventByIdQuery=tt;exports.useEventCandlesticksQuery=bp;exports.useEventDetail=wn;exports.useEventV2Query=od;exports.useEvents=Yr;exports.useEventsCategories=Fr;exports.useEventsInfiniteQuery=fr;exports.useEventsQuery=Ed;exports.useEventsV2=dn;exports.useEventsV2Query=td;exports.useFilterOutcomeMintsMutation=am;exports.useFiltersBySportsQuery=_p;exports.useForecastPercentileHistoryByMintQuery=Ep;exports.useForecastPercentileHistoryQuery=Mp;exports.useInitPredictionMarketMutation=Em;exports.useIntentQuoteQuery=Pm;exports.useLiveDataByEventQuery=Ip;exports.useLiveDataByMintQuery=Qp;exports.useLiveDataQuery=Np;exports.useMarketByIdQuery=Vd;exports.useMarketByMintQuery=$d;exports.useMarketCandlesticksByMintQuery=kp;exports.useMarketCandlesticksQuery=Bt;exports.useMarketPositions=Mr;exports.useMarketsBatchQuery=jd;exports.useMarketsQuery=Wd;exports.useOnchainTradesByEventInfiniteQuery=fp;exports.useOnchainTradesByEventQuery=lp;exports.useOnchainTradesByMarketInfiniteQuery=gp;exports.useOnchainTradesByMarketQuery=cp;exports.useOnchainTradesByWalletInfiniteQuery=yp;exports.useOnchainTradesByWalletQuery=hr;exports.useOpenOrders=gs;exports.useOrderBook=ds;exports.useOrderBookByMintQuery=ep;exports.useOrderBookQuery=Qe;exports.useOrderQuery=Rr;exports.useOrderStatusQuery=Or;exports.useOrderbookSubscription=ty;exports.useOutcomeMintsQuery=om;exports.usePositions=Ps;exports.usePositionsByWalletQuery=Tr;exports.usePredictClient=h;exports.usePredictContext=yr;exports.usePredictV2Client=Ne;exports.usePredictV2Context=mr;exports.usePriceHistoryQuery=Pp;exports.usePricesSubscription=Ym;exports.useQuoteQuery=um;exports.useSearchQuery=Kp;exports.useSeriesByTickerQuery=Cr;exports.useSeriesQuery=Pr;exports.useSubmitIntentSwapMutation=Cm;exports.useTagsByCategoriesQuery=Ut;exports.useTokensQuery=Nm;exports.useTokensWithDecimalsQuery=Im;exports.useTradeForm=Pn;exports.useTradeHistory=hs;exports.useTradesByMintQuery=sp;exports.useTradesQuery=vr;exports.useTradesSubscription=Zm;exports.useUserPredictContext=Zp;exports.useVenuesQuery=Um;exports.useWsClient=$m;exports.useWsConnection=Vm;exports.venuesQueryKey=Ua;exports.version=Fs;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map