@liberfi.io/ui-perpetuals 0.2.1 → 0.2.3

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,4 +1,4 @@
1
- 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),ui=require('@liberfi.io/ui'),reactHookForm=require('react-hook-form');typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.1");var Zt="0.2.1";var j=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;constructor(e){this.wsEndpoint=e;}async connect(){return new Promise((e,r)=>{try{this.ws&&this.ws.close(),this.ws=new WebSocket(this.wsEndpoint),this.ws.onopen=()=>{console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),e();},this.ws.onmessage=s=>{this.handleMessage(s.data);},this.ws.onerror=s=>{console.error("[WebSocket] Error:",s),this.isConnected=!1,this.isReconnecting||r(new Error("WebSocket connection failed"));},this.ws.onclose=s=>{console.log(`[WebSocket] Closed: ${s.code} - ${s.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),s.code!==1e3&&this.attemptReconnect();};}catch(s){r(s);}})}disconnect(){this.stopHeartbeat(),this.subscriptions.clear(),this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(1e3,"Normal closure"),this.ws=null),this.isConnected=false,this.isReconnecting=false,this.reconnectAttempts=0;}attemptReconnect(){if(this.isReconnecting)return;if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[WebSocket] Max reconnection attempts reached");return}this.isReconnecting=true,this.reconnectAttempts++;let e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[WebSocket] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=window.setTimeout(()=>{this.connect().then(()=>{this.resubscribeAll();}).catch(r=>{console.error("[WebSocket] Reconnection failed:",r),this.isReconnecting=false;});},e);}startHeartbeat(){this.heartbeatInterval=window.setInterval(()=>{this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.send({method:"ping"});},this.pingInterval);}stopHeartbeat(){this.heartbeatInterval!==null&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}send(e){this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):this.messageQueue.push(e);}flushMessageQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}resubscribeAll(){this.subscriptions.forEach(e=>{this.sendSubscription(e.type,e.param);});}handleMessage(e){try{let r=JSON.parse(e);r.channel?this.handleChannelMessage(r):r.method;}catch(r){console.error("[WebSocket] Failed to parse message:",r,e);}}handleChannelMessage(e){let r=e.channel;this.subscriptions.forEach((s,n)=>{if(this.isChannelMatch(r,s.type,s.param))try{let o=this.transformData(s.type,e.data,s.param);s.callback(o);}catch(o){console.error(`[WebSocket] Error in subscription callback (${n}):`,o);}});}isChannelMatch(e,r,s){return r==="ticker"?e==="allMids":r==="trades"?e==="trades":r==="orderBook"?e==="l2Book":r==="candle"?e==="candle":r==="userFills"?e==="userFills":r==="userEvents"?e==="userEvents":false}transformData(e,r,s){return e==="ticker"?this.transformTickerData(r):e==="trades"?this.transformTradesData(r,s):e==="orderBook"?this.transformOrderBookData(r,s):e==="candle"?this.transformCandleData(r,s):e==="userFills"?this.transformUserFillsData(r):e==="userEvents"?this.transformUserEventsData(r):r}transformTickerData(e){let r=e.mids||{};return Object.entries(r).map(([s,n])=>({symbol:`${s}-USDC`,price:parseFloat(n),timestamp:Date.now()}))}transformTradesData(e,r){return Array.isArray(e)?e.map(s=>({symbol:r,side:s.side==="B"?"buy":"sell",price:parseFloat(s.px),quantity:parseFloat(s.sz),timestamp:s.time,tradeId:s.tid})):[]}transformOrderBookData(e,r){let[s,n]=e.levels||[[],[]];return {symbol:r,bids:s.map(o=>({price:parseFloat(o.px),quantity:parseFloat(o.sz),count:o.n})),asks:n.map(o=>({price:parseFloat(o.px),quantity:parseFloat(o.sz),count:o.n})),timestamp:e.time||Date.now()}}transformCandleData(e,r){let[s]=r.split(":");return {symbol:s,open:parseFloat(e.o),high:parseFloat(e.h),low:parseFloat(e.l),close:parseFloat(e.c),volume:parseFloat(e.v),timestamp:e.t,closeTimestamp:e.T}}transformUserFillsData(e){return Array.isArray(e)?e.map(r=>({tradeId:r.tid?.toString(),orderId:r.oid?.toString(),symbol:`${r.coin}-USDC`,side:r.dir?.includes("Long")?"long":"short",price:parseFloat(r.px),quantity:parseFloat(r.sz),fee:parseFloat(r.fee||"0"),feeCurrency:r.feeToken||"USDC",isMaker:r.side==="M",timestamp:r.time})):[]}transformUserEventsData(e){return e}sendSubscription(e,r){let s;if(e==="ticker")s={method:"subscribe",subscription:{type:"allMids"}};else if(e==="trades")s={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(e==="orderBook")s={method:"subscribe",subscription:{type:"l2Book",coin:r.split("-")[0]}};else if(e==="candle"){let[n,o]=r.split(":");s={method:"subscribe",subscription:{type:"candle",coin:n.split("-")[0],interval:o}};}else e==="userFills"?s={method:"subscribe",subscription:{type:"userFills",user:r}}:e==="userEvents"&&(s={method:"subscribe",subscription:{type:"userEvents",user:r}});s&&this.send(s);}sendUnsubscription(e,r){let s;if(e==="ticker")s={method:"unsubscribe",subscription:{type:"allMids"}};else if(e==="trades")s={method:"unsubscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(e==="orderBook")s={method:"unsubscribe",subscription:{type:"l2Book",coin:r.split("-")[0]}};else if(e==="candle"){let[n,o]=r.split(":");s={method:"unsubscribe",subscription:{type:"candle",coin:n.split("-")[0],interval:o}};}else e==="userFills"?s={method:"unsubscribe",subscription:{type:"userFills",user:r}}:e==="userEvents"&&(s={method:"unsubscribe",subscription:{type:"userEvents",user:r}});s&&this.send(s);}subscribe(e,r,s){let n=`${e}:${r}`;return this.subscriptions.set(n,{type:e,param:r,callback:s}),this.sendSubscription(e,r),n}unsubscribe(e){let r=this.subscriptions.get(e);r&&(this.sendUnsubscription(r.type,r.param),this.subscriptions.delete(e));}isConnectedNow(){return this.isConnected}};var lt={testnet:{api:"https://api.hyperliquid-testnet.xyz",ws:"wss://api.hyperliquid-testnet.xyz/ws"},mainnet:{api:"https://api.hyperliquid.xyz",ws:"wss://api.hyperliquid.xyz/ws"}},xe=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;constructor(e={}){this.environment=e.environment||"testnet",this.apiEndpoint=e.apiEndpoint||lt[this.environment].api,this._wsEndpoint=e.wsEndpoint||lt[this.environment].ws,this.timeout=e.timeout||3e4;}async request(e,r){let s=`${this.apiEndpoint}${e}`;try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(o),!i.ok)throw new _(`HTTP ${i.status}: ${i.statusText}`,i.status,await i.text());return await i.json()}catch(n){throw n.name==="AbortError"?new _(`Request timeout after ${this.timeout}ms`,408,""):n instanceof _?n:new _(`Network error: ${n.message}`,0,"")}}symbolToCoin(e){return e.split("-")[0]}parseInterval(e){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[e]}async getSupportedCoins(){let[e]=await this.request("/info",{type:"metaAndAssetCtxs"});return e.universe.map(r=>`${r.name}-USDC`)}async getMarket(e){let r=await this.getMarkets([e]);return r.length>0?r[0]:null}async getMarkets(e){let[r,s]=await this.request("/info",{type:"metaAndAssetCtxs"}),n=r.universe.map((o,i)=>{let a=s[i],l=`${o.name}-USDC`,c=parseFloat(a.midPx||a.markPx||"0"),u=a.prevDayPx?parseFloat(a.prevDayPx):c,d=u>0?(c-u)/u*100:0;return {symbol:l,price:c,change24h:d,volume24h:parseFloat(a.dayNtlVlm||"0"),fundingRate:parseFloat(a.funding||"0"),openInterest:parseFloat(a.openInterest||"0"),markPrice:parseFloat(a.markPx||"0"),indexPrice:parseFloat(a.oraclePx||a.midPx||"0")}});if(e&&e.length>0){let o=new Set(e);return n.filter(i=>o.has(i.symbol))}return n}async getKlines(e,r,s=100){let n=this.symbolToCoin(e),o=this.parseInterval(r),i=Date.now(),a=i-o*s;return (await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:a,endTime:i}})).map(c=>({symbol:e,open:parseFloat(c.o),high:parseFloat(c.h),low:parseFloat(c.l),close:parseFloat(c.c),volume:parseFloat(c.v),timestamp:c.t,closeTimestamp:c.T}))}async getOrderBook(e,r=10){let s=this.symbolToCoin(e),n=await this.request("/info",{type:"l2Book",coin:s}),[o,i]=n.levels;return {symbol:e,bids:o.slice(0,r).map(a=>({price:parseFloat(a.px),quantity:parseFloat(a.sz),count:a.n})),asks:i.slice(0,r).map(a=>({price:parseFloat(a.px),quantity:parseFloat(a.sz),count:a.n})),timestamp:n.time}}async getRecentTrades(e,r=50){let s=this.symbolToCoin(e);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(o=>({symbol:e,side:o.side==="B"?"buy":"sell",price:parseFloat(o.px),quantity:parseFloat(o.sz),timestamp:o.time,tradeId:o.tid}))}async placeOrder(e){throw new Error("placeOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async cancelOrder(e){throw new Error("cancelOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async getPositions(e={}){if(!e.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"clearinghouseState",user:e.userAddress}),s=r.assetPositions.map(o=>{let i=o.position,a=`${i.coin}-USDC`,l=parseFloat(i.szi);if(l===0)return null;let c=parseFloat(i.entryPx),u=parseFloat(i.unrealizedPnl),d=parseFloat(i.positionValue);return {symbol:a,side:l>0?"long":"short",quantity:Math.abs(l),entryPrice:c,markPrice:c,unrealizedPnl:u,unrealizedPnlPercent:parseFloat(i.returnOnEquity)*100,leverage:i.leverage.value,liquidationPrice:i.liquidationPx?parseFloat(i.liquidationPx):void 0,margin:parseFloat(i.marginUsed),notionalValue:Math.abs(d)}}).filter(Boolean),n=e.symbol?s.filter(o=>o.symbol===e.symbol):s;return {positions:n,totalEquity:parseFloat(r.marginSummary.accountValue),availableBalance:parseFloat(r.marginSummary.accountValue)-parseFloat(r.marginSummary.totalMarginUsed),totalUnrealizedPnl:n.reduce((o,i)=>o+i.unrealizedPnl,0),raw:r}}async getOpenOrders(e={}){if(!e.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"openOrders",user:e.userAddress}),s=r.map(o=>{let i=`${o.coin}-USDC`,a=parseFloat(o.origSz),l=parseFloat(o.sz),c=a-l;return {orderId:o.oid.toString(),clientOrderId:o.cloid,symbol:i,side:o.side?"long":"short",orderType:"limit",price:parseFloat(o.limitPx),quantity:a,filledQuantity:c,remainingQuantity:l,status:c>0&&l>0?"partially_filled":"pending",timestamp:o.timestamp,updateTimestamp:o.timestamp}}),n=e.symbol?s.filter(o=>o.symbol===e.symbol):s;return {orders:n,totalCount:n.length,raw:r}}async getTrades(e={}){if(!e.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"userFills",user:e.userAddress}),s=r.map(n=>{let o=`${n.coin}-USDC`,i=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:o,side:i?"long":"short",price:parseFloat(n.px),quantity:parseFloat(n.sz),fee:parseFloat(n.fee||"0"),feeCurrency:n.feeToken||"USDC",isMaker:n.side==="M",timestamp:n.time}});return e.symbol&&(s=s.filter(n=>n.symbol===e.symbol)),e.startTime&&(s=s.filter(n=>n.timestamp>=e.startTime)),e.endTime&&(s=s.filter(n=>n.timestamp<=e.endTime)),e.limit&&(s=s.slice(0,e.limit)),{trades:s,totalCount:s.length,raw:r}}async connectWebSocket(){if(this.wsManager||(this.wsManager=new j(this._wsEndpoint)),this.wsManager.isConnectedNow()){console.log("[WebSocket] Already connected");return}await this.wsManager.connect();}disconnectWebSocket(){this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(e,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(e,r,s)}subscribeCandles(e,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=`${e}:${r}`;return this.wsManager.subscribe("candle",n,s)}subscribeUserData(e,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=e==="fills"?"userFills":"userEvents";return this.wsManager.subscribe(n,r,s)}unsubscribe(e){this.wsManager&&this.wsManager.unsubscribe(e);}},_=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var H=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},er="wss://api.hyperliquid.xyz/ws",tr=3e4,Pe=class{baseUrl;wsEndpoint;timeout;provider;headers;signTypedData;wsManager=null;constructor(e){if(!e.baseUrl)throw new Error("LiberFiPerpetualsClient: `baseUrl` is required (e.g. https://api.liberfi.io/perpetuals).");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.wsEndpoint=e.wsEndpoint??er,this.timeout=e.timeout??tr,this.provider=e.provider,this.headers=e.headers,this.signTypedData=e.signTypedData;}url(e,r){let s=new URLSearchParams;if(this.provider&&s.set("provider",this.provider),r)for(let[o,i]of Object.entries(r))i===void 0||i===""||s.set(o,i);let n=s.toString();return `${this.baseUrl}${e}${n?`?${n}`:""}`}async request(e,r,s){let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout);try{let i=await fetch(r,{method:e,headers:{Accept:"application/json",...e==="POST"?{"Content-Type":"application/json"}:{},...this.headers},body:e==="POST"?JSON.stringify(s??{}):void 0,signal:n.signal});if(!i.ok){let l=await rr(i);throw new H(`HTTP ${i.status} ${i.statusText} from ${e} ${r}`,i.status,l)}return i.status===204?void 0:await i.json()}catch(i){if(i instanceof H)throw i;if(i instanceof Error&&i.name==="AbortError")throw new H(`Request timeout after ${this.timeout}ms: ${e} ${r}`,408,"");let a=i instanceof Error?i.message:String(i);throw new H(`Network error: ${e} ${r}: ${a}`,0,"")}finally{clearTimeout(o);}}async getSupportedCoins(){return (await this.request("GET",this.url("/v1/coins"))).map(r=>r.symbol)}async getMarket(e){try{return await this.request("GET",this.url(`/v1/markets/${encodeURIComponent(e)}`))}catch(r){if(r instanceof H&&r.statusCode===404)return null;throw r}}async getMarkets(e){let r=e&&e.length>0?{symbols:e.join(",")}:void 0;return this.request("GET",this.url("/v1/markets",r))}async getKlines(e,r,s=100){return this.request("GET",this.url(`/v1/markets/${encodeURIComponent(e)}/klines`,{interval:r,limit:String(s)}))}async getOrderBook(e,r=10){return this.request("GET",this.url(`/v1/markets/${encodeURIComponent(e)}/orderbook`,{maxLevel:String(r)}))}async getRecentTrades(e,r=50){return this.request("GET",this.url(`/v1/markets/${encodeURIComponent(e)}/trades`,{limit:String(r)}))}async getPositions(e={}){if(!e.userAddress)throw new Error("LiberFiPerpetualsClient.getPositions requires `userAddress`.");let r=await this.request("GET",this.url(`/v1/users/${encodeURIComponent(e.userAddress)}/positions`,{symbol:e.symbol}));return {positions:r.positions,totalEquity:r.account?.totalEquity,availableBalance:r.account?.availableBalance,totalUnrealizedPnl:r.account?.totalUnrealizedPnl,raw:r}}async getOpenOrders(e={}){if(!e.userAddress)throw new Error("LiberFiPerpetualsClient.getOpenOrders requires `userAddress`.");let r=await this.request("GET",this.url(`/v1/users/${encodeURIComponent(e.userAddress)}/orders`,{symbol:e.symbol}));return {orders:r,totalCount:r.length,raw:r}}async getTrades(e={}){if(!e.userAddress)throw new Error("LiberFiPerpetualsClient.getTrades requires `userAddress`.");let r=await this.request("GET",this.url(`/v1/users/${encodeURIComponent(e.userAddress)}/fills`,{symbol:e.symbol,limit:e.limit!==void 0?String(e.limit):void 0,startTime:e.startTime!==void 0?String(e.startTime):void 0,endTime:e.endTime!==void 0?String(e.endTime):void 0})),s=r.map(n=>({tradeId:n.tradeId,orderId:n.orderId,symbol:n.symbol,side:n.side,price:n.price,quantity:n.quantity,fee:n.fee,feeCurrency:n.feeCurrency,isMaker:n.isMaker,timestamp:n.timestamp}));return {trades:s,totalCount:s.length,raw:r}}async placeOrder(e){if(!this.signTypedData)throw new Error("LiberFiPerpetualsClient.placeOrder requires `signTypedData` to be configured.");if(!e.userAddress)throw new Error("LiberFiPerpetualsClient.placeOrder requires `userAddress` (the signing wallet).");let r=await this.request("POST",this.url("/v1/orders/prepare"),{userAddress:e.userAddress,symbol:e.symbol,side:e.side,orderType:e.orderType,amount:e.amount,price:e.price,leverage:e.leverage,reduceOnly:e.reduceOnly,takeProfitPrice:e.takeProfitPrice,stopLossPrice:e.stopLossPrice,clientOrderId:e.clientOrderId}),s=await this.signTypedData(r.typedData);return this.request("POST",this.url("/v1/orders/submit"),{action:r.action,signature:s,nonce:r.nonce,vaultAddress:r.vaultAddress})}async cancelOrder(e){if(!this.signTypedData)throw new Error("LiberFiPerpetualsClient.cancelOrder requires `signTypedData` to be configured.");if(!e.userAddress)throw new Error("LiberFiPerpetualsClient.cancelOrder requires `userAddress` (the signing wallet).");let r=await this.request("POST",this.url("/v1/orders/cancel/prepare"),{userAddress:e.userAddress,symbol:e.symbol,orderId:e.orderId,clientOrderId:e.clientOrderId}),s=await this.signTypedData(r.typedData);return this.request("POST",this.url("/v1/orders/cancel/submit"),{action:r.action,signature:s,nonce:r.nonce,vaultAddress:r.vaultAddress})}async connectWebSocket(){this.wsManager||(this.wsManager=new j(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(e,r,s){return this.requireWS().subscribe(e,r,s)}subscribeCandles(e,r,s){return this.requireWS().subscribe("candle",`${e}:${r}`,s)}subscribeUserData(e,r,s){let n=e==="fills"?"userFills":"userEvents";return this.requireWS().subscribe(n,r,s)}unsubscribe(e){this.wsManager&&this.wsManager.unsubscribe(e);}requireWS(){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager}};async function rr(t){try{return await t.text()}catch{return ""}}var ne=react.createContext({});function nr({client:t,children:e}){return jsxRuntime.jsx(ne.Provider,{value:{client:t},children:e})}function P(){let t=react.useContext(ne);if(!t||!t.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return t}function ct(){return ["perps","coins"]}async function ut(t){return await t.getSupportedCoins()}function ve(t={}){let{client:e}=P();return reactQuery.useQuery({queryKey:ct(),queryFn:async()=>ut(e),staleTime:300*1e3,...t})}function dt(t){return ["perps","market",t.symbol]}async function pt(t,{symbol:e}){return await t.getMarket(e)}function oe(t,e={}){let{client:r}=P();return reactQuery.useQuery({queryKey:dt(t),queryFn:async()=>pt(r,t),staleTime:10*1e3,...e})}function mt(t={}){return ["perps","markets",JSON.stringify((t.symbols??[]).sort())]}async function ft(t,{symbols:e}={}){return await t.getMarkets(e)}function Se(t={},e={}){let{client:r}=P();return reactQuery.useQuery({queryKey:mt(t),queryFn:async()=>ft(r,t),staleTime:10*1e3,...e})}function yt(t){return ["perps","klines",t.symbol,t.interval,String(t.limit??100)]}async function gt(t,{symbol:e,interval:r,limit:s}){return await t.getKlines(e,r,s)}function dr(t,e={}){let{client:r}=P();return reactQuery.useQuery({queryKey:yt(t),queryFn:async()=>gt(r,t),staleTime:30*1e3,...e})}function bt(t){return ["perps","orderBook",t.symbol,String(t.maxLevel??20)]}async function ht(t,{symbol:e,maxLevel:r}){return await t.getOrderBook(e,r)}function ke(t,e={}){let{client:r}=P();return reactQuery.useQuery({queryKey:bt(t),queryFn:async()=>ht(r,t),staleTime:5*1e3,...e})}function xt(t){return ["perps","recentTrades",t.symbol,String(t.limit??50)]}async function Pt(t,{symbol:e,limit:r}){return await t.getRecentTrades(e,r)}function Ce(t,e={}){let{client:r}=P();return reactQuery.useQuery({queryKey:xt(t),queryFn:async()=>Pt(r,t),staleTime:5*1e3,...e})}function vt(t){return ["perps","positions",t.userAddress??"",t.symbol??""]}async function St(t,e){return await t.getPositions(e)}function ie(t,e={}){let{client:r}=P(),{enabled:s=true,...n}=t;return reactQuery.useQuery({queryKey:vt(n),queryFn:async()=>St(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...e})}function kt(t){return ["perps","orders",t.userAddress??"",t.symbol??""]}async function Ct(t,e){return await t.getOpenOrders(e)}function we(t,e={}){let{client:r}=P(),{enabled:s=true,...n}=t;return reactQuery.useQuery({queryKey:kt(n),queryFn:async()=>Ct(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...e})}function wt(t){return ["perps","trades",t.userAddress??"",t.symbol??"",String(t.limit??50),String(t.startTime??""),String(t.endTime??"")]}async function Ot(t,e){return await t.getTrades(e)}function Oe(t,e={}){let{client:r}=P(),{enabled:s=true,...n}=t;return reactQuery.useQuery({queryKey:wt(n),queryFn:async()=>Ot(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...e})}async function Tt(t,e){return await t.placeOrder(e)}function ae(t={}){let{client:e}=P();return reactQuery.useMutation({mutationFn:async r=>Tt(e,r),...t})}async function Nt(t,e){return await t.cancelOrder(e)}function Te(t={}){let{client:e}=P();return reactQuery.useMutation({mutationFn:async r=>Nt(e,r),...t})}function V(t){let{type:e,symbol:r,enabled:s=true}=t,{client:n}=P(),[o,i]=react.useState(null),[a,l]=react.useState(false),[c,u]=react.useState(null),d=react.useCallback(f=>{i(f);},[]);return react.useEffect(()=>{if(!s)return;let f=null,p=true;return (async()=>{try{if(await n.connectWebSocket(),!p)return;l(!0),u(null),f=n.subscribeMarketData(e,r,d);}catch(y){p&&(u(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(p=false,f)try{n.unsubscribe(f);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),i(null);}},[n,e,r,s,d]),{data:o,isConnected:a,error:c}}function kr(t){let{symbol:e,interval:r,enabled:s=true}=t,{client:n}=P(),[o,i]=react.useState(null),[a,l]=react.useState(false),[c,u]=react.useState(null),d=react.useCallback(f=>{i(f);},[]);return react.useEffect(()=>{if(!s)return;let f=null,p=true;return (async()=>{try{if(await n.connectWebSocket(),!p)return;l(!0),u(null),f=n.subscribeCandles(e,r,d);}catch(y){p&&(u(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(p=false,f)try{n.unsubscribe(f);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),i(null);}},[n,e,r,s,d]),{data:o,isConnected:a,error:c}}function le(t){let{type:e,userAddress:r,enabled:s=true}=t,{client:n}=P(),[o,i]=react.useState(null),[a,l]=react.useState(false),[c,u]=react.useState(null),d=react.useCallback(f=>{i(f);},[]);return react.useEffect(()=>{if(!s||!r)return;let f=null,p=true;return (async()=>{try{if(await n.connectWebSocket(),!p)return;l(!0),u(null),f=n.subscribeUserData(e,r,d);}catch(y){p&&(u(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(p=false,f)try{n.unsubscribe(f);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),i(null);}},[n,e,r,s,d]),{data:o,isConnected:a,error:c}}function Me(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}function De(){return jsxRuntime.jsxs("div",{className:"flex items-center gap-6 px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-20 rounded"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-28 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]})]}),jsxRuntime.jsx("div",{className:"h-8 w-px bg-neutral-800"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-24 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-32 rounded"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-20 rounded"})]})]})]})]})}function Ee(t){let[e,r]=react.useState(),[s,n]=react.useState(0),{data:o,isPending:i}=oe({symbol:t}),{data:a,isConnected:l}=V({type:"ticker",symbol:t,enabled:!!o});return react.useEffect(()=>{o&&r(o);},[o]),react.useEffect(()=>{if(!a)return;let c=Or(a,t);c&&r(u=>Tr(u??o??void 0,c,t));},[a,o,t]),react.useEffect(()=>{let c=()=>{let d=Date.now(),f=480*60*1e3,p=d%f,g=f-p;return Math.floor(g/1e3)};n(c());let u=setInterval(()=>{n(c());},1e3);return ()=>clearInterval(u)},[]),{marketData:e,isLoading:i,fundingCountdown:s}}function Or(t,e){if(Array.isArray(t)){let r=t.find(s=>!s||typeof s!="object"?false:s.symbol===e);return r&&typeof r=="object"?r:null}return t&&typeof t=="object"?t:null}function J(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function Tr(t,e,r){return {symbol:e.symbol??t?.symbol??r,price:J(e.price,t?.price??0),change24h:J(e.change24h,t?.change24h??0),volume24h:J(e.volume24h,t?.volume24h??0),fundingRate:J(e.fundingRate,t?.fundingRate??0),openInterest:J(e.openInterest,t?.openInterest??0),markPrice:J(e.markPrice,t?.markPrice??0),indexPrice:typeof e.indexPrice=="number"&&Number.isFinite(e.indexPrice)?e.indexPrice:t?.indexPrice,high24h:typeof e.high24h=="number"&&Number.isFinite(e.high24h)?e.high24h:t?.high24h,low24h:typeof e.low24h=="number"&&Number.isFinite(e.low24h)?e.low24h:t?.low24h}}function Nr(t){let e=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60;return `${String(e).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function Mt(t,e=2){return typeof t!="number"||!Number.isFinite(t)?"-":t>=1e9?`$${(t/1e9).toFixed(e)}B`:t>=1e6?`$${(t/1e6).toFixed(e)}M`:t>=1e3?`$${(t/1e3).toFixed(e)}K`:`$${t.toFixed(e)}`}function Dt(t){return typeof t!="number"||!Number.isFinite(t)?"-":t>=1e3?t.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):t>=1?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):t.toFixed(6)}function Re({marketData:t,fundingCountdown:e}){let{symbol:r,price:s,change24h:n,indexPrice:o,volume24h:i,openInterest:a,fundingRate:l}=t,c=typeof n=="number"&&Number.isFinite(n)?n:0,u=typeof l=="number"&&Number.isFinite(l)?l:0,d=c>=0,f=c.toFixed(2);return jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:16},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Dt(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",f,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:16},children:[jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:o?Dt(o):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Mt(i,0)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Mt(a*(t.markPrice||s))})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Nr(e)})]})]})]})]})}function Ur({symbol:t}){let{marketData:e,isLoading:r,fundingCountdown:s}=Ee(t);return r?jsxRuntime.jsx(De,{}):e?jsxRuntime.jsx(Re,{marketData:e,fundingCountdown:s}):jsxRuntime.jsx(Me,{})}function ze({onSelectCoin:t}={}){let[e,r]=react.useState(""),[s,n]=react.useState([]),{data:o,isPending:i}=ve(),{data:a,isPending:l}=Se({symbols:o},{enabled:!!o&&o.length>0});react.useEffect(()=>{a&&n(a);},[a]);let c=react.useMemo(()=>{if(!e.trim())return s;let d=e.toLowerCase().trim();return s.filter(f=>f.symbol.toLowerCase().includes(d))},[s,e]);return {coins:s,isLoading:i||l,searchQuery:e,setSearchQuery:r,filteredCoins:c,handleSelectCoin:d=>{t?.(d);}}}function Et(t,e=2){return t>=1e9?`$${(t/1e9).toFixed(e)}B`:t>=1e6?`$${(t/1e6).toFixed(e)}M`:t>=1e3?`$${(t/1e3).toFixed(e)}K`:`$${t.toFixed(e)}`}function Ir(t){return t>=1e3?t.toFixed(2):t>=1?t.toFixed(4):t.toFixed(6)}function Ae({coins:t,searchQuery:e,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsxRuntime.jsx("div",{style:{padding:"16px 16px 12px"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsxRuntime.jsx(ui.SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsxRuntime.jsx("input",{type:"text",placeholder:"Search coins...",value:e,onChange:o=>r(o.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxRuntime.jsxs("div",{className:"flex-1 overflow-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):t.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:e?"No coins found":"No coins available"})}):t.map(o=>{let i=o.change24h>=0,a=o.change24h.toFixed(2),l=(o.fundingRate*100).toFixed(4),c=o.fundingRate>=0,u=o.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(o.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:d=>{let f=d.target;f.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:Ir(o.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:i?"#C7FF2E":"#F76816",textAlign:"right"},children:[i?"+":"",a,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:c?"#C7FF2E":"#F76816",textAlign:"right"},children:[l,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Et(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Et(o.openInterest*o.price)})]},o.symbol)})]})]})}function Er({onSelectCoin:t,className:e}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:o,handleSelectCoin:i}=ze({onSelectCoin:t});return jsxRuntime.jsx("div",{className:e,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(Ae,{coins:r,searchQuery:n,onSearchChange:o,onSelectCoin:i,isLoading:s})})}function zt(t,e){if(e<=0)return t;let r=new Map;return t.forEach(s=>{let n=Math.floor(s.price/e)*e,o=r.get(n);o?(o.quantity+=s.quantity,s.count&&(o.count=(o.count||0)+s.count)):r.set(n,{price:n,quantity:s.quantity,count:s.count});}),Array.from(r.values())}function At(t){let e=0,r=t.map(n=>{let o=n.quantity*n.price;return e+=o,{...n,quantity:o,total:e,percentage:0}}),s=e;return r.map(n=>({...n,percentage:s>0?n.total/s*100:0}))}function Qe({symbol:t,maxLevel:e=20,precision:r=.01}){let[s,n]=react.useState(null),[o,i]=react.useState(r),{data:a,isPending:l}=ke({symbol:t,maxLevel:e}),{data:c}=V({type:"orderBook",symbol:t,enabled:!!a});return react.useEffect(()=>{c?n(c):a&&n(a);},[c,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let d=zt(s.bids,o),f=zt(s.asks,o),p=d.sort((E,R)=>R.price-E.price).slice(0,e),g=f.sort((E,R)=>E.price-R.price).slice(0,e),y=At(p),w=At(g),x=y[0]?.price||0,D=(w[0]?.price||0)-x,$=x>0?D/x*100:0;return {bids:y,asks:w,spread:D,spreadPercentage:$}},[s,o,e]),isLoading:l,precision:o,setPrecision:i}}function zr(t){return t>=1e3?t.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):t>=1?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):t.toFixed(6)}function Qt(t){return Math.round(t).toLocaleString("en-US")}function Lt({price:t,quantity:e,total:r,percentage:s,side:n,onClick:o}){let i=n==="ask";return jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:{height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},onClick:o,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:{height:20,width:`${s}%`,background:i?"linear-gradient(to right, rgba(247,104,22,0), #F76816)":"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15}}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:{flex:"1 1 0%"},children:jsxRuntime.jsx("span",{style:{color:i?"#F76816":"#C7FF2E",fontWeight:400},children:zr(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Qt(e)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Qt(r)})]})}function Le({bids:t,asks:e,spread:r,spreadPercentage:s,onPriceClick:n}){let o=[...e].reverse();return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000",fontSize:11},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},children:[jsxRuntime.jsx("div",{className:"flex items-center",style:{flex:"1 1 0%"},children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:{flex:"1 1 0%"},children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:{flex:"1 1 0%"},children:"Total (USD)"})]}),jsxRuntime.jsx("div",{className:"flex-1 flex flex-col-reverse overflow-hidden",children:o.map((i,a)=>jsxRuntime.jsx(Lt,{price:i.price,quantity:i.quantity,total:i.total,percentage:i.percentage,side:"ask",onClick:()=>n?.(i.price)},`ask-${i.price}-${a}`))}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:12,fontSize:12,color:"#ffffff"},children:[jsxRuntime.jsx("span",{style:{color:"#ffffff"},children:"Spread:"}),jsxRuntime.jsx("button",{type:"button",className:"hover:text-white transition-colors cursor-pointer",style:{color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0},onClick:()=>n?.(r),children:r>=1?Math.round(r).toLocaleString("en-US"):r.toFixed(4)}),jsxRuntime.jsxs("span",{style:{color:"#ffffff",fontWeight:500},children:[s.toFixed(3),"%"]})]})}),jsxRuntime.jsx("div",{className:"flex-1 overflow-hidden",children:t.map((i,a)=>jsxRuntime.jsx(Lt,{price:i.price,quantity:i.quantity,total:i.total,percentage:i.percentage,side:"bid",onClick:()=>n?.(i.price)},`bid-${i.price}-${a}`))})]})}function Ar(){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{padding:"0 16px"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:28,marginBottom:4},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]}),Array.from({length:10}).map((t,e)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]},`ask-skeleton-${e}`)),jsxRuntime.jsx("div",{className:"flex justify-center items-center",style:{height:28},children:jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-32 rounded"})}),Array.from({length:10}).map((t,e)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]},`bid-skeleton-${e}`))]})}function Qr(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function Lr({symbol:t,maxLevel:e=20,onPriceClick:r,className:s}){let{bids:n,asks:o,spread:i,spreadPercentage:a,isLoading:l}=Qe({symbol:t,maxLevel:e});return l?jsxRuntime.jsx(Ar,{}):n.length===0&&o.length===0?jsxRuntime.jsx(Qr,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(Le,{bids:n,asks:o,spread:i,spreadPercentage:a,onPriceClick:r})})}function Be({symbol:t,limit:e=50}){let[r,s]=react.useState([]),{data:n,isPending:o}=Ce({symbol:t,limit:e}),{data:i}=V({type:"trades",symbol:t,enabled:!!n});return react.useEffect(()=>{n&&s(n.filter(Wt));},[n]),react.useEffect(()=>{i&&s(a=>{let l=Wr(i);if(l.length===0)return a;let c=l.filter(d=>!a.some(f=>f.timestamp===d.timestamp&&f.price===d.price&&f.quantity===d.quantity));return c.length===0?a:[...c,...a].slice(0,e)});},[i,e]),{trades:r,isLoading:o}}function Wr(t){return (Array.isArray(t)?t:[t]).filter(Wt)}function Wt(t){return t?typeof t.symbol=="string"&&(t.side==="buy"||t.side==="sell")&&typeof t.price=="number"&&Number.isFinite(t.price)&&typeof t.quantity=="number"&&Number.isFinite(t.quantity)&&typeof t.timestamp=="number"&&Number.isFinite(t.timestamp):false}function $r(t){return typeof t!="number"||!Number.isFinite(t)?"-":t>=1e3?t.toFixed(2):t>=1?t.toFixed(4):t.toFixed(6)}function $t(t){return typeof t!="number"||!Number.isFinite(t)?"-":t>=1e6?(t/1e6).toFixed(2)+"M":t>=1e3?(t/1e3).toFixed(2)+"K":t.toFixed(2)}function Hr(t){if(typeof t!="number"||!Number.isFinite(t))return "-";let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),n=String(e.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function $e({trades:t,onTradeClick:e}){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full overflow-auto",style:{backgroundColor:"#000000",fontSize:11},children:[jsxRuntime.jsxs("div",{className:"sticky top-0 z-10 flex items-center",style:{height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},children:[jsxRuntime.jsx("div",{className:"flex-1",style:{maxWidth:100},children:"Price"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",children:"Amount"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100},children:"Total"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70},children:"Time"})]}),jsxRuntime.jsx("div",{className:"flex-1",children:t.map((r,s)=>{let n=r.side==="buy",o=typeof r.price=="number"&&Number.isFinite(r.price)&&typeof r.quantity=="number"&&Number.isFinite(r.quantity)?r.price*r.quantity:void 0;return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:{height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},onClick:()=>e?.(r),children:[jsxRuntime.jsx("div",{className:"flex-1",style:{maxWidth:100},children:jsxRuntime.jsx("span",{style:{color:n?"#C7FF2E":"#F76816",fontWeight:400},children:$r(r.price)})}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{color:"#ffffff"},children:$t(r.quantity)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100,color:"#ffffff"},children:$t(o)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70,color:"#b5b5b5"},children:Hr(r.timestamp)})]},`${r.timestamp}-${r.price}-${s}`)})})]})}function Kr(){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{padding:"0 16px"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:28,marginBottom:4},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"})]}),Array.from({length:12}).map((t,e)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"})]},`trade-skeleton-${e}`))]})}function Gr(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function _r({symbol:t,limit:e=50,onTradeClick:r,className:s}){let{trades:n,isLoading:o}=Be({symbol:t,limit:e});return o?jsxRuntime.jsx(Kr,{}):n.length===0?jsxRuntime.jsx(Gr,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx($e,{trades:n,onTradeClick:r})})}function Ke({symbol:t,userAddress:e,maxLeverage:r=150,onSuccess:s,onError:n}){let[o,i]=react.useState("long"),[a,l]=react.useState("market"),c=reactHookForm.useForm({defaultValues:{amount:0,leverage:20,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:u}=oe({symbol:t}),{mutateAsync:d,isPending:f}=ae({onSuccess:()=>{c.reset(),s?.();},onError:k=>{n?.(k);}}),p=c.watch(),{amount:g,leverage:y,price:w}=p,x=react.useMemo(()=>a==="limit"&&w?w:u?.price||0,[a,w,u?.price]),L=react.useMemo(()=>!g||!x?0:g*x*5e-4,[g,x]),D=react.useMemo(()=>!g||!x?0:g*x+L,[g,x,L]),$=react.useMemo(()=>{if(!g||!x||!y||y===1)return;let k=.005,de=x;return o==="long"?de*(1-(1/y-k)):de*(1+(1/y-k))},[g,x,y,o]),{data:E}=ie({userAddress:e,symbol:t}),R=E?.totalEquity??0,ge=E?.availableBalance??0,C=react.useMemo(()=>{let k=E?.positions?.[0];return k?k.side==="short"?-k.quantity:k.quantity:0},[E?.positions]),re=react.useCallback(async k=>{if(!e)throw new Error("User address is required");let de=a==="limit"?k.price:void 0,be=k.takeProfitPrice,he=k.stopLossPrice;if(!be&&k.takeProfitPercent&&k.takeProfitPercent>0&&x){let se=k.takeProfitPercent/100;be=o==="long"?x*(1+se):x*(1-se);}if(!he&&k.stopLossPercent&&k.stopLossPercent>0&&x){let se=k.stopLossPercent/100;he=o==="long"?x*(1-se):x*(1+se);}await d({symbol:t,side:o,orderType:a,amount:k.amount,price:de,leverage:k.leverage,takeProfitPrice:be,stopLossPrice:he,userAddress:e});},[t,o,a,x,e,d]);return {form:c,side:o,orderType:a,setSide:i,setOrderType:l,handleSubmit:re,isSubmitting:f,currentPrice:x,estimatedFee:L,estimatedTotal:D,liquidationPrice:$,availableMargin:ge,accountValue:R,currentPosition:C,maxLeverage:r}}function me(t,e=2){return t.toFixed(e)}function Zr({leverage:t,maxLeverage:e,onLeverageChange:r,onClose:s}){let n=[1,2,3,5,10,20,25,50,100].filter(o=>o<=e);return jsxRuntime.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[jsxRuntime.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:s,onKeyDown:o=>o.key==="Escape"&&s(),role:"button",tabIndex:-1,"aria-label":"Close"}),jsxRuntime.jsxs("div",{className:"relative z-10 w-72 bg-neutral-900 border border-neutral-700 rounded-lg p-4 shadow-2xl",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-4",children:[jsxRuntime.jsx("h3",{className:"text-sm font-medium text-white",children:"Adjust Leverage"}),jsxRuntime.jsx("button",{type:"button",onClick:s,className:"text-neutral-400 hover:text-white",children:jsxRuntime.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]}),jsxRuntime.jsxs("div",{className:"text-center text-2xl font-bold text-white mb-4",children:[t,"x"]}),jsxRuntime.jsx(ui.Slider,{value:[t],onChange:o=>r(Array.isArray(o)?o[0]:o),minValue:1,maxValue:e,step:1,className:"w-full mb-3"}),jsxRuntime.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>jsxRuntime.jsxs("button",{type:"button",className:ui.cn("px-2.5 py-1 text-xs rounded transition-colors",t===o?"bg-green-600 text-white":"bg-neutral-800 text-neutral-400 hover:bg-neutral-700"),onClick:()=>r(o),children:[o,"x"]},o))}),jsxRuntime.jsx("button",{type:"button",className:"w-full mt-4 text-white h-9 rounded cursor-pointer transition-colors",style:{backgroundColor:"#C7FF2E"},onClick:s,children:"Confirm"})]})]})}function Ge({methods:t,side:e,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:o,isSubmitting:i,symbol:a,currentPrice:l,estimatedFee:c,liquidationPrice:u,availableMargin:d,accountValue:f,currentPosition:p,maxLeverage:g}){let[y,w]=react.useState(false),[x,L]=react.useState(false),D=t.watch("leverage")||20,$=t.watch("amount")||0,E=a.split("-")[0],R=d>0&&l?Math.min($*l/(d*D)*100,100):0,ge=C=>{let re=(Array.isArray(C)?C[0]:C)/100;if(l&&l>0){let k=d*D*re/l;t.setValue("amount",Number(k.toFixed(6)));}};return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsxs("div",{className:"perp-order-form flex-1 overflow-y-auto",style:{padding:"16px 16px",display:"flex",flexDirection:"column",gap:16},children:[jsxRuntime.jsxs("div",{className:"flex",style:{border:"1px solid rgba(26,26,26,0.5)",borderRadius:8,padding:4,gap:4},children:[jsxRuntime.jsx("button",{type:"button",className:"flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:16,borderRadius:4,backgroundColor:e==="long"?"#C7FF2E":"transparent",color:e==="long"?"#000000":"#b5b5b5",fontWeight:e==="long"?700:500},onClick:()=>s("long"),children:"Long"}),jsxRuntime.jsx("button",{type:"button",className:"flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:16,borderRadius:4,backgroundColor:e==="short"?"#F76816":"transparent",color:e==="short"?"#000000":"#b5b5b5",fontWeight:e==="short"?700:500},onClick:()=>s("short"),children:"Short"})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:"Market"},{key:"limit",label:"Limit"}].map(C=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===C.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===C.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(C.key),children:C.label})},C.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer transition-colors",style:{height:24,padding:"0 5px",fontSize:12,borderRadius:4,backgroundColor:"rgba(26,26,26,0.5)",color:"#ffffff",fontWeight:400,border:"1px solid rgba(26,26,26,0.5)"},onClick:()=>w(true),children:["Leverage: ",D,"x"]})]}),jsxRuntime.jsx(ui.RHForm,{methods:t,onSubmit:o,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[r==="limit"&&jsxRuntime.jsxs("div",{className:"perp-price-box",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Price"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"USDC"})]}),jsxRuntime.jsx(ui.RHNumberInput,{name:"price",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{className:"perp-buy-amt",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Buy Amount"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:E})]}),jsxRuntime.jsx(ui.RHNumberInput,{name:"amount",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
1
+ 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),ui=require('@liberfi.io/ui'),reactHookForm=require('react-hook-form'),i18n=require('@liberfi.io/i18n');typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.3");var us="0.2.3";var ue=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;constructor(t){this.wsEndpoint=t;}async connect(){return new Promise((t,r)=>{try{this.ws&&this.ws.close(),this.ws=new WebSocket(this.wsEndpoint),this.ws.onopen=()=>{console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),t();},this.ws.onmessage=s=>{this.handleMessage(s.data);},this.ws.onerror=s=>{console.error("[WebSocket] Error:",s),this.isConnected=!1,this.isReconnecting||r(new Error("WebSocket connection failed"));},this.ws.onclose=s=>{console.log(`[WebSocket] Closed: ${s.code} - ${s.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),s.code!==1e3&&this.attemptReconnect();};}catch(s){r(s);}})}disconnect(){this.stopHeartbeat(),this.subscriptions.clear(),this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(1e3,"Normal closure"),this.ws=null),this.isConnected=false,this.isReconnecting=false,this.reconnectAttempts=0;}attemptReconnect(){if(this.isReconnecting)return;if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[WebSocket] Max reconnection attempts reached");return}this.isReconnecting=true,this.reconnectAttempts++;let t=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[WebSocket] Reconnecting in ${t}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=window.setTimeout(()=>{this.connect().then(()=>{this.resubscribeAll();}).catch(r=>{console.error("[WebSocket] Reconnection failed:",r),this.isReconnecting=false;});},t);}startHeartbeat(){this.heartbeatInterval=window.setInterval(()=>{this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.send({method:"ping"});},this.pingInterval);}stopHeartbeat(){this.heartbeatInterval!==null&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}send(t){this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(JSON.stringify(t)):this.messageQueue.push(t);}flushMessageQueue(){for(;this.messageQueue.length>0;){let t=this.messageQueue.shift();t&&this.send(t);}}resubscribeAll(){this.subscriptions.forEach(t=>{this.sendSubscription(t.type,t.param);});}handleMessage(t){try{let r=JSON.parse(t);r.channel?this.handleChannelMessage(r):r.method;}catch(r){console.error("[WebSocket] Failed to parse message:",r,t);}}handleChannelMessage(t){let r=t.channel;this.subscriptions.forEach((s,n)=>{if(this.isChannelMatch(r,s.type,s.param))try{let o=this.transformData(s.type,t.data,s.param);s.callback(o);}catch(o){console.error(`[WebSocket] Error in subscription callback (${n}):`,o);}});}isChannelMatch(t,r,s){return r==="ticker"?t==="allMids":r==="trades"?t==="trades":r==="orderBook"?t==="l2Book":r==="candle"?t==="candle":r==="userFills"?t==="userFills":r==="userEvents"?t==="userEvents":false}transformData(t,r,s){return t==="ticker"?this.transformTickerData(r):t==="trades"?this.transformTradesData(r,s):t==="orderBook"?this.transformOrderBookData(r,s):t==="candle"?this.transformCandleData(r,s):t==="userFills"?this.transformUserFillsData(r):t==="userEvents"?this.transformUserEventsData(r):r}transformTickerData(t){let r=t.mids||{};return Object.entries(r).map(([s,n])=>({symbol:`${s}-USDC`,price:parseFloat(n),timestamp:Date.now()}))}transformTradesData(t,r){return Array.isArray(t)?t.map(s=>({symbol:r,side:s.side==="B"?"buy":"sell",price:parseFloat(s.px),quantity:parseFloat(s.sz),timestamp:s.time,tradeId:s.tid})):[]}transformOrderBookData(t,r){let[s,n]=t.levels||[[],[]];return {symbol:r,bids:s.map(o=>({price:parseFloat(o.px),quantity:parseFloat(o.sz),count:o.n})),asks:n.map(o=>({price:parseFloat(o.px),quantity:parseFloat(o.sz),count:o.n})),timestamp:t.time||Date.now()}}transformCandleData(t,r){let[s]=r.split(":");return {symbol:s,open:parseFloat(t.o),high:parseFloat(t.h),low:parseFloat(t.l),close:parseFloat(t.c),volume:parseFloat(t.v),timestamp:t.t,closeTimestamp:t.T}}transformUserFillsData(t){return Array.isArray(t)?t.map(r=>({tradeId:r.tid?.toString(),orderId:r.oid?.toString(),symbol:`${r.coin}-USDC`,side:r.dir?.includes("Long")?"long":"short",price:parseFloat(r.px),quantity:parseFloat(r.sz),fee:parseFloat(r.fee||"0"),feeCurrency:r.feeToken||"USDC",isMaker:r.side==="M",timestamp:r.time})):[]}transformUserEventsData(t){return t}sendSubscription(t,r){let s;if(t==="ticker")s={method:"subscribe",subscription:{type:"allMids"}};else if(t==="trades")s={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook")s={method:"subscribe",subscription:{type:"l2Book",coin:r.split("-")[0]}};else if(t==="candle"){let[n,o]=r.split(":");s={method:"subscribe",subscription:{type:"candle",coin:n.split("-")[0],interval:o}};}else t==="userFills"?s={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(s={method:"subscribe",subscription:{type:"userEvents",user:r}});s&&this.send(s);}sendUnsubscription(t,r){let s;if(t==="ticker")s={method:"unsubscribe",subscription:{type:"allMids"}};else if(t==="trades")s={method:"unsubscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook")s={method:"unsubscribe",subscription:{type:"l2Book",coin:r.split("-")[0]}};else if(t==="candle"){let[n,o]=r.split(":");s={method:"unsubscribe",subscription:{type:"candle",coin:n.split("-")[0],interval:o}};}else t==="userFills"?s={method:"unsubscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(s={method:"unsubscribe",subscription:{type:"userEvents",user:r}});s&&this.send(s);}subscribe(t,r,s){let n=`${t}:${r}`;return this.subscriptions.set(n,{type:t,param:r,callback:s}),this.sendSubscription(t,r),n}unsubscribe(t){let r=this.subscriptions.get(t);r&&(this.sendUnsubscription(r.type,r.param),this.subscriptions.delete(t));}isConnectedNow(){return this.isConnected}};var Xt={testnet:{api:"https://api.hyperliquid-testnet.xyz",ws:"wss://api.hyperliquid-testnet.xyz/ws"},mainnet:{api:"https://api.hyperliquid.xyz",ws:"wss://api.hyperliquid.xyz/ws"}},Ge=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||Xt[this.environment].api,this._wsEndpoint=t.wsEndpoint||Xt[this.environment].ws,this.timeout=t.timeout||3e4;}async request(t,r){let s=`${this.apiEndpoint}${t}`;try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(o),!i.ok)throw new se(`HTTP ${i.status}: ${i.statusText}`,i.status,await i.text());return await i.json()}catch(n){throw n.name==="AbortError"?new se(`Request timeout after ${this.timeout}ms`,408,""):n instanceof se?n:new se(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){let[t]=await this.request("/info",{type:"metaAndAssetCtxs"});return t.universe.map(r=>`${r.name}-USDC`)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let[r,s]=await this.request("/info",{type:"metaAndAssetCtxs"}),n=r.universe.map((o,i)=>{let a=s[i],p=`${o.name}-USDC`,l=parseFloat(a.midPx||a.markPx||"0"),u=a.prevDayPx?parseFloat(a.prevDayPx):l,d=u>0?(l-u)/u*100:0;return {symbol:p,price:l,change24h:d,volume24h:parseFloat(a.dayNtlVlm||"0"),fundingRate:parseFloat(a.funding||"0"),openInterest:parseFloat(a.openInterest||"0"),markPrice:parseFloat(a.markPx||"0"),indexPrice:parseFloat(a.oraclePx||a.midPx||"0")}});if(t&&t.length>0){let o=new Set(t);return n.filter(i=>o.has(i.symbol))}return n}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),o=this.parseInterval(r),i=Date.now(),a=i-o*s;return (await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:a,endTime:i}})).map(l=>({symbol:t,open:parseFloat(l.o),high:parseFloat(l.h),low:parseFloat(l.l),close:parseFloat(l.c),volume:parseFloat(l.v),timestamp:l.t,closeTimestamp:l.T}))}async getOrderBook(t,r=10){let s=this.symbolToCoin(t),n=await this.request("/info",{type:"l2Book",coin:s}),[o,i]=n.levels;return {symbol:t,bids:o.slice(0,r).map(a=>({price:parseFloat(a.px),quantity:parseFloat(a.sz),count:a.n})),asks:i.slice(0,r).map(a=>({price:parseFloat(a.px),quantity:parseFloat(a.sz),count:a.n})),timestamp:n.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(o=>({symbol:t,side:o.side==="B"?"buy":"sell",price:parseFloat(o.px),quantity:parseFloat(o.sz),timestamp:o.time,tradeId:o.tid}))}async placeOrder(t){throw new Error("placeOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async cancelOrder(t){throw new Error("cancelOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async getPositions(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"clearinghouseState",user:t.userAddress}),s=r.assetPositions.map(o=>{let i=o.position,a=`${i.coin}-USDC`,p=parseFloat(i.szi);if(p===0)return null;let l=parseFloat(i.entryPx),u=parseFloat(i.unrealizedPnl),d=parseFloat(i.positionValue);return {symbol:a,side:p>0?"long":"short",quantity:Math.abs(p),entryPrice:l,markPrice:l,unrealizedPnl:u,unrealizedPnlPercent:parseFloat(i.returnOnEquity)*100,leverage:i.leverage.value,liquidationPrice:i.liquidationPx?parseFloat(i.liquidationPx):void 0,margin:parseFloat(i.marginUsed),notionalValue:Math.abs(d)}}).filter(Boolean),n=t.symbol?s.filter(o=>o.symbol===t.symbol):s;return {positions:n,totalEquity:parseFloat(r.marginSummary.accountValue),availableBalance:parseFloat(r.marginSummary.accountValue)-parseFloat(r.marginSummary.totalMarginUsed),totalUnrealizedPnl:n.reduce((o,i)=>o+i.unrealizedPnl,0),raw:r}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"openOrders",user:t.userAddress}),s=r.map(o=>{let i=`${o.coin}-USDC`,a=parseFloat(o.origSz),p=parseFloat(o.sz),l=a-p;return {orderId:o.oid.toString(),clientOrderId:o.cloid,symbol:i,side:o.side?"long":"short",orderType:"limit",price:parseFloat(o.limitPx),quantity:a,filledQuantity:l,remainingQuantity:p,status:l>0&&p>0?"partially_filled":"pending",timestamp:o.timestamp,updateTimestamp:o.timestamp}}),n=t.symbol?s.filter(o=>o.symbol===t.symbol):s;return {orders:n,totalCount:n.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"userFills",user:t.userAddress}),s=r.map(n=>{let o=`${n.coin}-USDC`,i=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:o,side:i?"long":"short",price:parseFloat(n.px),quantity:parseFloat(n.sz),fee:parseFloat(n.fee||"0"),feeCurrency:n.feeToken||"USDC",isMaker:n.side==="M",timestamp:n.time}});return t.symbol&&(s=s.filter(n=>n.symbol===t.symbol)),t.startTime&&(s=s.filter(n=>n.timestamp>=t.startTime)),t.endTime&&(s=s.filter(n=>n.timestamp<=t.endTime)),t.limit&&(s=s.slice(0,t.limit)),{trades:s,totalCount:s.length,raw:r}}async connectWebSocket(){if(this.wsManager||(this.wsManager=new ue(this._wsEndpoint)),this.wsManager.isConnectedNow()){console.log("[WebSocket] Already connected");return}await this.wsManager.connect();}disconnectWebSocket(){this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(t,r,s)}subscribeCandles(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=`${t}:${r}`;return this.wsManager.subscribe("candle",n,s)}subscribeUserData(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=t==="fills"?"userFills":"userEvents";return this.wsManager.subscribe(n,r,s)}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}},se=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var _=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},ds=3e4,ne=class{baseUrl;timeout;headers;defaultQuery;fetchImpl;constructor(t){if(!t.baseUrl)throw new Error("LiberFiHttpTransport: `baseUrl` is required (e.g. https://api.liberfi.io/perpetuals).");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.timeout=t.timeout??ds,this.headers=t.headers,this.defaultQuery=t.defaultQuery,this.fetchImpl=t.fetchImpl??globalThis.fetch.bind(globalThis);}getBaseUrl(){return this.baseUrl}buildUrl(t,r){let s=new URLSearchParams;if(this.defaultQuery)for(let[o,i]of Object.entries(this.defaultQuery))i===void 0||i===""||s.set(o,i);if(r)for(let[o,i]of Object.entries(r))i===void 0||i===""||s.set(o,i);let n=s.toString();return `${this.baseUrl}${t}${n?`?${n}`:""}`}async request(t,r){let s=this.buildUrl(r.path,r.query),n=new AbortController,o=r.timeoutMs??this.timeout,i=setTimeout(()=>n.abort(),o);try{let a=await this.fetchImpl(s,{method:t,headers:{Accept:"application/json",...t==="POST"?{"Content-Type":"application/json"}:{},...this.headers,...r.headers},body:t==="POST"?JSON.stringify(r.body??{}):void 0,signal:n.signal});if(!a.ok){let p=await cs(a);throw new _(`HTTP ${a.status} ${a.statusText} from ${t} ${s}`,a.status,p)}return a.status===204?void 0:await a.json()}catch(a){if(a instanceof _)throw a;if(a instanceof Error&&a.name==="AbortError")throw new _(`Request timeout after ${o}ms: ${t} ${s}`,408,"");let p=a instanceof Error?a.message:String(a);throw new _(`Network error: ${t} ${s}: ${p}`,0,"")}finally{clearTimeout(i);}}};async function cs(e){try{return await e.text()}catch{return ""}}var ms="wss://api.hyperliquid.xyz/ws",Ve=class{transport;wsEndpoint;signTypedData;wsManager=null;constructor(t){if(t.transport)this.transport=t.transport;else {if(!t.baseUrl)throw new Error("LiberFiPerpetualsClient: either `baseUrl` or a pre-built `transport` is required.");this.transport=new ne({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??ms,this.signTypedData=t.signTypedData;}async getSupportedCoins(){return (await this.transport.request("GET",{path:"/v1/coins"})).map(r=>r.symbol)}async getMarket(t){try{return await this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}`})}catch(r){if(r instanceof _&&r.statusCode===404)return null;throw r}}async getMarkets(t){return this.transport.request("GET",{path:"/v1/markets",query:t&&t.length>0?{symbols:t.join(",")}:void 0})}async getKlines(t,r,s=100){return this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:{interval:r,limit:String(s)}})}async getOrderBook(t,r=10){return this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/orderbook`,query:{maxLevel:String(r)}})}async getRecentTrades(t,r=50){return this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/trades`,query:{limit:String(r)}})}async getPositions(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getPositions requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/positions`,query:{symbol:t.symbol}});return {positions:r.positions,totalEquity:r.account?.totalEquity,availableBalance:r.account?.availableBalance,totalUnrealizedPnl:r.account?.totalUnrealizedPnl,raw:r}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getOpenOrders requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/orders`,query:{symbol:t.symbol}});return {orders:r,totalCount:r.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getTrades requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/fills`,query:{symbol:t.symbol,limit:t.limit!==void 0?String(t.limit):void 0,startTime:t.startTime!==void 0?String(t.startTime):void 0,endTime:t.endTime!==void 0?String(t.endTime):void 0}}),s=r.map(n=>({tradeId:n.tradeId,orderId:n.orderId,symbol:n.symbol,side:n.side,price:n.price,quantity:n.quantity,fee:n.fee,feeCurrency:n.feeCurrency,isMaker:n.isMaker,timestamp:n.timestamp}));return {trades:s,totalCount:s.length,raw:r}}async placeOrder(t){if(!this.signTypedData)throw new Error("LiberFiPerpetualsClient.placeOrder requires `signTypedData` to be configured.");if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.placeOrder requires `userAddress` (the signing wallet).");let r=await this.transport.request("POST",{path:"/v1/orders/prepare",body:{userAddress:t.userAddress,symbol:t.symbol,side:t.side,orderType:t.orderType,amount:t.amount,price:t.price,leverage:t.leverage,reduceOnly:t.reduceOnly,takeProfitPrice:t.takeProfitPrice,stopLossPrice:t.stopLossPrice,clientOrderId:t.clientOrderId}}),s=await this.signTypedData(r.typedData);return this.transport.request("POST",{path:"/v1/orders/submit",body:{action:r.action,signature:s,nonce:r.nonce,vaultAddress:r.vaultAddress}})}async cancelOrder(t){if(!this.signTypedData)throw new Error("LiberFiPerpetualsClient.cancelOrder requires `signTypedData` to be configured.");if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.cancelOrder requires `userAddress` (the signing wallet).");let r=await this.transport.request("POST",{path:"/v1/orders/cancel/prepare",body:{userAddress:t.userAddress,symbol:t.symbol,orderId:t.orderId,clientOrderId:t.clientOrderId}}),s=await this.signTypedData(r.typedData);return this.transport.request("POST",{path:"/v1/orders/cancel/submit",body:{action:r.action,signature:s,nonce:r.nonce,vaultAddress:r.vaultAddress}})}async connectWebSocket(){this.wsManager||(this.wsManager=new ue(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s){return this.requireWS().subscribe(t,r,s)}subscribeCandles(t,r,s){return this.requireWS().subscribe("candle",`${t}:${r}`,s)}subscribeUserData(t,r,s){let n=t==="fills"?"userFills":"userEvents";return this.requireWS().subscribe(n,r,s)}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}requireWS(){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager}};var je=class{transport;constructor(t){this.transport="transport"in t?t.transport:new ne(t);}getBaseUrl(){return this.transport.getBaseUrl()}async quote(t){return this.transport.request("POST",{path:"/v1/deposits/quote",body:t})}async submit(t){return this.transport.request("POST",{path:"/v1/deposits/submit",body:t})}async status(t){if(!t)throw new Error("intentId is required");return this.transport.request("GET",{path:`/v1/deposits/${encodeURIComponent(t)}`})}async refresh(t){if(!t)throw new Error("intentId is required");return this.transport.request("POST",{path:`/v1/deposits/${encodeURIComponent(t)}/refresh`})}};var xe=new Set(["settled","refunded","failed"]);var Ue={phase:"idle"};function Je(e,t){switch(t.type){case "RESET":return Ue;case "QUOTE_REQUEST":return e.phase==="idle"||e.phase==="ready_to_sign"||e.phase==="expired"||e.phase==="failed"?{phase:"quoting"}:e;case "QUOTE_RECEIVED":return e.phase==="quoting"?{phase:"ready_to_sign",quote:t.quote,expiresAtMs:Date.parse(t.quote.expiresAt)}:e;case "QUOTE_FAILED":return e.phase==="quoting"?{phase:"failed",error:t.error}:e;case "QUOTE_EXPIRED":return e.phase==="ready_to_sign"?{phase:"expired",quote:e.quote}:e;case "SIGN_START":return e.phase==="ready_to_sign"?{phase:"signing",quote:e.quote}:e;case "SIGN_FAILED":return e.phase==="signing"?{phase:"failed",error:t.error}:e;case "BROADCAST_START":return e.phase==="signing"?{phase:"broadcasting",quote:e.quote}:e;case "BROADCAST_FAILED":return e.phase==="broadcasting"||e.phase==="signing"?{phase:"failed",error:t.error}:e;case "SUBMIT_OK":return e.phase==="broadcasting"?{phase:"submitted",quote:e.quote,intentId:t.intentId,solanaTxHash:t.solanaTxHash}:e;case "SUBMIT_FAILED":return e.phase==="broadcasting"?{phase:"failed",error:t.error}:e;case "STATUS_UPDATE":{if(e.phase!=="submitted"&&e.phase!=="tracking")return e;let r=(e.phase==="submitted",e.intentId);return fs(t.status,r)}}}function fs(e,t){switch(e.status){case "settled":return {phase:"succeeded",intentId:t,status:e};case "refunded":return {phase:"refunded",intentId:t,status:e};case "failed":case "stuck":return {phase:"failed",error:e.lastError??{code:e.status==="stuck"?"STUCK":"FAILED",message:e.status==="stuck"?"Deposit hasn't been observed by Relay yet \u2014 please contact support if this persists.":"Deposit failed. Funds will be refunded to your wallet shortly.",recoverable:false},intentId:t,status:e};default:return {phase:"tracking",intentId:t,status:e}}}function ys(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function gs(e){return e.phase==="submitted"||e.phase==="tracking"}function bs(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function hs(e){if(e.phase==="ready_to_sign"||e.phase==="signing"||e.phase==="broadcasting"||e.phase==="submitted"||e.phase==="expired")return e.quote.breakdown;if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.breakdown}function xs(e){return e!==void 0&&xe.has(e)}var oe=react.createContext({});function vs({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(oe.Provider,{value:s,children:r})}function P(){let e=react.useContext(oe);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Yt(){return ["perps","coins"]}async function Zt(e){return await e.getSupportedCoins()}function Xe(e={}){let{client:t}=P();return reactQuery.useQuery({queryKey:Yt(),queryFn:async()=>Zt(t),staleTime:300*1e3,...e})}function er(e){return ["perps","market",e.symbol]}async function tr(e,{symbol:t}){return await e.getMarket(t)}function Se(e,t={}){let{client:r}=P();return reactQuery.useQuery({queryKey:er(e),queryFn:async()=>tr(r,e),staleTime:10*1e3,...t})}function rr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function sr(e,{symbols:t}={}){return await e.getMarkets(t)}function Ye(e={},t={}){let{client:r}=P();return reactQuery.useQuery({queryKey:rr(e),queryFn:async()=>sr(r,e),staleTime:10*1e3,...t})}function nr(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function or(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function Ns(e,t={}){let{client:r}=P();return reactQuery.useQuery({queryKey:nr(e),queryFn:async()=>or(r,e),staleTime:30*1e3,...t})}function ir(e){return ["perps","orderBook",e.symbol,String(e.maxLevel??20)]}async function ar(e,{symbol:t,maxLevel:r}){return await e.getOrderBook(t,r)}function Ze(e,t={}){let{client:r}=P();return reactQuery.useQuery({queryKey:ir(e),queryFn:async()=>ar(r,e),staleTime:5*1e3,...t})}function pr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function lr(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function et(e,t={}){let{client:r}=P();return reactQuery.useQuery({queryKey:pr(e),queryFn:async()=>lr(r,e),staleTime:5*1e3,...t})}function ur(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function dr(e,t){return await e.getPositions(t)}function Pe(e,t={}){let{client:r}=P(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:ur(n),queryFn:async()=>dr(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function cr(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function mr(e,t){return await e.getOpenOrders(t)}function tt(e,t={}){let{client:r}=P(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:cr(n),queryFn:async()=>mr(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function fr(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function yr(e,t){return await e.getTrades(t)}function rt(e,t={}){let{client:r}=P(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:fr(n),queryFn:async()=>yr(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}async function gr(e,t){return await e.placeOrder(t)}function ve(e={}){let{client:t}=P();return reactQuery.useMutation({mutationFn:async r=>gr(t,r),...e})}async function br(e,t){return await e.cancelOrder(t)}function st(e={}){let{client:t}=P();return reactQuery.useMutation({mutationFn:async r=>br(t,r),...e})}function ie(e){let{type:t,symbol:r,enabled:s=true}=e,{client:n}=P(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(m=>{i(m);},[]);return react.useEffect(()=>{if(!s)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;p(!0),u(null),m=n.subscribeMarketData(t,r,d);}catch(y){f&&(u(y instanceof Error?y:new Error("Connection failed")),p(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function Hs(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=P(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(m=>{i(m);},[]);return react.useEffect(()=>{if(!s)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;p(!0),u(null),m=n.subscribeCandles(t,r,d);}catch(y){f&&(u(y instanceof Error?y:new Error("Connection failed")),p(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function De(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=P(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(m=>{i(m);},[]);return react.useEffect(()=>{if(!s||!r)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;p(!0),u(null),m=n.subscribeUserData(t,r,d);}catch(y){f&&(u(y instanceof Error?y:new Error("Connection failed")),p(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function ae(){let e=react.useContext(oe);if(!e||!e.client)throw new Error("usePerpDepositClient must be used within a <PerpetualsProvider>.");if(!e.depositClient)throw new Error("usePerpDepositClient: <PerpetualsProvider> was rendered without a `depositClient` prop. Pass a `LiberFiPerpDepositClient` instance to enable the deposit flow.");return e.depositClient}function hr(e){return ["perps","deposit","quote",e]}async function xr(e,t){return e.quote(t)}function at(e,t={}){let r=ae(),s=t.enabled??!!Ks(e);return reactQuery.useQuery({queryKey:hr(e??null),queryFn:async()=>xr(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Ks(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function pt(e){let t=ae(),[r,s]=react.useReducer(Je,Ue),n=react.useCallback(()=>{s({type:"RESET"});},[]),o=react.useCallback(async i=>{let{quote:a}=i;s({type:"SIGN_START"});let p;try{if(p=await e(a.serializedTxBase64,{isVersioned:a.isVersioned,sizeBytes:a.sizeBytes}),!p)throw new Error("wallet returned an empty tx hash")}catch(u){let d=Pr(u,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),u}s({type:"BROADCAST_START"});let l={userSolanaAddress:i.userSolanaAddress,hyperliquidRecipient:i.hyperliquidRecipient,solanaTxHash:p,breakdown:a.breakdown,userId:i.userId,source:i.source,campaign:i.campaign,quoteIssuedAt:a.issuedAt};try{let u=await t.submit(l);return s({type:"SUBMIT_OK",intentId:u.intentId,solanaTxHash:p}),u.intentId}catch(u){let d=Pr(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,e]);return {state:r,execute:o,reset:n,dispatch:s}}function Pr(e,t){if(e instanceof _){let r=Vs(e.responseBody);return {code:r?.code??t,message:r?.message??e.message,recoverable:e.statusCode>=500||e.statusCode===408}}return e instanceof Error?{code:t,message:e.message,recoverable:true}:{code:t,message:String(e),recoverable:true}}function Vs(e){if(e)try{return JSON.parse(e)}catch{return}}function vr(e){return ["perps","deposit","status",e??null]}async function Dr(e,t){return e.status(t)}function lt(e,t={}){let r=ae(),s=t.enabled??!!e,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:vr(e??void 0),queryFn:async()=>Dr(r,e),enabled:s,refetchInterval:o=>{let i=o.state.data;return i&&xe.has(i.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var Te={phase:"idle",steps:[]};function Ee(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Js(r.builder,e.params.builder)&&r.maxFeeRate>=e.params.maxFeeRate?"skipped":"pending"}case "setReferrer":return t.referrer?"skipped":"pending";case "updateLeverage":return t.leverage[e.params.asset]===e.params.leverage?"skipped":"pending"}}function Fe(e,t){switch(t.type){case "START_LOADING":return {phase:"loading",steps:e.steps,accountState:e.accountState};case "LOAD_SUCCESS":return {phase:t.steps.every(s=>s.status==="skipped"||s.status==="done")?"done":"ready",accountState:t.accountState,steps:t.steps};case "LOAD_ERROR":return {phase:"error",steps:e.steps,error:t.error};case "RUN_STEP":return {phase:"executing",steps:e.steps.map((s,n)=>n===t.index?{...s,status:"running",error:void 0}:s),accountState:e.accountState,currentIndex:t.index};case "STEP_SUCCESS":{let r=e.steps.map((o,i)=>i===t.index?{...o,status:"done",txHash:t.txHash,error:void 0}:o),s=t.accountState&&e.accountState?Xs(e.accountState,t.accountState):t.accountState??e.accountState;return {phase:r.every(o=>o.status==="skipped"||o.status==="done")?"done":"ready",steps:r,accountState:s,currentIndex:void 0}}case "STEP_ERROR":return {phase:"ready",steps:e.steps.map((s,n)=>n===t.index?{...s,status:"error",error:t.error}:s),accountState:e.accountState,currentIndex:void 0};case "RESET":return Te}}function qe(e){for(let t=0;t<e.steps.length;t++){let r=e.steps[t].status;if(r==="pending"||r==="error")return t}return null}function Js(e,t){return e.toLowerCase()===t.toLowerCase()}function Xs(e,t){return {builderApproval:t.builderApproval!==void 0?t.builderApproval:e.builderApproval,referrer:t.referrer!==void 0?t.referrer:e.referrer,leverage:{...e.leverage,...t.leverage??{}}}}function Ae(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:o,onError:i}=e,[a,p]=react.useReducer(Fe,Te),l=react.useRef(t),u=react.useRef(s),d=react.useRef(o),m=react.useRef(i);l.current=t,u.current=s,d.current=o,m.current=i;let f=react.useCallback(async()=>{if(r){p({type:"START_LOADING"});try{let k=await l.current.getAccountState(r),C=u.current.map(N=>({step:N,status:Ee(N,k)}));p({type:"LOAD_SUCCESS",accountState:k,steps:C});}catch(k){let C=Cr(k);p({type:"LOAD_ERROR",error:C.message}),m.current?.(C,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let b=react.useCallback(async k=>{let C=a.steps[k];if(C){p({type:"RUN_STEP",index:k});try{let N=await Zs(l.current,C.step);p({type:"STEP_SUCCESS",index:k,txHash:N.txHash,accountState:N.state});}catch(N){let R=Cr(N);p({type:"STEP_ERROR",index:k,error:R.message}),m.current?.(R,{stepId:C.step.id});}}},[a.steps]),y=react.useCallback(async()=>{let k=qe(a);k!=null&&await b(k);},[a,b]),w=react.useCallback(()=>p({type:"RESET"}),[]),h=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!h.current?(h.current=true,d.current?.(a)):a.phase!=="done"&&(h.current=false);},[a]),{state:a,reload:f,runNext:y,runStep:b,reset:w}}function Zs(e,t){switch(t.id){case "approveBuilderFee":return e.approveBuilderFee(t.params);case "setReferrer":return e.setReferrer(t.params);case "updateLeverage":return e.updateLeverage(t.params)}}function Cr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function ut(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}function dt(){return jsxRuntime.jsxs("div",{className:"flex items-center gap-6 px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-6 w-20 rounded"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-8 w-28 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]})]}),jsxRuntime.jsx("div",{className:"h-8 w-px bg-neutral-800"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-20 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-24 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-32 rounded"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-16 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-5 w-20 rounded"})]})]})]})]})}function mt(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:o,isPending:i}=Se({symbol:e}),{data:a,isConnected:p}=ie({type:"ticker",symbol:e,enabled:!!o});return react.useEffect(()=>{o&&r(o);},[o]),react.useEffect(()=>{if(!a)return;let l=en(a,e);l&&r(u=>tn(u??o??void 0,l,e));},[a,o,e]),react.useEffect(()=>{let l=()=>{let d=Date.now(),m=480*60*1e3,f=d%m,b=m-f;return Math.floor(b/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:i,fundingCountdown:s}}function en(e,t){if(Array.isArray(e)){let r=e.find(s=>!s||typeof s!="object"?false:s.symbol===t);return r&&typeof r=="object"?r:null}return e&&typeof e=="object"?e:null}function de(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function tn(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:de(t.price,e?.price??0),change24h:de(t.change24h,e?.change24h??0),volume24h:de(t.volume24h,e?.volume24h??0),fundingRate:de(t.fundingRate,e?.fundingRate??0),openInterest:de(t.openInterest,e?.openInterest??0),markPrice:de(t.markPrice,e?.markPrice??0),indexPrice:typeof t.indexPrice=="number"&&Number.isFinite(t.indexPrice)?t.indexPrice:e?.indexPrice,high24h:typeof t.high24h=="number"&&Number.isFinite(t.high24h)?t.high24h:e?.high24h,low24h:typeof t.low24h=="number"&&Number.isFinite(t.low24h)?t.low24h:e?.low24h}}function rn(e){let t=Math.floor(e/3600),r=Math.floor(e%3600/60),s=e%60;return `${String(t).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function Or(e,t=2){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e9?`$${(e/1e9).toFixed(t)}B`:e>=1e6?`$${(e/1e6).toFixed(t)}M`:e>=1e3?`$${(e/1e3).toFixed(t)}K`:`$${e.toFixed(t)}`}function Nr(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e3?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e>=1?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):e.toFixed(6)}function ft({marketData:e,fundingCountdown:t}){let{symbol:r,price:s,change24h:n,indexPrice:o,volume24h:i,openInterest:a,fundingRate:p}=e,l=typeof n=="number"&&Number.isFinite(n)?n:0,u=typeof p=="number"&&Number.isFinite(p)?p:0,d=l>=0,m=l.toFixed(2);return jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:16},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Nr(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",m,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:16},children:[jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:o?Nr(o):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Or(i,0)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Or(a*(e.markPrice||s))})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:rn(t)})]})]})]})]})}function sn({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=mt(e);return r?jsxRuntime.jsx(dt,{}):t?jsxRuntime.jsx(ft,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx(ut,{})}function gt({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:o,isPending:i}=Xe(),{data:a,isPending:p}=Ye({symbols:o},{enabled:!!o&&o.length>0});react.useEffect(()=>{a&&n(a);},[a]);let l=react.useMemo(()=>{if(!t.trim())return s;let d=t.toLowerCase().trim();return s.filter(m=>m.symbol.toLowerCase().includes(d))},[s,t]);return {coins:s,isLoading:i||p,searchQuery:t,setSearchQuery:r,filteredCoins:l,handleSelectCoin:d=>{e?.(d);}}}function Ir(e,t=2){return e>=1e9?`$${(e/1e9).toFixed(t)}B`:e>=1e6?`$${(e/1e6).toFixed(t)}M`:e>=1e3?`$${(e/1e3).toFixed(t)}K`:`$${e.toFixed(t)}`}function pn(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function bt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsxRuntime.jsx("div",{style:{padding:"16px 16px 12px"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsxRuntime.jsx(ui.SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsxRuntime.jsx("input",{type:"text",placeholder:"Search coins...",value:t,onChange:o=>r(o.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxRuntime.jsxs("div",{className:"flex-1 overflow-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:t?"No coins found":"No coins available"})}):e.map(o=>{let i=o.change24h>=0,a=o.change24h.toFixed(2),p=(o.fundingRate*100).toFixed(4),l=o.fundingRate>=0,u=o.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(o.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:d=>{let m=d.target;m.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:pn(o.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:i?"#C7FF2E":"#F76816",textAlign:"right"},children:[i?"+":"",a,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:l?"#C7FF2E":"#F76816",textAlign:"right"},children:[p,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ir(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ir(o.openInterest*o.price)})]},o.symbol)})]})]})}function ln({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:o,handleSelectCoin:i}=gt({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(bt,{coins:r,searchQuery:n,onSearchChange:o,onSelectCoin:i,isLoading:s})})}function Fr(e,t){if(t<=0)return e;let r=new Map;return e.forEach(s=>{let n=Math.floor(s.price/t)*t,o=r.get(n);o?(o.quantity+=s.quantity,s.count&&(o.count=(o.count||0)+s.count)):r.set(n,{price:n,quantity:s.quantity,count:s.count});}),Array.from(r.values())}function qr(e){let t=0,r=e.map(n=>{let o=n.quantity*n.price;return t+=o,{...n,quantity:o,total:t,percentage:0}}),s=t;return r.map(n=>({...n,percentage:s>0?n.total/s*100:0}))}function ht({symbol:e,maxLevel:t=20,precision:r=.01}){let[s,n]=react.useState(null),[o,i]=react.useState(r),{data:a,isPending:p}=Ze({symbol:e,maxLevel:t}),{data:l}=ie({type:"orderBook",symbol:e,enabled:!!a});return react.useEffect(()=>{l?n(l):a&&n(a);},[l,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let d=Fr(s.bids,o),m=Fr(s.asks,o),f=d.sort((R,q)=>q.price-R.price).slice(0,t),b=m.sort((R,q)=>R.price-q.price).slice(0,t),y=qr(f),w=qr(b),h=y[0]?.price||0,C=(w[0]?.price||0)-h,N=h>0?C/h*100:0;return {bids:y,asks:w,spread:C,spreadPercentage:N}},[s,o,t]),isLoading:p,precision:o,setPrecision:i}}function cn(e){return e>=1e3?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e>=1?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):e.toFixed(6)}function Mr(e){return Math.round(e).toLocaleString("en-US")}function Ar({price:e,quantity:t,total:r,percentage:s,side:n,onClick:o}){let i=n==="ask";return jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:{height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},onClick:o,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:{height:20,width:`${s}%`,background:i?"linear-gradient(to right, rgba(247,104,22,0), #F76816)":"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15}}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:{flex:"1 1 0%"},children:jsxRuntime.jsx("span",{style:{color:i?"#F76816":"#C7FF2E",fontWeight:400},children:cn(e)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Mr(t)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Mr(r)})]})}function xt({bids:e,asks:t,spread:r,spreadPercentage:s,onPriceClick:n}){let o=[...t].reverse();return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000",fontSize:11},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},children:[jsxRuntime.jsx("div",{className:"flex items-center",style:{flex:"1 1 0%"},children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:{flex:"1 1 0%"},children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:{flex:"1 1 0%"},children:"Total (USD)"})]}),jsxRuntime.jsx("div",{className:"flex-1 flex flex-col-reverse overflow-hidden",children:o.map((i,a)=>jsxRuntime.jsx(Ar,{price:i.price,quantity:i.quantity,total:i.total,percentage:i.percentage,side:"ask",onClick:()=>n?.(i.price)},`ask-${i.price}-${a}`))}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:12,fontSize:12,color:"#ffffff"},children:[jsxRuntime.jsx("span",{style:{color:"#ffffff"},children:"Spread:"}),jsxRuntime.jsx("button",{type:"button",className:"hover:text-white transition-colors cursor-pointer",style:{color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0},onClick:()=>n?.(r),children:r>=1?Math.round(r).toLocaleString("en-US"):r.toFixed(4)}),jsxRuntime.jsxs("span",{style:{color:"#ffffff",fontWeight:500},children:[s.toFixed(3),"%"]})]})}),jsxRuntime.jsx("div",{className:"flex-1 overflow-hidden",children:e.map((i,a)=>jsxRuntime.jsx(Ar,{price:i.price,quantity:i.quantity,total:i.total,percentage:i.percentage,side:"bid",onClick:()=>n?.(i.price)},`bid-${i.price}-${a}`))})]})}function mn(){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{padding:"0 16px"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:28,marginBottom:4},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]}),Array.from({length:10}).map((e,t)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]},`ask-skeleton-${t}`)),jsxRuntime.jsx("div",{className:"flex justify-center items-center",style:{height:28},children:jsxRuntime.jsx(ui.Skeleton,{className:"h-4 w-32 rounded"})}),Array.from({length:10}).map((e,t)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"})]},`bid-skeleton-${t}`))]})}function fn(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function yn({symbol:e,maxLevel:t=20,onPriceClick:r,className:s}){let{bids:n,asks:o,spread:i,spreadPercentage:a,isLoading:p}=ht({symbol:e,maxLevel:t});return p?jsxRuntime.jsx(mn,{}):n.length===0&&o.length===0?jsxRuntime.jsx(fn,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(xt,{bids:n,asks:o,spread:i,spreadPercentage:a,onPriceClick:r})})}function St({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:o}=et({symbol:e,limit:t}),{data:i}=ie({type:"trades",symbol:e,enabled:!!n});return react.useEffect(()=>{n&&s(n.filter(Br));},[n]),react.useEffect(()=>{i&&s(a=>{let p=bn(i);if(p.length===0)return a;let l=p.filter(d=>!a.some(m=>m.timestamp===d.timestamp&&m.price===d.price&&m.quantity===d.quantity));return l.length===0?a:[...l,...a].slice(0,t)});},[i,t]),{trades:r,isLoading:o}}function bn(e){return (Array.isArray(e)?e:[e]).filter(Br)}function Br(e){return e?typeof e.symbol=="string"&&(e.side==="buy"||e.side==="sell")&&typeof e.price=="number"&&Number.isFinite(e.price)&&typeof e.quantity=="number"&&Number.isFinite(e.quantity)&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp):false}function hn(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Qr(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e6?(e/1e6).toFixed(2)+"M":e>=1e3?(e/1e3).toFixed(2)+"K":e.toFixed(2)}function xn(e){if(typeof e!="number"||!Number.isFinite(e))return "-";let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function vt({trades:e,onTradeClick:t}){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full overflow-auto",style:{backgroundColor:"#000000",fontSize:11},children:[jsxRuntime.jsxs("div",{className:"sticky top-0 z-10 flex items-center",style:{height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},children:[jsxRuntime.jsx("div",{className:"flex-1",style:{maxWidth:100},children:"Price"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",children:"Amount"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100},children:"Total"}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70},children:"Time"})]}),jsxRuntime.jsx("div",{className:"flex-1",children:e.map((r,s)=>{let n=r.side==="buy",o=typeof r.price=="number"&&Number.isFinite(r.price)&&typeof r.quantity=="number"&&Number.isFinite(r.quantity)?r.price*r.quantity:void 0;return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:{height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},onClick:()=>t?.(r),children:[jsxRuntime.jsx("div",{className:"flex-1",style:{maxWidth:100},children:jsxRuntime.jsx("span",{style:{color:n?"#C7FF2E":"#F76816",fontWeight:400},children:hn(r.price)})}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{color:"#ffffff"},children:Qr(r.quantity)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100,color:"#ffffff"},children:Qr(o)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70,color:"#b5b5b5"},children:xn(r.timestamp)})]},`${r.timestamp}-${r.price}-${s}`)})})]})}function Sn(){return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{padding:"0 16px"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:28,marginBottom:4},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"})]}),Array.from({length:12}).map((e,t)=>jsxRuntime.jsxs("div",{className:"flex justify-between items-center",style:{height:22},children:[jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-14 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-10 rounded"}),jsxRuntime.jsx(ui.Skeleton,{className:"h-3 w-12 rounded"})]},`trade-skeleton-${t}`))]})}function Pn(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function vn({symbol:e,limit:t=50,onTradeClick:r,className:s}){let{trades:n,isLoading:o}=St({symbol:e,limit:t});return o?jsxRuntime.jsx(Sn,{}):n.length===0?jsxRuntime.jsx(Pn,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(vt,{trades:n,onTradeClick:r})})}function Tt({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n}){let[o,i]=react.useState("long"),[a,p]=react.useState("market"),l=reactHookForm.useForm({defaultValues:{amount:0,leverage:20,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:u}=Se({symbol:e}),{mutateAsync:d,isPending:m}=ve({onSuccess:()=>{l.reset(),s?.();},onError:T=>{n?.(T);}}),f=l.watch(),{amount:b,leverage:y,price:w}=f,h=react.useMemo(()=>a==="limit"&&w?w:u?.price||0,[a,w,u?.price]),k=react.useMemo(()=>!b||!h?0:b*h*5e-4,[b,h]),C=react.useMemo(()=>!b||!h?0:b*h+k,[b,h,k]),N=react.useMemo(()=>{if(!b||!h||!y||y===1)return;let T=.005,L=h;return o==="long"?L*(1-(1/y-T)):L*(1+(1/y-T))},[b,h,y,o]),{data:R}=Pe({userAddress:t,symbol:e}),q=R?.totalEquity??0,A=R?.availableBalance??0,c=react.useMemo(()=>{let T=R?.positions?.[0];return T?T.side==="short"?-T.quantity:T.quantity:0},[R?.positions]),X=react.useCallback(async T=>{if(!t)throw new Error("User address is required");let L=a==="limit"?T.price:void 0,le=T.takeProfitPrice,te=T.stopLossPrice;if(!le&&T.takeProfitPercent&&T.takeProfitPercent>0&&h){let re=T.takeProfitPercent/100;le=o==="long"?h*(1+re):h*(1-re);}if(!te&&T.stopLossPercent&&T.stopLossPercent>0&&h){let re=T.stopLossPercent/100;te=o==="long"?h*(1-re):h*(1+re);}await d({symbol:e,side:o,orderType:a,amount:T.amount,price:L,leverage:T.leverage,takeProfitPrice:le,stopLossPrice:te,userAddress:t});},[e,o,a,h,t,d]);return {form:l,side:o,orderType:a,setSide:i,setOrderType:p,handleSubmit:X,isSubmitting:m,currentPrice:h,estimatedFee:k,estimatedTotal:C,liquidationPrice:N,availableMargin:A,accountValue:q,currentPosition:c,maxLeverage:r}}function Be(e,t=2){return e.toFixed(t)}function On({leverage:e,maxLeverage:t,onLeverageChange:r,onClose:s}){let n=[1,2,3,5,10,20,25,50,100].filter(o=>o<=t);return jsxRuntime.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[jsxRuntime.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:s,onKeyDown:o=>o.key==="Escape"&&s(),role:"button",tabIndex:-1,"aria-label":"Close"}),jsxRuntime.jsxs("div",{className:"relative z-10 w-72 bg-neutral-900 border border-neutral-700 rounded-lg p-4 shadow-2xl",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-4",children:[jsxRuntime.jsx("h3",{className:"text-sm font-medium text-white",children:"Adjust Leverage"}),jsxRuntime.jsx("button",{type:"button",onClick:s,className:"text-neutral-400 hover:text-white",children:jsxRuntime.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:jsxRuntime.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]}),jsxRuntime.jsxs("div",{className:"text-center text-2xl font-bold text-white mb-4",children:[e,"x"]}),jsxRuntime.jsx(ui.Slider,{value:[e],onChange:o=>r(Array.isArray(o)?o[0]:o),minValue:1,maxValue:t,step:1,className:"w-full mb-3"}),jsxRuntime.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>jsxRuntime.jsxs("button",{type:"button",className:ui.cn("px-2.5 py-1 text-xs rounded transition-colors",e===o?"bg-green-600 text-white":"bg-neutral-800 text-neutral-400 hover:bg-neutral-700"),onClick:()=>r(o),children:[o,"x"]},o))}),jsxRuntime.jsx("button",{type:"button",className:"w-full mt-4 text-white h-9 rounded cursor-pointer transition-colors",style:{backgroundColor:"#C7FF2E"},onClick:s,children:"Confirm"})]})]})}function Ct({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:o,isSubmitting:i,symbol:a,currentPrice:p,estimatedFee:l,liquidationPrice:u,availableMargin:d,accountValue:m,currentPosition:f,maxLeverage:b}){let[y,w]=react.useState(false),[h,k]=react.useState(false),C=e.watch("leverage")||20,N=e.watch("amount")||0,R=a.split("-")[0],q=d>0&&p?Math.min(N*p/(d*C)*100,100):0,A=c=>{let X=(Array.isArray(c)?c[0]:c)/100;if(p&&p>0){let T=d*C*X/p;e.setValue("amount",Number(T.toFixed(6)));}};return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsxs("div",{className:"perp-order-form flex-1 overflow-y-auto",style:{padding:"16px 16px",display:"flex",flexDirection:"column",gap:16},children:[jsxRuntime.jsxs("div",{className:"flex",style:{border:"1px solid rgba(26,26,26,0.5)",borderRadius:8,padding:4,gap:4},children:[jsxRuntime.jsx("button",{type:"button",className:"flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:16,borderRadius:4,backgroundColor:t==="long"?"#C7FF2E":"transparent",color:t==="long"?"#000000":"#b5b5b5",fontWeight:t==="long"?700:500},onClick:()=>s("long"),children:"Long"}),jsxRuntime.jsx("button",{type:"button",className:"flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:16,borderRadius:4,backgroundColor:t==="short"?"#F76816":"transparent",color:t==="short"?"#000000":"#b5b5b5",fontWeight:t==="short"?700:500},onClick:()=>s("short"),children:"Short"})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:"Market"},{key:"limit",label:"Limit"}].map(c=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===c.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===c.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(c.key),children:c.label})},c.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer transition-colors",style:{height:24,padding:"0 5px",fontSize:12,borderRadius:4,backgroundColor:"rgba(26,26,26,0.5)",color:"#ffffff",fontWeight:400,border:"1px solid rgba(26,26,26,0.5)"},onClick:()=>w(true),children:["Leverage: ",C,"x"]})]}),jsxRuntime.jsx(ui.RHForm,{methods:e,onSubmit:o,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[r==="limit"&&jsxRuntime.jsxs("div",{className:"perp-price-box",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Price"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"USDC"})]}),jsxRuntime.jsx(ui.RHNumberInput,{name:"price",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{className:"perp-buy-amt",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Buy Amount"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:R})]}),jsxRuntime.jsx(ui.RHNumberInput,{name:"amount",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
2
2
  .perp-buy-amt input, .perp-price-box input { font-size: 18px !important; line-height: 23px !important; }
3
3
  .perp-order-form .group,
4
4
  .perp-order-form .group div { background: transparent !important; border: none !important; padding: 0 !important; border-radius: 0 !important; min-height: 0 !important; height: auto !important; }
@@ -8,6 +8,6 @@
8
8
  .perp-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; border-radius: 50%; background: #C7FF2E; margin-top: -4px; border: none; }
9
9
  .perp-slider::-moz-range-track { height: 4px; border-radius: 2px; background: #1c1c1c; border: none; }
10
10
  .perp-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: #C7FF2E; border: none; }
11
- `}),jsxRuntime.jsx("input",{type:"range",value:Math.round(R),onChange:C=>ge(Number(C.target.value)),min:0,max:100,step:1,className:"perp-slider"}),jsxRuntime.jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsxRuntime.jsx("span",{children:"0%"}),jsxRuntime.jsx("span",{children:"25%"}),jsxRuntime.jsx("span",{children:"50%"}),jsxRuntime.jsx("span",{children:"75%"}),jsxRuntime.jsx("span",{children:"100%"})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>L(C=>!C),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:x?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:x&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsx("span",{children:"Est. Liq. Price: "}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?me(u,2):"--"})]})]}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"takeProfitPrice",placeholder:"Enter TP price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"takeProfitPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),jsxRuntime.jsx("button",{type:"button",className:"w-full cursor-pointer transition-colors",style:{height:36,fontSize:14,fontWeight:700,color:"#000000",backgroundColor:"#C7FF2E",borderRadius:9999,border:"none"},children:"Add More Funds"}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"stopLossPrice",placeholder:"Enter SL price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"stopLossPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]})]})})]}),jsxRuntime.jsxs("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column",gap:6},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxRuntime.jsxs("span",{style:{color:"#C7FF2E",fontSize:12,fontWeight:500},children:[me(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[me(f)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:p?me(p):"--"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-end",style:{gap:6,paddingTop:8},children:[jsxRuntime.jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:C=>{let re=C.target;re.style.display="none";}})]})]}),y&&jsxRuntime.jsx(Zr,{leverage:D,maxLeverage:g,onLeverageChange:C=>t.setValue("leverage",C),onClose:()=>w(false)})]})}function es({symbol:t,userAddress:e,maxLeverage:r,onSuccess:s,onError:n,className:o}){let{form:i,side:a,orderType:l,setSide:c,setOrderType:u,handleSubmit:d,isSubmitting:f,currentPrice:p,estimatedFee:g,estimatedTotal:y,liquidationPrice:w,availableMargin:x,accountValue:L,currentPosition:D,maxLeverage:$}=Ke({symbol:t,userAddress:e,maxLeverage:r,onSuccess:s,onError:n});return jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsx(Ge,{methods:i,side:a,orderType:l,onSideChange:c,onOrderTypeChange:u,onSubmit:d,isSubmitting:f,symbol:t,currentPrice:p,estimatedFee:g,estimatedTotal:y,liquidationPrice:w,availableMargin:x,accountValue:L,currentPosition:D,maxLeverage:$})})}function _e({userAddress:t,symbol:e,onCloseSuccess:r,onCloseError:s}){let[n,o]=react.useState([]),{data:i,isLoading:a,error:l}=ie({userAddress:t,symbol:e},{enabled:!!t}),{data:c}=le({type:"positions",userAddress:t||"",enabled:!!t}),{mutateAsync:u,isPending:d}=ae({onSuccess:()=>{r?.();},onError:p=>{s?.(p);}});react.useEffect(()=>{i?.positions&&o(i.positions);},[i]),react.useEffect(()=>{c&&o(p=>{let g=p.findIndex(y=>y.symbol===c.symbol);if(c.quantity===0)return g!==-1?p.filter((y,w)=>w!==g):p;if(g!==-1){let y=[...p];return y[g]=c,y}return [...p,c]});},[c]);let f=react.useCallback(async p=>{if(!t)throw new Error("User address is required");let g=p.side==="long"?"short":"long";await u({symbol:p.symbol,side:g,orderType:"market",amount:Math.abs(p.quantity),leverage:p.leverage,userAddress:t});},[t,u]);return {positions:n,isLoading:a,error:l,handleClosePosition:f,isClosing:d}}function X(t,e=2){return t.toFixed(e)}function Ve(t){return X(t,4)}function os(t){return X(Math.abs(t),4)}function is(t){return `${t>=0?"+":""}${X(t,2)}`}function as(t){return `${t>=0?"+":""}${X(t,2)}%`}function je({positions:t,onClosePosition:e,isClosing:r}){let s=jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position Value"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Entry Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Mark Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Liquidation"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Margin Used (PNL) \u2193"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"TP"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"SL"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Close"})]});return t.length===0?jsxRuntime.jsxs("div",{className:"w-full overflow-x-auto bg-transparent",children:[jsxRuntime.jsx("table",{className:"w-full",style:{fontSize:12},children:jsxRuntime.jsx("thead",{children:s})}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{fontSize:14,color:"#b5b5b5",padding:"24px 0"},children:"No open positions"})]}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:12},children:[jsxRuntime.jsx("thead",{children:s}),jsxRuntime.jsx("tbody",{children:t.map(n=>{let i=n.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:n.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui.cn(n.side==="long"?"text-bullish":"text-bearish"),children:[n.leverage,"x ",n.side.toUpperCase()]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:os(n.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",X(n.notionalValue)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Ve(n.entryPrice)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Ve(n.markPrice)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:n.liquidationPrice?`$${Ve(n.liquidationPrice)}`:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsxs("div",{className:"flex flex-col items-end",children:[jsxRuntime.jsxs("span",{style:{color:"#ffffff"},children:["$",X(n.margin)]}),jsxRuntime.jsxs("span",{className:i,children:[is(n.unrealizedPnl)," (",as(n.unrealizedPnlPercent),")"]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx(ui.Button,{size:"sm",onClick:()=>e(n),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Close"})})]},n.symbol)})})]})})}function Je(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function ls(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:14,color:"#b5b5b5"},children:"No open positions"})}function cs({userAddress:t,symbol:e,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:o,isLoading:i,handleClosePosition:a,isClosing:l}=_e({userAddress:t,symbol:e,onCloseSuccess:r,onCloseError:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Je,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(je,{positions:o,onClosePosition:a,isClosing:l})})}function Ye({userAddress:t,symbol:e,onCancelSuccess:r,onCancelError:s}){let[n,o]=react.useState([]),{data:i,isLoading:a,error:l}=we({userAddress:t,symbol:e},{enabled:!!t}),{data:c}=le({type:"orders",userAddress:t||"",enabled:!!t}),{mutateAsync:u,isPending:d}=Te({onSuccess:()=>{r?.();},onError:p=>{s?.(p);}});react.useEffect(()=>{i?.orders&&o(i.orders);},[i]),react.useEffect(()=>{c&&o(p=>{let g=p.findIndex(y=>y.orderId===c.orderId);if(c.status==="cancelled"||c.status==="filled"||c.status==="rejected")return g!==-1?p.filter((y,w)=>w!==g):p;if(g!==-1){let y=[...p];return y[g]=c,y}return [c,...p]});},[c]);let f=react.useCallback(async p=>{if(!t)throw new Error("User address is required");await u({orderId:p.orderId,symbol:p.symbol,userAddress:t});},[t,u]);return {orders:n,isLoading:a,error:l,handleCancelOrder:f,isCanceling:d}}function Jt(t,e=2){return t.toFixed(e)}function ms(t){return Jt(t,4)}function Xe(t){return Jt(t,4)}function fs(t){let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),n=String(e.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function Ze({orders:t,onCancelOrder:e,isCanceling:r}){return t.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsxRuntime.jsx("tbody",{children:t.map(s=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui.cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${ms(s.price)}`}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Xe(s.quantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Xe(s.filledQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Xe(s.remainingQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:fs(s.timestamp)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsxRuntime.jsx(ui.Button,{size:"sm",onClick:()=>e(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsxRuntime.jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function et(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function tt(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function ys({userAddress:t,symbol:e,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:o,isLoading:i,handleCancelOrder:a,isCanceling:l}=Ye({userAddress:t,symbol:e,onCancelSuccess:r,onCancelError:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(et,{})}):o.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(tt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Ze,{orders:o,onCancelOrder:a,isCanceling:l})})}function gs(t){let e=Date.now(),r=e;switch(t){case "today":let s=new Date;return s.setHours(0,0,0,0),{startTime:s.getTime(),endTime:r};case "7d":return {startTime:e-10080*60*1e3,endTime:r};case "30d":return {startTime:e-720*60*60*1e3,endTime:r};default:return {}}}function st({userAddress:t,symbol:e,initialTimeRange:r="7d",pageSize:s=50}){let[n,o]=react.useState(r),[i,a]=react.useState(1),[l,c]=react.useState([]),{startTime:u,endTime:d}=gs(n),{data:f,isLoading:p,error:g}=Oe({userAddress:t,symbol:e,startTime:u,endTime:d,limit:1e3},{enabled:!!t});react.useEffect(()=>{f?.trades&&(c(f.trades),a(1));},[f]),react.useEffect(()=>{a(1);},[n]);let y=Math.ceil(l.length/s),w=(i-1)*s,x=w+s;return {trades:l.slice(w,x),isLoading:p,error:g,timeRange:n,setTimeRange:o,currentPage:i,totalPages:y,goToNextPage:()=>{i<y&&a(i+1);},goToPreviousPage:()=>{i>1&&a(i-1);},goToPage:R=>{R>=1&&R<=y&&a(R);}}}function nt(t,e=2){return t.toFixed(e)}function bs(t){return nt(t,4)}function hs(t){return nt(t,4)}function xs(t){let e=new Date(t),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),i=String(e.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${o}:${i}`}var Ps=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function ot({trades:t,timeRange:e,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:o,onPreviousPage:i,onGoToPage:a}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsxRuntime.jsx("div",{className:"flex gap-2",children:Ps.map(l=>{let c=e===l.value;return jsxRuntime.jsx("button",{type:"button",className:ui.cn("rounded px-3 transition-colors",!c&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:c?"#1c1c1c":"transparent",color:c?"#ffffff":"#b5b5b5"},onClick:()=>r(l.value),children:l.label},l.value)})}),t.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsxRuntime.jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsxRuntime.jsx("tbody",{children:t.map(l=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:l.symbol.split("-")[0]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded text-[11px]",l.side==="long"?"bg-bullish/20 text-bullish":"bg-bearish/20 text-bearish"),children:l.side.toUpperCase()})}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",bs(l.price)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:hs(l.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[nt(l.fee,4)," ",l.feeCurrency]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-center",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded text-[11px]",l.isMaker?"bg-blue-600/20 text-blue-500":"bg-purple-600/20 text-purple-500"),children:l.isMaker?"Maker":"Taker"})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:xs(l.timestamp)})]},l.tradeId))})]})}),n>1&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[jsxRuntime.jsx(ui.Button,{size:"sm",onClick:i,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsxRuntime.jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(l,c)=>{let u;return n<=5||s<=3?u=c+1:s>=n-2?u=n-4+c:u=s-2+c,jsxRuntime.jsx("button",{type:"button",className:ui.cn("w-8 h-8 text-sm rounded transition-colors",s===u?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>a(u),children:u},u)})}),jsxRuntime.jsx(ui.Button,{size:"sm",onClick:o,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function it(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function at(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function Ss({userAddress:t,symbol:e,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:o,isLoading:i,timeRange:a,setTimeRange:l,currentPage:c,totalPages:u,goToNextPage:d,goToPreviousPage:f,goToPage:p}=st({userAddress:t,symbol:e,initialTimeRange:r,pageSize:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(it,{})}):o.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(at,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(ot,{trades:o,timeRange:a,onTimeRangeChange:l,currentPage:c,totalPages:u,onNextPage:d,onPreviousPage:f,onGoToPage:p})})}
12
- exports.CoinInfoNotFoundUI=Me;exports.CoinInfoSkeletonsUI=De;exports.CoinInfoUI=Re;exports.CoinInfoWidget=Ur;exports.HyperliquidApiError=_;exports.HyperliquidPerpetualsClient=xe;exports.LiberFiApiError=H;exports.LiberFiPerpetualsClient=Pe;exports.OpenOrdersEmpty=tt;exports.OpenOrdersSkeleton=et;exports.OpenOrdersUI=Ze;exports.OpenOrdersWidget=ys;exports.OrderBookUI=Le;exports.OrderBookWidget=Lr;exports.PerpetualsContext=ne;exports.PerpetualsProvider=nr;exports.PlaceOrderFormUI=Ge;exports.PlaceOrderFormWidget=es;exports.PositionsEmpty=ls;exports.PositionsSkeleton=Je;exports.PositionsUI=je;exports.PositionsWidget=cs;exports.SearchCoinsUI=Ae;exports.SearchCoinsWidget=Er;exports.TradeHistoryEmpty=at;exports.TradeHistorySkeleton=it;exports.TradeHistoryUI=ot;exports.TradeHistoryWidget=Ss;exports.TradesUI=$e;exports.TradesWidget=_r;exports.cancelOrder=Nt;exports.coinsQueryKey=ct;exports.createOrder=Tt;exports.fetchCoins=ut;exports.fetchKlines=gt;exports.fetchMarket=pt;exports.fetchMarkets=ft;exports.fetchOrderBook=ht;exports.fetchOrders=Ct;exports.fetchPositions=St;exports.fetchRecentTrades=Pt;exports.fetchTrades=Ot;exports.klinesQueryKey=yt;exports.marketQueryKey=dt;exports.marketsQueryKey=mt;exports.orderBookQueryKey=bt;exports.ordersQueryKey=kt;exports.positionsQueryKey=vt;exports.recentTradesQueryKey=xt;exports.tradesQueryKey=wt;exports.useCancelOrderMutation=Te;exports.useCandlesSubscription=kr;exports.useCoinInfo=Ee;exports.useCoinsQuery=ve;exports.useCreateOrderMutation=ae;exports.useKlinesQuery=dr;exports.useMarketDataSubscription=V;exports.useMarketQuery=oe;exports.useMarketsQuery=Se;exports.useOpenOrdersScript=Ye;exports.useOrderBookQuery=ke;exports.useOrderBookScript=Qe;exports.useOrdersQuery=we;exports.usePerpetualsClient=P;exports.usePlaceOrderFormScript=Ke;exports.usePositionsQuery=ie;exports.usePositionsScript=_e;exports.useRecentTradesQuery=Ce;exports.useSearchCoinsScript=ze;exports.useTradeHistoryScript=st;exports.useTradesQuery=Oe;exports.useTradesScript=Be;exports.useUserDataSubscription=le;exports.version=Zt;//# sourceMappingURL=index.js.map
11
+ `}),jsxRuntime.jsx("input",{type:"range",value:Math.round(q),onChange:c=>A(Number(c.target.value)),min:0,max:100,step:1,className:"perp-slider"}),jsxRuntime.jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsxRuntime.jsx("span",{children:"0%"}),jsxRuntime.jsx("span",{children:"25%"}),jsxRuntime.jsx("span",{children:"50%"}),jsxRuntime.jsx("span",{children:"75%"}),jsxRuntime.jsx("span",{children:"100%"})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>k(c=>!c),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:h?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:h&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsx("span",{children:"Est. Liq. Price: "}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?Be(u,2):"--"})]})]}),h&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"takeProfitPrice",placeholder:"Enter TP price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"takeProfitPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),jsxRuntime.jsx("button",{type:"button",className:"w-full cursor-pointer transition-colors",style:{height:36,fontSize:14,fontWeight:700,color:"#000000",backgroundColor:"#C7FF2E",borderRadius:9999,border:"none"},children:"Add More Funds"}),h&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"stopLossPrice",placeholder:"Enter SL price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsxRuntime.jsx(ui.RHNumberInput,{name:"stopLossPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]})]})})]}),jsxRuntime.jsxs("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column",gap:6},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxRuntime.jsxs("span",{style:{color:"#C7FF2E",fontSize:12,fontWeight:500},children:[Be(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[Be(m)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?Be(f):"--"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-end",style:{gap:6,paddingTop:8},children:[jsxRuntime.jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:c=>{let X=c.target;X.style.display="none";}})]})]}),y&&jsxRuntime.jsx(On,{leverage:C,maxLeverage:b,onLeverageChange:c=>e.setValue("leverage",c),onClose:()=>w(false)})]})}function Nn({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,className:o}){let{form:i,side:a,orderType:p,setSide:l,setOrderType:u,handleSubmit:d,isSubmitting:m,currentPrice:f,estimatedFee:b,estimatedTotal:y,liquidationPrice:w,availableMargin:h,accountValue:k,currentPosition:C,maxLeverage:N}=Tt({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n});return jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsx(Ct,{methods:i,side:a,orderType:p,onSideChange:l,onOrderTypeChange:u,onSubmit:d,isSubmitting:m,symbol:e,currentPrice:f,estimatedFee:b,estimatedTotal:y,liquidationPrice:w,availableMargin:h,accountValue:k,currentPosition:C,maxLeverage:N})})}function kt({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s}){let[n,o]=react.useState([]),{data:i,isLoading:a,error:p}=Pe({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=De({type:"positions",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:d}=ve({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{i?.positions&&o(i.positions);},[i]),react.useEffect(()=>{l&&o(f=>{let b=f.findIndex(y=>y.symbol===l.symbol);if(l.quantity===0)return b!==-1?f.filter((y,w)=>w!==b):f;if(b!==-1){let y=[...f];return y[b]=l,y}return [...f,l]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");let b=f.side==="long"?"short":"long";await u({symbol:f.symbol,side:b,orderType:"market",amount:Math.abs(f.quantity),leverage:f.leverage,userAddress:e});},[e,u]);return {positions:n,isLoading:a,error:p,handleClosePosition:m,isClosing:d}}function me(e,t=2){return e.toFixed(t)}function wt(e){return me(e,4)}function Fn(e){return me(Math.abs(e),4)}function qn(e){return `${e>=0?"+":""}${me(e,2)}`}function Mn(e){return `${e>=0?"+":""}${me(e,2)}%`}function Ot({positions:e,onClosePosition:t,isClosing:r}){let s=jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position Value"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Entry Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Mark Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Liquidation"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Margin Used (PNL) \u2193"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"TP"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"SL"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Close"})]});return e.length===0?jsxRuntime.jsxs("div",{className:"w-full overflow-x-auto bg-transparent",children:[jsxRuntime.jsx("table",{className:"w-full",style:{fontSize:12},children:jsxRuntime.jsx("thead",{children:s})}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{fontSize:14,color:"#b5b5b5",padding:"24px 0"},children:"No open positions"})]}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:12},children:[jsxRuntime.jsx("thead",{children:s}),jsxRuntime.jsx("tbody",{children:e.map(n=>{let i=n.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:n.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui.cn(n.side==="long"?"text-bullish":"text-bearish"),children:[n.leverage,"x ",n.side.toUpperCase()]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Fn(n.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",me(n.notionalValue)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",wt(n.entryPrice)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",wt(n.markPrice)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:n.liquidationPrice?`$${wt(n.liquidationPrice)}`:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsxs("div",{className:"flex flex-col items-end",children:[jsxRuntime.jsxs("span",{style:{color:"#ffffff"},children:["$",me(n.margin)]}),jsxRuntime.jsxs("span",{className:i,children:[qn(n.unrealizedPnl)," (",Mn(n.unrealizedPnlPercent),")"]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx(ui.Button,{size:"sm",onClick:()=>t(n),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Close"})})]},n.symbol)})})]})})}function Nt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function An(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:14,color:"#b5b5b5"},children:"No open positions"})}function Ln({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:o,isLoading:i,handleClosePosition:a,isClosing:p}=kt({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Nt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Ot,{positions:o,onClosePosition:a,isClosing:p})})}function Rt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s}){let[n,o]=react.useState([]),{data:i,isLoading:a,error:p}=tt({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=De({type:"orders",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:d}=st({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{i?.orders&&o(i.orders);},[i]),react.useEffect(()=>{l&&o(f=>{let b=f.findIndex(y=>y.orderId===l.orderId);if(l.status==="cancelled"||l.status==="filled"||l.status==="rejected")return b!==-1?f.filter((y,w)=>w!==b):f;if(b!==-1){let y=[...f];return y[b]=l,y}return [l,...f]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");await u({orderId:f.orderId,symbol:f.symbol,userAddress:e});},[e,u]);return {orders:n,isLoading:a,error:p,handleCancelOrder:m,isCanceling:d}}function Gr(e,t=2){return e.toFixed(t)}function zn(e){return Gr(e,4)}function It(e){return Gr(e,4)}function _n(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function Ut({orders:e,onCancelOrder:t,isCanceling:r}){return e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsxRuntime.jsx("tbody",{children:e.map(s=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui.cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${zn(s.price)}`}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:It(s.quantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:It(s.filledQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:It(s.remainingQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:_n(s.timestamp)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsxRuntime.jsx(ui.Button,{size:"sm",onClick:()=>t(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsxRuntime.jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function Et(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Ft(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function $n({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:o,isLoading:i,handleCancelOrder:a,isCanceling:p}=Rt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Et,{})}):o.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Ft,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Ut,{orders:o,onCancelOrder:a,isCanceling:p})})}function Wn(e){let t=Date.now(),r=t;switch(e){case "today":let s=new Date;return s.setHours(0,0,0,0),{startTime:s.getTime(),endTime:r};case "7d":return {startTime:t-10080*60*1e3,endTime:r};case "30d":return {startTime:t-720*60*60*1e3,endTime:r};default:return {}}}function Mt({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50}){let[n,o]=react.useState(r),[i,a]=react.useState(1),[p,l]=react.useState([]),{startTime:u,endTime:d}=Wn(n),{data:m,isLoading:f,error:b}=rt({userAddress:e,symbol:t,startTime:u,endTime:d,limit:1e3},{enabled:!!e});react.useEffect(()=>{m?.trades&&(l(m.trades),a(1));},[m]),react.useEffect(()=>{a(1);},[n]);let y=Math.ceil(p.length/s),w=(i-1)*s,h=w+s;return {trades:p.slice(w,h),isLoading:f,error:b,timeRange:n,setTimeRange:o,currentPage:i,totalPages:y,goToNextPage:()=>{i<y&&a(i+1);},goToPreviousPage:()=>{i>1&&a(i-1);},goToPage:q=>{q>=1&&q<=y&&a(q);}}}function At(e,t=2){return e.toFixed(t)}function Kn(e){return At(e,4)}function Gn(e){return At(e,4)}function Vn(e){let t=new Date(e),r=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),i=String(t.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${o}:${i}`}var jn=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function Lt({trades:e,timeRange:t,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:o,onPreviousPage:i,onGoToPage:a}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsxRuntime.jsx("div",{className:"flex gap-2",children:jn.map(p=>{let l=t===p.value;return jsxRuntime.jsx("button",{type:"button",className:ui.cn("rounded px-3 transition-colors",!l&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:l?"#1c1c1c":"transparent",color:l?"#ffffff":"#b5b5b5"},onClick:()=>r(p.value),children:p.label},p.value)})}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsxRuntime.jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsxRuntime.jsx("tbody",{children:e.map(p=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:p.symbol.split("-")[0]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded text-[11px]",p.side==="long"?"bg-bullish/20 text-bullish":"bg-bearish/20 text-bearish"),children:p.side.toUpperCase()})}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Kn(p.price)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Gn(p.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[At(p.fee,4)," ",p.feeCurrency]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-center",children:jsxRuntime.jsx("span",{className:ui.cn("px-2 py-0.5 rounded text-[11px]",p.isMaker?"bg-blue-600/20 text-blue-500":"bg-purple-600/20 text-purple-500"),children:p.isMaker?"Maker":"Taker"})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Vn(p.timestamp)})]},p.tradeId))})]})}),n>1&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[jsxRuntime.jsx(ui.Button,{size:"sm",onClick:i,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsxRuntime.jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(p,l)=>{let u;return n<=5||s<=3?u=l+1:s>=n-2?u=n-4+l:u=s-2+l,jsxRuntime.jsx("button",{type:"button",className:ui.cn("w-8 h-8 text-sm rounded transition-colors",s===u?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>a(u),children:u},u)})}),jsxRuntime.jsx(ui.Button,{size:"sm",onClick:o,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function Bt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Qt(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function Xn({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:o,isLoading:i,timeRange:a,setTimeRange:p,currentPage:l,totalPages:u,goToNextPage:d,goToPreviousPage:m,goToPage:f}=Mt({userAddress:e,symbol:t,initialTimeRange:r,pageSize:s});return i?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Bt,{})}):o.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Qt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Lt,{trades:o,timeRange:a,onTimeRangeChange:p,currentPage:l,totalPages:u,onNextPage:d,onPreviousPage:m,onGoToPage:f})})}var Yn=1000000000n;var Zn=1000000n;function Oe(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Jr(r,Yn,t)}function Ht(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Jr(r,Zn,t)}function zt(e){if(!e)return "0";let[t,r=""]=e.replace(/[\s,]/g,"").split(".");if(!/^\d*$/.test(t)||!/^\d*$/.test(r))return "0";let s=(r+"000000000").slice(0,9),n=`${t||"0"}${s}`.replace(/^0+(?=\d)/,"");return n===""?"0":n}function Jr(e,t,r){let s=e<0n,n=s?-e:e,o=n/t,i=n%t;if(r<=0)return `${s?"-":""}${o.toString()}`;let a=10n**BigInt(r),l=((i*a+t/2n)/t).toString().padStart(r,"0");return l=l.replace(/0+$/,""),l?`${s?"-":""}${o.toString()}.${l}`:`${s?"-":""}${o.toString()}`}function Ne(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function ze(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function _t({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:o,onExpire:i,error:a}){let{t:p}=i18n.useTranslation(),l=t?Date.parse(t.expiresAt):0,[u,d]=react.useState(()=>l?Ne(l):0);return react.useEffect(()=>{if(!e||!l)return;d(Ne(l));let m=setInterval(()=>{let f=Ne(l);d(f),f===0&&(i?.(),clearInterval(m));},1e3);return ()=>clearInterval(m)},[e,l,i]),jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:m=>!m&&o(),hideCloseButton:true,backdrop:"blur",children:jsxRuntime.jsxs(ui.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui.ModalHeader,{children:p("perpDeposit.confirm.title")}),jsxRuntime.jsxs(ui.ModalBody,{children:[t?jsxRuntime.jsx(po,{breakdown:t.breakdown}):jsxRuntime.jsx("div",{className:"flex h-32 items-center justify-center",children:jsxRuntime.jsx(ui.Spinner,{})}),t&&!s&&jsxRuntime.jsx("div",{className:"text-default-500 mt-4 text-xs",children:p("perpDeposit.confirm.expiresIn",{seconds:u})}),s&&jsxRuntime.jsx("div",{className:"text-warning-500 mt-4 text-xs",children:p("perpDeposit.confirm.expired")}),a&&jsxRuntime.jsx("div",{className:"text-danger mt-4 text-xs",children:a})]}),jsxRuntime.jsxs(ui.ModalFooter,{className:"flex justify-between gap-2",children:[jsxRuntime.jsx(ui.Button,{variant:"flat",color:"default",onPress:o,isDisabled:r,children:p("perpDeposit.confirm.cancel")}),jsxRuntime.jsx(ui.Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:p("perpDeposit.confirm.cta")})]})]})})}function po({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(_e,{label:t("perpDeposit.confirm.send"),value:`${Oe(e.grossLamports)} SOL`}),jsxRuntime.jsx(_e,{label:t("perpDeposit.confirm.receive"),value:`${Ht(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(_e,{label:t("perpDeposit.confirm.platformFee"),value:`${Oe(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(_e,{label:t("perpDeposit.confirm.relayFee"),value:`${Oe(e.relayDepositLamports,6)} SOL`,muted:true})]})}function _e({label:e,value:t,highlight:r,muted:s}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("dt",{className:"text-default-500",children:e}),jsxRuntime.jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-default-500 text-xs":"text-foreground",children:t})]})}function $t({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:o,amountError:i,recipientError:a,onMax:p,className:l}){let{t:u}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui.cn("flex flex-col gap-4",l),children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-amount",className:"text-sm font-medium text-foreground",children:u("perpDeposit.amount")}),n&&jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:u("perpDeposit.amount.balance",{balance:n})})]}),jsxRuntime.jsx("div",{className:"relative",children:jsxRuntime.jsx(ui.Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:u("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:o,isInvalid:!!i,errorMessage:i,endContent:jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-default-500 text-sm",children:u("perpDeposit.amount.unit")}),n&&p&&jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"primary",onPress:p,isDisabled:o,children:u("perpDeposit.amount.max")})]})})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-recipient",className:"text-sm font-medium text-foreground mb-1.5 block",children:u("perpDeposit.recipient")}),jsxRuntime.jsx(ui.Input,{id:"perp-deposit-recipient",type:"text",placeholder:u("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:o,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}function Wt({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:o,onClose:i,errorMessage:a}){let{t:p}=i18n.useTranslation(),l=Po(t),u=t==="failed"?a||(r?.lastError?.message?p("perpDeposit.status.failed",{message:r.lastError.message}):p("perpDeposit.status.failed",{message:""})):t==="succeeded"?p("perpDeposit.status.settled"):t==="refunded"?p("perpDeposit.status.refunded"):r?.status==="broadcasted"?p("perpDeposit.status.broadcasted"):r?.status==="relay_waiting"?p("perpDeposit.status.relay_waiting"):r?.status==="relay_pending"?p("perpDeposit.status.relay_pending"):r?.status==="stuck"?p("perpDeposit.status.stuck"):p("perpDeposit.status.broadcasted");return jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:d=>!d&&i(),backdrop:"blur",children:jsxRuntime.jsxs(ui.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui.ModalHeader,{children:p("perpDeposit.status.title")}),jsxRuntime.jsx(ui.ModalBody,{children:jsxRuntime.jsxs("div",{className:ui.cn("flex flex-col items-center gap-4 py-4 text-center",vo(l)),children:[jsxRuntime.jsx(Do,{variant:l}),jsxRuntime.jsx("p",{className:"text-sm",children:u}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[r?.solanaTxHash&&s&&jsxRuntime.jsxs("a",{href:s,target:"_blank",rel:"noreferrer",className:"text-primary underline-offset-2 hover:underline",children:[p("perpDeposit.status.viewSolanaTx")," \xB7"," ",ze(r.solanaTxHash,8,6)]}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsxs("a",{href:n,target:"_blank",rel:"noreferrer",className:"text-primary underline-offset-2 hover:underline",children:[p("perpDeposit.status.viewHyperliquidTx")," \xB7"," ",ze(r.hyperliquidTxHash,8,6)]})]})]})}),jsxRuntime.jsxs(ui.ModalFooter,{className:"flex justify-between gap-2",children:[t==="failed"&&o?jsxRuntime.jsx(ui.Button,{color:"primary",onPress:o,children:p("perpDeposit.status.tryAgain")}):jsxRuntime.jsx("span",{}),jsxRuntime.jsx(ui.Button,{variant:"flat",onPress:i,children:p("perpDeposit.status.close")})]})]})})}function Po(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function vo(e){switch(e){case "success":return "text-success-600";case "warning":return "text-warning-600";case "error":return "text-danger";default:return "text-foreground"}}function Do({variant:e}){return e==="progress"?jsxRuntime.jsx(ui.Spinner,{size:"lg"}):e==="success"?jsxRuntime.jsx(To,{className:"size-12"}):e==="warning"?jsxRuntime.jsx(Co,{className:"size-12"}):jsxRuntime.jsx(ko,{className:"size-12"})}function To(e){return jsxRuntime.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsxRuntime.jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm-1.2 14.6l-4-4 1.4-1.4 2.6 2.6 6-6 1.4 1.4-7.4 7.4z"})})}function Co(e){return jsxRuntime.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsxRuntime.jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm0 4c.6 0 1 .4 1 1v6c0 .6-.4 1-1 1s-1-.4-1-1V7c0-.6.4-1 1-1zm0 12c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"})})}function ko(e){return jsxRuntime.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsxRuntime.jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm5 13.6L15.6 17 12 13.4 8.4 17 7 15.6 10.6 12 7 8.4 8.4 7 12 10.6 15.6 7 17 8.4 13.4 12 17 15.6z"})})}function Io({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:o,balanceSol:i,onMaxClick:a,validateRecipient:p,buildSolanaExplorerUrl:l,buildHyperliquidExplorerUrl:u,onSettled:d,onError:m,className:f}){let{t:b}=i18n.useTranslation(),[y,w]=react.useState(""),[h,k]=react.useState(n??""),C=react.useMemo(()=>{if(y&&(!/^\d+(\.\d+)?$/.test(y.trim())||Number(y)<=0))return b("perpDeposit.error.amountInvalid")},[y,b]),N=react.useMemo(()=>{if(h)return p?p(h):void 0},[h,p]),R=react.useMemo(()=>C?"":zt(y),[y,C]),q=react.useMemo(()=>!R||R==="0"||N||!h?null:{userSolanaAddress:e,hyperliquidRecipient:h,grossLamports:R,source:r},[R,h,N,r,e]),A=at(q,{enabled:!!q}),{state:c,execute:X,reset:T,dispatch:L}=pt(o),le=c.phase==="submitted"||c.phase==="tracking"||c.phase==="succeeded"||c.phase==="refunded"||c.phase==="failed"?c.intentId:void 0,te=lt(le,{enabled:!!le&&c.phase!=="succeeded"&&c.phase!=="refunded"&&c.phase!=="failed"});react.useEffect(()=>{te.data&&L({type:"STATUS_UPDATE",status:te.data});},[te.data,L]),react.useEffect(()=>{c.phase==="succeeded"?d?.(c.intentId):c.phase==="failed"&&m?.(c.intentId,c.error.message);},[c,d,m]);let re=react.useCallback(()=>{A.data&&(L({type:"QUOTE_REQUEST"}),L({type:"QUOTE_RECEIVED",quote:A.data}));},[L,A.data]),ns=react.useCallback(async()=>{if(c.phase==="ready_to_sign")try{await X({quote:c.quote,userSolanaAddress:e,hyperliquidRecipient:h,userId:t,source:r,campaign:s});}catch{}},[c,X,e,h,t,r,s]),os=react.useCallback(()=>{L({type:"QUOTE_EXPIRED"});},[L]),is=react.useCallback(async()=>{L({type:"RESET"}),await A.refetch();},[L,A]),as=c.phase==="ready_to_sign"||c.phase==="signing"||c.phase==="broadcasting"||c.phase==="expired",ps=c.phase==="submitted"||c.phase==="tracking"||c.phase==="succeeded"||c.phase==="refunded"||c.phase==="failed"&&!!c.intentId,he=c.phase==="tracking"||c.phase==="succeeded"||c.phase==="refunded"||c.phase==="failed"?c.status:void 0,ls=!A.data||A.isFetching||!!C||!!N||!q;return jsxRuntime.jsxs(ui.Card,{className:f,children:[jsxRuntime.jsxs(ui.CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:b("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:b("perpDeposit.description")})]}),jsxRuntime.jsx($t,{amount:y,onAmountChange:w,recipient:h,onRecipientChange:k,balanceSol:i,onMax:a,amountError:C,recipientError:N,disabled:c.phase!=="idle"&&c.phase!=="expired"&&c.phase!=="failed"}),jsxRuntime.jsx(ui.Button,{color:"primary",isDisabled:ls,isLoading:A.isFetching,onPress:re,children:A.isFetching?b("perpDeposit.gettingQuote"):b("perpDeposit.confirmQuote")}),A.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:b("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(_t,{isOpen:as,quote:c.phase==="ready_to_sign"||c.phase==="signing"||c.phase==="broadcasting"||c.phase==="expired"?c.quote:void 0,isExecuting:c.phase==="signing"||c.phase==="broadcasting",isExpired:c.phase==="expired",onConfirm:ns,onCancel:T,onExpire:os}),jsxRuntime.jsx(Wt,{isOpen:ps,phase:c.phase,status:he,solanaExplorerUrl:he?.solanaTxHash&&l?l(he.solanaTxHash):void 0,hyperliquidExplorerUrl:he?.hyperliquidTxHash&&u?u(he.hyperliquidTxHash):void 0,onRetry:c.phase==="failed"?is:void 0,onClose:T,errorMessage:c.phase==="failed"?c.error.message:void 0})]})}function jt({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:o}){let{t:i}=i18n.useTranslation(),a=e.phase,p=a==="executing",l=a==="loading",u=a==="error"&&e.steps.length===0;return jsxRuntime.jsxs(ui.Card,{className:ui.cn("w-full max-w-md",o),children:[jsxRuntime.jsxs(ui.CardHeader,{className:"flex flex-col items-start gap-1",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:i("perpDeposit.setup.title")}),jsxRuntime.jsx("p",{className:"text-foreground-500 text-sm",children:i("perpDeposit.setup.description")})]}),jsxRuntime.jsxs(ui.CardBody,{className:"gap-3",children:[l&&jsxRuntime.jsx(Ao,{}),u&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:i("perpDeposit.setup.loadFailed",{message:e.error??""})}),!l&&!u&&e.steps.map((d,m)=>jsxRuntime.jsx(Mo,{rec:d,index:m,isCurrent:e.currentIndex===m,onRetry:r},`${d.step.id}-${m}`)),a==="done"&&jsxRuntime.jsx("p",{className:"text-success text-sm",children:i("perpDeposit.setup.alreadyActive")})]}),jsxRuntime.jsxs(ui.CardFooter,{className:"flex justify-between gap-2",children:[n&&jsxRuntime.jsx(ui.Button,{variant:"light",onPress:n,isDisabled:p,children:i(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsxRuntime.jsx("div",{className:"flex-1"}),u&&s&&jsxRuntime.jsx(ui.Button,{color:"primary",onPress:s,children:i("perpDeposit.setup.retry")}),!u&&a!=="done"&&jsxRuntime.jsx(ui.Button,{color:"primary",onPress:t,isLoading:p,isDisabled:p||l,children:e.steps.some(d=>d.status==="done")?i("perpDeposit.setup.continue"):i("perpDeposit.setup.cta")})]})]})}function Mo({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),o=Qo(e.step.id,()=>{switch(e.step.id){case "approveBuilderFee":return n("perpDeposit.setup.builderFee.label");case "setReferrer":return n("perpDeposit.setup.referrer.label");case "updateLeverage":return n("perpDeposit.setup.leverage.label")}}),i=(()=>{switch(e.step.id){case "approveBuilderFee":{let p=(e.step.params.maxFeeRate/10).toFixed(1);return n("perpDeposit.setup.builderFee.description",{bps:p})}case "setReferrer":return n("perpDeposit.setup.referrer.description",{code:e.step.params.code});case "updateLeverage":return n("perpDeposit.setup.leverage.description")}})(),a=(()=>{switch(e.status){case "pending":return n("perpDeposit.setup.step.pending");case "skipped":return n("perpDeposit.setup.step.skipped");case "running":return n("perpDeposit.setup.step.running");case "done":return n("perpDeposit.setup.step.done");case "error":return n("perpDeposit.setup.step.error")}})();return jsxRuntime.jsxs("div",{className:ui.cn("border-divider flex items-start justify-between gap-3 rounded-md border p-3",e.status==="error"&&"border-danger",e.status==="done"&&"border-success/40 bg-success/5",e.status==="skipped"&&"border-default bg-default-100/40"),children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsxRuntime.jsx(Lo,{status:e.status,isCurrent:r}),jsxRuntime.jsx("span",{children:o})]}),jsxRuntime.jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:i}),e.status==="error"&&e.error&&jsxRuntime.jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsxRuntime.jsx("span",{className:ui.cn(Bo(e.status)),children:a}),e.status==="error"&&s&&jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function Ao(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsxRuntime.jsx(ui.Spinner,{size:"sm"}),jsxRuntime.jsx("span",{children:e("perpDeposit.setup.loading")})]})}function Lo({status:e,isCurrent:t}){return e==="running"||t?jsxRuntime.jsx(ui.Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsxRuntime.jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Bo(e){switch(e){case "done":return "text-success";case "skipped":return "text-foreground-500";case "running":return "text-primary";case "error":return "text-danger";default:return "text-foreground-500"}}function Qo(e,t){return t()}function Ho({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:o,onDismiss:i,className:a}){let{state:p,runNext:l,runStep:u,reload:d}=Ae({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:o}),m=react.useCallback(()=>{l();},[l]),f=react.useCallback(y=>{u(y);},[u]),b=react.useCallback(()=>{d();},[d]);return jsxRuntime.jsx(jt,{state:p,onContinue:m,onRetryStep:f,onReload:b,onDismiss:i,className:a})}
12
+ exports.CoinInfoNotFoundUI=ut;exports.CoinInfoSkeletonsUI=dt;exports.CoinInfoUI=ft;exports.CoinInfoWidget=sn;exports.DepositConfirmUI=_t;exports.DepositFlowWidget=Io;exports.DepositFormUI=$t;exports.DepositStatusUI=Wt;exports.HyperliquidApiError=se;exports.HyperliquidInitUI=jt;exports.HyperliquidInitWidget=Ho;exports.HyperliquidPerpetualsClient=Ge;exports.LiberFiApiError=_;exports.LiberFiHttpTransport=ne;exports.LiberFiPerpDepositClient=je;exports.LiberFiPerpetualsClient=Ve;exports.OpenOrdersEmpty=Ft;exports.OpenOrdersSkeleton=Et;exports.OpenOrdersUI=Ut;exports.OpenOrdersWidget=$n;exports.OrderBookUI=xt;exports.OrderBookWidget=yn;exports.PerpetualsContext=oe;exports.PerpetualsProvider=vs;exports.PlaceOrderFormUI=Ct;exports.PlaceOrderFormWidget=Nn;exports.PositionsEmpty=An;exports.PositionsSkeleton=Nt;exports.PositionsUI=Ot;exports.PositionsWidget=Ln;exports.SearchCoinsUI=bt;exports.SearchCoinsWidget=ln;exports.TERMINAL_DEPOSIT_STATUSES=xe;exports.TradeHistoryEmpty=Qt;exports.TradeHistorySkeleton=Bt;exports.TradeHistoryUI=Lt;exports.TradeHistoryWidget=Xn;exports.TradesUI=vt;exports.TradesWidget=vn;exports.cancelOrder=br;exports.classifyStep=Ee;exports.coinsQueryKey=Yt;exports.createOrder=gr;exports.currentDepositBreakdown=hs;exports.currentDepositStatus=bs;exports.fetchCoins=Zt;exports.fetchKlines=or;exports.fetchMarket=tr;exports.fetchMarkets=sr;exports.fetchOrderBook=ar;exports.fetchOrders=mr;exports.fetchPerpDepositQuote=xr;exports.fetchPerpDepositStatus=Dr;exports.fetchPositions=dr;exports.fetchRecentTrades=lr;exports.fetchTrades=yr;exports.initialDepositState=Ue;exports.initialSetupState=Te;exports.isDepositPolling=gs;exports.isDepositTerminal=ys;exports.isTerminalDepositLifecycle=xs;exports.klinesQueryKey=nr;exports.lamportsToSol=Oe;exports.marketQueryKey=er;exports.marketsQueryKey=rr;exports.microUsdcToUsdc=Ht;exports.nextRunnableStep=qe;exports.orderBookQueryKey=ir;exports.ordersQueryKey=cr;exports.perpDepositQuoteQueryKey=hr;exports.perpDepositStatusQueryKey=vr;exports.positionsQueryKey=ur;exports.recentTradesQueryKey=pr;exports.reduceDepositState=Je;exports.reduceSetupState=Fe;exports.secondsUntil=Ne;exports.shortAddress=ze;exports.solToLamports=zt;exports.tradesQueryKey=fr;exports.useCancelOrderMutation=st;exports.useCandlesSubscription=Hs;exports.useCoinInfo=mt;exports.useCoinsQuery=Xe;exports.useCreateOrderMutation=ve;exports.useHyperliquidSetup=Ae;exports.useKlinesQuery=Ns;exports.useMarketDataSubscription=ie;exports.useMarketQuery=Se;exports.useMarketsQuery=Ye;exports.useOpenOrdersScript=Rt;exports.useOrderBookQuery=Ze;exports.useOrderBookScript=ht;exports.useOrdersQuery=tt;exports.usePerpDepositClient=ae;exports.usePerpDepositExecute=pt;exports.usePerpDepositQuote=at;exports.usePerpDepositStatus=lt;exports.usePerpetualsClient=P;exports.usePlaceOrderFormScript=Tt;exports.usePositionsQuery=Pe;exports.usePositionsScript=kt;exports.useRecentTradesQuery=et;exports.useSearchCoinsScript=gt;exports.useTradeHistoryScript=Mt;exports.useTradesQuery=rt;exports.useTradesScript=St;exports.useUserDataSubscription=De;exports.version=us;//# sourceMappingURL=index.js.map
13
13
  //# sourceMappingURL=index.js.map