@liberfi.io/ui-perpetuals 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -12,7 +12,7 @@ declare global {
12
12
  };
13
13
  }
14
14
  }
15
- declare const _default: "0.2.10";
15
+ declare const _default: "0.2.11";
16
16
 
17
17
  /**
18
18
  * Trading pair symbol format
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ declare global {
12
12
  };
13
13
  }
14
14
  }
15
- declare const _default: "0.2.10";
15
+ declare const _default: "0.2.11";
16
16
 
17
17
  /**
18
18
  * Trading pair symbol format
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'),i18n=require('@liberfi.io/i18n');typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.10");var cs="0.2.10";var de=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;connectPromise=null;manuallyDisconnected=false;constructor(t){this.wsEndpoint=t;}async connect(){if(!(this.isConnected&&this.ws?.readyState===WebSocket.OPEN))return this.connectPromise?this.connectPromise:(this.manuallyDisconnected=false,this.connectPromise=new Promise((t,r)=>{let s=false,n=o=>{s||(s=true,this.connectPromise=null,o());};try{let o=new WebSocket(this.wsEndpoint);this.ws=o,o.onopen=()=>{this.ws===o&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},o.onmessage=i=>{this.ws===o&&this.handleMessage(i.data);},o.onerror=i=>{this.ws===o&&(console.error("[WebSocket] Error:",i),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},o.onclose=i=>{this.ws===o&&(console.log(`[WebSocket] Closed: ${i.code} - ${i.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${i.code}`))),!this.manuallyDisconnected&&i.code!==1e3&&this.attemptReconnect());};}catch(o){n(()=>r(o));}}),this.connectPromise)}disconnect(){this.manuallyDisconnected=true,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 Yt={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;wsRefCount=0;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||Yt[this.environment].api,this._wsEndpoint=t.wsEndpoint||Yt[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 ne(`HTTP ${i.status}: ${i.statusText}`,i.status,await i.text());return await i.json()}catch(n){throw n.name==="AbortError"?new ne(`Request timeout after ${this.timeout}ms`,408,""):n instanceof ne?n:new ne(`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(){this.wsRefCount+=1,this.wsManager||(this.wsManager=new de(this._wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&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);}},ne=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";}},ms=3e4,oe=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??ms,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 fs(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 fs(e){try{return await e.text()}catch{return ""}}var ys="wss://api.hyperliquid.xyz/ws",Ve=class{transport;wsEndpoint;signTypedData;wsManager=null;wsRefCount=0;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 oe({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??ys,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.wsRefCount+=1,this.wsManager||(this.wsManager=new de(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&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 oe(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 gs(t.status,r)}}}function gs(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 bs(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function hs(e){return e.phase==="submitted"||e.phase==="tracking"}function xs(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Ss(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 Ps(e){return e!==void 0&&xe.has(e)}var ie=react.createContext({});function Cs({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(ie.Provider,{value:s,children:r})}function D(){let e=react.useContext(ie);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Zt(){return ["perps","coins"]}async function er(e){return await e.getSupportedCoins()}function Xe(e={}){let{client:t}=D();return reactQuery.useQuery({queryKey:Zt(),queryFn:async()=>er(t),staleTime:300*1e3,...e})}function tr(e){return ["perps","market",e.symbol]}async function rr(e,{symbol:t}){return await e.getMarket(t)}function Se(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:tr(e),queryFn:async()=>rr(r,e),staleTime:10*1e3,...t})}function sr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function nr(e,{symbols:t}={}){return await e.getMarkets(t)}function Ye(e={},t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:sr(e),queryFn:async()=>nr(r,e),staleTime:10*1e3,...t})}function or(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function ir(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function Is(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:or(e),queryFn:async()=>ir(r,e),staleTime:30*1e3,...t})}function ar(e){return ["perps","orderBook",e.symbol,String(e.maxLevel??20)]}async function pr(e,{symbol:t,maxLevel:r}){return await e.getOrderBook(t,r)}function Ze(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:ar(e),queryFn:async()=>pr(r,e),staleTime:5*1e3,...t})}function lr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function ur(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function et(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:lr(e),queryFn:async()=>ur(r,e),staleTime:5*1e3,...t})}function dr(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function cr(e,t){return await e.getPositions(t)}function Pe(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:dr(n),queryFn:async()=>cr(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function mr(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function fr(e,t){return await e.getOpenOrders(t)}function tt(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:mr(n),queryFn:async()=>fr(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function yr(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function gr(e,t){return await e.getTrades(t)}function rt(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:yr(n),queryFn:async()=>gr(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}async function br(e,t){return await e.placeOrder(t)}function ve(e={}){let{client:t}=D();return reactQuery.useMutation({mutationFn:async r=>br(t,r),...e})}async function hr(e,t){return await e.cancelOrder(t)}function st(e={}){let{client:t}=D();return reactQuery.useMutation({mutationFn:async r=>hr(t,r),...e})}function ae(e){let{type:t,symbol:r,enabled:s=true}=e,{client:n}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeMarketData(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function _s(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeCandles(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}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}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s||!r)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeUserData(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function pe(){let e=react.useContext(ie);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 xr(e){return ["perps","deposit","quote",e]}async function Sr(e,t){return e.quote(t)}function at(e,t={}){let r=pe(),s=t.enabled??!!Vs(e);return reactQuery.useQuery({queryKey:xr(e??null),queryFn:async()=>Sr(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Vs(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function pt(e){let t=pe(),[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=vr(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=vr(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,e]);return {state:r,execute:o,reset:n,dispatch:s}}function vr(e,t){if(e instanceof $){let r=Js(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 Js(e){if(e)try{return JSON.parse(e)}catch{return}}function Dr(e){return ["perps","deposit","status",e??null]}async function Cr(e,t){return e.status(t)}function lt(e,t={}){let r=pe(),s=t.enabled??!!e,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:Dr(e??void 0),queryFn:async()=>Cr(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 Ce={phase:"idle",steps:[]};function Ee(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Ys(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?Zs(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 Ce}}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 Ys(e,t){return e.toLowerCase()===t.toLowerCase()}function Zs(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,Ce),l=react.useRef(t),u=react.useRef(s),d=react.useRef(o),c=react.useRef(i);l.current=t,u.current=s,d.current=o,c.current=i;let m=react.useCallback(async()=>{if(r){p({type:"START_LOADING"});try{let w=await l.current.getAccountState(r),O=u.current.map(k=>({step:k,status:Ee(k,w)}));p({type:"LOAD_SUCCESS",accountState:w,steps:O});}catch(w){let O=wr(w);p({type:"LOAD_ERROR",error:O.message}),c.current?.(O,{});}}},[r]);react.useEffect(()=>{n&&r&&m();},[n,r,m]);let b=react.useCallback(async w=>{let O=a.steps[w];if(O){p({type:"RUN_STEP",index:w});try{let k=await tn(l.current,O.step);p({type:"STEP_SUCCESS",index:w,txHash:k.txHash,accountState:k.state});}catch(k){let U=wr(k);p({type:"STEP_ERROR",index:w,error:U.message}),c.current?.(U,{stepId:O.step.id});}}},[a.steps]),f=react.useCallback(async()=>{let w=qe(a);w!=null&&await b(w);},[a,b]),I=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:m,runNext:f,runStep:b,reset:I}}function tn(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 wr(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}=ae({type:"ticker",symbol:e,enabled:!!o});return react.useEffect(()=>{o&&r(o);},[o]),react.useEffect(()=>{if(!a)return;let l=rn(a,e);l&&r(u=>sn(u??o??void 0,l,e));},[a,o,e]),react.useEffect(()=>{let l=()=>{let d=Date.now(),c=480*60*1e3,m=d%c,b=c-m;return Math.floor(b/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:i,fundingCountdown:s}}function rn(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 ce(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function sn(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:ce(t.price,e?.price??0),change24h:ce(t.change24h,e?.change24h??0),volume24h:ce(t.volume24h,e?.volume24h??0),fundingRate:ce(t.fundingRate,e?.fundingRate??0),openInterest:ce(t.openInterest,e?.openInterest??0),markPrice:ce(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 nn(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 Nr(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 Rr(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,c=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:Rr(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",c,"%"]})]}),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?Rr(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:Nr(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:Nr(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:nn(t)})]})]})]})]})}function on({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(c=>c.symbol.toLowerCase().includes(d))},[s,t]);return {coins:s,isLoading:i||p,searchQuery:t,setSearchQuery:r,filteredCoins:l,handleSelectCoin:d=>{e?.(d);}}}function Ur(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 un(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 c=d.target;c.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:un(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:Ur(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ur(o.openInterest*o.price)})]},o.symbol)})]})]})}function dn({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 qr(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 Mr(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}=ae({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=qr(s.bids,o),c=qr(s.asks,o),m=d.sort((U,A)=>A.price-U.price).slice(0,t),b=c.sort((U,A)=>U.price-A.price).slice(0,t),f=Mr(m),I=Mr(b),h=f[0]?.price||0,O=(I[0]?.price||0)-h,k=h>0?O/h*100:0;return {bids:f,asks:I,spread:O,spreadPercentage:k}},[s,o,t]),isLoading:p,precision:o,setPrecision:i}}function fn(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 Ar(e){return Math.round(e).toLocaleString("en-US")}function Lr({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:fn(e)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Ar(t)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Ar(r)})]})}function xt({bids:e,asks:t,spread:r,spreadPercentage:s,onPriceClick:n}){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:t.map((o,i)=>jsxRuntime.jsx(Lr,{price:o.price,quantity:o.quantity,total:o.total,percentage:o.percentage,side:"ask",onClick:()=>n?.(o.price)},`ask-${o.price}-${i}`))}),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((o,i)=>jsxRuntime.jsx(Lr,{price:o.price,quantity:o.quantity,total:o.total,percentage:o.percentage,side:"bid",onClick:()=>n?.(o.price)},`bid-${o.price}-${i}`))})]})}function yn(){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 gn(){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 bn({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(yn,{}):n.length===0&&o.length===0?jsxRuntime.jsx(gn,{}):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}=ae({type:"trades",symbol:e,enabled:!!n});return react.useEffect(()=>{n&&s(n.filter(Br));},[n]),react.useEffect(()=>{i&&s(a=>{let p=xn(i);if(p.length===0)return a;let l=p.filter(d=>!a.some(c=>c.timestamp===d.timestamp&&c.price===d.price&&c.quantity===d.quantity));return l.length===0?a:[...l,...a].slice(0,t)});},[i,t]),{trades:r,isLoading:o}}function xn(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 Sn(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Hr(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 Pn(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:Sn(r.price)})}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{color:"#ffffff"},children:Hr(r.quantity)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100,color:"#ffffff"},children:Hr(o)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70,color:"#b5b5b5"},children:Pn(r.timestamp)})]},`${r.timestamp}-${r.price}-${s}`)})})]})}function vn(){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 Dn(){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 Cn({symbol:e,limit:t=50,onTradeClick:r,className:s}){let{trades:n,isLoading:o}=St({symbol:e,limit:t});return o?jsxRuntime.jsx(vn,{}):n.length===0?jsxRuntime.jsx(Dn,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(vt,{trades:n,onTradeClick:r})})}function Ct({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:c}=ve({onSuccess:()=>{l.reset(),s?.();},onError:v=>{n?.(v);}}),m=l.watch(),{amount:b,leverage:f,price:I}=m,h=react.useMemo(()=>a==="limit"&&I?I:u?.price||0,[a,I,u?.price]),w=react.useMemo(()=>!b||!h?0:b*h*5e-4,[b,h]),O=react.useMemo(()=>!b||!h?0:b*h+w,[b,h,w]),k=react.useMemo(()=>{if(!b||!h||!f||f===1)return;let v=.005,q=h;return o==="long"?q*(1-(1/f-v)):q*(1+(1/f-v))},[b,h,f,o]),{data:U}=Pe({userAddress:t,symbol:e}),A=U?.totalEquity??0,Q=U?.availableBalance??0,y=react.useMemo(()=>{let v=U?.positions?.[0];return v?v.side==="short"?-v.quantity:v.quantity:0},[U?.positions]),N=react.useCallback(async v=>{if(!t)throw new Error("User address is required");let q=a==="limit"?v.price:void 0,ue=v.takeProfitPrice,re=v.stopLossPrice;if(!ue&&v.takeProfitPercent&&v.takeProfitPercent>0&&h){let se=v.takeProfitPercent/100;ue=o==="long"?h*(1+se):h*(1-se);}if(!re&&v.stopLossPercent&&v.stopLossPercent>0&&h){let se=v.stopLossPercent/100;re=o==="long"?h*(1-se):h*(1+se);}await d({symbol:e,side:o,orderType:a,amount:v.amount,price:q,leverage:v.leverage,takeProfitPrice:ue,stopLossPrice:re,userAddress:t});},[e,o,a,h,t,d]);return {form:l,side:o,orderType:a,setSide:i,setOrderType:p,handleSubmit:N,isSubmitting:c,currentPrice:h,estimatedFee:w,estimatedTotal:O,liquidationPrice:k,availableMargin:Q,accountValue:A,currentPosition:y,maxLeverage:r}}function Qe(e,t=2){return e.toFixed(t)}function Rn({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 Tt({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:c,currentPosition:m,maxLeverage:b,onAddFunds:f}){let[I,h]=react.useState(false),[w,O]=react.useState(false),k=e.watch("leverage")||20,U=e.watch("amount")||0,A=a.split("-")[0],Q=d>0&&p?Math.min(U*p/(d*k)*100,100):0,y=N=>{let v=(Array.isArray(N)?N[0]:N)/100;if(p&&p>0){let q=d*k*v/p;e.setValue("amount",Number(q.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(N=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===N.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===N.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(N.key),children:N.label})},N.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:()=>h(true),children:["Leverage: ",k,"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:A})]}),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.11");var cs="0.2.11";var de=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;connectPromise=null;manuallyDisconnected=false;constructor(t){this.wsEndpoint=t;}async connect(){if(!(this.isConnected&&this.ws?.readyState===WebSocket.OPEN))return this.connectPromise?this.connectPromise:(this.manuallyDisconnected=false,this.connectPromise=new Promise((t,r)=>{let s=false,n=o=>{s||(s=true,this.connectPromise=null,o());};try{let o=new WebSocket(this.wsEndpoint);this.ws=o,o.onopen=()=>{this.ws===o&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},o.onmessage=i=>{this.ws===o&&this.handleMessage(i.data);},o.onerror=i=>{this.ws===o&&(console.error("[WebSocket] Error:",i),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},o.onclose=i=>{this.ws===o&&(console.log(`[WebSocket] Closed: ${i.code} - ${i.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${i.code}`))),!this.manuallyDisconnected&&i.code!==1e3&&this.attemptReconnect());};}catch(o){n(()=>r(o));}}),this.connectPromise)}disconnect(){this.manuallyDisconnected=true,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 Yt={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;wsRefCount=0;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||Yt[this.environment].api,this._wsEndpoint=t.wsEndpoint||Yt[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 ne(`HTTP ${i.status}: ${i.statusText}`,i.status,await i.text());return await i.json()}catch(n){throw n.name==="AbortError"?new ne(`Request timeout after ${this.timeout}ms`,408,""):n instanceof ne?n:new ne(`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(){this.wsRefCount+=1,this.wsManager||(this.wsManager=new de(this._wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&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);}},ne=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";}},ms=3e4,oe=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??ms,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 fs(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 fs(e){try{return await e.text()}catch{return ""}}var ys="wss://api.hyperliquid.xyz/ws",Ve=class{transport;wsEndpoint;signTypedData;wsManager=null;wsRefCount=0;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 oe({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??ys,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.wsRefCount+=1,this.wsManager||(this.wsManager=new de(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&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 oe(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 gs(t.status,r)}}}function gs(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 bs(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function hs(e){return e.phase==="submitted"||e.phase==="tracking"}function xs(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Ss(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 Ps(e){return e!==void 0&&xe.has(e)}var ie=react.createContext({});function Cs({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(ie.Provider,{value:s,children:r})}function D(){let e=react.useContext(ie);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Zt(){return ["perps","coins"]}async function er(e){return await e.getSupportedCoins()}function Xe(e={}){let{client:t}=D();return reactQuery.useQuery({queryKey:Zt(),queryFn:async()=>er(t),staleTime:300*1e3,...e})}function tr(e){return ["perps","market",e.symbol]}async function rr(e,{symbol:t}){return await e.getMarket(t)}function Se(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:tr(e),queryFn:async()=>rr(r,e),staleTime:10*1e3,...t})}function sr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function nr(e,{symbols:t}={}){return await e.getMarkets(t)}function Ye(e={},t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:sr(e),queryFn:async()=>nr(r,e),staleTime:10*1e3,...t})}function or(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function ir(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function Is(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:or(e),queryFn:async()=>ir(r,e),staleTime:30*1e3,...t})}function ar(e){return ["perps","orderBook",e.symbol,String(e.maxLevel??20)]}async function pr(e,{symbol:t,maxLevel:r}){return await e.getOrderBook(t,r)}function Ze(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:ar(e),queryFn:async()=>pr(r,e),staleTime:5*1e3,...t})}function lr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function ur(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function et(e,t={}){let{client:r}=D();return reactQuery.useQuery({queryKey:lr(e),queryFn:async()=>ur(r,e),staleTime:5*1e3,...t})}function dr(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function cr(e,t){return await e.getPositions(t)}function Pe(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:dr(n),queryFn:async()=>cr(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function mr(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function fr(e,t){return await e.getOpenOrders(t)}function tt(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:mr(n),queryFn:async()=>fr(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function yr(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function gr(e,t){return await e.getTrades(t)}function rt(e,t={}){let{client:r}=D(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:yr(n),queryFn:async()=>gr(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}async function br(e,t){return await e.placeOrder(t)}function ve(e={}){let{client:t}=D();return reactQuery.useMutation({mutationFn:async r=>br(t,r),...e})}async function hr(e,t){return await e.cancelOrder(t)}function st(e={}){let{client:t}=D();return reactQuery.useMutation({mutationFn:async r=>hr(t,r),...e})}function ae(e){let{type:t,symbol:r,enabled:s=true}=e,{client:n}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeMarketData(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function _s(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeCandles(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}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}=D(),[o,i]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(c=>{i(c);},[]);return react.useEffect(()=>{if(!s||!r)return;let c=null,m=true;return (async()=>{try{if(await n.connectWebSocket(),!m)return;p(!0),u(null),c=n.subscribeUserData(t,r,d);}catch(f){m&&(u(f instanceof Error?f:new Error("Connection failed")),p(false));}})(),()=>{if(m=false,c)try{n.unsubscribe(c);}catch(f){console.error("Failed to unsubscribe:",f);}n.disconnectWebSocket(),p(false),i(null);}},[n,t,r,s,d]),{data:o,isConnected:a,error:l}}function pe(){let e=react.useContext(ie);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 xr(e){return ["perps","deposit","quote",e]}async function Sr(e,t){return e.quote(t)}function at(e,t={}){let r=pe(),s=t.enabled??!!Vs(e);return reactQuery.useQuery({queryKey:xr(e??null),queryFn:async()=>Sr(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Vs(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function pt(e){let t=pe(),[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=vr(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=vr(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,e]);return {state:r,execute:o,reset:n,dispatch:s}}function vr(e,t){if(e instanceof $){let r=Js(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 Js(e){if(e)try{return JSON.parse(e)}catch{return}}function Dr(e){return ["perps","deposit","status",e??null]}async function Cr(e,t){return e.status(t)}function lt(e,t={}){let r=pe(),s=t.enabled??!!e,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:Dr(e??void 0),queryFn:async()=>Cr(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 Ce={phase:"idle",steps:[]};function Ee(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Ys(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?Zs(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 Ce}}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 Ys(e,t){return e.toLowerCase()===t.toLowerCase()}function Zs(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,Ce),l=react.useRef(t),u=react.useRef(s),d=react.useRef(o),c=react.useRef(i);l.current=t,u.current=s,d.current=o,c.current=i;let m=react.useCallback(async()=>{if(r){p({type:"START_LOADING"});try{let w=await l.current.getAccountState(r),O=u.current.map(k=>({step:k,status:Ee(k,w)}));p({type:"LOAD_SUCCESS",accountState:w,steps:O});}catch(w){let O=wr(w);p({type:"LOAD_ERROR",error:O.message}),c.current?.(O,{});}}},[r]);react.useEffect(()=>{n&&r&&m();},[n,r,m]);let b=react.useCallback(async w=>{let O=a.steps[w];if(O){p({type:"RUN_STEP",index:w});try{let k=await tn(l.current,O.step);p({type:"STEP_SUCCESS",index:w,txHash:k.txHash,accountState:k.state});}catch(k){let U=wr(k);p({type:"STEP_ERROR",index:w,error:U.message}),c.current?.(U,{stepId:O.step.id});}}},[a.steps]),f=react.useCallback(async()=>{let w=qe(a);w!=null&&await b(w);},[a,b]),I=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:m,runNext:f,runStep:b,reset:I}}function tn(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 wr(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}=ae({type:"ticker",symbol:e,enabled:!!o});return react.useEffect(()=>{o&&r(o);},[o]),react.useEffect(()=>{if(!a)return;let l=rn(a,e);l&&r(u=>sn(u??o??void 0,l,e));},[a,o,e]),react.useEffect(()=>{let l=()=>{let d=Date.now(),c=480*60*1e3,m=d%c,b=c-m;return Math.floor(b/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:i,fundingCountdown:s}}function rn(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 ce(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function sn(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:ce(t.price,e?.price??0),change24h:ce(t.change24h,e?.change24h??0),volume24h:ce(t.volume24h,e?.volume24h??0),fundingRate:ce(t.fundingRate,e?.fundingRate??0),openInterest:ce(t.openInterest,e?.openInterest??0),markPrice:ce(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 nn(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 Nr(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 Rr(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,c=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:Rr(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",c,"%"]})]}),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?Rr(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:Nr(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:Nr(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:nn(t)})]})]})]})]})}function on({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(c=>c.symbol.toLowerCase().includes(d))},[s,t]);return {coins:s,isLoading:i||p,searchQuery:t,setSearchQuery:r,filteredCoins:l,handleSelectCoin:d=>{e?.(d);}}}function Ur(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 un(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 c=d.target;c.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:un(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:Ur(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ur(o.openInterest*o.price)})]},o.symbol)})]})]})}function dn({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 qr(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 Mr(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}=ae({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=qr(s.bids,o),c=qr(s.asks,o),m=d.sort((U,A)=>A.price-U.price).slice(0,t),b=c.sort((U,A)=>U.price-A.price).slice(0,t),f=Mr(m),I=Mr(b),h=f[0]?.price||0,O=(I[0]?.price||0)-h,k=h>0?O/h*100:0;return {bids:f,asks:I,spread:O,spreadPercentage:k}},[s,o,t]),isLoading:p,precision:o,setPrecision:i}}function fn(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 Ar(e){return Math.round(e).toLocaleString("en-US")}function Lr({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:fn(e)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Ar(t)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:{flex:"1 1 0%",color:"#ffffff"},children:Ar(r)})]})}function xt({bids:e,asks:t,spread:r,spreadPercentage:s,onPriceClick:n}){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:t.map((o,i)=>jsxRuntime.jsx(Lr,{price:o.price,quantity:o.quantity,total:o.total,percentage:o.percentage,side:"ask",onClick:()=>n?.(o.price)},`ask-${o.price}-${i}`))}),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((o,i)=>jsxRuntime.jsx(Lr,{price:o.price,quantity:o.quantity,total:o.total,percentage:o.percentage,side:"bid",onClick:()=>n?.(o.price)},`bid-${o.price}-${i}`))})]})}function yn(){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 gn(){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 bn({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(yn,{}):n.length===0&&o.length===0?jsxRuntime.jsx(gn,{}):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}=ae({type:"trades",symbol:e,enabled:!!n});return react.useEffect(()=>{n&&s(n.filter(Br));},[n]),react.useEffect(()=>{i&&s(a=>{let p=xn(i);if(p.length===0)return a;let l=p.filter(d=>!a.some(c=>c.timestamp===d.timestamp&&c.price===d.price&&c.quantity===d.quantity));return l.length===0?a:[...l,...a].slice(0,t)});},[i,t]),{trades:r,isLoading:o}}function xn(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 Sn(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Hr(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 Pn(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:Sn(r.price)})}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{color:"#ffffff"},children:Hr(r.quantity)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:100,color:"#ffffff"},children:Hr(o)}),jsxRuntime.jsx("div",{className:"flex-1 text-right",style:{maxWidth:70,color:"#b5b5b5"},children:Pn(r.timestamp)})]},`${r.timestamp}-${r.price}-${s}`)})})]})}function vn(){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 Dn(){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 Cn({symbol:e,limit:t=50,onTradeClick:r,className:s}){let{trades:n,isLoading:o}=St({symbol:e,limit:t});return o?jsxRuntime.jsx(vn,{}):n.length===0?jsxRuntime.jsx(Dn,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(vt,{trades:n,onTradeClick:r})})}function Ct({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:c}=ve({onSuccess:()=>{l.reset(),s?.();},onError:v=>{n?.(v);}}),m=l.watch(),{amount:b,leverage:f,price:I}=m,h=react.useMemo(()=>a==="limit"&&I?I:u?.price||0,[a,I,u?.price]),w=react.useMemo(()=>!b||!h?0:b*h*5e-4,[b,h]),O=react.useMemo(()=>!b||!h?0:b*h+w,[b,h,w]),k=react.useMemo(()=>{if(!b||!h||!f||f===1)return;let v=.005,q=h;return o==="long"?q*(1-(1/f-v)):q*(1+(1/f-v))},[b,h,f,o]),{data:U}=Pe({userAddress:t,symbol:e}),A=U?.totalEquity??0,Q=U?.availableBalance??0,y=react.useMemo(()=>{let v=U?.positions?.[0];return v?v.side==="short"?-v.quantity:v.quantity:0},[U?.positions]),N=react.useCallback(async v=>{if(!t)throw new Error("User address is required");let q=a==="limit"?v.price:void 0,ue=v.takeProfitPrice,re=v.stopLossPrice;if(!ue&&v.takeProfitPercent&&v.takeProfitPercent>0&&h){let se=v.takeProfitPercent/100;ue=o==="long"?h*(1+se):h*(1-se);}if(!re&&v.stopLossPercent&&v.stopLossPercent>0&&h){let se=v.stopLossPercent/100;re=o==="long"?h*(1-se):h*(1+se);}await d({symbol:e,side:o,orderType:a,amount:v.amount,price:q,leverage:v.leverage,takeProfitPrice:ue,stopLossPrice:re,userAddress:t});},[e,o,a,h,t,d]);return {form:l,side:o,orderType:a,setSide:i,setOrderType:p,handleSubmit:N,isSubmitting:c,currentPrice:h,estimatedFee:w,estimatedTotal:O,liquidationPrice:k,availableMargin:Q,accountValue:A,currentPosition:y,maxLeverage:r}}function Qe(e,t=2){return e.toFixed(t)}function Rn({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 Tt({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:c,currentPosition:m,maxLeverage:b,onAddFunds:f}){let[I,h]=react.useState(false),[w,O]=react.useState(false),k=e.watch("leverage")||20,U=e.watch("amount")||0,A=a.split("-")[0],Q=d>0&&p?Math.min(U*p/(d*k)*100,100):0,y=N=>{let v=(Array.isArray(N)?N[0]:N)/100;if(p&&p>0){let q=d*k*v/p;e.setValue("amount",Number(q.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(N=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===N.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===N.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(N.key),children:N.label})},N.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:()=>h(true),children:["Leverage: ",k,"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:A})]}),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; }