@liberfi.io/ui-perpetuals 0.2.13 → 0.2.14

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