@liberfi.io/ui-predict 0.1.143 → 0.1.144
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +15 -15
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {createContext,memo,useRef,forwardRef,useState,useImperativeHandle,useMemo,useEffect,useCallback,useContext,Fragment as Fragment$1,startTransition,Component}from'react';import {PolymarketIcon,KalshiIcon,cn as cn$1,Skeleton,toast,StyledModal,ModalContent,useDisclosure,Tabs,Tab,StyledInput,StyledSwitch,Select,SelectItem,StyledNumberInput,ChevronDownIcon,Button,Spinner,useScreen,TimerIcon,DropletIcon,ChartLineIcon,CalendarIcon,Linkable,Avatar,ChevronUpIcon,OrderbookTableIcon,OrderbookDepthIcon,RefreshIcon,Dropdown,DropdownTrigger,DropdownMenu,DropdownItem,ChevronRightIcon,ChevronLeftIcon,TrashIcon,Chip,XCloseIcon,Kbd,SearchIcon,EmptyIcon,ModalHeader,ModalBody}from'@liberfi.io/ui';import {AsyncModal,useAsyncModal}from'@liberfi.io/ui-scaffold';import {useTranslation}from'@liberfi.io/i18n';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {useWallets,useAuth,useSwitchChain,useAuthCallback}from'@liberfi.io/wallet-connector';import {keepPreviousData,useQueryClient,useQueries}from'@tanstack/react-query';import {ChartRange,useInfiniteMatchMarkets,useBalance,useDFlowKYC,usePolymarketSetup,usePredictClient,PolymarketContext,useTickSize,useFeeRate,usePositions,useDFlowQuote,useDFlowSubmit,useOrder,buildCtfExchangeDomain,buildOrderMessage,CTF_ORDER_TYPES,buildSignedOrder,buildClobPayload,buildPolymarketL2Headers,resolveEventsParams,useInfiniteEvents,useRedeemPosition,useAvailableShares,getPolymarketSharesPrecision,useInfiniteOrders,useCancelOrder,useInfiniteTrades,useOrderbook,useMarketHistory,useEvent,useSimilarEvents,candlesticksQueryKey,useSearchEvents}from'@liberfi.io/react-predict';export{PredictClient,PredictContext,PredictProvider,PredictWsClient,createPredictClient,createPredictWsClient,eventStatsQueryKey,fetchMatchMarketsPage,fetchMatchesPage,matchMarketsQueryKey,matchQueryKey,matchesQueryKey,useBalance,useCancelOrder,useCandlesticks,useDFlowKYC,useDFlowQuote,useDFlowSubmit,useEvent,useEventStats,useEvents,useInfiniteEvents,useInfiniteMatchMarkets,useInfiniteMatches,useInfiniteOrders,useInfiniteTrades,useMarket,useMarketHistory,useMarketTrades,useMatch,useOrder,useOrderbook,useOrders,usePositions,usePredictClient,usePriceHistory,useRedeemPosition,useSearchEvents,useSimilarEvents,useTrades}from'@liberfi.io/react-predict';import {ChainNamespace,Chain}from'@liberfi.io/types';import {SOLANA_TOKENS,debounce}from'@liberfi.io/utils';import Qn from'canvas-confetti';import {List}from'react-window';import {useInfiniteLoader}from'react-window-infinite-loader';import {useScrollCollapse,useResizeObserver,useCallbackRef}from'@liberfi.io/hooks';import {ResponsiveContainer,LineChart,CartesianGrid,XAxis,YAxis,Tooltip,Line,ReferenceDot}from'recharts';import {useAtom}from'jotai';import {atomWithStorage}from'jotai/utils';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.143");var kl="0.1.143";var Sl={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:["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},Qo=["Politics","Sports","Crypto","Economics","Financials","Elections","Entertainment","Companies","Science and Technology","Climate and Weather","Mentions","Social","World"],Yn=(()=>{let e=t=>{let r=Qo.indexOf(t);return r===-1?Qo.length:r};return Object.entries(Sl).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 Zo({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:o,onTagSelect:i,trailing:a,pulsingTab:l="Trending",className:s}){let{t:c}=useTranslation(),m=useCallback(()=>{o(null);},[o]),u=c("predict.categories.trending");return jsxs("div",{className:cn$1("sticky top-0 z-30 flex w-full flex-col justify-between gap-2 px-4 py-2.5 lg:px-4 lg:py-2",s),children:[jsx("style",{children:".cat-primary-row{display:flex;width:100%;flex-direction:column;gap:8px}@media(min-width:1024px){.cat-primary-row{flex-direction:row;align-items:center}}.cat-primary-row>.cat-tabs{min-width:0;overflow-x:auto;overflow-y:hidden;-ms-overflow-style:none;scrollbar-width:none}.cat-primary-row>.cat-tabs::-webkit-scrollbar{display:none}@media(min-width:1024px){.cat-primary-row>.cat-tabs{flex:1 1 0%}}"}),jsxs("div",{className:"cat-primary-row",children:[jsx("div",{className:"cat-tabs hideScrollbar",children:jsxs("div",{className:"flex min-h-9 items-stretch gap-x-3 lg:min-h-10",children:[jsx(Xo,{label:u,isSelected:t===null,onPress:m,showPulse:u===l}),jsx(Cl,{}),e.map(p=>jsx(Xo,{label:p.category,isSelected:t===p.category,onPress:()=>o(p.category),badge:p.badge,showPulse:p.category===l},p.category))]})}),a&&jsx("div",{className:"flex-shrink-0",children:a})]}),t&&n.length>0&&jsx("div",{className:"hideScrollbar overflow-x-auto overflow-y-hidden flex items-center",children:jsxs("div",{className:"flex gap-x-1.5 pl-1 lg:w-full lg:gap-x-2",children:[jsx(Jo,{label:c("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>i(null)}),n.map(p=>jsx(Jo,{label:p.label,icon:p.icon,isSelected:r===p.label,onPress:()=>i(p.label)},p.label))]})})]})}function Xo({label:e,isSelected:t,onPress:r,badge:n,showPulse:o}){return jsxs("button",{type:"button",onClick:r,className:cn$1("relative shrink-0 cursor-pointer whitespace-nowrap border-b px-2.5 py-1.5 text-sm font-medium capitalize transition-colors",t?"border-primary/50 text-primary":"border-transparent text-neutral-500 hover:text-neutral-300"),children:[o?jsxs("span",{className:"flex items-center gap-x-1.5",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-[rgb(240,68,56)]"}),jsx("span",{children:e})]}):e,n&&jsx("span",{className:"absolute -right-1 top-0 rounded bg-primary px-0.5 py-px text-[0.625rem] font-semibold leading-none text-neutral-950",children:n})]})}function Cl(){return jsx("span",{className:"flex items-center text-neutral-600","aria-hidden":"true",children:"|"})}function Jo({label:e,icon:t,isSelected:r,onPress:n}){return jsxs("button",{type:"button",onClick:n,className:cn$1("flex shrink-0 items-center justify-center gap-x-1 min-w-14 rounded-2xl border px-3 py-1.5 text-sm font-medium uppercase transition-colors cursor-pointer",r?"border-primary/40 bg-primary/15 text-primary":"border-border/80 text-neutral-500 hover:bg-primary/10 hover:text-primary"),children:[t&&jsx("span",{className:cn$1("iconify size-4",t)}),e]})}function T0({count:e=6}){return jsx("div",{className:"flex w-full flex-col gap-2 px-4 py-2.5 lg:px-4 lg:py-2",children:jsx("div",{className:"flex min-h-9 items-center gap-x-3 lg:min-h-10",children:Array.from({length:e}).map((t,r)=>jsx(Skeleton,{className:"h-6 w-16 shrink-0 rounded"},r))})})}function Ml(e){return e.map(t=>({category:t.label,tags:t.tags.map(r=>r.label)}))}function El(e){return e?e.tags.map(t=>({label:t.label,icon:t.icon})):[]}function ri({onSelect:e,trailing:t,className:r}){let[n,o]=useState(null),[i,a]=useState(null),l=useCallback(p=>{o(p),a(null),e?.({categorySlug:p,tagSlug:null});},[e]),s=useCallback(p=>{a(p),e?.({categorySlug:n,tagSlug:p});},[n,e]),c=Ml(Yn),m=Yn.find(p=>p.slug===n),u=El(m);return jsx(Zo,{categories:c,selectedCategory:n,selectedTag:i,activeTags:u,onCategorySelect:l,onTagSelect:s,trailing:t,className:r})}function rn(e){return {title:e.title,imageUrl:e.image_url}}function nn(e){let t=e.outcomes[0],r=e.outcomes[1];return {question:e.question,yesAsk:t?.best_ask??t?.price,noAsk:r?.best_ask??r?.price,yesBid:t?.best_bid,noBid:r?.best_bid,yesSubTitle:t?.label??"Yes",noSubTitle:r?.label??"No"}}var Nr=24,Gn=4,on={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},Ye={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},sn=Ye.ALL,B0={[Ye.ONE_DAY]:on.ONE_MINUTE,[Ye.ONE_WEEK]:on.ONE_HOUR,[Ye.ONE_MONTH]:on.ONE_HOUR,[Ye.ALL]:on.ONE_DAY},z0={[Ye.ONE_DAY]:300,[Ye.ONE_WEEK]:3600,[Ye.ONE_MONTH]:10800,[Ye.ALL]:1440*60},H0={[Ye.ONE_DAY]:1440*60,[Ye.ONE_WEEK]:10080*60,[Ye.ONE_MONTH]:720*60*60,[Ye.ALL]:null},an=1,ln=1,$0=1,W0=1,U0=99,gr={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},K0=gr.ONE_WEEK,V0={[gr.ONE_HOUR]:60,[gr.SIX_HOURS]:60,[gr.ONE_DAY]:300,[gr.ONE_WEEK]:1800,[gr.MAX]:1800};var ii=createContext(null);function Jt(){let e=useContext(ii);if(!e)throw new Error("usePredictWallet must be used within a PredictWalletProvider");return e}var Dl=1e4;function Al({pollingInterval:e=Dl,enabled:t=true,children:r}){let n=useWallets(),o=useMemo(()=>n.find(x=>x.chainNamespace===ChainNamespace.SOLANA&&x.isConnected)?.address,[n]),i=useMemo(()=>n.find(x=>x.chainNamespace===ChainNamespace.EVM&&x.isConnected)?.address,[n]),{data:a,isLoading:l,isFetching:s,error:c}=useBalance({source:"kalshi",user:o??""},{enabled:t&&!!o,refetchInterval:e}),{data:m,isLoading:u}=useDFlowKYC(o,{enabled:t&&!!o,refetchInterval:3e4}),{data:p,isLoading:d}=usePolymarketSetup(i,{enabled:t&&!!i,refetchInterval:3e4}),f=p?.safe_address,g=p?.verified??false,{data:h,isLoading:v,isFetching:k,error:w}=useBalance({source:"polymarket",user:i??""},{enabled:t&&g&&!!i,refetchInterval:e}),R=useMemo(()=>({solanaAddress:o,evmAddress:i,polymarketSafeAddress:f,kalshiUsdcBalance:a?Number(a.balance):null,polymarketUsdcBalance:g&&h?Number(h.balance):null,kalshiKycVerified:m?.verified??false,kalshiKycUrl:m?.kyc_url??null,kalshiKycLoading:u,polymarketSetupVerified:g,polymarketSafeDeployed:p?.safe_deployed??false,polymarketTokenApproved:p?.token_approved??false,polymarketSetupLoading:d,isLoading:l||v,isFetching:s||k,error:c??w??null}),[o,i,f,a,h,g,m,u,p,d,l,v,s,k,c,w]);return jsx(ii.Provider,{value:R,children:r})}var Bl={minutes:60,hours:3600,days:86400};function cn(e,t,r){let n=Math.floor(Date.now()/1e3);switch(e){case "5m":return n+300;case "1h":return n+3600;case "12h":return n+720*60;case "24h":return n+1440*60;case "eod":{let o=new Date;return o.setUTCHours(23,59,59,0),Math.floor(o.getTime()/1e3)}case "custom":return n+t*Bl[r]}}function dn(e,t){let r=parseFloat(t);return !r||r<=0?e:Math.round(e/r)*r}function Pe(e,t){let r=Math.pow(10,t);return Math.floor(e*r)/r}function pn(e,t,r){let n=e.match(/Size\s*\(([\d.]+)\)\s*lower than the minimum:\s*([\d.]+)/i);if(n)return t("predict.trade.polymarket.minOrderSize",{current:n[1],min:n[2]});let o=e.match(/balance:\s*(\d+),\s*sum of active orders:\s*(\d+)/i);if(o){let a=parseInt(o[1],10)/1e6,l=parseInt(o[2],10)/1e6,s=Math.max(0,a-l);return t("predict.trade.polymarket.insufficientBalance",{total:Pe(a,2).toFixed(2),active:Pe(l,2).toFixed(2),available:Pe(s,2).toFixed(2)})}return /not enough balance/i.test(e)?t(r==="sell"?"predict.trade.insufficientShares":"predict.trade.insufficientBalance"):/max accuracy of/i.test(e)?t("predict.trade.polymarket.decimalAccuracy"):/tick size/i.test(e)?t("predict.trade.polymarket.tickSizeError"):/couldn.*fully filled|FOK.*filled or killed/i.test(e)?t("predict.trade.polymarket.fokNotFilled"):e.replace(/order\s+0x[a-f0-9]+\s+is invalid\.\s*/i,"")||e}function Cr(e,t=2){return parseFloat(Pe(e,t).toFixed(t)).toString()}function Zt(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Qn({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Qn({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Qn({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function ci({market:e,initialOutcome:t="yes"}){let{t:r}=useTranslation(),{status:n}=useAuth(),o=useWallets(),i=useSwitchChain(),a=usePredictClient(),l=useContext(PolymarketContext),s=useQueryClient(),c=e.source,m=c==="polymarket",u=o.find(D=>D.chainNamespace===ChainNamespace.SOLANA&&D.isConnected),p=o.find(D=>D.chainNamespace===ChainNamespace.EVM&&D.isConnected&&"switchChain"in D),d=n==="authenticated",f=u?.address,g=p?.address,h=useMemo(()=>{if(c!=="polymarket")return;let D=e.provider_meta?.["polymarket.clobTokenIds"];return D?(typeof D=="string"?JSON.parse(D):D)[0]:void 0},[c,e.provider_meta]),{data:v,isLoading:k}=useTickSize(h),w=v?.minimum_tick_size?String(v.minimum_tick_size):"0.01",{data:R,isLoading:x}=useFeeRate(h),N=String(R?.base_fee??0),[S,K]=useState(t),[A,Q]=useState("market"),[P,L]=useState(NaN),[E,O]=useState(NaN),[de,U]=useState(false),[b,y]=useState(null),[j,Y]=useState(false),[q,pe]=useState(false),[Se,st]=useState("1h"),[he,Be]=useState(30),[ze,bt]=useState("minutes"),ve=null,Ve=false,rt=null,nt;try{let D=Jt();ve={kalshiUsdcBalance:D.kalshiUsdcBalance,polymarketUsdcBalance:D.polymarketUsdcBalance,isLoading:D.isLoading},Ve=D.kalshiKycVerified,rt=D.kalshiKycUrl,nt=D.polymarketSafeAddress;}catch{}let we=useMemo(()=>{let D=S==="yes"?0:1,Te=e.outcomes[D];return Te?.best_ask??Te?.price??.5},[e.outcomes,S]),B=useCallback(D=>{Q(D);},[]),ge=useCallback(D=>{K(D),O(NaN);},[]);useEffect(()=>{A==="limit"&&isNaN(E)&&O(Math.round(we*100)/100);},[A,E,we]);let Oe=useMemo(()=>isNaN(P)||P<=0?0:we>0?P/we:0,[P,we]),He=useMemo(()=>isNaN(P)||P<=0?"0":String(Math.round(P*1e6)),[P]),I=e.provider_meta?.["dflow.yesMint"]??"",Ee=e.provider_meta?.["dflow.noMint"]??"",yt=SOLANA_TOKENS.stablecoins.USDC.address,Wn=S==="yes"?I:Ee,at=yt,Gt=Wn,dr=c==="kalshi"?f??"":g??"",{data:qt,isLoading:Dt}=usePositions({source:c,user:dr},{enabled:!!dr}),$e=c==="kalshi"&&!!at&&!!Gt&&!!f&&He!=="0",{refetch:Vr}=useDFlowQuote({inputMint:at,outputMint:Gt,amount:He,userPublicKey:f??"",slippageBps:100},{enabled:$e}),pr=useMemo(()=>ve?c==="kalshi"?ve.kalshiUsdcBalance:ve.polymarketUsdcBalance:qt&&qt.positions.reduce((Te,lt)=>lt.side==="USDC"||lt.side==="collateral"?Te+(lt.current_value??0):Te,0)||null,[ve,qt,c]),Un=ve?ve.isLoading:Dt,mt=useMemo(()=>A==="limit"&&m&&!isNaN(E)?E:we,[A,m,E,we]),jr=useMemo(()=>isNaN(P)||P<=0?0:P,[P]),Yr=useMemo(()=>isNaN(P)||P<=0?0:mt>0?P/mt*1:0,[P,mt]),Vo=Yr-jr,Gr=useCallback(D=>{if(isNaN(D)){L(NaN);return}L(Math.round(Math.max(0,D)*100)/100);},[]),Kn=useCallback(D=>{if(isNaN(D)){O(NaN);return}let Te=Math.max(.01,Math.min(.99,D));O(Math.round(Te*100)/100);},[]),ft=useCallback(()=>{L(NaN),O(NaN),Q("market"),pe(false),st("1h"),Be(30),bt("minutes");},[]),kt=useMemo(()=>{let D=[];return isNaN(P)||P<=0?D.push(r("predict.trade.minAmountUsd",{amount:ln})):P<ln&&D.push(r("predict.trade.minAmountUsd",{amount:ln})),e.status!=="open"&&D.push(r("predict.trade.marketNotActive")),pr!=null&&!isNaN(P)&&P>0&&P>Pe(pr,2)&&D.push(r("predict.trade.insufficientBalance")),A==="limit"&&m&&(isNaN(E)||E<.01||E>.99)&&D.push(r("predict.trade.limitPriceRange")),A==="limit"&&m&&q&&Se==="custom"&&(isNaN(he)||he<=0)&&D.push(r("predict.trade.expiration.invalidDate")),{isValid:D.length===0,errors:D}},[P,e.status,pr,A,m,E,q,Se,he,r]),{mutateAsync:At}=useDFlowSubmit(),{data:Ft}=useOrder({id:b??"",source:c},{enabled:!!b});useEffect(()=>{if(!Ft||!b)return;let{status:D}=Ft;D==="closed"?(y(null),U(false),toast.success(r("predict.trade.submitSuccess")),Zt(),ft(),s.invalidateQueries({queryKey:["predict","positions"]})):(D==="failed"||D==="expired")&&(U(false),y(null),toast.error(r("predict.trade.submitError")));},[Ft,b,s,ft,r]);let qr=useCallback(async()=>{if(!f||!u)return;if(!at||!Gt){toast.error("Missing token mint addresses"),U(false);return}if(!Ve){Y(true),U(false);return}let ur=(await Vr()).data?.transaction;if(!ur){toast.error(r("predict.trade.submitError")),U(false);return}let Bt=Uint8Array.from(atob(ur),zt=>zt.charCodeAt(0)),St=await u.signTransaction(Bt),wt=await At({signedTransaction:btoa(String.fromCharCode(...St)),orderContext:{user_public_key:f,input_mint:at,output_mint:Gt,amount:He,price:String(we),side:"BUY",outcome:S==="yes"?"YES":"NO",market_slug:e.slug,slippage_bps:100}});y(wt.signature);},[f,u,Vr,At,at,Gt,He,we,S,e.slug,r,Ve]),Pr=useCallback(async()=>{if(!p||!l)return;let D=p.chain,Te=D!==Chain.POLYGON;Te&&await i(Chain.POLYGON);try{let lt=await p.getEip1193Provider();if(!lt){toast.error(r("predict.trade.submitError")),U(!1);return}let ur=!!nt,Bt={address:p.address,signatureType:ur?2:0,signTypedData:async(ue,Ht,en,jn)=>{let $t=[];"name"in ue&&$t.push({name:"name",type:"string"}),"version"in ue&&$t.push({name:"version",type:"string"}),"chainId"in ue&&$t.push({name:"chainId",type:"uint256"}),"verifyingContract"in ue&&$t.push({name:"verifyingContract",type:"address"}),"salt"in ue&&$t.push({name:"salt",type:"bytes32"});let jo={EIP712Domain:$t,...Ht};return await lt.request({method:"eth_signTypedData_v4",params:[p.address,JSON.stringify({domain:ue,types:jo,primaryType:en,message:jn})]})}},St=l.credentials??await l.authenticate(Bt),wt=S==="yes"?0:1,zt="",Pt=e.provider_meta?.["polymarket.clobTokenIds"];Pt&&(zt=(typeof Pt=="string"?JSON.parse(Pt):Pt)[wt]??"");let mr=e.provider_meta?.["polymarket.negRisk"]??!1,Qr=A==="limit"&&!isNaN(E)?E:we,Nt=dn(Qr,w),Xr=A==="limit"?q?"GTD":"GTC":"FOK",Jr=A==="market"?P:Nt>0?P/Nt:0,Zr={tokenId:zt,price:Nt,size:Jr,side:"BUY",orderType:Xr,tickSize:w,negRisk:mr,...nt&&{funderAddress:nt},...A==="limit"&&q&&{expiration:cn(Se,he,ze)}},M=buildCtfExchangeDomain(mr),xe=buildOrderMessage({...Zr,signerAddress:Bt.address,signatureType:Bt.signatureType,feeRateBps:N}),je=await Bt.signTypedData(M,CTF_ORDER_TYPES,"Order",xe),De=buildSignedOrder(xe,je,Zr.orderType),ot=buildClobPayload(De,St.apiKey),We=JSON.stringify(ot),Ct=await buildPolymarketL2Headers(St.address,{apiKey:St.apiKey,secret:St.secret,passphrase:St.passphrase,method:"POST",requestPath:"/order",body:We});await a.createPolymarketOrder(ot,Ct),s.invalidateQueries({queryKey:["predict","orders"]}),s.invalidateQueries({queryKey:["predict","positions"]}),toast.success(r("predict.trade.submitSuccess")),Zt(),ft(),U(!1);}finally{Te&&D&&i(D).catch(()=>{});}},[p,l,i,S,e.provider_meta,A,E,we,P,a,s,q,Se,he,ze,ft,r,w,N,nt]),Vn=useCallback(async()=>{if(!(!kt.isValid||!d)){U(true),y(null),Y(false);try{c==="kalshi"?await qr():await Pr();}catch(D){let Te=D instanceof Error?D.message:"",lt=c==="polymarket"&&Te?pn(Te,r,"buy"):Te||void 0;toast.error(lt||r("predict.trade.submitError")),U(false);}}},[kt.isValid,d,c,qr,Pr,r]);return {outcome:S,orderType:A,quantity:P,limitPrice:E,shares:Oe,estimatedCost:jr,potentialPayout:Yr,potentialProfit:Vo,usdcBalance:pr,isBalanceLoading:Un,isMarketDataLoading:c==="polymarket"&&(x||k),isSubmitting:de,validation:kt,supportsLimitOrder:m,kycRequired:j,kycUrl:rt,expirationEnabled:q,expirationPreset:Se,customDuration:he,customDurationUnit:ze,setOutcome:ge,setOrderType:B,setQuantity:Gr,setLimitPrice:Kn,setExpirationEnabled:pe,setExpirationPreset:st,setCustomDuration:Be,setCustomDurationUnit:bt,submit:Vn}}function un({isOpen:e,onClose:t,kycUrl:r}){let{t:n}=useTranslation();return jsx(StyledModal,{isOpen:e,onOpenChange:o=>{o||t();},size:"md",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4",children:[jsx("h3",{className:"text-base font-semibold text-white",children:n("predict.trade.kycModalTitle")}),jsx("button",{type:"button",onClick:t,className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),jsxs("div",{className:"px-5 pb-5",children:[jsx("p",{className:"text-[13px] text-zinc-400 mb-4 text-left",children:n("predict.trade.kycModalDescription")}),jsx("div",{className:"flex flex-col gap-2 mb-4",children:["predict.trade.kycModalBullet1","predict.trade.kycModalBullet2","predict.trade.kycModalBullet3"].map(o=>jsxs("div",{className:"flex items-center gap-2.5 text-[13px] text-zinc-300",children:[jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",className:"text-[#c7ff2e] shrink-0",children:jsx("polyline",{points:"20 6 9 17 4 12"})}),jsx("span",{children:n(o)})]},o))}),r&&jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[13px] text-[#c7ff2e]/70 hover:text-[#c7ff2e] transition-colors mb-3",children:[n("predict.trade.goToKYC")," \u2192"]}),jsx("p",{className:"text-[11px] text-zinc-500 mb-5",children:n("predict.trade.kycModalNote")}),jsx("button",{type:"button",onClick:t,className:"w-full py-2.5 rounded-[10px] bg-[#c7ff2e] text-zinc-900 text-sm font-semibold hover:bg-[#c7ff2e]/90 transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:n("common.ok")})]})]})})})}var bc=`https://s1.chainstream.io/chains/sol/tokens/${SOLANA_TOKENS.stablecoins.USDC.address}/image.png`,yc=["5m","1h","12h","24h","eod","custom"],kc={"5m":"predict.trade.expiration.5m","1h":"predict.trade.expiration.1h","12h":"predict.trade.expiration.12h","24h":"predict.trade.expiration.24h",eod:"predict.trade.expiration.eod",custom:"predict.trade.expiration.custom"},Sc=["minutes","hours","days"],wc={minutes:"predict.trade.expiration.minutes",hours:"predict.trade.expiration.hours",days:"predict.trade.expiration.days"},Pc={maximumFractionDigits:0};function vi({event:e,market:t,variant:r="bordered",outcome:n,orderType:o,quantity:i,limitPrice:a,shares:l,potentialProfit:s,potentialPayout:c,estimatedCost:m,usdcBalance:u,isBalanceLoading:p,isMarketDataLoading:d,isSubmitting:f,isValid:g,validationErrors:h,supportsLimitOrder:v,kycRequired:k,kycUrl:w,expirationEnabled:R,expirationPreset:x,customDuration:N,customDurationUnit:S,onOutcomeChange:K,onOrderTypeChange:A,onQuantityChange:Q,onLimitPriceChange:P,onExpirationEnabledChange:L,onExpirationPresetChange:E,onCustomDurationChange:O,onCustomDurationUnitChange:de,onSubmit:U}){let{t:b}=useTranslation(),[y,j]=useState(false),Y=useDisclosure(),[q,pe]=useState(""),Se=useRef(false);useEffect(()=>{Se.current||pe(isNaN(i)?"":String(i));},[i]);let[st,he]=useState(""),Be=useRef(false);useEffect(()=>{Be.current||(isNaN(a)?he(""):he(String(parseFloat((a*100).toFixed(2)))));},[a]);let ze=useCallback(I=>{if(I!==""&&!/^\d*\.?\d{0,2}$/.test(I))return;if(he(I),I===""||I==="."){P(NaN);return}let yt=parseFloat(I);isNaN(yt)||P(yt/100);},[P]),bt=useCallback(I=>{if(I!==""&&!/^\d*\.?\d{0,2}$/.test(I))return;if(pe(I),Oe(false),I===""||I==="."){Q(NaN);return}let yt=parseFloat(I);isNaN(yt)||Q(yt);},[Q]);useEffect(()=>{k&&!Y.isOpen&&Y.onOpen();},[k]);let ve=useMemo(()=>{let I=n==="yes"?t.yesAsk:t.noAsk;return I!=null?parseFloat((Number(I)*100).toFixed(2)):null},[n,t]),Ve=!isNaN(i)&&i>0,rt=useMemo(()=>{if(p)return b("predict.trade.loadingBalance");if(d)return b("predict.trade.loadingMarketData");if(f)return b("predict.trade.submitting");if(k)return b("predict.trade.kycRequired");if(!Ve)return b("predict.trade.enterAmount");let I=b(n==="yes"?"predict.trade.yes":"predict.trade.no"),Ee=s>0?` \u2192 Win $${s.toFixed(2)}`:"";return `${b("predict.trade.buy")} ${I}${Ee}`},[p,d,f,k,Ve,n,s,b]),nt=useMemo(()=>n==="yes"?"primary":"secondary",[n]),we=()=>{Q(Math.floor((u??0)/2*100)/100);},B=()=>{Q(Pe(u??0,2));},[ge,Oe]=useState(false),He=()=>{if(k){Y.onOpen();return}if(!g){Oe(true);return}Oe(false),U();};return jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col gap-y-4 p-4",style:r==="bordered"?{borderRadius:14,border:"1px solid rgba(39,39,42,0.6)",background:"rgba(24,24,27,0.4)",transition:"border-color 0.2s"}:void 0,onMouseEnter:I=>{r==="bordered"&&(I.currentTarget.style.borderColor="rgba(63,63,70,0.8)");},onMouseLeave:I=>{r==="bordered"&&(I.currentTarget.style.borderColor="rgba(39,39,42,0.6)");},children:[e&&jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxs("span",{className:n==="yes"?"text-bullish":"text-bearish",children:[b("predict.trade.buy")," ",b(n==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxs("span",{className:"text-foreground",children:[" \xB7 ",t.yesSubTitle]})]})]})]}),jsxs("div",{className:"flex items-center justify-between",children:[v?jsxs(Tabs,{variant:"underlined",selectedKey:o,onSelectionChange:I=>A(I),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:b("predict.trade.market")},"market"),jsx(Tab,{title:b("predict.trade.limit")},"limit")]}):jsx("span",{className:"text-sm font-medium text-foreground",children:b("predict.trade.market")}),o==="limit"&&v?jsx(StyledInput,{"aria-label":"Limit price",placeholder:"50",size:"sm",radius:"none",inputMode:"decimal",value:st,onChange:I=>ze(I.target.value),onFocus:()=>{Be.current=true;},onBlur:()=>{Be.current=false,isNaN(a)?he(""):he(String(parseFloat((a*100).toFixed(2))));},endContent:jsx("span",{className:"text-xl font-bold tabular-nums text-foreground",children:"\xA2"}),classNames:{base:"w-28",inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 rounded-lg px-2 h-9 min-h-9",input:"text-xl font-bold tabular-nums text-right"}}):ve!=null&&jsxs("span",{className:"text-xl font-bold tabular-nums",children:[ve," \xA2"]})]}),jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(I=>{let Ee=I==="yes"?t.yesAsk:t.noAsk;return jsx("div",{className:"flex flex-1 flex-col gap-y-1",children:jsxs("button",{type:"button",onClick:()=>K(I),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${n===I?I==="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:[jsx("span",{children:b(I==="yes"?"predict.trade.yes":"predict.trade.no")}),Ee!=null&&jsxs("span",{className:"ml-1 opacity-70",children:[parseFloat((Number(Ee)*100).toFixed(2)),"\xA2"]})]})},I)})}),jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsxs("div",{className:"flex items-center justify-between text-xs text-neutral-500",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:b("predict.trade.youArePaying")}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("img",{src:bc,alt:"USDC",className:"h-3.5 w-3.5 rounded-full object-cover"}),jsx("span",{className:"font-medium text-foreground tabular-nums",children:u!=null?`${Pe(u,2).toFixed(2)} USDC`:"\u2013"}),jsx("button",{type:"button",onClick:we,className:"rounded px-1.5 py-0.5 bg-content2 hover:bg-content3 transition-colors cursor-pointer text-foreground font-medium",children:b("predict.trade.half")}),jsx("button",{type:"button",onClick:B,className:"rounded px-1.5 py-0.5 bg-content2 hover:bg-content3 transition-colors cursor-pointer text-foreground font-medium",children:b("predict.trade.max")})]})]}),jsx(StyledInput,{"aria-label":"Trade amount",fullWidth:true,placeholder:"0",radius:"lg",size:"lg",inputMode:"decimal",value:q,onChange:I=>bt(I.target.value),onFocus:()=>{Se.current=true;},onBlur:()=>{Se.current=false,pe(isNaN(i)?"":String(i));},startContent:jsx("span",{className:"text-default-600 text-xl",children:"$"}),classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}}),ge&&h.length>0&&jsx("div",{className:"flex flex-col gap-y-0.5",children:h.map(I=>jsx("span",{className:"text-xs text-danger",children:I},I))})]}),o==="limit"&&v&&jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{className:"text-sm font-medium text-primary",children:b("predict.trade.setExpiration")}),jsx(StyledSwitch,{size:"sm",color:"primary",isSelected:R,onValueChange:L,"aria-label":b("predict.trade.setExpiration")})]}),R&&jsxs(Fragment,{children:[jsx(Select,{"aria-label":b("predict.trade.setExpiration"),selectedKeys:[x],onSelectionChange:I=>{let Ee=Array.from(I)[0];Ee&&E(Ee);},size:"sm",radius:"lg",classNames:{trigger:"bg-content2 data-[hover=true]:bg-content2 min-h-10",value:"text-sm"},children:yc.map(I=>jsx(SelectItem,{children:b(kc[I])},I))}),x==="custom"&&jsxs("div",{className:"flex gap-x-2",children:[jsx(StyledNumberInput,{"aria-label":"Duration amount",size:"sm",radius:"lg",value:isNaN(N)?void 0:N,onValueChange:O,minValue:1,step:1,formatOptions:Pc,classNames:{base:"flex-1",inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 min-h-10",input:"text-sm"}}),jsx(Select,{"aria-label":"Duration unit",selectedKeys:[S],onSelectionChange:I=>{let Ee=Array.from(I)[0];Ee&&de(Ee);},size:"sm",radius:"lg",classNames:{base:"w-32",trigger:"bg-content2 data-[hover=true]:bg-content2 min-h-10",value:"text-sm"},children:Sc.map(I=>jsx(SelectItem,{children:b(wc[I])},I))})]})]})]}),jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxs("div",{className:"flex items-center justify-between text-sm",children:[jsxs("button",{type:"button",onClick:()=>j(I=>!I),className:"flex items-center gap-x-1 text-neutral-500 hover:text-foreground cursor-pointer transition-colors",children:[jsx("span",{children:b("predict.trade.odds")}),jsx(ChevronDownIcon,{className:cn$1("h-3.5 w-3.5 transition-transform",y&&"rotate-180")})]}),ve!=null&&jsx("span",{className:"text-foreground font-medium tabular-nums",children:b("predict.trade.chance",{percent:ve})})]}),y&&jsxs("div",{className:"flex flex-col gap-y-1.5 border-l-2 border-default-300 pl-3 text-sm text-neutral-500",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.totalSize")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(i)&&i>0?`$${m.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.numContracts")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(l)&&l>0?Cr(l):"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.payout")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(i)&&i>0?`$${c.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.estProfit")}),jsx("span",{className:"tabular-nums text-bullish",children:!isNaN(i)&&i>0&&s>0?`+$${s.toFixed(2)}`:"\u2013"})]})]})]}),jsx(Button,{color:nt,fullWidth:true,radius:"lg",size:"lg",isDisabled:p||d||!Ve||f,isLoading:f||p||d,spinner:jsx(Spinner,{size:"sm",color:"current"}),onPress:He,children:rt})]}),jsx(un,{isOpen:Y.isOpen,onClose:Y.onClose,kycUrl:w})]})}function fn({event:e,market:t,variant:r,initialOutcome:n,chain:o}){let{outcome:i,orderType:a,quantity:l,limitPrice:s,shares:c,estimatedCost:m,potentialPayout:u,potentialProfit:p,usdcBalance:d,isBalanceLoading:f,isMarketDataLoading:g,isSubmitting:h,validation:v,supportsLimitOrder:k,kycRequired:w,kycUrl:R,expirationEnabled:x,expirationPreset:N,customDuration:S,customDurationUnit:K,setOutcome:A,setOrderType:Q,setQuantity:P,setLimitPrice:L,setExpirationEnabled:E,setExpirationPreset:O,setCustomDuration:de,setCustomDurationUnit:U,submit:b}=ci({market:t,initialOutcome:n}),y=useAuthCallback(b),j=useMemo(()=>e?rn(e):void 0,[e]),Y=useMemo(()=>nn(t),[t]);return jsx(vi,{event:j,market:Y,variant:r,outcome:i,orderType:a,quantity:l,limitPrice:s,shares:c,estimatedCost:m,potentialPayout:u,potentialProfit:p,usdcBalance:d,isBalanceLoading:f,isMarketDataLoading:g,isSubmitting:h,isValid:v.isValid,validationErrors:v.errors,supportsLimitOrder:k,kycRequired:w,kycUrl:R,expirationEnabled:x,expirationPreset:N,customDuration:S,customDurationUnit:K,onOutcomeChange:A,onOrderTypeChange:Q,onQuantityChange:P,onLimitPriceChange:L,onExpirationEnabledChange:E,onExpirationPresetChange:O,onCustomDurationChange:de,onCustomDurationUnitChange:U,onSubmit:y})}var Mr="predict-trade";function gn({id:e=Mr}){return jsx(AsyncModal,{id:e,children:t=>jsx(Rc,{...t})})}function Rc({params:e,isOpen:t,onOpenChange:r}){let{t:n}=useTranslation(),{isMobile:o}=useScreen();return e?jsx(StyledModal,{isOpen:t,onOpenChange:r,size:o?"lg":"md",backdrop:"blur",hideCloseButton:true,classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{className:o?"":"p-2",children:[jsx(fn,{event:e.event,market:e.market,initialOutcome:e.initialOutcome,chain:e.chain,variant:"flat"}),jsx("div",{className:"px-4 pb-4",children:jsx("button",{type:"button",onClick:()=>r(false),className:"w-full h-12 rounded-xl text-sm font-medium text-zinc-400 hover:text-white hover:bg-[rgba(39,39,42,0.5)] transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:n("common.cancel")})})]})})}):null}var Zn={sortPreset:"volume",sortAsc:false,source:void 0,timeRemaining:void 0,minVolume:void 0,minLiquidity:void 0};function eo(e){let t=0;return e.source&&t++,e.timeRemaining&&t++,e.minVolume&&t++,e.minLiquidity&&t++,t}function bi({isOpen:e,onClose:t,value:r,onChange:n}){let{t:o}=useTranslation(),[i,a]=useState(r),l=useCallback(h=>{h?a(r):t();},[r,t]),s=useCallback(()=>{a(Zn);},[]),c=useCallback(()=>{n(i),t();},[i,n,t]),m=useCallback((h,v)=>{a(k=>({...k,[h]:v}));},[]),u=useMemo(()=>eo(i),[i]),p=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"polymarket",label:o("predict.platform.polymarket")},{value:"kalshi",label:o("predict.platform.kalshi")}],[o]),d=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1d",label:o("predict.filter.lessThanDay")},{value:"7d",label:o("predict.filter.lessThanWeek")},{value:"30d",label:o("predict.filter.lessThanMonth")}],[o]),f=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[o]),g=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[o]);return jsx(StyledModal,{isOpen:e,onOpenChange:l,size:"md",backdrop:"blur",scrollBehavior:"inside",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4",children:[jsx("h3",{className:"text-base font-semibold text-white",children:o("predict.filter.title")}),jsx(Bc,{onClick:()=>l(false)})]}),jsxs("div",{style:{padding:"0 20px 16px",display:"flex",flexDirection:"column",gap:20},children:[jsx(vn,{label:o("predict.filter.platform"),children:jsx(xn,{options:p,selected:i.source,onSelect:h=>m("source",h)})}),jsx(vn,{label:o("predict.filter.timeRemaining"),children:jsx(xn,{options:d,selected:i.timeRemaining,onSelect:h=>m("timeRemaining",h)})}),jsx(vn,{label:o("predict.filter.minVolume"),children:jsx(xn,{options:f,selected:i.minVolume,onSelect:h=>m("minVolume",h)})}),jsx(vn,{label:o("predict.filter.minLiquidity"),children:jsx(xn,{options:g,selected:i.minLiquidity,onSelect:h=>m("minLiquidity",h)})})]}),jsxs("div",{className:"flex items-center gap-3 px-5 py-4",style:{borderTop:"1px solid rgba(39,39,42,0.5)"},children:[jsx("button",{type:"button",className:"inline-flex items-center justify-center py-2.5 px-5 rounded-[10px] text-zinc-400 text-sm font-medium hover:text-white transition-colors cursor-pointer",onClick:s,children:o("predict.filter.reset")}),jsxs("button",{type:"button",className:"flex-1 inline-flex items-center justify-center gap-2 py-2.5 rounded-[10px] bg-[#c7ff2e] text-zinc-900 text-sm font-semibold hover:bg-[#c7ff2e]/90 transition-colors cursor-pointer",onClick:c,children:[o("predict.filter.showResults"),u>0&&jsxs("span",{style:{opacity:.7},children:["(",u,")"]})]})]})]})})})}function vn({label:e,children:t}){return jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[jsx("span",{style:{fontSize:11,fontWeight:500,color:"#71717a",textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),t]})}function Bc({onClick:e}){return jsx("button",{type:"button",onClick:e,className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}function xn({options:e,selected:t,onSelect:r,allowDeselect:n=true}){return jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:e.map(o=>{let i=t===o.value;return jsx("button",{type:"button",onClick:()=>{r(i&&n?void 0:o.value);},style:{flexShrink:0,borderRadius:10,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer",transition:"all 0.15s",border:i?"1px solid rgba(199,255,46,0.3)":"1px solid rgba(63,63,70,0.5)",background:i?"rgba(199,255,46,0.08)":"rgba(39,39,42,0.4)",color:i?"#c7ff2e":"#a1a1aa"},onMouseEnter:a=>{i||(a.currentTarget.style.background="rgba(39,39,42,0.8)",a.currentTarget.style.color="#fff");},onMouseLeave:a=>{i||(a.currentTarget.style.background="rgba(39,39,42,0.4)",a.currentTarget.style.color="#a1a1aa");},children:o.label},o.value??"__all")})})}var Pi={start_time:{sort_by:"created_at"},volume:{sort_by:"volume"},liquidity:{sort_by:"liquidity"},ending_soon:{sort_by:"end_at"}},ki={start_time:"predict.sort.startTime",volume:"predict.sort.volume",liquidity:"predict.sort.liquidity",ending_soon:"predict.sort.endingSoon"},Yc=["start_time","volume","liquidity","ending_soon"],Si={display:"inline-flex",alignItems:"center",gap:8,borderRadius:10,border:"1px solid rgba(63,63,70,0.5)",background:"rgba(39,39,42,0.6)",padding:"8px 12px",fontSize:14,color:"#d4d4d8",cursor:"pointer",transition:"all 0.15s"},Gc={position:"absolute",left:0,top:"100%",zIndex:20,marginTop:8,borderRadius:14,border:"1px solid rgba(39,39,42,1)",background:"rgba(24,24,27,1)",boxShadow:"0 25px 50px -12px rgba(0,0,0,0.5)",overflow:"hidden"};function Ni({sortPreset:e,onSortChange:t,sortAsc:r,onSortAscChange:n,onFilterPress:o,filterCount:i=0,className:a}){let{t:l}=useTranslation(),[s,c]=useState(false),m=useRef(null),u=useCallback(d=>{m.current&&!m.current.contains(d.target)&&c(false);},[]);useEffect(()=>(document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)),[u]),useEffect(()=>{if(!s)return;let d=f=>{f.key==="Escape"&&c(false);};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[s]);let p=wi[e];return jsxs("div",{className:a,style:{display:"flex",alignItems:"center",gap:8},children:[jsxs("div",{ref:m,style:{position:"relative"},children:[jsxs("button",{type:"button",style:Si,onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)";},onClick:()=>c(d=>!d),children:[jsx(qc,{}),jsx(p,{className:"size-4 shrink-0",style:{color:"#a1a1aa"}}),jsx("span",{className:"hidden sm:block",style:{color:"#d4d4d8"},children:l(ki[e])}),jsx(Xc,{open:s})]}),s&&jsx("div",{style:{...Gc,width:224,padding:4},children:Yc.map(d=>{let f=wi[d],g=e===d;return jsxs("button",{type:"button",style:{display:"flex",width:"100%",alignItems:"center",gap:12,padding:"10px 12px",textAlign:"left",fontSize:14,border:"none",cursor:"pointer",transition:"all 0.15s",background:g?"rgba(199,255,46,0.08)":"transparent",color:g?"#c7ff2e":"#a1a1aa",borderRadius:10},onMouseEnter:h=>{g||(h.currentTarget.style.background="rgba(39,39,42,0.5)",h.currentTarget.style.color="#fff");},onMouseLeave:h=>{g||(h.currentTarget.style.background="transparent",h.currentTarget.style.color="#a1a1aa");},onClick:()=>{e===d?n(!r):t(d),c(false);},children:[jsx(f,{className:"size-4 shrink-0",style:{color:g?"#c7ff2e":"#71717a"}}),jsx("span",{style:{flex:1,fontWeight:500},children:l(ki[d])}),g&&jsx("svg",{viewBox:"0 0 24 24",style:{width:16,height:16,color:"#c7ff2e",flexShrink:0},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M20 6 9 17l-5-5"})})]},d)})})]}),jsx("button",{type:"button",style:{borderRadius:10,border:"1px solid rgba(63,63,70,0.5)",background:"rgba(39,39,42,0.6)",width:36,height:36,color:"#a1a1aa",cursor:"pointer",transition:"all 0.15s",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:14},onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)",d.currentTarget.style.color="#fff";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)",d.currentTarget.style.color="#a1a1aa";},onClick:()=>n(!r),children:r?"\u2191":"\u2193"}),jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[jsxs("button",{type:"button",style:Si,onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)";},onClick:o,children:[jsx(Qc,{}),jsx("span",{className:"hidden sm:block",style:{color:"#d4d4d8"},children:l("predict.filter.title")})]}),i>0&&jsx("span",{style:{position:"absolute",top:-4,right:-4,minWidth:16,height:16,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,background:"#c7ff2e",color:"#000",fontSize:10,fontWeight:600,padding:"0 4px"},children:i})]})]})}var wi={start_time:CalendarIcon,volume:ChartLineIcon,liquidity:DropletIcon,ending_soon:TimerIcon};function qc(){return jsxs("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#a1a1aa"},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m21 16-4 4-4-4"}),jsx("path",{d:"M17 20V4"}),jsx("path",{d:"m3 8 4-4 4 4"}),jsx("path",{d:"M7 4v16"})]})}function Qc(){return jsx("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#a1a1aa"},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"})})}function Xc({open:e}){return jsx("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#71717a",transition:"transform 0.15s",transform:e?"rotate(180deg)":void 0},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"m6 9 6 6 6-6"})})}function Ei(e={}){let t=useMemo(()=>resolveEventsParams(e),[e.tagSlugSelection,e.limit,e.status,e.sort_by,e.sort_asc,e.source,e.with_markets,e.minVolume,e.minLiquidity,e.timeRemaining,e.markets_limit]),{data:r,isLoading:n,isFetching:o,isFetchingNextPage:i,isError:a,error:l,hasNextPage:s,fetchNextPage:c,refetch:m}=useInfiniteEvents(t),u=useMemo(()=>r?.pages.flatMap(f=>f.items).filter(f=>f!=null)??[],[r]),p=useCallback(()=>{c();},[c]),d=useCallback(()=>{m();},[m]);return {data:u,isLoading:n,isFetching:o&&!i,isFetchingMore:i,isError:a,error:l??null,hasMore:s??false,fetchMore:p,refetch:d}}var Ti=`
|
|
1
|
+
import {createContext,memo,useRef,forwardRef,useState,useImperativeHandle,useMemo,useEffect,useCallback,useContext,Fragment as Fragment$1,startTransition,Component}from'react';import {PolymarketIcon,KalshiIcon,cn as cn$1,Skeleton,toast,StyledModal,ModalContent,useDisclosure,Tabs,Tab,StyledInput,StyledSwitch,Select,SelectItem,StyledNumberInput,ChevronDownIcon,Button,Spinner,useScreen,TimerIcon,DropletIcon,ChartLineIcon,CalendarIcon,Linkable,Avatar,ChevronUpIcon,OrderbookTableIcon,OrderbookDepthIcon,RefreshIcon,Dropdown,DropdownTrigger,DropdownMenu,DropdownItem,ChevronRightIcon,ChevronLeftIcon,TrashIcon,Chip,XCloseIcon,Kbd,SearchIcon,EmptyIcon,ModalHeader,ModalBody}from'@liberfi.io/ui';import {AsyncModal,useAsyncModal}from'@liberfi.io/ui-scaffold';import {useTranslation}from'@liberfi.io/i18n';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {useWallets,useAuth,useSwitchChain,useAuthCallback}from'@liberfi.io/wallet-connector';import {keepPreviousData,useQueryClient,useQueries}from'@tanstack/react-query';import {ChartRange,useInfiniteMatchMarkets,useBalance,useDFlowKYC,usePolymarketSetup,usePredictClient,PolymarketContext,useTickSize,useFeeRate,usePositions,useDFlowQuote,useDFlowSubmit,useOrder,buildCtfExchangeDomain,buildOrderMessage,CTF_ORDER_TYPES,buildSignedOrder,buildClobPayload,buildPolymarketL2Headers,resolveEventsParams,useInfiniteEvents,useRedeemPosition,useAvailableShares,getPolymarketSharesPrecision,useInfiniteOrders,useCancelOrder,useInfiniteTrades,useOrderbook,useMarketHistory,useEvent,useSimilarEvents,candlesticksQueryKey,useSearchEvents}from'@liberfi.io/react-predict';export{PredictClient,PredictContext,PredictProvider,PredictWsClient,createPredictClient,createPredictWsClient,eventStatsQueryKey,fetchMatchMarketsPage,fetchMatchesPage,matchMarketsQueryKey,matchQueryKey,matchesQueryKey,useBalance,useCancelOrder,useCandlesticks,useDFlowKYC,useDFlowQuote,useDFlowSubmit,useEvent,useEventStats,useEvents,useInfiniteEvents,useInfiniteMatchMarkets,useInfiniteMatches,useInfiniteOrders,useInfiniteTrades,useMarket,useMarketHistory,useMarketTrades,useMatch,useOrder,useOrderbook,useOrders,usePositions,usePredictClient,usePriceHistory,useRedeemPosition,useSearchEvents,useSimilarEvents,useTrades}from'@liberfi.io/react-predict';import {ChainNamespace,Chain}from'@liberfi.io/types';import {SOLANA_TOKENS,debounce}from'@liberfi.io/utils';import Qn from'canvas-confetti';import {List}from'react-window';import {useInfiniteLoader}from'react-window-infinite-loader';import {useScrollCollapse,useResizeObserver,useCallbackRef}from'@liberfi.io/hooks';import {ResponsiveContainer,LineChart,CartesianGrid,XAxis,YAxis,Tooltip,Line,ReferenceDot}from'recharts';import {useAtom}from'jotai';import {atomWithStorage}from'jotai/utils';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.144");var kl="0.1.144";var Sl={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:["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},Qo=["Politics","Sports","Crypto","Economics","Financials","Elections","Entertainment","Companies","Science and Technology","Climate and Weather","Mentions","Social","World"],Yn=(()=>{let e=t=>{let r=Qo.indexOf(t);return r===-1?Qo.length:r};return Object.entries(Sl).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 Zo({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:o,onTagSelect:i,trailing:a,pulsingTab:l="Trending",className:s}){let{t:c}=useTranslation(),m=useCallback(()=>{o(null);},[o]),u=c("predict.categories.trending");return jsxs("div",{className:cn$1("sticky top-0 z-30 flex w-full flex-col justify-between gap-2 px-4 py-2.5 lg:px-4 lg:py-2",s),children:[jsx("style",{children:".cat-primary-row{display:flex;width:100%;flex-direction:column;gap:8px}@media(min-width:1024px){.cat-primary-row{flex-direction:row;align-items:center}}.cat-primary-row>.cat-tabs{min-width:0;overflow-x:auto;overflow-y:hidden;-ms-overflow-style:none;scrollbar-width:none}.cat-primary-row>.cat-tabs::-webkit-scrollbar{display:none}@media(min-width:1024px){.cat-primary-row>.cat-tabs{flex:1 1 0%}}"}),jsxs("div",{className:"cat-primary-row",children:[jsx("div",{className:"cat-tabs hideScrollbar",children:jsxs("div",{className:"flex min-h-9 items-stretch gap-x-3 lg:min-h-10",children:[jsx(Xo,{label:u,isSelected:t===null,onPress:m,showPulse:u===l}),jsx(Cl,{}),e.map(p=>jsx(Xo,{label:p.category,isSelected:t===p.category,onPress:()=>o(p.category),badge:p.badge,showPulse:p.category===l},p.category))]})}),a&&jsx("div",{className:"flex-shrink-0",children:a})]}),t&&n.length>0&&jsx("div",{className:"hideScrollbar overflow-x-auto overflow-y-hidden flex items-center",children:jsxs("div",{className:"flex gap-x-1.5 pl-1 lg:w-full lg:gap-x-2",children:[jsx(Jo,{label:c("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>i(null)}),n.map(p=>jsx(Jo,{label:p.label,icon:p.icon,isSelected:r===p.label,onPress:()=>i(p.label)},p.label))]})})]})}function Xo({label:e,isSelected:t,onPress:r,badge:n,showPulse:o}){return jsxs("button",{type:"button",onClick:r,className:cn$1("relative shrink-0 cursor-pointer whitespace-nowrap border-b px-2.5 py-1.5 text-sm font-medium capitalize transition-colors",t?"border-primary/50 text-primary":"border-transparent text-neutral-500 hover:text-neutral-300"),children:[o?jsxs("span",{className:"flex items-center gap-x-1.5",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-[rgb(240,68,56)]"}),jsx("span",{children:e})]}):e,n&&jsx("span",{className:"absolute -right-1 top-0 rounded bg-primary px-0.5 py-px text-[0.625rem] font-semibold leading-none text-neutral-950",children:n})]})}function Cl(){return jsx("span",{className:"flex items-center text-neutral-600","aria-hidden":"true",children:"|"})}function Jo({label:e,icon:t,isSelected:r,onPress:n}){return jsxs("button",{type:"button",onClick:n,className:cn$1("flex shrink-0 items-center justify-center gap-x-1 min-w-14 rounded-2xl border px-3 py-1.5 text-sm font-medium uppercase transition-colors cursor-pointer",r?"border-primary/40 bg-primary/15 text-primary":"border-border/80 text-neutral-500 hover:bg-primary/10 hover:text-primary"),children:[t&&jsx("span",{className:cn$1("iconify size-4",t)}),e]})}function T0({count:e=6}){return jsx("div",{className:"flex w-full flex-col gap-2 px-4 py-2.5 lg:px-4 lg:py-2",children:jsx("div",{className:"flex min-h-9 items-center gap-x-3 lg:min-h-10",children:Array.from({length:e}).map((t,r)=>jsx(Skeleton,{className:"h-6 w-16 shrink-0 rounded"},r))})})}function Ml(e){return e.map(t=>({category:t.label,tags:t.tags.map(r=>r.label)}))}function El(e){return e?e.tags.map(t=>({label:t.label,icon:t.icon})):[]}function ri({onSelect:e,trailing:t,className:r}){let[n,o]=useState(null),[i,a]=useState(null),l=useCallback(p=>{o(p),a(null),e?.({categorySlug:p,tagSlug:null});},[e]),s=useCallback(p=>{a(p),e?.({categorySlug:n,tagSlug:p});},[n,e]),c=Ml(Yn),m=Yn.find(p=>p.slug===n),u=El(m);return jsx(Zo,{categories:c,selectedCategory:n,selectedTag:i,activeTags:u,onCategorySelect:l,onTagSelect:s,trailing:t,className:r})}function rn(e){return {title:e.title,imageUrl:e.image_url}}function nn(e){let t=e.outcomes[0],r=e.outcomes[1];return {question:e.question,yesAsk:t?.best_ask??t?.price,noAsk:r?.best_ask??r?.price,yesBid:t?.best_bid,noBid:r?.best_bid,yesSubTitle:t?.label??"Yes",noSubTitle:r?.label??"No"}}var Nr=24,Gn=4,on={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},Ye={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},sn=Ye.ALL,B0={[Ye.ONE_DAY]:on.ONE_MINUTE,[Ye.ONE_WEEK]:on.ONE_HOUR,[Ye.ONE_MONTH]:on.ONE_HOUR,[Ye.ALL]:on.ONE_DAY},z0={[Ye.ONE_DAY]:300,[Ye.ONE_WEEK]:3600,[Ye.ONE_MONTH]:10800,[Ye.ALL]:1440*60},H0={[Ye.ONE_DAY]:1440*60,[Ye.ONE_WEEK]:10080*60,[Ye.ONE_MONTH]:720*60*60,[Ye.ALL]:null},an=1,ln=1,$0=1,W0=1,U0=99,gr={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},K0=gr.ONE_WEEK,V0={[gr.ONE_HOUR]:60,[gr.SIX_HOURS]:60,[gr.ONE_DAY]:300,[gr.ONE_WEEK]:1800,[gr.MAX]:1800};var ii=createContext(null);function Jt(){let e=useContext(ii);if(!e)throw new Error("usePredictWallet must be used within a PredictWalletProvider");return e}var Dl=1e4;function Al({pollingInterval:e=Dl,enabled:t=true,children:r}){let n=useWallets(),o=useMemo(()=>n.find(x=>x.chainNamespace===ChainNamespace.SOLANA&&x.isConnected)?.address,[n]),i=useMemo(()=>n.find(x=>x.chainNamespace===ChainNamespace.EVM&&x.isConnected)?.address,[n]),{data:a,isLoading:l,isFetching:s,error:c}=useBalance({source:"kalshi",user:o??""},{enabled:t&&!!o,refetchInterval:e}),{data:m,isLoading:u}=useDFlowKYC(o,{enabled:t&&!!o,refetchInterval:3e4}),{data:p,isLoading:d}=usePolymarketSetup(i,{enabled:t&&!!i,refetchInterval:3e4}),f=p?.safe_address,g=p?.verified??false,{data:h,isLoading:v,isFetching:k,error:w}=useBalance({source:"polymarket",user:i??""},{enabled:t&&g&&!!i,refetchInterval:e}),R=useMemo(()=>({solanaAddress:o,evmAddress:i,polymarketSafeAddress:f,kalshiUsdcBalance:a?Number(a.balance):null,polymarketUsdcBalance:g&&h?Number(h.balance):null,kalshiKycVerified:m?.verified??false,kalshiKycUrl:m?.kyc_url??null,kalshiKycLoading:u,polymarketSetupVerified:g,polymarketSafeDeployed:p?.safe_deployed??false,polymarketTokenApproved:p?.token_approved??false,polymarketSetupLoading:d,isLoading:l||v,isFetching:s||k,error:c??w??null}),[o,i,f,a,h,g,m,u,p,d,l,v,s,k,c,w]);return jsx(ii.Provider,{value:R,children:r})}var Bl={minutes:60,hours:3600,days:86400};function cn(e,t,r){let n=Math.floor(Date.now()/1e3);switch(e){case "5m":return n+300;case "1h":return n+3600;case "12h":return n+720*60;case "24h":return n+1440*60;case "eod":{let o=new Date;return o.setUTCHours(23,59,59,0),Math.floor(o.getTime()/1e3)}case "custom":return n+t*Bl[r]}}function dn(e,t){let r=parseFloat(t);return !r||r<=0?e:Math.round(e/r)*r}function Pe(e,t){let r=Math.pow(10,t);return Math.floor(e*r)/r}function pn(e,t,r){let n=e.match(/Size\s*\(([\d.]+)\)\s*lower than the minimum:\s*([\d.]+)/i);if(n)return t("predict.trade.polymarket.minOrderSize",{current:n[1],min:n[2]});let o=e.match(/balance:\s*(\d+),\s*sum of active orders:\s*(\d+)/i);if(o){let a=parseInt(o[1],10)/1e6,l=parseInt(o[2],10)/1e6,s=Math.max(0,a-l);return t("predict.trade.polymarket.insufficientBalance",{total:Pe(a,2).toFixed(2),active:Pe(l,2).toFixed(2),available:Pe(s,2).toFixed(2)})}return /not enough balance/i.test(e)?t(r==="sell"?"predict.trade.insufficientShares":"predict.trade.insufficientBalance"):/max accuracy of/i.test(e)?t("predict.trade.polymarket.decimalAccuracy"):/tick size/i.test(e)?t("predict.trade.polymarket.tickSizeError"):/couldn.*fully filled|FOK.*filled or killed/i.test(e)?t("predict.trade.polymarket.fokNotFilled"):e.replace(/order\s+0x[a-f0-9]+\s+is invalid\.\s*/i,"")||e}function Cr(e,t=2){return parseFloat(Pe(e,t).toFixed(t)).toString()}function Zt(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Qn({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Qn({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Qn({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function ci({market:e,initialOutcome:t="yes"}){let{t:r}=useTranslation(),{status:n}=useAuth(),o=useWallets(),i=useSwitchChain(),a=usePredictClient(),l=useContext(PolymarketContext),s=useQueryClient(),c=e.source,m=c==="polymarket",u=o.find(D=>D.chainNamespace===ChainNamespace.SOLANA&&D.isConnected),p=o.find(D=>D.chainNamespace===ChainNamespace.EVM&&D.isConnected&&"switchChain"in D),d=n==="authenticated",f=u?.address,g=p?.address,h=useMemo(()=>{if(c!=="polymarket")return;let D=e.provider_meta?.["polymarket.clobTokenIds"];return D?(typeof D=="string"?JSON.parse(D):D)[0]:void 0},[c,e.provider_meta]),{data:v,isLoading:k}=useTickSize(h),w=v?.minimum_tick_size?String(v.minimum_tick_size):"0.01",{data:R,isLoading:x}=useFeeRate(h),N=String(R?.base_fee??0),[S,K]=useState(t),[A,Q]=useState("market"),[P,L]=useState(NaN),[E,O]=useState(NaN),[de,U]=useState(false),[b,y]=useState(null),[j,Y]=useState(false),[q,pe]=useState(false),[Se,st]=useState("1h"),[he,Be]=useState(30),[ze,bt]=useState("minutes"),ve=null,Ve=false,rt=null,nt;try{let D=Jt();ve={kalshiUsdcBalance:D.kalshiUsdcBalance,polymarketUsdcBalance:D.polymarketUsdcBalance,isLoading:D.isLoading},Ve=D.kalshiKycVerified,rt=D.kalshiKycUrl,nt=D.polymarketSafeAddress;}catch{}let we=useMemo(()=>{let D=S==="yes"?0:1,Te=e.outcomes[D];return Te?.best_ask??Te?.price??.5},[e.outcomes,S]),B=useCallback(D=>{Q(D);},[]),ge=useCallback(D=>{K(D),O(NaN);},[]);useEffect(()=>{A==="limit"&&isNaN(E)&&O(Math.round(we*100)/100);},[A,E,we]);let Oe=useMemo(()=>isNaN(P)||P<=0?0:we>0?P/we:0,[P,we]),He=useMemo(()=>isNaN(P)||P<=0?"0":String(Math.round(P*1e6)),[P]),I=e.provider_meta?.["dflow.yesMint"]??"",Ee=e.provider_meta?.["dflow.noMint"]??"",yt=SOLANA_TOKENS.stablecoins.USDC.address,Wn=S==="yes"?I:Ee,at=yt,Gt=Wn,dr=c==="kalshi"?f??"":g??"",{data:qt,isLoading:Dt}=usePositions({source:c,user:dr},{enabled:!!dr}),$e=c==="kalshi"&&!!at&&!!Gt&&!!f&&He!=="0",{refetch:Vr}=useDFlowQuote({inputMint:at,outputMint:Gt,amount:He,userPublicKey:f??"",slippageBps:100},{enabled:$e}),pr=useMemo(()=>ve?c==="kalshi"?ve.kalshiUsdcBalance:ve.polymarketUsdcBalance:qt&&qt.positions.reduce((Te,lt)=>lt.side==="USDC"||lt.side==="collateral"?Te+(lt.current_value??0):Te,0)||null,[ve,qt,c]),Un=ve?ve.isLoading:Dt,mt=useMemo(()=>A==="limit"&&m&&!isNaN(E)?E:we,[A,m,E,we]),jr=useMemo(()=>isNaN(P)||P<=0?0:P,[P]),Yr=useMemo(()=>isNaN(P)||P<=0?0:mt>0?P/mt*1:0,[P,mt]),Vo=Yr-jr,Gr=useCallback(D=>{if(isNaN(D)){L(NaN);return}L(Math.round(Math.max(0,D)*100)/100);},[]),Kn=useCallback(D=>{if(isNaN(D)){O(NaN);return}let Te=Math.max(.01,Math.min(.99,D));O(Math.round(Te*100)/100);},[]),ft=useCallback(()=>{L(NaN),O(NaN),Q("market"),pe(false),st("1h"),Be(30),bt("minutes");},[]),kt=useMemo(()=>{let D=[];return isNaN(P)||P<=0?D.push(r("predict.trade.minAmountUsd",{amount:ln})):P<ln&&D.push(r("predict.trade.minAmountUsd",{amount:ln})),e.status!=="open"&&D.push(r("predict.trade.marketNotActive")),pr!=null&&!isNaN(P)&&P>0&&P>Pe(pr,2)&&D.push(r("predict.trade.insufficientBalance")),A==="limit"&&m&&(isNaN(E)||E<.01||E>.99)&&D.push(r("predict.trade.limitPriceRange")),A==="limit"&&m&&q&&Se==="custom"&&(isNaN(he)||he<=0)&&D.push(r("predict.trade.expiration.invalidDate")),{isValid:D.length===0,errors:D}},[P,e.status,pr,A,m,E,q,Se,he,r]),{mutateAsync:At}=useDFlowSubmit(),{data:Ft}=useOrder({id:b??"",source:c},{enabled:!!b});useEffect(()=>{if(!Ft||!b)return;let{status:D}=Ft;D==="closed"?(y(null),U(false),toast.success(r("predict.trade.submitSuccess")),Zt(),ft(),s.invalidateQueries({queryKey:["predict","positions"]})):(D==="failed"||D==="expired")&&(U(false),y(null),toast.error(r("predict.trade.submitError")));},[Ft,b,s,ft,r]);let qr=useCallback(async()=>{if(!f||!u)return;if(!at||!Gt){toast.error("Missing token mint addresses"),U(false);return}if(!Ve){Y(true),U(false);return}let ur=(await Vr()).data?.transaction;if(!ur){toast.error(r("predict.trade.submitError")),U(false);return}let Bt=Uint8Array.from(atob(ur),zt=>zt.charCodeAt(0)),St=await u.signTransaction(Bt),wt=await At({signedTransaction:btoa(String.fromCharCode(...St)),orderContext:{user_public_key:f,input_mint:at,output_mint:Gt,amount:He,price:String(we),side:"BUY",outcome:S==="yes"?"YES":"NO",market_slug:e.slug,slippage_bps:100}});y(wt.signature);},[f,u,Vr,At,at,Gt,He,we,S,e.slug,r,Ve]),Pr=useCallback(async()=>{if(!p||!l)return;let D=p.chain,Te=D!==Chain.POLYGON;Te&&await i(Chain.POLYGON);try{let lt=await p.getEip1193Provider();if(!lt){toast.error(r("predict.trade.submitError")),U(!1);return}let ur=!!nt,Bt={address:p.address,signatureType:ur?2:0,signTypedData:async(ue,Ht,en,jn)=>{let $t=[];"name"in ue&&$t.push({name:"name",type:"string"}),"version"in ue&&$t.push({name:"version",type:"string"}),"chainId"in ue&&$t.push({name:"chainId",type:"uint256"}),"verifyingContract"in ue&&$t.push({name:"verifyingContract",type:"address"}),"salt"in ue&&$t.push({name:"salt",type:"bytes32"});let jo={EIP712Domain:$t,...Ht};return await lt.request({method:"eth_signTypedData_v4",params:[p.address,JSON.stringify({domain:ue,types:jo,primaryType:en,message:jn})]})}},St=l.credentials??await l.authenticate(Bt),wt=S==="yes"?0:1,zt="",Pt=e.provider_meta?.["polymarket.clobTokenIds"];Pt&&(zt=(typeof Pt=="string"?JSON.parse(Pt):Pt)[wt]??"");let mr=e.provider_meta?.["polymarket.negRisk"]??!1,Qr=A==="limit"&&!isNaN(E)?E:we,Nt=dn(Qr,w),Xr=A==="limit"?q?"GTD":"GTC":"FOK",Jr=A==="market"?P:Nt>0?P/Nt:0,Zr={tokenId:zt,price:Nt,size:Jr,side:"BUY",orderType:Xr,tickSize:w,negRisk:mr,...nt&&{funderAddress:nt},...A==="limit"&&q&&{expiration:cn(Se,he,ze)}},M=buildCtfExchangeDomain(mr),xe=buildOrderMessage({...Zr,signerAddress:Bt.address,signatureType:Bt.signatureType,feeRateBps:N}),je=await Bt.signTypedData(M,CTF_ORDER_TYPES,"Order",xe),De=buildSignedOrder(xe,je,Zr.orderType),ot=buildClobPayload(De,St.apiKey),We=JSON.stringify(ot),Ct=await buildPolymarketL2Headers(St.address,{apiKey:St.apiKey,secret:St.secret,passphrase:St.passphrase,method:"POST",requestPath:"/order",body:We});await a.createPolymarketOrder(ot,Ct),s.invalidateQueries({queryKey:["predict","orders"]}),s.invalidateQueries({queryKey:["predict","positions"]}),toast.success(r("predict.trade.submitSuccess")),Zt(),ft(),U(!1);}finally{Te&&D&&i(D).catch(()=>{});}},[p,l,i,S,e.provider_meta,A,E,we,P,a,s,q,Se,he,ze,ft,r,w,N,nt]),Vn=useCallback(async()=>{if(!(!kt.isValid||!d)){U(true),y(null),Y(false);try{c==="kalshi"?await qr():await Pr();}catch(D){let Te=D instanceof Error?D.message:"",lt=c==="polymarket"&&Te?pn(Te,r,"buy"):Te||void 0;toast.error(lt||r("predict.trade.submitError")),U(false);}}},[kt.isValid,d,c,qr,Pr,r]);return {outcome:S,orderType:A,quantity:P,limitPrice:E,shares:Oe,estimatedCost:jr,potentialPayout:Yr,potentialProfit:Vo,usdcBalance:pr,isBalanceLoading:Un,isMarketDataLoading:c==="polymarket"&&(x||k),isSubmitting:de,validation:kt,supportsLimitOrder:m,kycRequired:j,kycUrl:rt,expirationEnabled:q,expirationPreset:Se,customDuration:he,customDurationUnit:ze,setOutcome:ge,setOrderType:B,setQuantity:Gr,setLimitPrice:Kn,setExpirationEnabled:pe,setExpirationPreset:st,setCustomDuration:Be,setCustomDurationUnit:bt,submit:Vn}}function un({isOpen:e,onClose:t,kycUrl:r}){let{t:n}=useTranslation();return jsx(StyledModal,{isOpen:e,onOpenChange:o=>{o||t();},size:"md",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4",children:[jsx("h3",{className:"text-base font-semibold text-white",children:n("predict.trade.kycModalTitle")}),jsx("button",{type:"button",onClick:t,className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),jsxs("div",{className:"px-5 pb-5",children:[jsx("p",{className:"text-[13px] text-zinc-400 mb-4 text-left",children:n("predict.trade.kycModalDescription")}),jsx("div",{className:"flex flex-col gap-2 mb-4",children:["predict.trade.kycModalBullet1","predict.trade.kycModalBullet2","predict.trade.kycModalBullet3"].map(o=>jsxs("div",{className:"flex items-center gap-2.5 text-[13px] text-zinc-300",children:[jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",className:"text-[#c7ff2e] shrink-0",children:jsx("polyline",{points:"20 6 9 17 4 12"})}),jsx("span",{children:n(o)})]},o))}),r&&jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[13px] text-[#c7ff2e]/70 hover:text-[#c7ff2e] transition-colors mb-3",children:[n("predict.trade.goToKYC")," \u2192"]}),jsx("p",{className:"text-[11px] text-zinc-500 mb-5",children:n("predict.trade.kycModalNote")}),jsx("button",{type:"button",onClick:t,className:"w-full py-2.5 rounded-[10px] bg-[#c7ff2e] text-zinc-900 text-sm font-semibold hover:bg-[#c7ff2e]/90 transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:n("common.ok")})]})]})})})}var bc=`https://s1.chainstream.io/chains/sol/tokens/${SOLANA_TOKENS.stablecoins.USDC.address}/image.png`,yc=["5m","1h","12h","24h","eod","custom"],kc={"5m":"predict.trade.expiration.5m","1h":"predict.trade.expiration.1h","12h":"predict.trade.expiration.12h","24h":"predict.trade.expiration.24h",eod:"predict.trade.expiration.eod",custom:"predict.trade.expiration.custom"},Sc=["minutes","hours","days"],wc={minutes:"predict.trade.expiration.minutes",hours:"predict.trade.expiration.hours",days:"predict.trade.expiration.days"},Pc={maximumFractionDigits:0};function vi({event:e,market:t,variant:r="bordered",outcome:n,orderType:o,quantity:i,limitPrice:a,shares:l,potentialProfit:s,potentialPayout:c,estimatedCost:m,usdcBalance:u,isBalanceLoading:p,isMarketDataLoading:d,isSubmitting:f,isValid:g,validationErrors:h,supportsLimitOrder:v,kycRequired:k,kycUrl:w,expirationEnabled:R,expirationPreset:x,customDuration:N,customDurationUnit:S,onOutcomeChange:K,onOrderTypeChange:A,onQuantityChange:Q,onLimitPriceChange:P,onExpirationEnabledChange:L,onExpirationPresetChange:E,onCustomDurationChange:O,onCustomDurationUnitChange:de,onSubmit:U}){let{t:b}=useTranslation(),[y,j]=useState(false),Y=useDisclosure(),[q,pe]=useState(""),Se=useRef(false);useEffect(()=>{Se.current||pe(isNaN(i)?"":String(i));},[i]);let[st,he]=useState(""),Be=useRef(false);useEffect(()=>{Be.current||(isNaN(a)?he(""):he(String(parseFloat((a*100).toFixed(2)))));},[a]);let ze=useCallback(I=>{if(I!==""&&!/^\d*\.?\d{0,2}$/.test(I))return;if(he(I),I===""||I==="."){P(NaN);return}let yt=parseFloat(I);isNaN(yt)||P(yt/100);},[P]),bt=useCallback(I=>{if(I!==""&&!/^\d*\.?\d{0,2}$/.test(I))return;if(pe(I),Oe(false),I===""||I==="."){Q(NaN);return}let yt=parseFloat(I);isNaN(yt)||Q(yt);},[Q]);useEffect(()=>{k&&!Y.isOpen&&Y.onOpen();},[k]);let ve=useMemo(()=>{let I=n==="yes"?t.yesAsk:t.noAsk;return I!=null?parseFloat((Number(I)*100).toFixed(2)):null},[n,t]),Ve=!isNaN(i)&&i>0,rt=useMemo(()=>{if(p)return b("predict.trade.loadingBalance");if(d)return b("predict.trade.loadingMarketData");if(f)return b("predict.trade.submitting");if(k)return b("predict.trade.kycRequired");if(!Ve)return b("predict.trade.enterAmount");let I=b(n==="yes"?"predict.trade.yes":"predict.trade.no"),Ee=s>0?` \u2192 Win $${s.toFixed(2)}`:"";return `${b("predict.trade.buy")} ${I}${Ee}`},[p,d,f,k,Ve,n,s,b]),nt=useMemo(()=>n==="yes"?"primary":"secondary",[n]),we=()=>{Q(Math.floor((u??0)/2*100)/100);},B=()=>{Q(Pe(u??0,2));},[ge,Oe]=useState(false),He=()=>{if(k){Y.onOpen();return}if(!g){Oe(true);return}Oe(false),U();};return jsxs(Fragment,{children:[jsxs("div",{className:"flex w-full flex-col gap-y-4 p-4",style:r==="bordered"?{borderRadius:14,border:"1px solid rgba(39,39,42,0.6)",background:"rgba(24,24,27,0.4)",transition:"border-color 0.2s"}:void 0,onMouseEnter:I=>{r==="bordered"&&(I.currentTarget.style.borderColor="rgba(63,63,70,0.8)");},onMouseLeave:I=>{r==="bordered"&&(I.currentTarget.style.borderColor="rgba(39,39,42,0.6)");},children:[e&&jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxs("span",{className:n==="yes"?"text-bullish":"text-bearish",children:[b("predict.trade.buy")," ",b(n==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxs("span",{className:"text-foreground",children:[" \xB7 ",t.yesSubTitle]})]})]})]}),jsxs("div",{className:"flex items-center justify-between",children:[v?jsxs(Tabs,{variant:"underlined",selectedKey:o,onSelectionChange:I=>A(I),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:b("predict.trade.market")},"market"),jsx(Tab,{title:b("predict.trade.limit")},"limit")]}):jsx("span",{className:"text-sm font-medium text-foreground",children:b("predict.trade.market")}),o==="limit"&&v?jsx(StyledInput,{"aria-label":"Limit price",placeholder:"50",size:"sm",radius:"none",inputMode:"decimal",value:st,onChange:I=>ze(I.target.value),onFocus:()=>{Be.current=true;},onBlur:()=>{Be.current=false,isNaN(a)?he(""):he(String(parseFloat((a*100).toFixed(2))));},endContent:jsx("span",{className:"text-xl font-bold tabular-nums text-foreground",children:"\xA2"}),classNames:{base:"w-28",inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 rounded-lg px-2 h-9 min-h-9",input:"text-xl font-bold tabular-nums text-right"}}):ve!=null&&jsxs("span",{className:"text-xl font-bold tabular-nums",children:[ve," \xA2"]})]}),jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(I=>{let Ee=I==="yes"?t.yesAsk:t.noAsk;return jsx("div",{className:"flex flex-1 flex-col gap-y-1",children:jsxs("button",{type:"button",onClick:()=>K(I),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${n===I?I==="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:[jsx("span",{children:b(I==="yes"?"predict.trade.yes":"predict.trade.no")}),Ee!=null&&jsxs("span",{className:"ml-1 opacity-70",children:[parseFloat((Number(Ee)*100).toFixed(2)),"\xA2"]})]})},I)})}),jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsxs("div",{className:"flex items-center justify-between text-xs text-neutral-500",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:b("predict.trade.youArePaying")}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("img",{src:bc,alt:"USDC",className:"h-3.5 w-3.5 rounded-full object-cover"}),jsx("span",{className:"font-medium text-foreground tabular-nums",children:u!=null?`${Pe(u,2).toFixed(2)} USDC`:"\u2013"}),jsx("button",{type:"button",onClick:we,className:"rounded px-1.5 py-0.5 bg-content2 hover:bg-content3 transition-colors cursor-pointer text-foreground font-medium",children:b("predict.trade.half")}),jsx("button",{type:"button",onClick:B,className:"rounded px-1.5 py-0.5 bg-content2 hover:bg-content3 transition-colors cursor-pointer text-foreground font-medium",children:b("predict.trade.max")})]})]}),jsx(StyledInput,{"aria-label":"Trade amount",fullWidth:true,placeholder:"0",radius:"lg",size:"lg",inputMode:"decimal",value:q,onChange:I=>bt(I.target.value),onFocus:()=>{Se.current=true;},onBlur:()=>{Se.current=false,pe(isNaN(i)?"":String(i));},startContent:jsx("span",{className:"text-default-600 text-xl",children:"$"}),classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}}),ge&&h.length>0&&jsx("div",{className:"flex flex-col gap-y-0.5",children:h.map(I=>jsx("span",{className:"text-xs text-danger",children:I},I))})]}),o==="limit"&&v&&jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{className:"text-sm font-medium text-primary",children:b("predict.trade.setExpiration")}),jsx(StyledSwitch,{size:"sm",color:"primary",isSelected:R,onValueChange:L,"aria-label":b("predict.trade.setExpiration")})]}),R&&jsxs(Fragment,{children:[jsx(Select,{"aria-label":b("predict.trade.setExpiration"),selectedKeys:[x],onSelectionChange:I=>{let Ee=Array.from(I)[0];Ee&&E(Ee);},size:"sm",radius:"lg",classNames:{trigger:"bg-content2 data-[hover=true]:bg-content2 min-h-10",value:"text-sm"},children:yc.map(I=>jsx(SelectItem,{children:b(kc[I])},I))}),x==="custom"&&jsxs("div",{className:"flex gap-x-2",children:[jsx(StyledNumberInput,{"aria-label":"Duration amount",size:"sm",radius:"lg",value:isNaN(N)?void 0:N,onValueChange:O,minValue:1,step:1,formatOptions:Pc,classNames:{base:"flex-1",inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 min-h-10",input:"text-sm"}}),jsx(Select,{"aria-label":"Duration unit",selectedKeys:[S],onSelectionChange:I=>{let Ee=Array.from(I)[0];Ee&&de(Ee);},size:"sm",radius:"lg",classNames:{base:"w-32",trigger:"bg-content2 data-[hover=true]:bg-content2 min-h-10",value:"text-sm"},children:Sc.map(I=>jsx(SelectItem,{children:b(wc[I])},I))})]})]})]}),jsxs("div",{className:"flex flex-col gap-y-2",children:[jsxs("div",{className:"flex items-center justify-between text-sm",children:[jsxs("button",{type:"button",onClick:()=>j(I=>!I),className:"flex items-center gap-x-1 text-neutral-500 hover:text-foreground cursor-pointer transition-colors",children:[jsx("span",{children:b("predict.trade.odds")}),jsx(ChevronDownIcon,{className:cn$1("h-3.5 w-3.5 transition-transform",y&&"rotate-180")})]}),ve!=null&&jsx("span",{className:"text-foreground font-medium tabular-nums",children:b("predict.trade.chance",{percent:ve})})]}),y&&jsxs("div",{className:"flex flex-col gap-y-1.5 border-l-2 border-default-300 pl-3 text-sm text-neutral-500",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.totalSize")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(i)&&i>0?`$${m.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.numContracts")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(l)&&l>0?Cr(l):"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.payout")}),jsx("span",{className:"tabular-nums text-foreground",children:!isNaN(i)&&i>0?`$${c.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{children:b("predict.trade.estProfit")}),jsx("span",{className:"tabular-nums text-bullish",children:!isNaN(i)&&i>0&&s>0?`+$${s.toFixed(2)}`:"\u2013"})]})]})]}),jsx(Button,{color:nt,fullWidth:true,radius:"lg",size:"lg",isDisabled:p||d||!Ve||f,isLoading:f||p||d,spinner:jsx(Spinner,{size:"sm",color:"current"}),onPress:He,children:rt})]}),jsx(un,{isOpen:Y.isOpen,onClose:Y.onClose,kycUrl:w})]})}function fn({event:e,market:t,variant:r,initialOutcome:n,chain:o}){let{outcome:i,orderType:a,quantity:l,limitPrice:s,shares:c,estimatedCost:m,potentialPayout:u,potentialProfit:p,usdcBalance:d,isBalanceLoading:f,isMarketDataLoading:g,isSubmitting:h,validation:v,supportsLimitOrder:k,kycRequired:w,kycUrl:R,expirationEnabled:x,expirationPreset:N,customDuration:S,customDurationUnit:K,setOutcome:A,setOrderType:Q,setQuantity:P,setLimitPrice:L,setExpirationEnabled:E,setExpirationPreset:O,setCustomDuration:de,setCustomDurationUnit:U,submit:b}=ci({market:t,initialOutcome:n}),y=useAuthCallback(b),j=useMemo(()=>e?rn(e):void 0,[e]),Y=useMemo(()=>nn(t),[t]);return jsx(vi,{event:j,market:Y,variant:r,outcome:i,orderType:a,quantity:l,limitPrice:s,shares:c,estimatedCost:m,potentialPayout:u,potentialProfit:p,usdcBalance:d,isBalanceLoading:f,isMarketDataLoading:g,isSubmitting:h,isValid:v.isValid,validationErrors:v.errors,supportsLimitOrder:k,kycRequired:w,kycUrl:R,expirationEnabled:x,expirationPreset:N,customDuration:S,customDurationUnit:K,onOutcomeChange:A,onOrderTypeChange:Q,onQuantityChange:P,onLimitPriceChange:L,onExpirationEnabledChange:E,onExpirationPresetChange:O,onCustomDurationChange:de,onCustomDurationUnitChange:U,onSubmit:y})}var Mr="predict-trade";function gn({id:e=Mr}){return jsx(AsyncModal,{id:e,children:t=>jsx(Rc,{...t})})}function Rc({params:e,isOpen:t,onOpenChange:r}){let{t:n}=useTranslation(),{isMobile:o}=useScreen();return e?jsx(StyledModal,{isOpen:t,onOpenChange:r,size:o?"lg":"md",backdrop:"blur",hideCloseButton:true,classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{className:o?"":"p-2",children:[jsx(fn,{event:e.event,market:e.market,initialOutcome:e.initialOutcome,chain:e.chain,variant:"flat"}),jsx("div",{className:"px-4 pb-4",children:jsx("button",{type:"button",onClick:()=>r(false),className:"w-full h-12 rounded-xl text-sm font-medium text-zinc-400 hover:text-white hover:bg-[rgba(39,39,42,0.5)] transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:n("common.cancel")})})]})})}):null}var Zn={sortPreset:"volume",sortAsc:false,source:void 0,timeRemaining:void 0,minVolume:void 0,minLiquidity:void 0};function eo(e){let t=0;return e.source&&t++,e.timeRemaining&&t++,e.minVolume&&t++,e.minLiquidity&&t++,t}function bi({isOpen:e,onClose:t,value:r,onChange:n}){let{t:o}=useTranslation(),[i,a]=useState(r),l=useCallback(h=>{h?a(r):t();},[r,t]),s=useCallback(()=>{a(Zn);},[]),c=useCallback(()=>{n(i),t();},[i,n,t]),m=useCallback((h,v)=>{a(k=>({...k,[h]:v}));},[]),u=useMemo(()=>eo(i),[i]),p=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"polymarket",label:o("predict.platform.polymarket")},{value:"kalshi",label:o("predict.platform.kalshi")}],[o]),d=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1d",label:o("predict.filter.lessThanDay")},{value:"7d",label:o("predict.filter.lessThanWeek")},{value:"30d",label:o("predict.filter.lessThanMonth")}],[o]),f=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[o]),g=useMemo(()=>[{value:void 0,label:o("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[o]);return jsx(StyledModal,{isOpen:e,onOpenChange:l,size:"md",backdrop:"blur",scrollBehavior:"inside",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]",body:"!p-0"},children:jsx(ModalContent,{children:jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4",children:[jsx("h3",{className:"text-base font-semibold text-white",children:o("predict.filter.title")}),jsx(Bc,{onClick:()=>l(false)})]}),jsxs("div",{style:{padding:"0 20px 16px",display:"flex",flexDirection:"column",gap:20},children:[jsx(vn,{label:o("predict.filter.platform"),children:jsx(xn,{options:p,selected:i.source,onSelect:h=>m("source",h)})}),jsx(vn,{label:o("predict.filter.timeRemaining"),children:jsx(xn,{options:d,selected:i.timeRemaining,onSelect:h=>m("timeRemaining",h)})}),jsx(vn,{label:o("predict.filter.minVolume"),children:jsx(xn,{options:f,selected:i.minVolume,onSelect:h=>m("minVolume",h)})}),jsx(vn,{label:o("predict.filter.minLiquidity"),children:jsx(xn,{options:g,selected:i.minLiquidity,onSelect:h=>m("minLiquidity",h)})})]}),jsxs("div",{className:"flex items-center gap-3 px-5 py-4",style:{borderTop:"1px solid rgba(39,39,42,0.5)"},children:[jsx("button",{type:"button",className:"inline-flex items-center justify-center py-2.5 px-5 rounded-[10px] text-zinc-400 text-sm font-medium hover:text-white transition-colors cursor-pointer",onClick:s,children:o("predict.filter.reset")}),jsxs("button",{type:"button",className:"flex-1 inline-flex items-center justify-center gap-2 py-2.5 rounded-[10px] bg-[#c7ff2e] text-zinc-900 text-sm font-semibold hover:bg-[#c7ff2e]/90 transition-colors cursor-pointer",onClick:c,children:[o("predict.filter.showResults"),u>0&&jsxs("span",{style:{opacity:.7},children:["(",u,")"]})]})]})]})})})}function vn({label:e,children:t}){return jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[jsx("span",{style:{fontSize:11,fontWeight:500,color:"#71717a",textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),t]})}function Bc({onClick:e}){return jsx("button",{type:"button",onClick:e,className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",children:jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}function xn({options:e,selected:t,onSelect:r,allowDeselect:n=true}){return jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:e.map(o=>{let i=t===o.value;return jsx("button",{type:"button",onClick:()=>{r(i&&n?void 0:o.value);},style:{flexShrink:0,borderRadius:10,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer",transition:"all 0.15s",border:i?"1px solid rgba(199,255,46,0.3)":"1px solid rgba(63,63,70,0.5)",background:i?"rgba(199,255,46,0.08)":"rgba(39,39,42,0.4)",color:i?"#c7ff2e":"#a1a1aa"},onMouseEnter:a=>{i||(a.currentTarget.style.background="rgba(39,39,42,0.8)",a.currentTarget.style.color="#fff");},onMouseLeave:a=>{i||(a.currentTarget.style.background="rgba(39,39,42,0.4)",a.currentTarget.style.color="#a1a1aa");},children:o.label},o.value??"__all")})})}var Pi={start_time:{sort_by:"created_at"},volume:{sort_by:"volume"},liquidity:{sort_by:"liquidity"},ending_soon:{sort_by:"end_at"}},ki={start_time:"predict.sort.startTime",volume:"predict.sort.volume",liquidity:"predict.sort.liquidity",ending_soon:"predict.sort.endingSoon"},Yc=["start_time","volume","liquidity","ending_soon"],Si={display:"inline-flex",alignItems:"center",gap:8,borderRadius:10,border:"1px solid rgba(63,63,70,0.5)",background:"rgba(39,39,42,0.6)",padding:"8px 12px",fontSize:14,color:"#d4d4d8",cursor:"pointer",transition:"all 0.15s"},Gc={position:"absolute",left:0,top:"100%",zIndex:20,marginTop:8,borderRadius:14,border:"1px solid rgba(39,39,42,1)",background:"rgba(24,24,27,1)",boxShadow:"0 25px 50px -12px rgba(0,0,0,0.5)",overflow:"hidden"};function Ni({sortPreset:e,onSortChange:t,sortAsc:r,onSortAscChange:n,onFilterPress:o,filterCount:i=0,className:a}){let{t:l}=useTranslation(),[s,c]=useState(false),m=useRef(null),u=useCallback(d=>{m.current&&!m.current.contains(d.target)&&c(false);},[]);useEffect(()=>(document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)),[u]),useEffect(()=>{if(!s)return;let d=f=>{f.key==="Escape"&&c(false);};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[s]);let p=wi[e];return jsxs("div",{className:a,style:{display:"flex",alignItems:"center",gap:8},children:[jsxs("div",{ref:m,style:{position:"relative"},children:[jsxs("button",{type:"button",style:Si,onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)";},onClick:()=>c(d=>!d),children:[jsx(qc,{}),jsx(p,{className:"size-4 shrink-0",style:{color:"#a1a1aa"}}),jsx("span",{className:"hidden sm:block",style:{color:"#d4d4d8"},children:l(ki[e])}),jsx(Xc,{open:s})]}),s&&jsx("div",{style:{...Gc,width:224,padding:4},children:Yc.map(d=>{let f=wi[d],g=e===d;return jsxs("button",{type:"button",style:{display:"flex",width:"100%",alignItems:"center",gap:12,padding:"10px 12px",textAlign:"left",fontSize:14,border:"none",cursor:"pointer",transition:"all 0.15s",background:g?"rgba(199,255,46,0.08)":"transparent",color:g?"#c7ff2e":"#a1a1aa",borderRadius:10},onMouseEnter:h=>{g||(h.currentTarget.style.background="rgba(39,39,42,0.5)",h.currentTarget.style.color="#fff");},onMouseLeave:h=>{g||(h.currentTarget.style.background="transparent",h.currentTarget.style.color="#a1a1aa");},onClick:()=>{e===d?n(!r):t(d),c(false);},children:[jsx(f,{className:"size-4 shrink-0",style:{color:g?"#c7ff2e":"#71717a"}}),jsx("span",{style:{flex:1,fontWeight:500},children:l(ki[d])}),g&&jsx("svg",{viewBox:"0 0 24 24",style:{width:16,height:16,color:"#c7ff2e",flexShrink:0},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M20 6 9 17l-5-5"})})]},d)})})]}),jsx("button",{type:"button",style:{borderRadius:10,border:"1px solid rgba(63,63,70,0.5)",background:"rgba(39,39,42,0.6)",width:36,height:36,color:"#a1a1aa",cursor:"pointer",transition:"all 0.15s",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:14},onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)",d.currentTarget.style.color="#fff";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)",d.currentTarget.style.color="#a1a1aa";},onClick:()=>n(!r),children:r?"\u2191":"\u2193"}),jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[jsxs("button",{type:"button",style:Si,onMouseEnter:d=>{d.currentTarget.style.background="rgba(39,39,42,1)";},onMouseLeave:d=>{d.currentTarget.style.background="rgba(39,39,42,0.6)";},onClick:o,children:[jsx(Qc,{}),jsx("span",{className:"hidden sm:block",style:{color:"#d4d4d8"},children:l("predict.filter.title")})]}),i>0&&jsx("span",{style:{position:"absolute",top:-4,right:-4,minWidth:16,height:16,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,background:"#c7ff2e",color:"#000",fontSize:10,fontWeight:600,padding:"0 4px"},children:i})]})]})}var wi={start_time:CalendarIcon,volume:ChartLineIcon,liquidity:DropletIcon,ending_soon:TimerIcon};function qc(){return jsxs("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#a1a1aa"},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m21 16-4 4-4-4"}),jsx("path",{d:"M17 20V4"}),jsx("path",{d:"m3 8 4-4 4 4"}),jsx("path",{d:"M7 4v16"})]})}function Qc(){return jsx("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#a1a1aa"},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"})})}function Xc({open:e}){return jsx("svg",{viewBox:"0 0 24 24",style:{width:14,height:14,color:"#71717a",transition:"transform 0.15s",transform:e?"rotate(180deg)":void 0},fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"m6 9 6 6 6-6"})})}function Ei(e={}){let t=useMemo(()=>resolveEventsParams(e),[e.tagSlugSelection,e.limit,e.status,e.sort_by,e.sort_asc,e.source,e.with_markets,e.minVolume,e.minLiquidity,e.timeRemaining,e.markets_limit]),{data:r,isLoading:n,isFetching:o,isFetchingNextPage:i,isError:a,error:l,hasNextPage:s,fetchNextPage:c,refetch:m}=useInfiniteEvents(t),u=useMemo(()=>r?.pages.flatMap(f=>f.items).filter(f=>f!=null)??[],[r]),p=useCallback(()=>{c();},[c]),d=useCallback(()=>{m();},[m]);return {data:u,isLoading:n,isFetching:o&&!i,isFetchingMore:i,isError:a,error:l??null,hasMore:s??false,fetchMore:p,refetch:d}}var Ti=`
|
|
2
2
|
@keyframes evtShimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
|
|
3
3
|
@media(max-width:1279px){.evt-skel-grid{grid-template-columns:repeat(3,1fr)!important}}
|
|
4
4
|
@media(max-width:1023px){.evt-skel-grid{grid-template-columns:repeat(2,1fr)!important}.evt-skel-card{min-height:200px!important}}
|