@liberfi.io/ui-perpetuals 0.2.18 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),ui$1=require('@liberfi.io/ui'),reactWindow=require('react-window'),hooks=require('@liberfi.io/hooks'),reactHookForm=require('react-hook-form'),i18n=require('@liberfi.io/i18n');typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.18");var Ws="0.2.18";function $s(e,t,r){if(e!=="orderBook"||!r||r.nSigFigs===void 0)return `${e}:${t}`;let s=r.nSigFigs===5&&r.mantissa&&r.mantissa!==1?`:m${r.mantissa}`:"";return `${e}:${t}: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(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=i=>{s||(s=true,this.connectPromise=null,i());};try{let i=new WebSocket(this.wsEndpoint);this.ws=i,i.onopen=()=>{this.ws===i&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},i.onmessage=o=>{this.ws===i&&this.handleMessage(o.data);},i.onerror=o=>{this.ws===i&&(console.error("[WebSocket] Error:",o),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},i.onclose=o=>{this.ws===i&&(console.log(`[WebSocket] Closed: ${o.code} - ${o.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${o.code}`))),!this.manuallyDisconnected&&o.code!==1e3&&this.attemptReconnect());};}catch(i){n(()=>r(i));}}),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,t.aggregation);});}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 i=this.transformData(s.type,t.data,s.param);s.callback(i);}catch(i){console.error(`[WebSocket] Error in subscription callback (${n}):`,i);}});}isChannelMatch(t,r,s,n){if(r==="ticker"){if(t!=="activeAssetCtx")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else if(r==="trades"){if(t!=="trades")return false;let i=s.split("-")[0],o=Array.isArray(n?.data)?n.data[0]?.coin:void 0;return typeof o!="string"||o===i}else if(r==="orderBook"){if(t!=="l2Book")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else {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`,i=t?.ctx??{},o=parseFloat(i.midPx??i.markPx??"0"),a=parseFloat(i.markPx??i.midPx??"0"),p=i.prevDayPx?parseFloat(i.prevDayPx):o,l=p>0?(o-p)/p*100:0;return {symbol:n,price:o,change24h:l,volume24h:parseFloat(i.dayNtlVlm??"0"),fundingRate:parseFloat(i.funding??"0"),openInterest:parseFloat(i.openInterest??"0"),markPrice:a,indexPrice:parseFloat(i.oraclePx??i.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(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),asks:n.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.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,s){let n;if(t==="ticker")n={method:"subscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"subscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"subscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(n={method:"subscribe",subscription:{type:"userEvents",user:r}});n&&this.send(n);}sendUnsubscription(t,r,s){let n;if(t==="ticker")n={method:"unsubscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"unsubscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"unsubscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"unsubscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"unsubscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(n={method:"unsubscribe",subscription:{type:"userEvents",user:r}});n&&this.send(n);}subscribe(t,r,s,n){let i=$s(t,r,n);return this.subscriptions.set(i,{type:t,param:r,callback:s,aggregation:n}),this.sendSubscription(t,r,n),i}unsubscribe(t){let r=this.subscriptions.get(t);r&&(this.sendUnsubscription(r.type,r.param,r.aggregation),this.subscriptions.delete(t));}isConnectedNow(){return this.isConnected}};var yr={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"}},st=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||yr[this.environment].api,this._wsEndpoint=t.wsEndpoint||yr[this.environment].ws,this.timeout=t.timeout||3e4;}async request(t,r){let s=`${this.apiEndpoint}${t}`;try{let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout),o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(i),!o.ok)throw new se(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new se(`Request timeout after ${this.timeout}ms`,408,""):n instanceof se?n:new se(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){let[t]=await this.request("/info",{type:"metaAndAssetCtxs"});return t.universe.map(r=>`${r.name}-USDC`)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let[r,s]=await this.request("/info",{type:"metaAndAssetCtxs"}),n=r.universe.map((i,o)=>{let a=s[o],p=`${i.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 i=new Set(t);return n.filter(o=>i.has(o.symbol))}return n}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),i=typeof s=="number"?{limit:s}:s,o=this.parseInterval(r),a=i.limit,p,l;i.from!==void 0&&i.to!==void 0?(p=i.from,l=i.to):i.to!==void 0&&a?(l=i.to,p=l-o*a):i.from!==void 0&&a?(p=i.from,l=p+o*a):(l=Date.now(),p=l-o*(a??100));let d=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:p,endTime:l}})).map(m=>({symbol:t,open:parseFloat(m.o),high:parseFloat(m.h),low:parseFloat(m.l),close:parseFloat(m.c),volume:parseFloat(m.v),timestamp:m.t,closeTimestamp:m.T}));return a&&d.length>a&&(d=d.slice(d.length-a)),d}async getOrderBook(t,r=10,s){let i={type:"l2Book",coin:this.symbolToCoin(t)};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa));let o=await this.request("/info",i),[a,p]=o.levels;return {symbol:t,bids:a.slice(0,r).map(l=>({price:parseFloat(l.px),quantity:parseFloat(l.sz),count:l.n})),asks:p.slice(0,r).map(l=>({price:parseFloat(l.px),quantity:parseFloat(l.sz),count:l.n})),timestamp:o.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(i=>({symbol:t,side:i.side==="B"?"buy":"sell",price:parseFloat(i.px),quantity:parseFloat(i.sz),timestamp:i.time,tradeId:i.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(i=>{let o=i.position,a=`${o.coin}-USDC`,p=parseFloat(o.szi);if(p===0)return null;let l=parseFloat(o.entryPx),u=parseFloat(o.unrealizedPnl),d=parseFloat(o.positionValue);return {symbol:a,side:p>0?"long":"short",quantity:Math.abs(p),entryPrice:l,markPrice:l,unrealizedPnl:u,unrealizedPnlPercent:parseFloat(o.returnOnEquity)*100,leverage:o.leverage.value,liquidationPrice:o.liquidationPx?parseFloat(o.liquidationPx):void 0,margin:parseFloat(o.marginUsed),notionalValue:Math.abs(d)}}).filter(Boolean),n=t.symbol?s.filter(i=>i.symbol===t.symbol):s;return {positions:n,totalEquity:parseFloat(r.marginSummary.accountValue),availableBalance:parseFloat(r.marginSummary.accountValue)-parseFloat(r.marginSummary.totalMarginUsed),totalUnrealizedPnl:n.reduce((i,o)=>i+o.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(i=>{let o=`${i.coin}-USDC`,a=parseFloat(i.origSz),p=parseFloat(i.sz),l=a-p;return {orderId:i.oid.toString(),clientOrderId:i.cloid,symbol:o,side:i.side?"long":"short",orderType:"limit",price:parseFloat(i.limitPx),quantity:a,filledQuantity:l,remainingQuantity:p,status:l>0&&p>0?"partially_filled":"pending",timestamp:i.timestamp,updateTimestamp:i.timestamp}}),n=t.symbol?s.filter(i=>i.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 i=`${n.coin}-USDC`,o=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:i,side:o?"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 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(t,r,s,n){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(t,r,s,n?.aggregation)}subscribeCandles(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=`${t}:${r}`;return this.wsManager.subscribe("candle",n,s)}subscribeUserData(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=t==="fills"?"userFills":"userEvents";return this.wsManager.subscribe(n,r,s)}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}},se=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var z=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Ks=3e4,ne=class{baseUrl;timeout;headers;defaultQuery;fetchImpl;constructor(t){if(!t.baseUrl)throw new Error("LiberFiHttpTransport: `baseUrl` is required (e.g. https://api.liberfi.io/perpetuals).");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.timeout=t.timeout??Ks,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[i,o]of Object.entries(this.defaultQuery))o===void 0||o===""||s.set(i,o);if(r)for(let[i,o]of Object.entries(r))o===void 0||o===""||s.set(i,o);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,i=r.timeoutMs??this.timeout,o=setTimeout(()=>n.abort(),i);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 Gs(a);throw new z(`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 z)throw a;if(a instanceof Error&&a.name==="AbortError")throw new z(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let p=a instanceof Error?a.message:String(a);throw new z(`Network error: ${t} ${s}: ${p}`,0,"")}finally{clearTimeout(o);}}};async function Gs(e){try{return await e.text()}catch{return ""}}var Vs="wss://api.hyperliquid.xyz/ws",nt=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 ne({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??Vs,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 z&&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){let n=typeof s=="number"?{limit:s}:s,i={interval:r};return n.limit!==void 0&&(i.limit=String(n.limit)),n.from!==void 0&&(i.start=String(n.from)),n.to!==void 0&&(i.end=String(n.to)),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:i})}async getOrderBook(t,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(t)}/orderbook`,query:n})}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 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(t,r,s,n){return this.requireWS().subscribe(t,r,s,n?.aggregation)}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 it=class{transport;constructor(t){this.transport="transport"in t?t.transport:new ne(t);}getBaseUrl(){return this.transport.getBaseUrl()}async quote(t){return this.transport.request("POST",{path:"/v1/deposits/quote",body:t})}async submit(t){return this.transport.request("POST",{path:"/v1/deposits/submit",body:t})}async status(t){if(!t)throw new Error("intentId is required");return this.transport.request("GET",{path:`/v1/deposits/${encodeURIComponent(t)}`})}async refresh(t){if(!t)throw new Error("intentId is required");return this.transport.request("POST",{path:`/v1/deposits/${encodeURIComponent(t)}/refresh`})}};var De=new Set(["settled","refunded","failed"]);var Me={phase:"idle"};function ot(e,t){switch(t.type){case "RESET":return Me;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 js(t.status,r)}}}function js(e,t){switch(e.status){case "settled":return {phase:"succeeded",intentId:t,status:e};case "refunded":return {phase:"refunded",intentId:t,status:e};case "failed":case "stuck":return {phase:"failed",error:e.lastError??{code:e.status==="stuck"?"STUCK":"FAILED",message:e.status==="stuck"?"Deposit hasn't been observed by Relay yet \u2014 please contact support if this persists.":"Deposit failed. Funds will be refunded to your wallet shortly.",recoverable:false},intentId:t,status:e};default:return {phase:"tracking",intentId:t,status:e}}}function Ys(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function Xs(e){return e.phase==="submitted"||e.phase==="tracking"}function Js(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Zs(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 en(e){return e!==void 0&&De.has(e)}var Z=react.createContext({});function sn({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(Z.Provider,{value:s,children:r})}function T(){let e=react.useContext(Z);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function br(){return ["perps","coins"]}async function hr(e){return await e.getSupportedCoins()}function at(e={}){let{client:t}=T();return reactQuery.useQuery({queryKey:br(),queryFn:async()=>hr(t),staleTime:300*1e3,...e})}function xr(e){return ["perps","market",e.symbol]}async function Sr(e,{symbol:t}){return await e.getMarket(t)}function ke(e,t={}){let{client:r}=T();return reactQuery.useQuery({queryKey:xr(e),queryFn:async()=>Sr(r,e),staleTime:10*1e3,...t})}function Pr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function vr(e,{symbols:t}={}){return await e.getMarkets(t)}function pt(e={},t={}){let{client:r}=T();return reactQuery.useQuery({queryKey:Pr(e),queryFn:async()=>vr(r,e),staleTime:10*1e3,...t})}function Cr(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Tr(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function cn(e,t={}){let{client:r}=T();return reactQuery.useQuery({queryKey:Cr(e),queryFn:async()=>Tr(r,e),staleTime:30*1e3,...t})}function Dr(e){let t=e.aggregation,r=t?.nSigFigs!==void 0?`n${t.nSigFigs}${t.nSigFigs===5&&t.mantissa&&t.mantissa!==1?`m${t.mantissa}`:""}`:"raw";return ["perps","orderBook",e.symbol,String(e.maxLevel??20),r]}async function kr(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function lt(e,t={}){let{client:r}=T();return reactQuery.useQuery({queryKey:Dr(e),queryFn:async()=>kr(r,e),staleTime:5*1e3,...t})}function wr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Or(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function ut(e,t={}){let{client:r}=T();return reactQuery.useQuery({queryKey:wr(e),queryFn:async()=>Or(r,e),staleTime:5*1e3,...t})}function Rr(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function Er(e,t){return await e.getPositions(t)}function we(e,t={}){let{client:r}=T(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Rr(n),queryFn:async()=>Er(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function Nr(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function Ir(e,t){return await e.getOpenOrders(t)}function ct(e,t={}){let{client:r}=T(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Nr(n),queryFn:async()=>Ir(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function Ur(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function Fr(e,t){return await e.getTrades(t)}function dt(e,t={}){let{client:r}=T(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Ur(n),queryFn:async()=>Fr(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}async function Ar(e,t){return await e.placeOrder(t)}function Oe(e={}){let{client:t}=T();return reactQuery.useMutation({mutationFn:async r=>Ar(t,r),...e})}async function Lr(e,t){return await e.cancelOrder(t)}function mt(e={}){let{client:t}=T();return reactQuery.useMutation({mutationFn:async r=>Lr(t,r),...e})}function ie(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=T(),[a,p]=react.useState(null),[l,u]=react.useState(false),[d,m]=react.useState(null),f=react.useRef(null),c=react.useRef(null),g=react.useRef(i);g.current=i;let N=react.useCallback(x=>{let v=g.current;if(!v||v<=0){p(x);return}f.current=x,c.current===null&&(c.current=setTimeout(()=>{if(c.current=null,f.current!==null){let O=f.current;f.current=null,p(O);}},v));},[]),h=n?.nSigFigs!==void 0?`n${n.nSigFigs}${n.nSigFigs===5&&n.mantissa&&n.mantissa!==1?`m${n.mantissa}`:""}`:"";return react.useEffect(()=>{if(!s)return;let x=null,v=true;return (async()=>{try{if(await o.connectWebSocket(),!v)return;u(!0),m(null),x=o.subscribeMarketData(t,r,N,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(w){v&&(m(w instanceof Error?w:new Error("Connection failed")),u(false));}})(),()=>{if(v=false,x)try{o.unsubscribe(x);}catch(w){console.error("Failed to unsubscribe:",w);}o.disconnectWebSocket(),c.current!==null&&(clearTimeout(c.current),c.current=null),f.current=null,u(false),p(null);}},[o,t,r,s,N,h]),{data:a,isConnected:l,error:d}}function Cn(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=T(),[i,o]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(m=>{o(m);},[]);return react.useEffect(()=>{if(!s)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;p(!0),u(null),m=n.subscribeCandles(t,r,d);}catch(g){f&&(u(g instanceof Error?g:new Error("Connection failed")),p(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(g){console.error("Failed to unsubscribe:",g);}n.disconnectWebSocket(),p(false),o(null);}},[n,t,r,s,d]),{data:i,isConnected:a,error:l}}function Re(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=T(),[i,o]=react.useState(null),[a,p]=react.useState(false),[l,u]=react.useState(null),d=react.useCallback(m=>{o(m);},[]);return react.useEffect(()=>{if(!s||!r)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;p(!0),u(null),m=n.subscribeUserData(t,r,d);}catch(g){f&&(u(g instanceof Error?g:new Error("Connection failed")),p(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(g){console.error("Failed to unsubscribe:",g);}n.disconnectWebSocket(),p(false),o(null);}},[n,t,r,s,d]),{data:i,isConnected:a,error:l}}function kn(){let e=react.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 oe(){return react.useContext(Z)?.depositClient}function qr(e){return ["perps","deposit","quote",e]}async function _r(e,t){return e.quote(t)}function ht(e,t={}){let r=oe(),s=(t.enabled??!!On(e))&&!!r;return reactQuery.useQuery({queryKey:qr(e??null),queryFn:async()=>_r(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function On(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function xt(e){let t=oe(),[r,s]=react.useReducer(ot,Me),n=react.useCallback(()=>{s({type:"RESET"});},[]),i=react.useCallback(async o=>{let{quote:a}=o;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=Hr(u,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),u}s({type:"BROADCAST_START"});let l={userSolanaAddress:o.userSolanaAddress,hyperliquidRecipient:o.hyperliquidRecipient,solanaTxHash:p,breakdown:a.breakdown,userId:o.userId,source:o.source,campaign:o.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=Hr(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,e]);return {state:r,execute:i,reset:n,dispatch:s}}function Hr(e,t){if(e instanceof z){let r=En(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 En(e){if(e)try{return JSON.parse(e)}catch{return}}function Qr(e){return ["perps","deposit","status",e??null]}async function zr(e,t){return e.status(t)}function St(e,t={}){let r=oe(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:Qr(e??void 0),queryFn:async()=>zr(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&De.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var Ee={phase:"idle",steps:[]};function qe(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&In(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 _e(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((i,o)=>o===t.index?{...i,status:"done",txHash:t.txHash,error:void 0}:i),s=t.accountState&&e.accountState?Un(e.accountState,t.accountState):t.accountState??e.accountState;return {phase:r.every(i=>i.status==="skipped"||i.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 Ee}}function Be(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 In(e,t){return e.toLowerCase()===t.toLowerCase()}function Un(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 Qe(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,p]=react.useReducer(_e,Ee),l=react.useRef(t),u=react.useRef(s),d=react.useRef(i),m=react.useRef(o);l.current=t,u.current=s,d.current=i,m.current=o;let f=react.useCallback(async()=>{if(r){p({type:"START_LOADING"});try{let x=await l.current.getAccountState(r),v=u.current.map(O=>({step:O,status:qe(O,x)}));p({type:"LOAD_SUCCESS",accountState:x,steps:v});}catch(x){let v=$r(x);p({type:"LOAD_ERROR",error:v.message}),m.current?.(v,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let c=react.useCallback(async x=>{let v=a.steps[x];if(v){p({type:"RUN_STEP",index:x});try{let O=await An(l.current,v.step);p({type:"STEP_SUCCESS",index:x,txHash:O.txHash,accountState:O.state});}catch(O){let w=$r(O);p({type:"STEP_ERROR",index:x,error:w.message}),m.current?.(w,{stepId:v.step.id});}}},[a.steps]),g=react.useCallback(async()=>{let x=Be(a);x!=null&&await c(x);},[a,c]),N=react.useCallback(()=>p({type:"RESET"}),[]),h=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!h.current?(h.current=true,d.current?.(a)):a.phase!=="done"&&(h.current=false);},[a]),{state:a,reload:f,runNext:g,runStep:c,reset:N}}function An(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 $r(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function Pt(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}var Gr="liberfi-perp-shimmer",Ln=`
2
- @keyframes ${Gr}{0%{background-position:200% 0}100%{background-position:-200% 0}}
3
- `;function de(){return jsxRuntime.jsx("style",{children:Ln})}var Mn={background:"linear-gradient(90deg, rgba(255,255,255,0.03) 25%, rgba(255,255,255,0.06) 50%, rgba(255,255,255,0.03) 75%)",backgroundSize:"200% 100%",animation:`${Gr} 1.8s ease-in-out infinite`,borderRadius:6};function W(e){return {...Mn,animationDelay:`${e}ms`}}function Ct(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(de,{}),jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("div",{style:pe(0,84,23)}),jsxRuntime.jsx("div",{style:pe(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(vt,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(vt,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(vt,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:pe(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:pe(330,64,17)}),jsxRuntime.jsx("div",{style:pe(360,64,17)})]})]})]})]})]})}function vt({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:pe(r,e,16)}),jsxRuntime.jsx("div",{style:pe(r+30,t,17)})]})}function pe(e,t,r){return {...W(e),width:t,height:r}}function Dt(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:i,isPending:o}=ke({symbol:e}),{data:a,isConnected:p}=ie({type:"ticker",symbol:e,enabled:!!i});return react.useEffect(()=>{i&&r(i);},[i]),react.useEffect(()=>{if(!a)return;let l=Bn(a,e);l&&r(u=>Hn(u??i??void 0,l,e));},[a,i,e]),react.useEffect(()=>{let l=()=>{let d=Date.now(),m=480*60*1e3,f=d%m,c=m-f;return Math.floor(c/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function Bn(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 me(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Hn(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:me(t.price,e?.price??0),change24h:me(t.change24h,e?.change24h??0),volume24h:me(t.volume24h,e?.volume24h??0),fundingRate:me(t.fundingRate,e?.fundingRate??0),openInterest:me(t.openInterest,e?.openInterest??0),markPrice:me(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 Qn(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 jr(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 Yr(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 kt({marketData:e,fundingCountdown:t}){let{symbol:r,price:s,change24h:n,indexPrice:i,volume24h:o,openInterest:a,fundingRate:p}=e,l=typeof n=="number"&&Number.isFinite(n)?n:0,u=typeof p=="number"&&Number.isFinite(p)?p:0,d=l>=0,m=l.toFixed(2);return jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Yr(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",m,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:i?Yr(i):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:jr(o,0)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:jr(a*(e.markPrice||s))})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Qn(t)})]})]})]})]})}function zn({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Dt(e);return r?jsxRuntime.jsx(Ct,{}):t?jsxRuntime.jsx(kt,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx(Pt,{})}function Ot({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:i,isPending:o}=at(),{data:a,isPending:p}=pt({symbols:i},{enabled:!!i&&i.length>0});react.useEffect(()=>{a&&n(a);},[a]);let l=react.useMemo(()=>{if(!t.trim())return s;let d=t.toLowerCase().trim();return s.filter(m=>m.symbol.toLowerCase().includes(d))},[s,t]);return {coins:s,isLoading:o||p,searchQuery:t,setSearchQuery:r,filteredCoins:l,handleSelectCoin:d=>{e?.(d);}}}function Jr(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 Gn(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Rt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsxRuntime.jsx("div",{style:{padding:"16px 16px 12px"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsxRuntime.jsx(ui$1.SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsxRuntime.jsx("input",{type:"text",placeholder:"Search coins...",value:t,onChange:i=>r(i.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxRuntime.jsxs("div",{className:"flex-1 overflow-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:t?"No coins found":"No coins available"})}):e.map(i=>{let o=i.change24h>=0,a=i.change24h.toFixed(2),p=(i.fundingRate*100).toFixed(4),l=i.fundingRate>=0,u=i.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(i.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:d=>{let m=d.target;m.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:Gn(i.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:o?"#C7FF2E":"#F76816",textAlign:"right"},children:[o?"+":"",a,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:l?"#C7FF2E":"#F76816",textAlign:"right"},children:[p,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Jr(i.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Jr(i.openInterest*i.price)})]},i.symbol)})]})]})}function Vn({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Ot({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(Rt,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function ns(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return {};let r=Math.floor(Math.log10(e)),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,i=null;for(let o of s)o.step<=t+n&&(!i||o.step>i.step)&&(i=o);return i?i.mantissa&&i.mantissa!==1?{nSigFigs:i.nSigFigs,mantissa:i.mantissa}:{nSigFigs:i.nSigFigs}:{nSigFigs:5}}function rs(e,t,r){if(t<=0)return e;let s=new Map,n=r==="ask"?Math.ceil:Math.floor;return e.forEach(i=>{let o=n(i.price/t)*t,a=s.get(o);a?(a.quantity+=i.quantity,i.count&&(a.count=(a.count||0)+i.count)):s.set(o,{price:o,quantity:i.quantity,count:i.count});}),Array.from(s.values())}function ss(e){let t=0,r=e.map(n=>{let i=n.quantity*n.price;return t+=i,{...n,quantity:i,total:t,percentage:0}}),s=t;return r.map(n=>({...n,percentage:s>0?n.total/s*100:0}))}function Nt({symbol:e,maxLevel:t=20,precision:r=1}){let[s,n]=react.useState(null),[i,o]=react.useState(r);react.useEffect(()=>{o(r);},[r]);let{data:a,isPending:p}=lt({symbol:e,maxLevel:t}),l=react.useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,c=s?.asks[0]?.price??a?.asks[0]?.price,g=f&&c?(f+c)/2:c??f??0;return g>0?Math.floor(Math.log10(g)):null},[s,a]),u=react.useMemo(()=>{if(l===null)return;let f=Math.pow(10,l);return ns(f,i)},[i,l]),{data:d}=ie({type:"orderBook",symbol:e,enabled:!!a,aggregation:u,throttleMs:100});return react.useEffect(()=>{d?n(d):a&&n(a);},[d,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=rs(s.bids,i,"bid"),c=rs(s.asks,i,"ask"),g=f.sort((A,y)=>y.price-A.price).slice(0,t),N=c.sort((A,y)=>A.price-y.price).slice(0,t),h=ss(g),x=ss(N),v=h[0]?.price||0,w=(x[0]?.price||0)-v,_=v>0?w/v*100:0;return {bids:h,asks:x,spread:w,spreadPercentage:_}},[s,i,t]),isLoading:p,precision:i,setPrecision:o}}var os={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Xn={backgroundColor:"#000000",fontSize:11},Jn={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},It={flex:"1 1 0%"},Zn={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ei={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},ti={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},ri={color:"#F76816",fontWeight:400},si={color:"#C7FF2E",fontWeight:400},as={flex:"1 1 0%",color:"#ffffff"},ni={flex:"1 1 0%"},ii={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},oi={gap:12,fontSize:12,color:"#ffffff"},ai={color:"#ffffff"},pi={color:"#ffffff",fontWeight:500},li={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},ui={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)"},cs={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},ci={...cs,color:"#C7FF2E"};function di(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 ps(e){return Math.round(e).toLocaleString("en-US")}function ls(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var us=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",p=react.useMemo(()=>a?{...ei,width:`${n}%`}:{...ti,width:`${n}%`},[a,n]),l=react.useMemo(()=>o?()=>o(t):void 0,[o,t]);return jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Zn,onClick:l,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:p}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:ni,children:jsxRuntime.jsx("span",{style:a?ri:si,children:di(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:as,children:ps(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:as,children:ps(s)})]})},(e,t)=>e.price===t.price&&e.quantity===t.quantity&&e.total===t.total&&e.percentage===t.percentage&&e.side===t.side&&e.onPriceClick===t.onPriceClick);function mi({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let[n,i]=react.useState(false),o=react.useRef(null);react.useEffect(()=>{if(!n)return;let p=l=>{o.current?.contains(l.target)||i(false);};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[n]);let a=react.useMemo(()=>({color:"#6b6b6b",transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[n]);return jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:ii,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:oi,children:[jsxRuntime.jsx("span",{style:ai,children:"Spread:"}),jsxRuntime.jsxs("div",{ref:o,className:"relative",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-white/80 transition-colors",style:li,onClick:()=>i(p=>!p),"aria-haspopup":"listbox","aria-expanded":n,children:[jsxRuntime.jsx("span",{children:ls(t)}),jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:a,children:jsxRuntime.jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&jsxRuntime.jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:ui,children:r.map(p=>{let l=p===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":l,className:"cursor-pointer transition-colors",style:l?ci:cs,onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(p),i(false);},children:ls(p)},p)})})]}),jsxRuntime.jsxs("span",{style:pi,children:[e.toFixed(3),"%"]})]})})}function Ft({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let a=react.useRef(null),p=react.useRef(null),l=react.useRef(true),u=react.useRef(true),d=react.useMemo(()=>[...t].reverse(),[t]);react.useEffect(()=>{let c=a.current;if(!c||!l.current)return;let g=c.scrollHeight;c.scrollTop!==g&&(c.scrollTop=g);},[d]),react.useEffect(()=>{let c=p.current;!c||!u.current||c.scrollTop!==0&&(c.scrollTop=0);},[e]);let m=react.useCallback(()=>{let c=a.current;if(!c)return;let g=c.scrollHeight-c.scrollTop-c.clientHeight;l.current=g<=24;},[]),f=react.useCallback(()=>{let c=p.current;c&&(u.current=c.scrollTop<=24);},[]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Xn,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Jn,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:It,children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:It,children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:It,children:"Total (USD)"})]}),jsxRuntime.jsx("div",{ref:a,onScroll:m,className:"flex-1 min-h-0 overflow-y-auto",style:os,children:d.map((c,g)=>jsxRuntime.jsx(us,{price:c.price,quantity:c.quantity,total:c.total,percentage:c.percentage,side:"ask",onPriceClick:o},`ask-${c.price}-${g}`))}),jsxRuntime.jsx("div",{className:"flex-none",children:jsxRuntime.jsx(mi,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsxRuntime.jsx("div",{ref:p,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:os,children:e.map((c,g)=>jsxRuntime.jsx(us,{price:c.price,quantity:c.quantity,total:c.total,percentage:c.percentage,side:"bid",onPriceClick:o},`bid-${c.price}-${g}`))})]})}var ms=[1,2,5,10,100,1e3],fi={backgroundColor:"#000000",fontSize:11},gi={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},fe={flex:"1 1 0%"},yi={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},bi={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function ds({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:yi,children:[jsxRuntime.jsx("div",{style:fe,children:jsxRuntime.jsx("div",{style:{...W(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:fe,children:jsxRuntime.jsx("div",{style:{...W(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:fe,children:jsxRuntime.jsx("div",{style:{...W(e+60),height:11,width:64}})})]})}function hi(){let e=Array.from({length:8},(r,s)=>s),t=Array.from({length:8},(r,s)=>s);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(de,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:fi,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:gi,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:fe,children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:fe,children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:fe,children:"Total (USD)"})]}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(ds,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:bi,children:jsxRuntime.jsx("div",{style:{...W(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(ds,{delay:200+r*40},`bid-${r}`))})]})]})}function xi(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function Si({symbol:e,maxLevel:t=40,precisionOptions:r=ms,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:p,spreadPercentage:l,isLoading:u,precision:d,setPrecision:m}=Nt({symbol:e,maxLevel:t,precision:o});return u?jsxRuntime.jsx(hi,{}):a.length===0&&p.length===0?jsxRuntime.jsx(xi,{}):jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(Ft,{bids:a,asks:p,spreadPercentage:l,precision:d,precisionOptions:r,onPrecisionChange:m,onPriceClick:n})})}var Ci=200;function Mt({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:i}=ut({symbol:e,limit:t}),{data:o}=ie({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(fs));},[n]);let a=react.useRef([]),p=react.useRef(null),l=react.useRef(t);return l.current=t,react.useEffect(()=>{if(!o)return;let u=Ti(o);u.length!==0&&(a.current.push(...u),p.current===null&&(p.current=setTimeout(()=>{p.current=null;let d=a.current;a.current=[],d.length!==0&&s(m=>{let f=d.filter(c=>!m.some(g=>g.timestamp===c.timestamp&&g.price===c.price&&g.quantity===c.quantity));return f.length===0?m:[...f.reverse(),...m].slice(0,l.current)});},Ci)));},[o]),react.useEffect(()=>()=>{p.current!==null&&(clearTimeout(p.current),p.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function Ti(e){return (Array.isArray(e)?e:[e]).filter(fs)}function fs(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}var $e=22,gs=28,ys=100,bs=120,Ri={backgroundColor:"#000000",fontSize:11},Ei={height:gs,minHeight:gs,padding:"0 16px",color:"#6b6b6b",fontSize:11},Ni={flex:"1 1 0%",maxWidth:ys},Ii={flex:"1 1 0%",marginLeft:20},Ui={flex:"1 1 0%",maxWidth:bs,textAlign:"right"},Fi={height:$e,minHeight:$e,maxHeight:$e,padding:"0 16px"},Ai={flex:"1 1 0%",maxWidth:ys},Li={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Mi={flex:"1 1 0%",maxWidth:bs,textAlign:"right",color:"#777A8C"},qi={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},_i={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function Bi(e){return 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 Hi(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"-"}function Qi(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return `${t}s`;let r=Math.floor(t/60);if(r<60)return `${r}m`;let s=Math.floor(r/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function zi(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Wi({index:e,style:t,trades:r,onTradeClick:s}){let n=r[e],i=n?.timestamp??Date.now(),o=hooks.useTickAge(i),a=react.useMemo(()=>!n||!Number.isFinite(n.price)||!Number.isFinite(n.quantity)?0:n.price*n.quantity,[n]),p=react.useMemo(()=>({...n?.side==="buy"?qi:_i,width:`${zi(a)}%`}),[n,a]);if(!n)return null;let l=n.side==="buy";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Fi,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:p}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Ai,children:jsxRuntime.jsx("span",{className:l?"text-bullish":"text-bearish",children:Bi(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Li,children:Hi(a)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Mi,children:Qi(o)})]})})}function Bt({trades:e,onTradeClick:t}){let r=react.useRef(null),{height:s=0}=hooks.useResizeObserver({ref:r}),n=react.useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:Ri,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ei,children:[jsxRuntime.jsx("div",{style:Ni,children:"Price"}),jsxRuntime.jsx("div",{style:Ii,children:"Size (USD)"}),jsxRuntime.jsx("div",{style:Ui,children:"Age"})]}),jsxRuntime.jsx("div",{ref:r,className:"flex-1 min-h-0",children:s>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:s},rowComponent:Wi,rowCount:e.length,rowHeight:$e,rowProps:n,overscanCount:4})})]})}var $i={backgroundColor:"#000000",fontSize:11},Ki={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},hs={flex:"1 1 0%",maxWidth:100},xs={flex:"1 1 0%",marginLeft:20},Ss={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Gi={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Vi({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Gi,children:[jsxRuntime.jsx("div",{style:hs,children:jsxRuntime.jsx("div",{style:{...W(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:xs,children:jsxRuntime.jsx("div",{style:{...W(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Ss,children:jsxRuntime.jsx("div",{style:{...W(e+60),height:11,width:28}})})]})}function ji(){let e=Array.from({length:12},(t,r)=>r);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(de,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:$i,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ki,children:[jsxRuntime.jsx("div",{style:hs,children:"Price"}),jsxRuntime.jsx("div",{style:xs,children:"Size (USD)"}),jsxRuntime.jsx("div",{style:Ss,children:"Age"})]}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(Vi,{delay:t*35},`trade-${t}`))})]})]})}function Yi(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function Xi({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=Mt({symbol:e,limit:t});return i?jsxRuntime.jsx(ji,{}):n.length===0?jsxRuntime.jsx(Yi,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(Bt,{trades:n,onTradeClick:r})})}function Ht({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n}){let[i,o]=react.useState("long"),[a,p]=react.useState("market"),l=reactHookForm.useForm({defaultValues:{amount:0,leverage:20,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:u}=ke({symbol:e}),{mutateAsync:d,isPending:m}=Oe({onSuccess:()=>{l.reset(),s?.();},onError:E=>{n?.(E);}}),f=l.watch(),{amount:c,leverage:g,price:N}=f,h=react.useMemo(()=>a==="limit"&&N?N:u?.price||0,[a,N,u?.price]),x=react.useMemo(()=>!c||!h?0:c*h*5e-4,[c,h]),v=react.useMemo(()=>!c||!h?0:c*h+x,[c,h,x]),O=react.useMemo(()=>{if(!c||!h||!g||g===1)return;let E=.005,J=h;return i==="long"?J*(1-(1/g-E)):J*(1+(1/g-E))},[c,h,g,i]),{data:w}=we({userAddress:t,symbol:e}),_=w?.totalEquity??0,A=w?.availableBalance??0,y=react.useMemo(()=>{let E=w?.positions?.[0];return E?E.side==="short"?-E.quantity:E.quantity:0},[w?.positions]),R=react.useMemo(()=>w?.positions?.[0]?.leverage,[w?.positions]),j=react.useRef(null);react.useEffect(()=>{R&&R>0&&j.current!==e&&(l.setValue("leverage",R),j.current=e);},[e,R,l]);let B=react.useCallback(async E=>{if(!t)throw new Error("User address is required");let J=a==="limit"?E.price:void 0,ve=E.takeProfitPrice,Ce=E.stopLossPrice;if(!ve&&E.takeProfitPercent&&E.takeProfitPercent>0&&h){let re=E.takeProfitPercent/100;ve=i==="long"?h*(1+re):h*(1-re);}if(!Ce&&E.stopLossPercent&&E.stopLossPercent>0&&h){let re=E.stopLossPercent/100;Ce=i==="long"?h*(1-re):h*(1+re);}await d({symbol:e,side:i,orderType:a,amount:E.amount,price:J,leverage:E.leverage,takeProfitPrice:ve,stopLossPrice:Ce,userAddress:t});},[e,i,a,h,t,d]);return {form:l,side:i,orderType:a,setSide:o,setOrderType:p,handleSubmit:B,isSubmitting:m,currentPrice:h,estimatedFee:x,estimatedTotal:v,liquidationPrice:O,availableMargin:A,accountValue:_,currentPosition:y,maxLeverage:r,currentLeverage:R}}var be="#C7FF2E",Cs="!bg-[rgba(24,24,27,1)] !border !border-[rgba(39,39,42,1)] !rounded-[14px] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] !px-3 !py-2 !text-xs !text-zinc-200";function Ge(e,t=2){return e.toFixed(t)}var Ve=0,je=40;function uo(){let t=[];for(let r=Ve;r<=je;r+=10)t.push({value:r,label:`${r}x`});return t}function co({isOpen:e,initialLeverage:t,onConfirm:r,onClose:s}){let[n,i]=react.useState(Math.max(Ve,Math.min(t,je)));react.useEffect(()=>{e&&i(Math.max(Ve,Math.min(t,je)));},[e,t]);let o=react.useMemo(()=>uo(),[]);return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:a=>!a&&s(),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:jsxRuntime.jsx(ui$1.ModalContent,{children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-2",children:[jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white m-0",children:"Adjust Leverage"}),jsxRuntime.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer",children:jsxRuntime.jsx(ui$1.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-5 pt-2 flex flex-col gap-4",children:[jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:"Adjust your leverage to manage your exposure. Higher leverage increases both potential profits and risks."}),jsxRuntime.jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[jsxRuntime.jsx("style",{children:`
1
+ 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),ui$1=require('@liberfi.io/ui'),reactWindow=require('react-window'),hooks=require('@liberfi.io/hooks'),reactHookForm=require('react-hook-form'),i18n=require('@liberfi.io/i18n');typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.19");var Ws="0.2.19";function $s(e,t,r){if(e!=="orderBook"||!r||r.nSigFigs===void 0)return `${e}:${t}`;let s=r.nSigFigs===5&&r.mantissa&&r.mantissa!==1?`:m${r.mantissa}`:"";return `${e}:${t}:n${r.nSigFigs}${s}`}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=i=>{s||(s=true,this.connectPromise=null,i());};try{let i=new WebSocket(this.wsEndpoint);this.ws=i,i.onopen=()=>{this.ws===i&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},i.onmessage=o=>{this.ws===i&&this.handleMessage(o.data);},i.onerror=o=>{this.ws===i&&(console.error("[WebSocket] Error:",o),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},i.onclose=o=>{this.ws===i&&(console.log(`[WebSocket] Closed: ${o.code} - ${o.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${o.code}`))),!this.manuallyDisconnected&&o.code!==1e3&&this.attemptReconnect());};}catch(i){n(()=>r(i));}}),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,t.aggregation);});}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 i=this.transformData(s.type,t.data,s.param);s.callback(i);}catch(i){console.error(`[WebSocket] Error in subscription callback (${n}):`,i);}});}isChannelMatch(t,r,s,n){if(r==="ticker"){if(t!=="activeAssetCtx")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else if(r==="trades"){if(t!=="trades")return false;let i=s.split("-")[0],o=Array.isArray(n?.data)?n.data[0]?.coin:void 0;return typeof o!="string"||o===i}else if(r==="orderBook"){if(t!=="l2Book")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else {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`,i=t?.ctx??{},o=parseFloat(i.midPx??i.markPx??"0"),p=parseFloat(i.markPx??i.midPx??"0"),a=i.prevDayPx?parseFloat(i.prevDayPx):o,l=a>0?(o-a)/a*100:0;return {symbol:n,price:o,change24h:l,volume24h:parseFloat(i.dayNtlVlm??"0"),fundingRate:parseFloat(i.funding??"0"),openInterest:parseFloat(i.openInterest??"0"),markPrice:p,indexPrice:parseFloat(i.oraclePx??i.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(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),asks:n.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.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,s){let n;if(t==="ticker")n={method:"subscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"subscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"subscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(n={method:"subscribe",subscription:{type:"userEvents",user:r}});n&&this.send(n);}sendUnsubscription(t,r,s){let n;if(t==="ticker")n={method:"unsubscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"unsubscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"unsubscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"unsubscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"unsubscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"&&(n={method:"unsubscribe",subscription:{type:"userEvents",user:r}});n&&this.send(n);}subscribe(t,r,s,n){let i=$s(t,r,n);return this.subscriptions.set(i,{type:t,param:r,callback:s,aggregation:n}),this.sendSubscription(t,r,n),i}unsubscribe(t){let r=this.subscriptions.get(t);r&&(this.sendUnsubscription(r.type,r.param,r.aggregation),this.subscriptions.delete(t));}isConnectedNow(){return this.isConnected}};var br={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"}},it=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||br[this.environment].api,this._wsEndpoint=t.wsEndpoint||br[this.environment].ws,this.timeout=t.timeout||3e4;}async request(t,r){let s=`${this.apiEndpoint}${t}`;try{let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout),o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(i),!o.ok)throw new te(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new te(`Request timeout after ${this.timeout}ms`,408,""):n instanceof te?n:new te(`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((i,o)=>{let p=s[o],a=`${i.name}-USDC`,l=parseFloat(p.midPx||p.markPx||"0"),u=p.prevDayPx?parseFloat(p.prevDayPx):l,c=u>0?(l-u)/u*100:0;return {symbol:a,price:l,change24h:c,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(t&&t.length>0){let i=new Set(t);return n.filter(o=>i.has(o.symbol))}return n}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),i=typeof s=="number"?{limit:s}:s,o=this.parseInterval(r),p=i.limit,a,l;i.from!==void 0&&i.to!==void 0?(a=i.from,l=i.to):i.to!==void 0&&p?(l=i.to,a=l-o*p):i.from!==void 0&&p?(a=i.from,l=a+o*p):(l=Date.now(),a=l-o*(p??100));let c=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:a,endTime:l}})).map(m=>({symbol:t,open:parseFloat(m.o),high:parseFloat(m.h),low:parseFloat(m.l),close:parseFloat(m.c),volume:parseFloat(m.v),timestamp:m.t,closeTimestamp:m.T}));return p&&c.length>p&&(c=c.slice(c.length-p)),c}async getOrderBook(t,r=10,s){let i={type:"l2Book",coin:this.symbolToCoin(t)};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa));let o=await this.request("/info",i),[p,a]=o.levels;return {symbol:t,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:o.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(i=>({symbol:t,side:i.side==="B"?"buy":"sell",price:parseFloat(i.px),quantity:parseFloat(i.sz),timestamp:i.time,tradeId:i.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(i=>{let o=i.position,p=`${o.coin}-USDC`,a=parseFloat(o.szi);if(a===0)return null;let l=parseFloat(o.entryPx),u=parseFloat(o.unrealizedPnl),c=parseFloat(o.positionValue);return {symbol:p,side:a>0?"long":"short",quantity:Math.abs(a),entryPrice:l,markPrice:l,unrealizedPnl:u,unrealizedPnlPercent:parseFloat(o.returnOnEquity)*100,leverage:o.leverage.value,liquidationPrice:o.liquidationPx?parseFloat(o.liquidationPx):void 0,margin:parseFloat(o.marginUsed),notionalValue:Math.abs(c)}}).filter(Boolean),n=t.symbol?s.filter(i=>i.symbol===t.symbol):s;return {positions:n,totalEquity:parseFloat(r.marginSummary.accountValue),availableBalance:parseFloat(r.marginSummary.accountValue)-parseFloat(r.marginSummary.totalMarginUsed),totalUnrealizedPnl:n.reduce((i,o)=>i+o.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(i=>{let o=`${i.coin}-USDC`,p=parseFloat(i.origSz),a=parseFloat(i.sz),l=p-a;return {orderId:i.oid.toString(),clientOrderId:i.cloid,symbol:o,side:i.side?"long":"short",orderType:"limit",price:parseFloat(i.limitPx),quantity:p,filledQuantity:l,remainingQuantity:a,status:l>0&&a>0?"partially_filled":"pending",timestamp:i.timestamp,updateTimestamp:i.timestamp}}),n=t.symbol?s.filter(i=>i.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 i=`${n.coin}-USDC`,o=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:i,side:o?"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,n){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(t,r,s,n?.aggregation)}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);}},te=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var z=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Ks=3e4,re=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??Ks,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[i,o]of Object.entries(this.defaultQuery))o===void 0||o===""||s.set(i,o);if(r)for(let[i,o]of Object.entries(r))o===void 0||o===""||s.set(i,o);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,i=r.timeoutMs??this.timeout,o=setTimeout(()=>n.abort(),i);try{let p=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(!p.ok){let a=await Gs(p);throw new z(`HTTP ${p.status} ${p.statusText} from ${t} ${s}`,p.status,a)}return p.status===204?void 0:await p.json()}catch(p){if(p instanceof z)throw p;if(p instanceof Error&&p.name==="AbortError")throw new z(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let a=p instanceof Error?p.message:String(p);throw new z(`Network error: ${t} ${s}: ${a}`,0,"")}finally{clearTimeout(o);}}};async function Gs(e){try{return await e.text()}catch{return ""}}var Vs="wss://api.hyperliquid.xyz/ws",ot=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 re({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??Vs,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 z&&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){let n=typeof s=="number"?{limit:s}:s,i={interval:r};return n.limit!==void 0&&(i.limit=String(n.limit)),n.from!==void 0&&(i.start=String(n.from)),n.to!==void 0&&(i.end=String(n.to)),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:i})}async getOrderBook(t,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(t)}/orderbook`,query:n})}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,n){return this.requireWS().subscribe(t,r,s,n?.aggregation)}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 at=class{transport;constructor(t){this.transport="transport"in t?t.transport:new re(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 ke=new Set(["settled","refunded","failed"]);var Be={phase:"idle"};function pt(e,t){switch(t.type){case "RESET":return Be;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 js(t.status,r)}}}function js(e,t){switch(e.status){case "settled":return {phase:"succeeded",intentId:t,status:e};case "refunded":return {phase:"refunded",intentId:t,status:e};case "failed":case "stuck":return {phase:"failed",error:e.lastError??{code:e.status==="stuck"?"STUCK":"FAILED",message:e.status==="stuck"?"Deposit hasn't been observed by Relay yet \u2014 please contact support if this persists.":"Deposit failed. Funds will be refunded to your wallet shortly.",recoverable:false},intentId:t,status:e};default:return {phase:"tracking",intentId:t,status:e}}}function Ys(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function Xs(e){return e.phase==="submitted"||e.phase==="tracking"}function Js(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Zs(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 en(e){return e!==void 0&&ke.has(e)}var X=react.createContext({});function sn({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(X.Provider,{value:s,children:r})}function C(){let e=react.useContext(X);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function hr(){return ["perps","coins"]}async function xr(e){return await e.getSupportedCoins()}function lt(e={}){let{client:t}=C();return reactQuery.useQuery({queryKey:hr(),queryFn:async()=>xr(t),staleTime:300*1e3,...e})}function Sr(e){return ["perps","market",e.symbol]}async function Pr(e,{symbol:t}){return await e.getMarket(t)}function we(e,t={}){let{client:r}=C();return reactQuery.useQuery({queryKey:Sr(e),queryFn:async()=>Pr(r,e),staleTime:10*1e3,...t})}function vr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function Cr(e,{symbols:t}={}){return await e.getMarkets(t)}function ut(e={},t={}){let{client:r}=C();return reactQuery.useQuery({queryKey:vr(e),queryFn:async()=>Cr(r,e),staleTime:10*1e3,...t})}function Tr(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Dr(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function cn(e,t={}){let{client:r}=C();return reactQuery.useQuery({queryKey:Tr(e),queryFn:async()=>Dr(r,e),staleTime:30*1e3,...t})}function kr(e){let t=e.aggregation,r=t?.nSigFigs!==void 0?`n${t.nSigFigs}${t.nSigFigs===5&&t.mantissa&&t.mantissa!==1?`m${t.mantissa}`:""}`:"raw";return ["perps","orderBook",e.symbol,String(e.maxLevel??20),r]}async function wr(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function ct(e,t={}){let{client:r}=C();return reactQuery.useQuery({queryKey:kr(e),queryFn:async()=>wr(r,e),staleTime:5*1e3,...t})}function Or(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Rr(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function dt(e,t={}){let{client:r}=C();return reactQuery.useQuery({queryKey:Or(e),queryFn:async()=>Rr(r,e),staleTime:5*1e3,...t})}function Er(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function Nr(e,t){return await e.getPositions(t)}function Oe(e,t={}){let{client:r}=C(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Er(n),queryFn:async()=>Nr(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function Ir(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function Ur(e,t){return await e.getOpenOrders(t)}function mt(e,t={}){let{client:r}=C(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Ir(n),queryFn:async()=>Ur(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function Fr(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function Ar(e,t){return await e.getTrades(t)}function ft(e,t={}){let{client:r}=C(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Fr(n),queryFn:async()=>Ar(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}async function Lr(e,t){return await e.placeOrder(t)}function Re(e={}){let{client:t}=C();return reactQuery.useMutation({mutationFn:async r=>Lr(t,r),...e})}async function Mr(e,t){return await e.cancelOrder(t)}function gt(e={}){let{client:t}=C();return reactQuery.useMutation({mutationFn:async r=>Mr(t,r),...e})}function se(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=C(),[p,a]=react.useState(null),[l,u]=react.useState(false),[c,m]=react.useState(null),f=react.useRef(null),d=react.useRef(null),g=react.useRef(i);g.current=i;let R=react.useCallback(h=>{let x=g.current;if(!x||x<=0){a(h);return}f.current=h,d.current===null&&(d.current=setTimeout(()=>{if(d.current=null,f.current!==null){let N=f.current;f.current=null,a(N);}},x));},[]),D=n?.nSigFigs!==void 0?`n${n.nSigFigs}${n.nSigFigs===5&&n.mantissa&&n.mantissa!==1?`m${n.mantissa}`:""}`:"";return react.useEffect(()=>{if(!s)return;let h=null,x=true;return (async()=>{try{if(await o.connectWebSocket(),!x)return;u(!0),m(null),h=o.subscribeMarketData(t,r,R,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(E){x&&(m(E instanceof Error?E:new Error("Connection failed")),u(false));}})(),()=>{if(x=false,h)try{o.unsubscribe(h);}catch(E){console.error("Failed to unsubscribe:",E);}o.disconnectWebSocket(),d.current!==null&&(clearTimeout(d.current),d.current=null),f.current=null,u(false),a(null);}},[o,t,r,s,R,D]),{data:p,isConnected:l,error:c}}function Cn(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=C(),[i,o]=react.useState(null),[p,a]=react.useState(false),[l,u]=react.useState(null),c=react.useCallback(m=>{o(m);},[]);return react.useEffect(()=>{if(!s)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;a(!0),u(null),m=n.subscribeCandles(t,r,c);}catch(g){f&&(u(g instanceof Error?g:new Error("Connection failed")),a(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(g){console.error("Failed to unsubscribe:",g);}n.disconnectWebSocket(),a(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:p,error:l}}function Ee(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=C(),[i,o]=react.useState(null),[p,a]=react.useState(false),[l,u]=react.useState(null),c=react.useCallback(m=>{o(m);},[]);return react.useEffect(()=>{if(!s||!r)return;let m=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;a(!0),u(null),m=n.subscribeUserData(t,r,c);}catch(g){f&&(u(g instanceof Error?g:new Error("Connection failed")),a(false));}})(),()=>{if(f=false,m)try{n.unsubscribe(m);}catch(g){console.error("Failed to unsubscribe:",g);}n.disconnectWebSocket(),a(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:p,error:l}}function kn(){let e=react.useContext(X);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 ne(){return react.useContext(X)?.depositClient}function _r(e){return ["perps","deposit","quote",e]}async function Br(e,t){return e.quote(t)}function St(e,t={}){let r=ne(),s=(t.enabled??!!On(e))&&!!r;return reactQuery.useQuery({queryKey:_r(e??null),queryFn:async()=>Br(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function On(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function Pt(e){let t=ne(),[r,s]=react.useReducer(pt,Be),n=react.useCallback(()=>{s({type:"RESET"});},[]),i=react.useCallback(async o=>{let{quote:p}=o;s({type:"SIGN_START"});let a;try{if(a=await e(p.serializedTxBase64,{isVersioned:p.isVersioned,sizeBytes:p.sizeBytes}),!a)throw new Error("wallet returned an empty tx hash")}catch(u){let c=Qr(u,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:c}),u}s({type:"BROADCAST_START"});let l={userSolanaAddress:o.userSolanaAddress,hyperliquidRecipient:o.hyperliquidRecipient,solanaTxHash:a,breakdown:p.breakdown,userId:o.userId,source:o.source,campaign:o.campaign,quoteIssuedAt:p.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:a}),u.intentId}catch(u){let c=Qr(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:c}),u}},[t,e]);return {state:r,execute:i,reset:n,dispatch:s}}function Qr(e,t){if(e instanceof z){let r=En(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 En(e){if(e)try{return JSON.parse(e)}catch{return}}function zr(e){return ["perps","deposit","status",e??null]}async function Wr(e,t){return e.status(t)}function vt(e,t={}){let r=ne(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:zr(e??void 0),queryFn:async()=>Wr(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&ke.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var Ne={phase:"idle",steps:[]};function He(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&In(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 Qe(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((i,o)=>o===t.index?{...i,status:"done",txHash:t.txHash,error:void 0}:i),s=t.accountState&&e.accountState?Un(e.accountState,t.accountState):t.accountState??e.accountState;return {phase:r.every(i=>i.status==="skipped"||i.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 Ne}}function ze(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 In(e,t){return e.toLowerCase()===t.toLowerCase()}function Un(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 $e(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[p,a]=react.useReducer(Qe,Ne),l=react.useRef(t),u=react.useRef(s),c=react.useRef(i),m=react.useRef(o);l.current=t,u.current=s,c.current=i,m.current=o;let f=react.useCallback(async()=>{if(r){a({type:"START_LOADING"});try{let h=await l.current.getAccountState(r),x=u.current.map(N=>({step:N,status:He(N,h)}));a({type:"LOAD_SUCCESS",accountState:h,steps:x});}catch(h){let x=Kr(h);a({type:"LOAD_ERROR",error:x.message}),m.current?.(x,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let d=react.useCallback(async h=>{let x=p.steps[h];if(x){a({type:"RUN_STEP",index:h});try{let N=await An(l.current,x.step);a({type:"STEP_SUCCESS",index:h,txHash:N.txHash,accountState:N.state});}catch(N){let E=Kr(N);a({type:"STEP_ERROR",index:h,error:E.message}),m.current?.(E,{stepId:x.step.id});}}},[p.steps]),g=react.useCallback(async()=>{let h=ze(p);h!=null&&await d(h);},[p,d]),R=react.useCallback(()=>a({type:"RESET"}),[]),D=react.useRef(false);return react.useEffect(()=>{p.phase==="done"&&!D.current?(D.current=true,c.current?.(p)):p.phase!=="done"&&(D.current=false);},[p]),{state:p,reload:f,runNext:g,runStep:d,reset:R}}function An(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 Ct(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}var Vr="liberfi-perp-shimmer",Ln=`
2
+ @keyframes ${Vr}{0%{background-position:200% 0}100%{background-position:-200% 0}}
3
+ `;function me(){return jsxRuntime.jsx("style",{children:Ln})}var Mn={background:"linear-gradient(90deg, rgba(255,255,255,0.03) 25%, rgba(255,255,255,0.06) 50%, rgba(255,255,255,0.03) 75%)",backgroundSize:"200% 100%",animation:`${Vr} 1.8s ease-in-out infinite`,borderRadius:6};function W(e){return {...Mn,animationDelay:`${e}ms`}}function Dt(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(me,{}),jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("div",{style:oe(0,84,23)}),jsxRuntime.jsx("div",{style:oe(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(Tt,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(Tt,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(Tt,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:oe(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:oe(330,64,17)}),jsxRuntime.jsx("div",{style:oe(360,64,17)})]})]})]})]})]})}function Tt({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:oe(r,e,16)}),jsxRuntime.jsx("div",{style:oe(r+30,t,17)})]})}function oe(e,t,r){return {...W(e),width:t,height:r}}function wt(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:i,isPending:o}=we({symbol:e}),{data:p,isConnected:a}=se({type:"ticker",symbol:e,enabled:!!i});return react.useEffect(()=>{i&&r(i);},[i]),react.useEffect(()=>{if(!p)return;let l=Bn(p,e);l&&r(u=>Hn(u??i??void 0,l,e));},[p,i,e]),react.useEffect(()=>{let l=()=>{let c=Date.now(),m=480*60*1e3,f=c%m,d=m-f;return Math.floor(d/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function Bn(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 fe(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Hn(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:fe(t.price,e?.price??0),change24h:fe(t.change24h,e?.change24h??0),volume24h:fe(t.volume24h,e?.volume24h??0),fundingRate:fe(t.fundingRate,e?.fundingRate??0),openInterest:fe(t.openInterest,e?.openInterest??0),markPrice:fe(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 Qn(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 Yr(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 Xr(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 Ot({marketData:e,fundingCountdown:t}){let{symbol:r,price:s,change24h:n,indexPrice:i,volume24h:o,openInterest:p,fundingRate:a}=e,l=typeof n=="number"&&Number.isFinite(n)?n:0,u=typeof a=="number"&&Number.isFinite(a)?a:0,c=l>=0,m=l.toFixed(2);return jsxRuntime.jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxRuntime.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsxRuntime.jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Xr(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:c?"#C7FF2E":"#F76816"},children:[c?"+":"",m,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:i?Xr(i):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Yr(o,0)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Yr(p*(e.markPrice||s))})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Qn(t)})]})]})]})]})}function zn({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=wt(e);return r?jsxRuntime.jsx(Dt,{}):t?jsxRuntime.jsx(Ot,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx(Ct,{})}function Et({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:i,isPending:o}=lt(),{data:p,isPending:a}=ut({symbols:i},{enabled:!!i&&i.length>0});react.useEffect(()=>{p&&n(p);},[p]);let l=react.useMemo(()=>{if(!t.trim())return s;let c=t.toLowerCase().trim();return s.filter(m=>m.symbol.toLowerCase().includes(c))},[s,t]);return {coins:s,isLoading:o||a,searchQuery:t,setSearchQuery:r,filteredCoins:l,handleSelectCoin:c=>{e?.(c);}}}function Zr(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 Gn(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Nt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsxRuntime.jsx("div",{style:{padding:"16px 16px 12px"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsxRuntime.jsx(ui$1.SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsxRuntime.jsx("input",{type:"text",placeholder:"Search coins...",value:t,onChange:i=>r(i.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxRuntime.jsxs("div",{className:"flex-1 overflow-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:t?"No coins found":"No coins available"})}):e.map(i=>{let o=i.change24h>=0,p=i.change24h.toFixed(2),a=(i.fundingRate*100).toFixed(4),l=i.fundingRate>=0,u=i.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(i.symbol),onMouseEnter:c=>{c.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:c=>{let m=c.target;m.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:Gn(i.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:o?"#C7FF2E":"#F76816",textAlign:"right"},children:[o?"+":"",p,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:l?"#C7FF2E":"#F76816",textAlign:"right"},children:[a,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Zr(i.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Zr(i.openInterest*i.price)})]},i.symbol)})]})]})}function Vn({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Et({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(Nt,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function is(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return {};let r=Math.floor(Math.log10(e)),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,i=null;for(let o of s)o.step<=t+n&&(!i||o.step>i.step)&&(i=o);return i?i.mantissa&&i.mantissa!==1?{nSigFigs:i.nSigFigs,mantissa:i.mantissa}:{nSigFigs:i.nSigFigs}:{nSigFigs:5}}function ss(e,t,r){if(t<=0)return e;let s=new Map,n=r==="ask"?Math.ceil:Math.floor;return e.forEach(i=>{let o=n(i.price/t)*t,p=s.get(o);p?(p.quantity+=i.quantity,i.count&&(p.count=(p.count||0)+i.count)):s.set(o,{price:o,quantity:i.quantity,count:i.count});}),Array.from(s.values())}function ns(e){let t=0,r=e.map(n=>{let i=n.quantity*n.price;return t+=i,{...n,quantity:i,total:t,percentage:0}}),s=t;return r.map(n=>({...n,percentage:s>0?n.total/s*100:0}))}function Ut({symbol:e,maxLevel:t=20,precision:r=1}){let[s,n]=react.useState(null),[i,o]=react.useState(r);react.useEffect(()=>{o(r);},[r]);let{data:p,isPending:a}=ct({symbol:e,maxLevel:t}),l=react.useMemo(()=>{let f=s?.bids[0]?.price??p?.bids[0]?.price,d=s?.asks[0]?.price??p?.asks[0]?.price,g=f&&d?(f+d)/2:d??f??0;return g>0?Math.floor(Math.log10(g)):null},[s,p]),u=react.useMemo(()=>{if(l===null)return;let f=Math.pow(10,l);return is(f,i)},[i,l]),{data:c}=se({type:"orderBook",symbol:e,enabled:!!p,aggregation:u,throttleMs:100});return react.useEffect(()=>{c?n(c):p&&n(p);},[c,p]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=ss(s.bids,i,"bid"),d=ss(s.asks,i,"ask"),g=f.sort((L,y)=>y.price-L.price).slice(0,t),R=d.sort((L,y)=>L.price-y.price).slice(0,t),D=ns(g),h=ns(R),x=D[0]?.price||0,E=(h[0]?.price||0)-x,A=x>0?E/x*100:0;return {bids:D,asks:h,spread:E,spreadPercentage:A}},[s,i,t]),isLoading:a,precision:i,setPrecision:o}}var as={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Xn={backgroundColor:"#000000",fontSize:11},Jn={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Ft={flex:"1 1 0%"},Zn={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ei={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},ti={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},ri={color:"#F76816",fontWeight:400},si={color:"#C7FF2E",fontWeight:400},ps={flex:"1 1 0%",color:"#ffffff"},ni={flex:"1 1 0%"},ii={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},oi={gap:12,fontSize:12,color:"#ffffff"},ai={color:"#ffffff"},pi={color:"#ffffff",fontWeight:500},li={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},ui={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)"},ds={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},ci={...ds,color:"#C7FF2E"};function di(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 ls(e){return Math.round(e).toLocaleString("en-US")}function us(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var cs=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let p=i==="ask",a=react.useMemo(()=>p?{...ei,width:`${n}%`}:{...ti,width:`${n}%`},[p,n]),l=react.useMemo(()=>o?()=>o(t):void 0,[o,t]);return jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Zn,onClick:l,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:a}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:ni,children:jsxRuntime.jsx("span",{style:p?ri:si,children:di(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:ps,children:ls(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:ps,children:ls(s)})]})},(e,t)=>e.price===t.price&&e.quantity===t.quantity&&e.total===t.total&&e.percentage===t.percentage&&e.side===t.side&&e.onPriceClick===t.onPriceClick);function mi({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let[n,i]=react.useState(false),o=react.useRef(null);react.useEffect(()=>{if(!n)return;let a=l=>{o.current?.contains(l.target)||i(false);};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[n]);let p=react.useMemo(()=>({color:"#6b6b6b",transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[n]);return jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:ii,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:oi,children:[jsxRuntime.jsx("span",{style:ai,children:"Spread:"}),jsxRuntime.jsxs("div",{ref:o,className:"relative",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-white/80 transition-colors",style:li,onClick:()=>i(a=>!a),"aria-haspopup":"listbox","aria-expanded":n,children:[jsxRuntime.jsx("span",{children:us(t)}),jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:p,children:jsxRuntime.jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&jsxRuntime.jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:ui,children:r.map(a=>{let l=a===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":l,className:"cursor-pointer transition-colors",style:l?ci:ds,onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(a),i(false);},children:us(a)},a)})})]}),jsxRuntime.jsxs("span",{style:pi,children:[e.toFixed(3),"%"]})]})})}function Lt({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let p=react.useRef(null),a=react.useRef(null),l=react.useRef(true),u=react.useRef(true),c=react.useMemo(()=>[...t].reverse(),[t]);react.useEffect(()=>{let d=p.current;if(!d||!l.current)return;let g=d.scrollHeight;d.scrollTop!==g&&(d.scrollTop=g);},[c]),react.useEffect(()=>{let d=a.current;!d||!u.current||d.scrollTop!==0&&(d.scrollTop=0);},[e]);let m=react.useCallback(()=>{let d=p.current;if(!d)return;let g=d.scrollHeight-d.scrollTop-d.clientHeight;l.current=g<=24;},[]),f=react.useCallback(()=>{let d=a.current;d&&(u.current=d.scrollTop<=24);},[]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Xn,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Jn,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Ft,children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Ft,children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Ft,children:"Total (USD)"})]}),jsxRuntime.jsx("div",{ref:p,onScroll:m,className:"flex-1 min-h-0 overflow-y-auto",style:as,children:c.map((d,g)=>jsxRuntime.jsx(cs,{price:d.price,quantity:d.quantity,total:d.total,percentage:d.percentage,side:"ask",onPriceClick:o},`ask-${d.price}-${g}`))}),jsxRuntime.jsx("div",{className:"flex-none",children:jsxRuntime.jsx(mi,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsxRuntime.jsx("div",{ref:a,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:as,children:e.map((d,g)=>jsxRuntime.jsx(cs,{price:d.price,quantity:d.quantity,total:d.total,percentage:d.percentage,side:"bid",onPriceClick:o},`bid-${d.price}-${g}`))})]})}var fs=[1,2,5,10,100,1e3],fi={backgroundColor:"#000000",fontSize:11},gi={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},ge={flex:"1 1 0%"},yi={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},bi={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function ms({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:yi,children:[jsxRuntime.jsx("div",{style:ge,children:jsxRuntime.jsx("div",{style:{...W(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ge,children:jsxRuntime.jsx("div",{style:{...W(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ge,children:jsxRuntime.jsx("div",{style:{...W(e+60),height:11,width:64}})})]})}function hi(){let e=Array.from({length:8},(r,s)=>s),t=Array.from({length:8},(r,s)=>s);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(me,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:fi,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:gi,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:ge,children:"Price"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ge,children:"Amount (USD)"}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ge,children:"Total (USD)"})]}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(ms,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:bi,children:jsxRuntime.jsx("div",{style:{...W(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(ms,{delay:200+r*40},`bid-${r}`))})]})]})}function xi(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function Si({symbol:e,maxLevel:t=40,precisionOptions:r=fs,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:p,asks:a,spreadPercentage:l,isLoading:u,precision:c,setPrecision:m}=Ut({symbol:e,maxLevel:t,precision:o});return u?jsxRuntime.jsx(hi,{}):p.length===0&&a.length===0?jsxRuntime.jsx(xi,{}):jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(Lt,{bids:p,asks:a,spreadPercentage:l,precision:c,precisionOptions:r,onPrecisionChange:m,onPriceClick:n})})}var Ci=200;function _t({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:i}=dt({symbol:e,limit:t}),{data:o}=se({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(gs));},[n]);let p=react.useRef([]),a=react.useRef(null),l=react.useRef(t);return l.current=t,react.useEffect(()=>{if(!o)return;let u=Ti(o);u.length!==0&&(p.current.push(...u),a.current===null&&(a.current=setTimeout(()=>{a.current=null;let c=p.current;p.current=[],c.length!==0&&s(m=>{let f=c.filter(d=>!m.some(g=>g.timestamp===d.timestamp&&g.price===d.price&&g.quantity===d.quantity));return f.length===0?m:[...f.reverse(),...m].slice(0,l.current)});},Ci)));},[o]),react.useEffect(()=>()=>{a.current!==null&&(clearTimeout(a.current),a.current=null),p.current=[];},[e]),{trades:r,isLoading:i}}function Ti(e){return (Array.isArray(e)?e:[e]).filter(gs)}function gs(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}var Ve=22,ys=28,bs=100,hs=120,Ri={backgroundColor:"#000000",fontSize:11},Ei={height:ys,minHeight:ys,padding:"0 16px",color:"#6b6b6b",fontSize:11},Ni={flex:"1 1 0%",maxWidth:bs},Ii={flex:"1 1 0%",marginLeft:20},Ui={flex:"1 1 0%",maxWidth:hs,textAlign:"right"},Fi={height:Ve,minHeight:Ve,maxHeight:Ve,padding:"0 16px"},Ai={flex:"1 1 0%",maxWidth:bs},Li={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Mi={flex:"1 1 0%",maxWidth:hs,textAlign:"right",color:"#777A8C"},qi={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},_i={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function Bi(e){return 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 Hi(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"-"}function Qi(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return `${t}s`;let r=Math.floor(t/60);if(r<60)return `${r}m`;let s=Math.floor(r/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function zi(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Wi({index:e,style:t,trades:r,onTradeClick:s}){let n=r[e],i=n?.timestamp??Date.now(),o=hooks.useTickAge(i),p=react.useMemo(()=>!n||!Number.isFinite(n.price)||!Number.isFinite(n.quantity)?0:n.price*n.quantity,[n]),a=react.useMemo(()=>({...n?.side==="buy"?qi:_i,width:`${zi(p)}%`}),[n,p]);if(!n)return null;let l=n.side==="buy";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Fi,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:a}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Ai,children:jsxRuntime.jsx("span",{className:l?"text-bullish":"text-bearish",children:Bi(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Li,children:Hi(p)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Mi,children:Qi(o)})]})})}function Qt({trades:e,onTradeClick:t}){let r=react.useRef(null),{height:s=0}=hooks.useResizeObserver({ref:r}),n=react.useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:Ri,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ei,children:[jsxRuntime.jsx("div",{style:Ni,children:"Price"}),jsxRuntime.jsx("div",{style:Ii,children:"Size (USD)"}),jsxRuntime.jsx("div",{style:Ui,children:"Age"})]}),jsxRuntime.jsx("div",{ref:r,className:"flex-1 min-h-0",children:s>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:s},rowComponent:Wi,rowCount:e.length,rowHeight:Ve,rowProps:n,overscanCount:4})})]})}var $i={backgroundColor:"#000000",fontSize:11},Ki={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},xs={flex:"1 1 0%",maxWidth:100},Ss={flex:"1 1 0%",marginLeft:20},Ps={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Gi={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Vi({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Gi,children:[jsxRuntime.jsx("div",{style:xs,children:jsxRuntime.jsx("div",{style:{...W(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:Ss,children:jsxRuntime.jsx("div",{style:{...W(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Ps,children:jsxRuntime.jsx("div",{style:{...W(e+60),height:11,width:28}})})]})}function ji(){let e=Array.from({length:12},(t,r)=>r);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(me,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:$i,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ki,children:[jsxRuntime.jsx("div",{style:xs,children:"Price"}),jsxRuntime.jsx("div",{style:Ss,children:"Size (USD)"}),jsxRuntime.jsx("div",{style:Ps,children:"Age"})]}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(Vi,{delay:t*35},`trade-${t}`))})]})]})}function Yi(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function Xi({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=_t({symbol:e,limit:t});return i?jsxRuntime.jsx(ji,{}):n.length===0?jsxRuntime.jsx(Yi,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(Qt,{trades:n,onTradeClick:r})})}function zt({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i}){let[o,p]=react.useState("long"),[a,l]=react.useState("market"),u=reactHookForm.useForm({defaultValues:{amount:0,leverage:20,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:c}=we({symbol:e}),{mutateAsync:m,isPending:f}=Re({onSuccess:()=>{u.reset(),s?.();},onError:w=>{n?.(w);}}),d=u.watch(),{amount:g,leverage:R,price:D}=d,h=react.useMemo(()=>a==="limit"&&D?D:c?.price||0,[a,D,c?.price]),x=react.useMemo(()=>!g||!h?0:g*h*5e-4,[g,h]),N=react.useMemo(()=>!g||!h?0:g*h+x,[g,h,x]),E=react.useMemo(()=>{if(!g||!h||!R||R===1)return;let w=.005,ce=h;return o==="long"?ce*(1-(1/R-w)):ce*(1+(1/R-w))},[g,h,R,o]),{data:A}=Oe({userAddress:t,symbol:e}),L=A?.totalEquity??0,y=A?.availableBalance??0,le=react.useMemo(()=>{let w=A?.positions?.[0];return w?w.side==="short"?-w.quantity:w.quantity:0},[A?.positions]),O=react.useMemo(()=>A?.positions?.[0]?.leverage,[A?.positions]),_=react.useRef(null);react.useEffect(()=>{O&&O>0&&_.current!==e&&(u.setValue("leverage",O),_.current=e);},[e,O,u]);let ue=react.useCallback(async w=>{if(!t)throw new Error("User address is required");let ce=a==="limit"?w.price:void 0,Ce=w.takeProfitPrice,Te=w.stopLossPrice;if(!Ce&&w.takeProfitPercent&&w.takeProfitPercent>0&&h){let ee=w.takeProfitPercent/100;Ce=o==="long"?h*(1+ee):h*(1-ee);}if(!Te&&w.stopLossPercent&&w.stopLossPercent>0&&h){let ee=w.stopLossPercent/100;Te=o==="long"?h*(1-ee):h*(1+ee);}await m({symbol:e,side:o,orderType:a,amount:w.amount,price:ce,leverage:w.leverage,takeProfitPrice:Ce,stopLossPrice:Te,userAddress:t});},[e,o,a,h,t,m]);return {form:u,side:o,orderType:a,setSide:p,setOrderType:l,handleSubmit:ue,isSubmitting:f,currentPrice:h,estimatedFee:x,estimatedTotal:N,liquidationPrice:E,availableMargin:y,accountValue:L,currentPosition:le,maxLeverage:r,currentLeverage:O,onUpdateLeverage:i}}var he="#C7FF2E",Ts="!bg-[rgba(24,24,27,1)] !border !border-[rgba(39,39,42,1)] !rounded-[14px] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)]";function Ye(e,t=2){return e.toFixed(t)}var Fe=1,Ae=40;function mo(){return [{value:Fe,label:`${Fe}x`},{value:10,label:"10x"},{value:20,label:"20x"},{value:30,label:"30x"},{value:Ae,label:`${Ae}x`}]}function fo({isOpen:e,initialLeverage:t,onConfirm:r,onUpdate:s,onClose:n}){let[i,o]=react.useState(Math.max(Fe,Math.min(t,Ae))),[p,a]=react.useState(false);react.useEffect(()=>{e&&(o(Math.max(Fe,Math.min(t,Ae))),a(false));},[e,t]);let l=react.useMemo(()=>mo(),[]),u=react.useCallback(async()=>{if(!p){if(!s){r(i),n();return}a(true);try{await s(i),r(i),n();}catch{a(false);}}},[p,s,i,r,n]);return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:c=>{p||c||n();},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:jsxRuntime.jsx(ui$1.ModalContent,{children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-2",children:[jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white m-0",children:"Adjust Leverage"}),jsxRuntime.jsx("button",{type:"button",onClick:n,disabled:p,"aria-label":"Close",className:"p-1 rounded-[10px] hover:bg-[rgba(39,39,42,0.5)] text-zinc-400 hover:text-white transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",children:jsxRuntime.jsx(ui$1.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-5 pt-2 flex flex-col gap-4",children:[jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:"Adjust your leverage to manage your exposure. Higher leverage increases both potential profits and risks."}),jsxRuntime.jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[jsxRuntime.jsx("style",{children:`
4
4
  .perp-leverage-slider [data-slot="track"] { background-color: rgba(255,255,255,0.08) !important; }
5
- .perp-leverage-slider [data-slot="filler"] { background-color: ${be} !important; }
6
- .perp-leverage-slider [data-slot="thumb"] { background-color: ${be} !important; }
7
- .perp-leverage-slider [data-slot="thumb"]::after { background-color: ${be} !important; }
5
+ .perp-leverage-slider [data-slot="filler"] { background-color: ${he} !important; }
6
+ .perp-leverage-slider [data-slot="thumb"] { background-color: ${he} !important; }
7
+ .perp-leverage-slider [data-slot="thumb"]::after { background-color: ${he} !important; }
8
8
  .perp-leverage-slider [data-slot="mark"] { color: #6b6b6b !important; }
9
- `}),jsxRuntime.jsx(ui$1.Slider,{value:[n],onChange:a=>i(Array.isArray(a)?a[0]:a),minValue:Ve,maxValue:je,step:1,marks:o,"aria-label":"Leverage"})]}),jsxRuntime.jsxs("div",{className:"text-sm text-white font-medium",children:["Leverage: ",n,"x"]}),jsxRuntime.jsx("button",{type:"button",onClick:()=>{r(n),s();},className:"cursor-pointer mt-1 w-full h-12 rounded-[12px] font-medium text-black bg-[#C7FF2E] hover:bg-[#b6ed1c] active:bg-[#a6d913] transition-colors",children:"Update Leverage"})]})]})})})}function zt({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:i,isSubmitting:o,symbol:a,currentPrice:p,estimatedFee:l,liquidationPrice:u,availableMargin:d,accountValue:m,currentPosition:f,maxLeverage:c,onAddFunds:g}){let[N,h]=react.useState(false),[x,v]=react.useState(false),O=e.watch("leverage")||20,w=e.watch("amount")||0,_=a.split("-")[0],A=d>0&&p?Math.min(w*p/(d*O)*100,100):0,y=R=>{let j=(Array.isArray(R)?R[0]:R)/100;if(p&&p>0){let B=d*O*j/p;e.setValue("amount",Number(B.toFixed(6)));}};return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsxs("div",{className:"perp-order-form flex-1 overflow-y-auto",style:{padding:"16px 16px",display:"flex",flexDirection:"column",gap:16},children:[jsxRuntime.jsxs("div",{className:"perp-side-tabs flex",style:{border:"1px solid rgba(39,39,42,0.8)",borderRadius:8,padding:4,gap:4},children:[jsxRuntime.jsx(ui$1.StyledTooltip,{content:"Buy asset, profit when price goes up",placement:"top",delay:200,closeDelay:0,classNames:{content:Cs},children:jsxRuntime.jsx("button",{type:"button","data-active":t==="long",className:"perp-side-tab perp-side-tab--long flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:14,borderRadius:4,backgroundColor:t==="long"?be:"transparent",color:t==="long"?"#000000":"#b5b5b5",fontWeight:t==="long"?500:400,border:"none"},onClick:()=>s("long"),children:"Long"})}),jsxRuntime.jsx(ui$1.StyledTooltip,{content:"Sell asset, profit when price goes down",placement:"top",delay:200,closeDelay:0,classNames:{content:Cs},children:jsxRuntime.jsx("button",{type:"button","data-active":t==="short",className:"perp-side-tab perp-side-tab--short flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:14,borderRadius:4,backgroundColor:t==="short"?"#F76816":"transparent",color:t==="short"?"#000000":"#b5b5b5",fontWeight:t==="short"?500:400,border:"none"},onClick:()=>s("short"),children:"Short"})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:"Market"},{key:"limit",label:"Limit"}].map(R=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===R.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===R.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(R.key),children:R.label})},R.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer transition-colors",style:{height:24,padding:"0 5px",fontSize:12,borderRadius:4,backgroundColor:"rgba(26,26,26,0.5)",color:"#ffffff",fontWeight:400,border:"1px solid rgba(26,26,26,0.5)"},onClick:()=>h(true),children:["Leverage: ",O,"x"]})]}),jsxRuntime.jsx(ui$1.RHForm,{methods:e,onSubmit:i,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[r==="limit"&&jsxRuntime.jsxs("div",{className:"perp-price-box",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Price"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"USDC"})]}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"price",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{className:"perp-buy-amt",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Buy Amount"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:_})]}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"amount",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
9
+ `}),jsxRuntime.jsx(ui$1.Slider,{value:[i],onChange:c=>o(Array.isArray(c)?c[0]:c),isDisabled:p,minValue:Fe,maxValue:Ae,step:1,marks:l,"aria-label":"Leverage"})]}),jsxRuntime.jsxs("div",{className:"text-sm text-white font-medium",children:["Leverage: ",i,"x"]}),jsxRuntime.jsxs("button",{type:"button",onClick:u,disabled:p,className:"cursor-pointer mt-1 w-full h-12 rounded-[12px] font-medium text-black bg-[#C7FF2E] hover:bg-[#b6ed1c] active:bg-[#a6d913] transition-colors flex items-center justify-center gap-2 disabled:bg-[#3f3f46] disabled:text-zinc-500 disabled:cursor-not-allowed",children:[p&&jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}),p?"Updating Leverage...":"Update Leverage"]})]})]})})})}function Wt({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:i,isSubmitting:o,symbol:p,currentPrice:a,estimatedFee:l,liquidationPrice:u,availableMargin:c,accountValue:m,currentPosition:f,maxLeverage:d,onAddFunds:g,onUpdateLeverage:R}){let[D,h]=react.useState(false),[x,N]=react.useState(false),E=e.watch("leverage")||20,A=e.watch("amount")||0,L=p.split("-")[0],y=c>0&&a?Math.min(A*a/(c*E)*100,100):0,le=O=>{let _=(Array.isArray(O)?O[0]:O)/100;if(a&&a>0){let ue=c*E*_/a;e.setValue("amount",Number(ue.toFixed(6)));}};return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsxs("div",{className:"perp-order-form flex-1 overflow-y-auto",style:{padding:"16px 16px",display:"flex",flexDirection:"column",gap:16},children:[jsxRuntime.jsxs("div",{className:"perp-side-tabs flex",style:{border:"1px solid rgba(39,39,42,0.8)",borderRadius:8,padding:4,gap:4},children:[jsxRuntime.jsx(ui$1.StyledTooltip,{content:"Buy asset, profit when price goes up",placement:"top",delay:200,closeDelay:0,classNames:{content:Ts},children:jsxRuntime.jsx("button",{type:"button","data-active":t==="long",className:"perp-side-tab perp-side-tab--long flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:14,borderRadius:4,backgroundColor:t==="long"?he:"transparent",color:t==="long"?"#000000":"#b5b5b5",fontWeight:t==="long"?500:400,border:"none"},onClick:()=>s("long"),children:"Long"})}),jsxRuntime.jsx(ui$1.StyledTooltip,{content:"Sell asset, profit when price goes down",placement:"top",delay:200,closeDelay:0,classNames:{content:Ts},children:jsxRuntime.jsx("button",{type:"button","data-active":t==="short",className:"perp-side-tab perp-side-tab--short flex-1 cursor-pointer transition-colors",style:{height:32,fontSize:14,borderRadius:4,backgroundColor:t==="short"?"#F76816":"transparent",color:t==="short"?"#000000":"#b5b5b5",fontWeight:t==="short"?500:400,border:"none"},onClick:()=>s("short"),children:"Short"})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:"Market"},{key:"limit",label:"Limit"}].map(O=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===O.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===O.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(O.key),children:O.label})},O.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-[10px] transition-colors text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800/40",onClick:()=>h(true),children:["Leverage: ",E,"x"]})]}),jsxRuntime.jsx(ui$1.RHForm,{methods:e,onSubmit:i,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[r==="limit"&&jsxRuntime.jsxs("div",{className:"perp-price-box",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Price"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"USDC"})]}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"price",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{className:"perp-buy-amt",style:{borderRadius:4,padding:8,backgroundColor:"rgba(26,26,26,0.5)",border:"1px solid #1c1c1c",height:64,display:"flex",flexDirection:"column",justifyContent:"center"},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Buy Amount"}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:L})]}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"amount",placeholder:"0.0 USDC",className:"w-full"})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
10
10
  .perp-buy-amt input, .perp-price-box input { font-size: 18px !important; line-height: 23px !important; }
11
11
  .perp-order-form .group,
12
12
  .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; }
@@ -17,7 +17,7 @@
17
17
  .perp-slider::-moz-range-track { height: 4px; border-radius: 2px; background: #1c1c1c; border: none; }
18
18
  .perp-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: #C7FF2E; border: none; }
19
19
  .perp-side-tab[data-active="false"]:hover { background-color: rgba(255,255,255,0.12) !important; color: #ffffff !important; }
20
- `}),jsxRuntime.jsx("input",{type:"range",value:Math.round(A),onChange:R=>y(Number(R.target.value)),min:0,max:100,step:1,className:"perp-slider"}),jsxRuntime.jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsxRuntime.jsx("span",{children:"0%"}),jsxRuntime.jsx("span",{children:"25%"}),jsxRuntime.jsx("span",{children:"50%"}),jsxRuntime.jsx("span",{children:"75%"}),jsxRuntime.jsx("span",{children:"100%"})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>v(R=>!R),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:x?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:x&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsx("span",{children:"Est. Liq. Price: "}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?Ge(u,2):"--"})]})]}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"takeProfitPrice",placeholder:"Enter TP price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"takeProfitPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"stopLossPrice",placeholder:"Enter SL price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"stopLossPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),g&&jsxRuntime.jsx("button",{type:"button",onClick:g,className:"w-full cursor-pointer transition-colors",style:{height:36,fontSize:14,fontWeight:500,color:"#000000",backgroundColor:be,borderRadius:9999,border:"none"},children:"Add More Funds"}),jsxRuntime.jsxs("div",{style:{fontSize:12,display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxRuntime.jsxs("span",{style:{color:be,fontSize:12,fontWeight:500},children:[Ge(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[Ge(m)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?Ge(f):"--"})]})]})]})})]}),jsxRuntime.jsx("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column"},children:jsxRuntime.jsxs("div",{className:"flex items-center justify-end",style:{gap:6},children:[jsxRuntime.jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:R=>{let j=R.target;j.style.display="none";}})]})}),jsxRuntime.jsx(co,{isOpen:N,initialLeverage:O,onConfirm:R=>e.setValue("leverage",R),onClose:()=>h(false)})]})}function mo({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,className:o}){let{form:a,side:p,orderType:l,setSide:u,setOrderType:d,handleSubmit:m,isSubmitting:f,currentPrice:c,estimatedFee:g,estimatedTotal:N,liquidationPrice:h,availableMargin:x,accountValue:v,currentPosition:O,maxLeverage:w}=Ht({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n});return jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsx(zt,{methods:a,side:p,orderType:l,onSideChange:u,onOrderTypeChange:d,onSubmit:m,isSubmitting:f,symbol:e,currentPrice:c,estimatedFee:g,estimatedTotal:N,liquidationPrice:h,availableMargin:x,accountValue:v,currentPosition:O,maxLeverage:w,onAddFunds:i})})}function Wt({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s}){let[n,i]=react.useState([]),{data:o,isLoading:a,error:p}=we({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=Re({type:"positions",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:d}=Oe({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{o?.positions&&i(o.positions);},[o]),react.useEffect(()=>{l&&i(f=>{let c=f.findIndex(g=>g.symbol===l.symbol);if(l.quantity===0)return c!==-1?f.filter((g,N)=>N!==c):f;if(c!==-1){let g=[...f];return g[c]=l,g}return [...f,l]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");let c=f.side==="long"?"short":"long";await u({symbol:f.symbol,side:c,orderType:"market",amount:Math.abs(f.quantity),leverage:f.leverage,userAddress:e});},[e,u]);return {positions:n,isLoading:a,error:p,handleClosePosition:m,isClosing:d}}function he(e,t=2){return e.toFixed(t)}function $t(e){return he(e,4)}function ho(e){return he(Math.abs(e),4)}function xo(e){return `${e>=0?"+":""}${he(e,2)}`}function So(e){return `${e>=0?"+":""}${he(e,2)}%`}function Kt({positions:e,onClosePosition:t,isClosing:r}){let s=jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position Value"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Entry Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Mark Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Liquidation"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Margin Used (PNL) \u2193"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"TP"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"SL"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Close"})]});return e.length===0?jsxRuntime.jsxs("div",{className:"w-full overflow-x-auto bg-transparent",children:[jsxRuntime.jsx("table",{className:"w-full",style:{fontSize:12},children:jsxRuntime.jsx("thead",{children:s})}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{fontSize:14,color:"#b5b5b5",padding:"24px 0"},children:"No open positions"})]}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:12},children:[jsxRuntime.jsx("thead",{children:s}),jsxRuntime.jsx("tbody",{children:e.map(n=>{let o=n.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:n.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui$1.cn(n.side==="long"?"text-bullish":"text-bearish"),children:[n.leverage,"x ",n.side.toUpperCase()]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:ho(n.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",he(n.notionalValue)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",$t(n.entryPrice)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",$t(n.markPrice)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:n.liquidationPrice?`$${$t(n.liquidationPrice)}`:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsxs("div",{className:"flex flex-col items-end",children:[jsxRuntime.jsxs("span",{style:{color:"#ffffff"},children:["$",he(n.margin)]}),jsxRuntime.jsxs("span",{className:o,children:[xo(n.unrealizedPnl)," (",So(n.unrealizedPnlPercent),")"]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx(ui$1.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 Gt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Po(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:14,color:"#b5b5b5"},children:"No open positions"})}function vo({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:i,isLoading:o,handleClosePosition:a,isClosing:p}=Wt({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Gt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Kt,{positions:i,onClosePosition:a,isClosing:p})})}function Vt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s}){let[n,i]=react.useState([]),{data:o,isLoading:a,error:p}=ct({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=Re({type:"orders",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:d}=mt({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{o?.orders&&i(o.orders);},[o]),react.useEffect(()=>{l&&i(f=>{let c=f.findIndex(g=>g.orderId===l.orderId);if(l.status==="cancelled"||l.status==="filled"||l.status==="rejected")return c!==-1?f.filter((g,N)=>N!==c):f;if(c!==-1){let g=[...f];return g[c]=l,g}return [l,...f]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");await u({orderId:f.orderId,symbol:f.symbol,userAddress:e});},[e,u]);return {orders:n,isLoading:a,error:p,handleCancelOrder:m,isCanceling:d}}function Os(e,t=2){return e.toFixed(t)}function ko(e){return Os(e,4)}function jt(e){return Os(e,4)}function wo(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 Yt({orders:e,onCancelOrder:t,isCanceling:r}){return e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsxRuntime.jsx("tbody",{children:e.map(s=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui$1.cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${ko(s.price)}`}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:jt(s.quantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:jt(s.filledQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:jt(s.remainingQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx("span",{className:ui$1.cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:wo(s.timestamp)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:()=>t(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsxRuntime.jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function Xt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Jt(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function Oo({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:i,isLoading:o,handleCancelOrder:a,isCanceling:p}=Vt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Xt,{})}):i.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Jt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Yt,{orders:i,onCancelOrder:a,isCanceling:p})})}function Ro(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 er({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50}){let[n,i]=react.useState(r),[o,a]=react.useState(1),[p,l]=react.useState([]),{startTime:u,endTime:d}=Ro(n),{data:m,isLoading:f,error:c}=dt({userAddress:e,symbol:t,startTime:u,endTime:d,limit:1e3},{enabled:!!e});react.useEffect(()=>{m?.trades&&(l(m.trades),a(1));},[m]),react.useEffect(()=>{a(1);},[n]);let g=Math.ceil(p.length/s),N=(o-1)*s,h=N+s;return {trades:p.slice(N,h),isLoading:f,error:c,timeRange:n,setTimeRange:i,currentPage:o,totalPages:g,goToNextPage:()=>{o<g&&a(o+1);},goToPreviousPage:()=>{o>1&&a(o-1);},goToPage:_=>{_>=1&&_<=g&&a(_);}}}function tr(e,t=2){return e.toFixed(t)}function Eo(e){return tr(e,4)}function No(e){return tr(e,4)}function Io(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"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${i}:${o}`}var Uo=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function rr({trades:e,timeRange:t,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:i,onPreviousPage:o,onGoToPage:a}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsxRuntime.jsx("div",{className:"flex gap-2",children:Uo.map(p=>{let l=t===p.value;return jsxRuntime.jsx("button",{type:"button",className:ui$1.cn("rounded px-3 transition-colors",!l&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:l?"#1c1c1c":"transparent",color:l?"#ffffff":"#b5b5b5"},onClick:()=>r(p.value),children:p.label},p.value)})}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsxRuntime.jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsxRuntime.jsx("tbody",{children:e.map(p=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:p.symbol.split("-")[0]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsx("span",{className:ui$1.cn("px-2 py-0.5 rounded text-[11px]",p.side==="long"?"bg-bullish/20 text-bullish":"bg-bearish/20 text-bearish"),children:p.side.toUpperCase()})}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Eo(p.price)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:No(p.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[tr(p.fee,4)," ",p.feeCurrency]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-center",children:jsxRuntime.jsx("span",{className:ui$1.cn("px-2 py-0.5 rounded text-[11px]",p.isMaker?"bg-blue-600/20 text-blue-500":"bg-purple-600/20 text-purple-500"),children:p.isMaker?"Maker":"Taker"})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Io(p.timestamp)})]},p.tradeId))})]})}),n>1&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:o,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsxRuntime.jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(p,l)=>{let u;return n<=5||s<=3?u=l+1:s>=n-2?u=n-4+l:u=s-2+l,jsxRuntime.jsx("button",{type:"button",className:ui$1.cn("w-8 h-8 text-sm rounded transition-colors",s===u?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>a(u),children:u},u)})}),jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:i,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function sr(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function nr(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function Ao({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:i,isLoading:o,timeRange:a,setTimeRange:p,currentPage:l,totalPages:u,goToNextPage:d,goToPreviousPage:m,goToPage:f}=er({userAddress:e,symbol:t,initialTimeRange:r,pageSize:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(sr,{})}):i.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(nr,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(rr,{trades:i,timeRange:a,onTimeRangeChange:p,currentPage:l,totalPages:u,onNextPage:d,onPreviousPage:m,onGoToPage:f})})}var Lo=1000000000n,Mo=8,qo=10n**BigInt(8);function Ue(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Ns(r,Lo,t)}function Je(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Ns(r,qo,t)}var _o=Je;function ir(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 Ns(e,t,r){let s=e<0n,n=s?-e:e,i=n/t,o=n%t;if(r<=0)return o*2n>=t&&(i+=1n),`${s?"-":""}${i.toString()}`;let a=10n**BigInt(r),p=(o*a+t/2n)/t;p>=a&&(i+=1n,p=0n);let l=p.toString().padStart(r,"0");return l=l.replace(/0+$/,""),l?`${s?"-":""}${i.toString()}.${l}`:`${s?"-":""}${i.toString()}`}function Fe(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function or(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function ar({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:a}){let{t:p}=i18n.useTranslation(),l=t?Date.parse(t.expiresAt):0,[u,d]=react.useState(()=>l?Fe(l):0);return react.useEffect(()=>{if(!e||!l)return;d(Fe(l));let m=setInterval(()=>{let f=Fe(l);d(f),f===0&&(o?.(),clearInterval(m));},1e3);return ()=>clearInterval(m)},[e,l,o]),jsxRuntime.jsx(ui$1.Modal,{isOpen:e,onOpenChange:m=>!m&&i(),hideCloseButton:true,backdrop:"blur",children:jsxRuntime.jsxs(ui$1.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui$1.ModalHeader,{children:p("perpDeposit.confirm.title")}),jsxRuntime.jsxs(ui$1.ModalBody,{children:[t?jsxRuntime.jsx(Vo,{breakdown:t.breakdown}):jsxRuntime.jsx("div",{className:"flex h-32 items-center justify-center",children:jsxRuntime.jsx(ui$1.Spinner,{})}),t&&!s&&jsxRuntime.jsx("div",{className:"text-default-500 mt-4 text-xs",children:p("perpDeposit.confirm.expiresIn",{seconds:u})}),s&&jsxRuntime.jsx("div",{className:"text-warning-500 mt-4 text-xs",children:p("perpDeposit.confirm.expired")}),a&&jsxRuntime.jsx("div",{className:"text-danger mt-4 text-xs",children:a})]}),jsxRuntime.jsxs(ui$1.ModalFooter,{className:"flex justify-between gap-2",children:[jsxRuntime.jsx(ui$1.Button,{variant:"flat",color:"default",onPress:i,isDisabled:r,children:p("perpDeposit.confirm.cancel")}),jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:p("perpDeposit.confirm.cta")})]})]})})}function Vo({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(Ze,{label:t("perpDeposit.confirm.send"),value:`${Ue(e.grossLamports)} SOL`}),jsxRuntime.jsx(Ze,{label:t("perpDeposit.confirm.receive"),value:`${Je(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(Ze,{label:t("perpDeposit.confirm.platformFee"),value:`${Ue(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(Ze,{label:t("perpDeposit.confirm.relayFee"),value:`${Ue(e.relayDepositLamports,6)} SOL`,muted:true})]})}function Ze({label:e,value:t,highlight:r,muted:s}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("dt",{className:"text-default-500",children:e}),jsxRuntime.jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-default-500 text-xs":"text-foreground",children:t})]})}function pr({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:p,className:l}){let{t:u}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui$1.cn("flex flex-col gap-4",l),children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-amount",className:"text-sm font-medium text-foreground",children:u("perpDeposit.amount")}),n&&jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:u("perpDeposit.amount.balance",{balance:n})})]}),jsxRuntime.jsx("div",{className:"relative",children:jsxRuntime.jsx(ui$1.Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:u("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:i,isInvalid:!!o,errorMessage:o,endContent:jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-default-500 text-sm",children:u("perpDeposit.amount.unit")}),n&&p&&jsxRuntime.jsx(ui$1.Button,{size:"sm",variant:"flat",color:"primary",onPress:p,isDisabled:i,children:u("perpDeposit.amount.max")})]})})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-recipient",className:"text-sm font-medium text-foreground mb-1.5 block",children:u("perpDeposit.recipient")}),jsxRuntime.jsx(ui$1.Input,{id:"perp-deposit-recipient",type:"text",placeholder:u("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:i,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}var Ls="#C7FF2E";function ur({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:p}=i18n.useTranslation(),l=na(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"&&!!i;return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:m=>!m&&o(),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:jsxRuntime.jsx(ui$1.ModalContent,{children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-start justify-between px-5 pt-5 pb-2",children:[jsxRuntime.jsx("div",{className:"flex items-center gap-2.5",children:jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white",children:p("perpDeposit.status.title")})}),jsxRuntime.jsx("button",{type:"button",onClick:o,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:jsxRuntime.jsx(ui$1.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-3 pt-2",children:[jsxRuntime.jsxs("div",{className:"rounded-[12px] bg-[#0a0a0b] border border-[#27272a] px-4 py-6 flex flex-col items-center text-center gap-4",children:[jsxRuntime.jsx(ra,{variant:l}),jsxRuntime.jsx("p",{className:ui$1.cn("text-sm leading-relaxed max-w-[320px]",ia(l)),children:u})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(As,{href:s,label:p("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(As,{href:n,label:p("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxRuntime.jsxs("div",{className:ui$1.cn("px-5 pb-5 pt-2 flex gap-2",d?"justify-between":"justify-end"),children:[d&&jsxRuntime.jsx("button",{type:"button",onClick:i,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")}),jsxRuntime.jsx("button",{type:"button",onClick:o,className:ui$1.cn("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 As({href:e,label:t,hash:r}){return jsxRuntime.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:[jsxRuntime.jsx("span",{className:"text-xs text-zinc-400 group-hover:text-white transition-colors",children:t}),jsxRuntime.jsxs("span",{className:"flex items-center gap-1.5 text-xs tabular-nums text-zinc-300 group-hover:text-[#C7FF2E] transition-colors",children:[or(r,6,4),jsxRuntime.jsx(la,{})]})]})}function ra({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(sa,{})}):e==="success"?jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(199,255,46,0.12)]",children:jsxRuntime.jsx(oa,{className:"w-8 h-8",style:{color:Ls}})}):e==="warning"?jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(245,158,11,0.12)]",children:jsxRuntime.jsx(aa,{className:"w-8 h-8 text-amber-400"})}):jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(239,68,68,0.12)]",children:jsxRuntime.jsx(pa,{className:"w-8 h-8 text-rose-400"})})}function sa(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("svg",{className:"lfi-perp-deposit-spinner",viewBox:"0 0 50 50",width:48,height:48,"aria-hidden":"true",children:[jsxRuntime.jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"4"}),jsxRuntime.jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:Ls,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsxRuntime.jsx("style",{children:`
20
+ `}),jsxRuntime.jsx("input",{type:"range",value:Math.round(y),onChange:O=>le(Number(O.target.value)),min:0,max:100,step:1,className:"perp-slider"}),jsxRuntime.jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsxRuntime.jsx("span",{children:"0%"}),jsxRuntime.jsx("span",{children:"25%"}),jsxRuntime.jsx("span",{children:"50%"}),jsxRuntime.jsx("span",{children:"75%"}),jsxRuntime.jsx("span",{children:"100%"})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>N(O=>!O),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:x?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:x&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsx("span",{children:"Est. Liq. Price: "}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?Ye(u,2):"--"})]})]}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"takeProfitPrice",placeholder:"Enter TP price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"takeProfitPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),x&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"stopLossPrice",placeholder:"Enter SL price",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsxRuntime.jsx(ui$1.RHNumberInput,{name:"stopLossPercent",placeholder:"0.0",className:"w-full",style:{fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4}})]})]}),g&&jsxRuntime.jsx("button",{type:"button",onClick:g,className:"w-full cursor-pointer transition-colors",style:{height:36,fontSize:14,fontWeight:500,color:"#000000",backgroundColor:he,borderRadius:9999,border:"none"},children:"Add More Funds"}),jsxRuntime.jsxs("div",{style:{fontSize:12,display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxRuntime.jsxs("span",{style:{color:he,fontSize:12,fontWeight:500},children:[Ye(c)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[Ye(m)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?Ye(f):"--"})]})]})]})})]}),jsxRuntime.jsx("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column"},children:jsxRuntime.jsxs("div",{className:"flex items-center justify-end",style:{gap:6},children:[jsxRuntime.jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:O=>{let _=O.target;_.style.display="none";}})]})}),jsxRuntime.jsx(fo,{isOpen:D,initialLeverage:E,onConfirm:O=>e.setValue("leverage",O),onUpdate:R,onClose:()=>h(false)})]})}function go({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,className:p}){let{form:a,side:l,orderType:u,setSide:c,setOrderType:m,handleSubmit:f,isSubmitting:d,currentPrice:g,estimatedFee:R,estimatedTotal:D,liquidationPrice:h,availableMargin:x,accountValue:N,currentPosition:E,maxLeverage:A,onUpdateLeverage:L}=zt({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o});return jsxRuntime.jsx("div",{className:p,children:jsxRuntime.jsx(Wt,{methods:a,side:l,orderType:u,onSideChange:c,onOrderTypeChange:m,onSubmit:f,isSubmitting:d,symbol:e,currentPrice:g,estimatedFee:R,estimatedTotal:D,liquidationPrice:h,availableMargin:x,accountValue:N,currentPosition:E,maxLeverage:A,onAddFunds:i,onUpdateLeverage:L})})}function $t({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s}){let[n,i]=react.useState([]),{data:o,isLoading:p,error:a}=Oe({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=Ee({type:"positions",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:c}=Re({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{o?.positions&&i(o.positions);},[o]),react.useEffect(()=>{l&&i(f=>{let d=f.findIndex(g=>g.symbol===l.symbol);if(l.quantity===0)return d!==-1?f.filter((g,R)=>R!==d):f;if(d!==-1){let g=[...f];return g[d]=l,g}return [...f,l]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");let d=f.side==="long"?"short":"long";await u({symbol:f.symbol,side:d,orderType:"market",amount:Math.abs(f.quantity),leverage:f.leverage,userAddress:e});},[e,u]);return {positions:n,isLoading:p,error:a,handleClosePosition:m,isClosing:c}}function xe(e,t=2){return e.toFixed(t)}function Kt(e){return xe(e,4)}function So(e){return xe(Math.abs(e),4)}function Po(e){return `${e>=0?"+":""}${xe(e,2)}`}function vo(e){return `${e>=0?"+":""}${xe(e,2)}%`}function Gt({positions:e,onClosePosition:t,isClosing:r}){let s=jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Position Value"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Entry Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Mark Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Liquidation"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Margin Used (PNL) \u2193"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"TP"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"SL"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:12,color:"#6b6b6b"},children:"Close"})]});return e.length===0?jsxRuntime.jsxs("div",{className:"w-full overflow-x-auto bg-transparent",children:[jsxRuntime.jsx("table",{className:"w-full",style:{fontSize:12},children:jsxRuntime.jsx("thead",{children:s})}),jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{fontSize:14,color:"#b5b5b5",padding:"24px 0"},children:"No open positions"})]}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:12},children:[jsxRuntime.jsx("thead",{children:s}),jsxRuntime.jsx("tbody",{children:e.map(n=>{let o=n.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:n.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui$1.cn(n.side==="long"?"text-bullish":"text-bearish"),children:[n.leverage,"x ",n.side.toUpperCase()]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:So(n.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",xe(n.notionalValue)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Kt(n.entryPrice)]}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Kt(n.markPrice)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:n.liquidationPrice?`$${Kt(n.liquidationPrice)}`:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsxs("div",{className:"flex flex-col items-end",children:[jsxRuntime.jsxs("span",{style:{color:"#ffffff"},children:["$",xe(n.margin)]}),jsxRuntime.jsxs("span",{className:o,children:[Po(n.unrealizedPnl)," (",vo(n.unrealizedPnlPercent),")"]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:"-"}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx(ui$1.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 Vt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Co(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:14,color:"#b5b5b5"},children:"No open positions"})}function To({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:i,isLoading:o,handleClosePosition:p,isClosing:a}=$t({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Vt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Gt,{positions:i,onClosePosition:p,isClosing:a})})}function jt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s}){let[n,i]=react.useState([]),{data:o,isLoading:p,error:a}=mt({userAddress:e,symbol:t},{enabled:!!e}),{data:l}=Ee({type:"orders",userAddress:e||"",enabled:!!e}),{mutateAsync:u,isPending:c}=gt({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});react.useEffect(()=>{o?.orders&&i(o.orders);},[o]),react.useEffect(()=>{l&&i(f=>{let d=f.findIndex(g=>g.orderId===l.orderId);if(l.status==="cancelled"||l.status==="filled"||l.status==="rejected")return d!==-1?f.filter((g,R)=>R!==d):f;if(d!==-1){let g=[...f];return g[d]=l,g}return [l,...f]});},[l]);let m=react.useCallback(async f=>{if(!e)throw new Error("User address is required");await u({orderId:f.orderId,symbol:f.symbol,userAddress:e});},[e,u]);return {orders:n,isLoading:p,error:a,handleCancelOrder:m,isCanceling:c}}function Rs(e,t=2){return e.toFixed(t)}function Oo(e){return Rs(e,4)}function Yt(e){return Rs(e,4)}function Ro(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 Xt({orders:e,onCancelOrder:t,isCanceling:r}){return e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsxRuntime.jsx("tbody",{children:e.map(s=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxRuntime.jsxs("span",{className:ui$1.cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${Oo(s.price)}`}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Yt(s.quantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Yt(s.filledQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Yt(s.remainingQuantity)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:jsxRuntime.jsx("span",{className:ui$1.cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Ro(s.timestamp)}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:()=>t(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsxRuntime.jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function Jt(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Zt(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function Eo({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:i,isLoading:o,handleCancelOrder:p,isCanceling:a}=jt({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Jt,{})}):i.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Zt,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(Xt,{orders:i,onCancelOrder:p,isCanceling:a})})}function No(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 tr({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50}){let[n,i]=react.useState(r),[o,p]=react.useState(1),[a,l]=react.useState([]),{startTime:u,endTime:c}=No(n),{data:m,isLoading:f,error:d}=ft({userAddress:e,symbol:t,startTime:u,endTime:c,limit:1e3},{enabled:!!e});react.useEffect(()=>{m?.trades&&(l(m.trades),p(1));},[m]),react.useEffect(()=>{p(1);},[n]);let g=Math.ceil(a.length/s),R=(o-1)*s,D=R+s;return {trades:a.slice(R,D),isLoading:f,error:d,timeRange:n,setTimeRange:i,currentPage:o,totalPages:g,goToNextPage:()=>{o<g&&p(o+1);},goToPreviousPage:()=>{o>1&&p(o-1);},goToPage:A=>{A>=1&&A<=g&&p(A);}}}function rr(e,t=2){return e.toFixed(t)}function Io(e){return rr(e,4)}function Uo(e){return rr(e,4)}function Fo(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"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${i}:${o}`}var Ao=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function sr({trades:e,timeRange:t,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:i,onPreviousPage:o,onGoToPage:p}){return jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsxRuntime.jsx("div",{className:"flex gap-2",children:Ao.map(a=>{let l=t===a.value;return jsxRuntime.jsx("button",{type:"button",className:ui$1.cn("rounded px-3 transition-colors",!l&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:l?"#1c1c1c":"transparent",color:l?"#ffffff":"#b5b5b5"},onClick:()=>r(a.value),children:a.label},a.value)})}),e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxRuntime.jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsxRuntime.jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsxRuntime.jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsxRuntime.jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsxRuntime.jsx("tbody",{children:e.map(a=>jsxRuntime.jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsxRuntime.jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:a.symbol.split("-")[0]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3",children:jsxRuntime.jsx("span",{className:ui$1.cn("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()})}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",Io(a.price)]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Uo(a.quantity)}),jsxRuntime.jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[rr(a.fee,4)," ",a.feeCurrency]}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-center",children:jsxRuntime.jsx("span",{className:ui$1.cn("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"})}),jsxRuntime.jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Fo(a.timestamp)})]},a.tradeId))})]})}),n>1&&jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:o,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsxRuntime.jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(a,l)=>{let u;return n<=5||s<=3?u=l+1:s>=n-2?u=n-4+l:u=s-2+l,jsxRuntime.jsx("button",{type:"button",className:ui$1.cn("w-8 h-8 text-sm rounded transition-colors",s===u?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>p(u),children:u},u)})}),jsxRuntime.jsx(ui$1.Button,{size:"sm",onClick:i,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function nr(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function ir(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function Mo({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:i,isLoading:o,timeRange:p,setTimeRange:a,currentPage:l,totalPages:u,goToNextPage:c,goToPreviousPage:m,goToPage:f}=tr({userAddress:e,symbol:t,initialTimeRange:r,pageSize:s});return o?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(nr,{})}):i.length===0?jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(ir,{})}):jsxRuntime.jsx("div",{className:n,children:jsxRuntime.jsx(sr,{trades:i,timeRange:p,onTimeRangeChange:a,currentPage:l,totalPages:u,onNextPage:c,onPreviousPage:m,onGoToPage:f})})}var qo=1000000000n,_o=8,Bo=10n**BigInt(8);function Le(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Is(r,qo,t)}function et(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Is(r,Bo,t)}var Ho=et;function or(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 Is(e,t,r){let s=e<0n,n=s?-e:e,i=n/t,o=n%t;if(r<=0)return o*2n>=t&&(i+=1n),`${s?"-":""}${i.toString()}`;let p=10n**BigInt(r),a=(o*p+t/2n)/t;a>=p&&(i+=1n,a=0n);let l=a.toString().padStart(r,"0");return l=l.replace(/0+$/,""),l?`${s?"-":""}${i.toString()}.${l}`:`${s?"-":""}${i.toString()}`}function Me(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function ar(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function pr({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:p}){let{t:a}=i18n.useTranslation(),l=t?Date.parse(t.expiresAt):0,[u,c]=react.useState(()=>l?Me(l):0);return react.useEffect(()=>{if(!e||!l)return;c(Me(l));let m=setInterval(()=>{let f=Me(l);c(f),f===0&&(o?.(),clearInterval(m));},1e3);return ()=>clearInterval(m)},[e,l,o]),jsxRuntime.jsx(ui$1.Modal,{isOpen:e,onOpenChange:m=>!m&&i(),hideCloseButton:true,backdrop:"blur",children:jsxRuntime.jsxs(ui$1.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui$1.ModalHeader,{children:a("perpDeposit.confirm.title")}),jsxRuntime.jsxs(ui$1.ModalBody,{children:[t?jsxRuntime.jsx(Yo,{breakdown:t.breakdown}):jsxRuntime.jsx("div",{className:"flex h-32 items-center justify-center",children:jsxRuntime.jsx(ui$1.Spinner,{})}),t&&!s&&jsxRuntime.jsx("div",{className:"text-default-500 mt-4 text-xs",children:a("perpDeposit.confirm.expiresIn",{seconds:u})}),s&&jsxRuntime.jsx("div",{className:"text-warning-500 mt-4 text-xs",children:a("perpDeposit.confirm.expired")}),p&&jsxRuntime.jsx("div",{className:"text-danger mt-4 text-xs",children:p})]}),jsxRuntime.jsxs(ui$1.ModalFooter,{className:"flex justify-between gap-2",children:[jsxRuntime.jsx(ui$1.Button,{variant:"flat",color:"default",onPress:i,isDisabled:r,children:a("perpDeposit.confirm.cancel")}),jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:a("perpDeposit.confirm.cta")})]})]})})}function Yo({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(tt,{label:t("perpDeposit.confirm.send"),value:`${Le(e.grossLamports)} SOL`}),jsxRuntime.jsx(tt,{label:t("perpDeposit.confirm.receive"),value:`${et(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(tt,{label:t("perpDeposit.confirm.platformFee"),value:`${Le(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(tt,{label:t("perpDeposit.confirm.relayFee"),value:`${Le(e.relayDepositLamports,6)} SOL`,muted:true})]})}function tt({label:e,value:t,highlight:r,muted:s}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("dt",{className:"text-default-500",children:e}),jsxRuntime.jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-default-500 text-xs":"text-foreground",children:t})]})}function lr({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:p,onMax:a,className:l}){let{t:u}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui$1.cn("flex flex-col gap-4",l),children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-amount",className:"text-sm font-medium text-foreground",children:u("perpDeposit.amount")}),n&&jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:u("perpDeposit.amount.balance",{balance:n})})]}),jsxRuntime.jsx("div",{className:"relative",children:jsxRuntime.jsx(ui$1.Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:u("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:i,isInvalid:!!o,errorMessage:o,endContent:jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-default-500 text-sm",children:u("perpDeposit.amount.unit")}),n&&a&&jsxRuntime.jsx(ui$1.Button,{size:"sm",variant:"flat",color:"primary",onPress:a,isDisabled:i,children:u("perpDeposit.amount.max")})]})})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{htmlFor:"perp-deposit-recipient",className:"text-sm font-medium text-foreground mb-1.5 block",children:u("perpDeposit.recipient")}),jsxRuntime.jsx(ui$1.Input,{id:"perp-deposit-recipient",type:"text",placeholder:u("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:i,isInvalid:!!p,errorMessage:p,autoComplete:"off",spellCheck:"false"})]})]})}var Ms="#C7FF2E";function cr({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:p}){let{t:a}=i18n.useTranslation(),l=oa(t),u=t==="failed"?p||(r?.lastError?.message?a("perpDeposit.status.failed",{message:r.lastError.message}):a("perpDeposit.status.failed",{message:""})):t==="succeeded"?a("perpDeposit.status.settled"):t==="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"),c=t==="failed"&&!!i;return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:m=>!m&&o(),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:jsxRuntime.jsx(ui$1.ModalContent,{children:jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsxs("div",{className:"flex items-start justify-between px-5 pt-5 pb-2",children:[jsxRuntime.jsx("div",{className:"flex items-center gap-2.5",children:jsxRuntime.jsx("h3",{className:"text-base font-semibold text-white",children:a("perpDeposit.status.title")})}),jsxRuntime.jsx("button",{type:"button",onClick:o,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:jsxRuntime.jsx(ui$1.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-3 pt-2",children:[jsxRuntime.jsxs("div",{className:"rounded-[12px] bg-[#0a0a0b] border border-[#27272a] px-4 py-6 flex flex-col items-center text-center gap-4",children:[jsxRuntime.jsx(na,{variant:l}),jsxRuntime.jsx("p",{className:ui$1.cn("text-sm leading-relaxed max-w-[320px]",aa(l)),children:u})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(Ls,{href:s,label:a("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(Ls,{href:n,label:a("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxRuntime.jsxs("div",{className:ui$1.cn("px-5 pb-5 pt-2 flex gap-2",c?"justify-between":"justify-end"),children:[c&&jsxRuntime.jsx("button",{type:"button",onClick:i,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")}),jsxRuntime.jsx("button",{type:"button",onClick:o,className:ui$1.cn("cursor-pointer h-10 rounded-[10px] font-medium transition-colors flex items-center justify-center",c?"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 Ls({href:e,label:t,hash:r}){return jsxRuntime.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:[jsxRuntime.jsx("span",{className:"text-xs text-zinc-400 group-hover:text-white transition-colors",children:t}),jsxRuntime.jsxs("span",{className:"flex items-center gap-1.5 text-xs tabular-nums text-zinc-300 group-hover:text-[#C7FF2E] transition-colors",children:[ar(r,6,4),jsxRuntime.jsx(ca,{})]})]})}function na({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(ia,{})}):e==="success"?jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(199,255,46,0.12)]",children:jsxRuntime.jsx(pa,{className:"w-8 h-8",style:{color:Ms}})}):e==="warning"?jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(245,158,11,0.12)]",children:jsxRuntime.jsx(la,{className:"w-8 h-8 text-amber-400"})}):jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(239,68,68,0.12)]",children:jsxRuntime.jsx(ua,{className:"w-8 h-8 text-rose-400"})})}function ia(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("svg",{className:"lfi-perp-deposit-spinner",viewBox:"0 0 50 50",width:48,height:48,"aria-hidden":"true",children:[jsxRuntime.jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"4"}),jsxRuntime.jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:Ms,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsxRuntime.jsx("style",{children:`
21
21
  .lfi-perp-deposit-spinner {
22
22
  animation: lfi-perp-deposit-spin 0.9s linear infinite;
23
23
  transform-origin: center;
@@ -25,5 +25,5 @@
25
25
  @keyframes lfi-perp-deposit-spin {
26
26
  to { transform: rotate(360deg); }
27
27
  }
28
- `})]})}function na(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function ia(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 oa(e){return jsxRuntime.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:jsxRuntime.jsx("path",{d:"M20 6L9 17l-5-5"})})}function aa(e){return jsxRuntime.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsxRuntime.jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm0 4c.6 0 1 .4 1 1v6c0 .6-.4 1-1 1s-1-.4-1-1V7c0-.6.4-1 1-1zm0 12c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"})})}function pa(e){return jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"10"}),jsxRuntime.jsx("path",{d:"M15 9l-6 6M9 9l6 6"})]})}function la(){return jsxRuntime.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:[jsxRuntime.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),jsxRuntime.jsx("polyline",{points:"15 3 21 3 21 9"}),jsxRuntime.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}function ga({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:p,buildSolanaExplorerUrl:l,buildHyperliquidExplorerUrl:u,onSettled:d,onError:m,className:f}){let{t:c}=i18n.useTranslation(),[g,N]=react.useState(""),[h,x]=react.useState(n??""),v=react.useMemo(()=>{if(g&&(!/^\d+(\.\d+)?$/.test(g.trim())||Number(g)<=0))return c("perpDeposit.error.amountInvalid")},[g,c]),O=react.useMemo(()=>{if(h)return p?p(h):void 0},[h,p]),w=react.useMemo(()=>v?"":ir(g),[g,v]),_=react.useMemo(()=>!w||w==="0"||O||!h?null:{userSolanaAddress:e,hyperliquidRecipient:h,grossLamports:w,source:r},[w,h,O,r,e]),A=ht(_,{enabled:!!_}),{state:y,execute:R,reset:j,dispatch:B}=xt(i),E=y.phase==="submitted"||y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"?y.intentId:void 0,J=St(E,{enabled:!!E&&y.phase!=="succeeded"&&y.phase!=="refunded"&&y.phase!=="failed"});react.useEffect(()=>{J.data&&B({type:"STATUS_UPDATE",status:J.data});},[J.data,B]),react.useEffect(()=>{y.phase==="succeeded"?d?.(y.intentId):y.phase==="failed"&&m?.(y.intentId,y.error.message);},[y,d,m]);let ve=react.useCallback(()=>{A.data&&(B({type:"QUOTE_REQUEST"}),B({type:"QUOTE_RECEIVED",quote:A.data}));},[B,A.data]),Ce=react.useCallback(async()=>{if(y.phase==="ready_to_sign")try{await R({quote:y.quote,userSolanaAddress:e,hyperliquidRecipient:h,userId:t,source:r,campaign:s});}catch{}},[y,R,e,h,t,r,s]),re=react.useCallback(()=>{B({type:"QUOTE_EXPIRED"});},[B]),Bs=react.useCallback(async()=>{B({type:"RESET"}),await A.refetch();},[B,A]),Hs=y.phase==="ready_to_sign"||y.phase==="signing"||y.phase==="broadcasting"||y.phase==="expired",Qs=y.phase==="submitted"||y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"&&!!y.intentId,Te=y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"?y.status:void 0,zs=!A.data||A.isFetching||!!v||!!O||!_;return jsxRuntime.jsxs(ui$1.Card,{className:f,children:[jsxRuntime.jsxs(ui$1.CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:c("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:c("perpDeposit.description")})]}),jsxRuntime.jsx(pr,{amount:g,onAmountChange:N,recipient:h,onRecipientChange:x,balanceSol:o,onMax:a,amountError:v,recipientError:O,disabled:y.phase!=="idle"&&y.phase!=="expired"&&y.phase!=="failed"}),jsxRuntime.jsx(ui$1.Button,{color:"primary",isDisabled:zs,isLoading:A.isFetching,onPress:ve,children:A.isFetching?c("perpDeposit.gettingQuote"):c("perpDeposit.confirmQuote")}),A.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:c("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(ar,{isOpen:Hs,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:Ce,onCancel:j,onExpire:re}),jsxRuntime.jsx(ur,{isOpen:Qs,phase:y.phase,status:Te,solanaExplorerUrl:Te?.solanaTxHash&&l?l(Te.solanaTxHash):void 0,hyperliquidExplorerUrl:Te?.hyperliquidTxHash&&u?u(Te.hyperliquidTxHash):void 0,onRetry:y.phase==="failed"?Bs:void 0,onClose:j,errorMessage:y.phase==="failed"?y.error.message:void 0})]})}function fr({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=i18n.useTranslation(),a=e.phase,p=a==="executing",l=a==="loading",u=a==="error"&&e.steps.length===0;return jsxRuntime.jsxs(ui$1.Card,{className:ui$1.cn("w-full max-w-md",i),children:[jsxRuntime.jsxs(ui$1.CardHeader,{className:"flex flex-col items-start gap-1",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:o("perpDeposit.setup.title")}),jsxRuntime.jsx("p",{className:"text-foreground-500 text-sm",children:o("perpDeposit.setup.description")})]}),jsxRuntime.jsxs(ui$1.CardBody,{className:"gap-3",children:[l&&jsxRuntime.jsx(Pa,{}),u&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!l&&!u&&e.steps.map((d,m)=>jsxRuntime.jsx(Sa,{rec:d,index:m,isCurrent:e.currentIndex===m,onRetry:r},`${d.step.id}-${m}`)),a==="done"&&jsxRuntime.jsx("p",{className:"text-success text-sm",children:o("perpDeposit.setup.alreadyActive")})]}),jsxRuntime.jsxs(ui$1.CardFooter,{className:"flex justify-between gap-2",children:[n&&jsxRuntime.jsx(ui$1.Button,{variant:"light",onPress:n,isDisabled:p,children:o(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsxRuntime.jsx("div",{className:"flex-1"}),u&&s&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:s,children:o("perpDeposit.setup.retry")}),!u&&a!=="done"&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:t,isLoading:p,isDisabled:p||l,children:e.steps.some(d=>d.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function Sa({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),i=Ta(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")}}),o=(()=>{switch(e.step.id){case "approveBuilderFee":{let p=(e.step.params.maxFeeRate/10).toFixed(1);return n("perpDeposit.setup.builderFee.description",{bps:p})}case "setReferrer":return n("perpDeposit.setup.referrer.description",{code:e.step.params.code});case "updateLeverage":return n("perpDeposit.setup.leverage.description")}})(),a=(()=>{switch(e.status){case "pending":return n("perpDeposit.setup.step.pending");case "skipped":return n("perpDeposit.setup.step.skipped");case "running":return n("perpDeposit.setup.step.running");case "done":return n("perpDeposit.setup.step.done");case "error":return n("perpDeposit.setup.step.error")}})();return jsxRuntime.jsxs("div",{className:ui$1.cn("border-divider flex items-start justify-between gap-3 rounded-md border p-3",e.status==="error"&&"border-danger",e.status==="done"&&"border-success/40 bg-success/5",e.status==="skipped"&&"border-default bg-default-100/40"),children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsxRuntime.jsx(va,{status:e.status,isCurrent:r}),jsxRuntime.jsx("span",{children:i})]}),jsxRuntime.jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:o}),e.status==="error"&&e.error&&jsxRuntime.jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsxRuntime.jsx("span",{className:ui$1.cn(Ca(e.status)),children:a}),e.status==="error"&&s&&jsxRuntime.jsx(ui$1.Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function Pa(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsxRuntime.jsx(ui$1.Spinner,{size:"sm"}),jsxRuntime.jsx("span",{children:e("perpDeposit.setup.loading")})]})}function va({status:e,isCurrent:t}){return e==="running"||t?jsxRuntime.jsx(ui$1.Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsxRuntime.jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Ca(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 Ta(e,t){return t()}function Da({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:p,runNext:l,runStep:u,reload:d}=Qe({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),m=react.useCallback(()=>{l();},[l]),f=react.useCallback(g=>{u(g);},[u]),c=react.useCallback(()=>{d();},[d]);return jsxRuntime.jsx(fr,{state:p,onContinue:m,onRetryStep:f,onReload:c,onDismiss:o,className:a})}exports.CoinInfoNotFoundUI=Pt;exports.CoinInfoSkeletonsUI=Ct;exports.CoinInfoUI=kt;exports.CoinInfoWidget=zn;exports.DEFAULT_ORDER_BOOK_PRECISION_OPTIONS=ms;exports.DepositConfirmUI=ar;exports.DepositFlowWidget=ga;exports.DepositFormUI=pr;exports.DepositStatusUI=ur;exports.HL_USDC_DECIMALS=Mo;exports.HyperliquidApiError=se;exports.HyperliquidInitUI=fr;exports.HyperliquidInitWidget=Da;exports.HyperliquidPerpetualsClient=st;exports.LiberFiApiError=z;exports.LiberFiHttpTransport=ne;exports.LiberFiPerpDepositClient=it;exports.LiberFiPerpetualsClient=nt;exports.OpenOrdersEmpty=Jt;exports.OpenOrdersSkeleton=Xt;exports.OpenOrdersUI=Yt;exports.OpenOrdersWidget=Oo;exports.OrderBookUI=Ft;exports.OrderBookWidget=Si;exports.PerpetualsContext=Z;exports.PerpetualsProvider=sn;exports.PlaceOrderFormUI=zt;exports.PlaceOrderFormWidget=mo;exports.PositionsEmpty=Po;exports.PositionsSkeleton=Gt;exports.PositionsUI=Kt;exports.PositionsWidget=vo;exports.SearchCoinsUI=Rt;exports.SearchCoinsWidget=Vn;exports.TERMINAL_DEPOSIT_STATUSES=De;exports.TradeHistoryEmpty=nr;exports.TradeHistorySkeleton=sr;exports.TradeHistoryUI=rr;exports.TradeHistoryWidget=Ao;exports.TradesUI=Bt;exports.TradesWidget=Xi;exports.aggregationFromStep=ns;exports.cancelOrder=Lr;exports.classifyStep=qe;exports.coinsQueryKey=br;exports.createOrder=Ar;exports.currentDepositBreakdown=Zs;exports.currentDepositStatus=Js;exports.fetchCoins=hr;exports.fetchKlines=Tr;exports.fetchMarket=Sr;exports.fetchMarkets=vr;exports.fetchOrderBook=kr;exports.fetchOrders=Ir;exports.fetchPerpDepositQuote=_r;exports.fetchPerpDepositStatus=zr;exports.fetchPositions=Er;exports.fetchRecentTrades=Or;exports.fetchTrades=Fr;exports.hlUsdcRawToUsdc=Je;exports.initialDepositState=Me;exports.initialSetupState=Ee;exports.isDepositPolling=Xs;exports.isDepositTerminal=Ys;exports.isTerminalDepositLifecycle=en;exports.klinesQueryKey=Cr;exports.lamportsToSol=Ue;exports.marketQueryKey=xr;exports.marketsQueryKey=Pr;exports.microUsdcToUsdc=_o;exports.nextRunnableStep=Be;exports.orderBookQueryKey=Dr;exports.ordersQueryKey=Nr;exports.perpDepositQuoteQueryKey=qr;exports.perpDepositStatusQueryKey=Qr;exports.positionsQueryKey=Rr;exports.recentTradesQueryKey=wr;exports.reduceDepositState=ot;exports.reduceSetupState=_e;exports.secondsUntil=Fe;exports.shortAddress=or;exports.solToLamports=ir;exports.tradesQueryKey=Ur;exports.useCancelOrderMutation=mt;exports.useCandlesSubscription=Cn;exports.useCoinInfo=Dt;exports.useCoinsQuery=at;exports.useCreateOrderMutation=Oe;exports.useHyperliquidSetup=Qe;exports.useKlinesQuery=cn;exports.useMarketDataSubscription=ie;exports.useMarketQuery=ke;exports.useMarketsQuery=pt;exports.useOpenOrdersScript=Vt;exports.useOrderBookQuery=lt;exports.useOrderBookScript=Nt;exports.useOrdersQuery=ct;exports.usePerpDepositClient=kn;exports.usePerpDepositClientMaybe=oe;exports.usePerpDepositExecute=xt;exports.usePerpDepositQuote=ht;exports.usePerpDepositStatus=St;exports.usePerpetualsClient=T;exports.usePlaceOrderFormScript=Ht;exports.usePositionsQuery=we;exports.usePositionsScript=Wt;exports.useRecentTradesQuery=ut;exports.useSearchCoinsScript=Ot;exports.useTradeHistoryScript=er;exports.useTradesQuery=dt;exports.useTradesScript=Mt;exports.useUserDataSubscription=Re;exports.version=Ws;//# sourceMappingURL=index.js.map
28
+ `})]})}function oa(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function aa(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 pa(e){return jsxRuntime.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:jsxRuntime.jsx("path",{d:"M20 6L9 17l-5-5"})})}function la(e){return jsxRuntime.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsxRuntime.jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm0 4c.6 0 1 .4 1 1v6c0 .6-.4 1-1 1s-1-.4-1-1V7c0-.6.4-1 1-1zm0 12c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"})})}function ua(e){return jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"10"}),jsxRuntime.jsx("path",{d:"M15 9l-6 6M9 9l6 6"})]})}function ca(){return jsxRuntime.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:[jsxRuntime.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),jsxRuntime.jsx("polyline",{points:"15 3 21 3 21 9"}),jsxRuntime.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}function ba({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:p,validateRecipient:a,buildSolanaExplorerUrl:l,buildHyperliquidExplorerUrl:u,onSettled:c,onError:m,className:f}){let{t:d}=i18n.useTranslation(),[g,R]=react.useState(""),[D,h]=react.useState(n??""),x=react.useMemo(()=>{if(g&&(!/^\d+(\.\d+)?$/.test(g.trim())||Number(g)<=0))return d("perpDeposit.error.amountInvalid")},[g,d]),N=react.useMemo(()=>{if(D)return a?a(D):void 0},[D,a]),E=react.useMemo(()=>x?"":or(g),[g,x]),A=react.useMemo(()=>!E||E==="0"||N||!D?null:{userSolanaAddress:e,hyperliquidRecipient:D,grossLamports:E,source:r},[E,D,N,r,e]),L=St(A,{enabled:!!A}),{state:y,execute:le,reset:O,dispatch:_}=Pt(i),ue=y.phase==="submitted"||y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"?y.intentId:void 0,w=vt(ue,{enabled:!!ue&&y.phase!=="succeeded"&&y.phase!=="refunded"&&y.phase!=="failed"});react.useEffect(()=>{w.data&&_({type:"STATUS_UPDATE",status:w.data});},[w.data,_]),react.useEffect(()=>{y.phase==="succeeded"?c?.(y.intentId):y.phase==="failed"&&m?.(y.intentId,y.error.message);},[y,c,m]);let ce=react.useCallback(()=>{L.data&&(_({type:"QUOTE_REQUEST"}),_({type:"QUOTE_RECEIVED",quote:L.data}));},[_,L.data]),Ce=react.useCallback(async()=>{if(y.phase==="ready_to_sign")try{await le({quote:y.quote,userSolanaAddress:e,hyperliquidRecipient:D,userId:t,source:r,campaign:s});}catch{}},[y,le,e,D,t,r,s]),Te=react.useCallback(()=>{_({type:"QUOTE_EXPIRED"});},[_]),ee=react.useCallback(async()=>{_({type:"RESET"}),await L.refetch();},[_,L]),Hs=y.phase==="ready_to_sign"||y.phase==="signing"||y.phase==="broadcasting"||y.phase==="expired",Qs=y.phase==="submitted"||y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"&&!!y.intentId,De=y.phase==="tracking"||y.phase==="succeeded"||y.phase==="refunded"||y.phase==="failed"?y.status:void 0,zs=!L.data||L.isFetching||!!x||!!N||!A;return jsxRuntime.jsxs(ui$1.Card,{className:f,children:[jsxRuntime.jsxs(ui$1.CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:d("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:d("perpDeposit.description")})]}),jsxRuntime.jsx(lr,{amount:g,onAmountChange:R,recipient:D,onRecipientChange:h,balanceSol:o,onMax:p,amountError:x,recipientError:N,disabled:y.phase!=="idle"&&y.phase!=="expired"&&y.phase!=="failed"}),jsxRuntime.jsx(ui$1.Button,{color:"primary",isDisabled:zs,isLoading:L.isFetching,onPress:ce,children:L.isFetching?d("perpDeposit.gettingQuote"):d("perpDeposit.confirmQuote")}),L.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:d("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(pr,{isOpen:Hs,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:Ce,onCancel:O,onExpire:Te}),jsxRuntime.jsx(cr,{isOpen:Qs,phase:y.phase,status:De,solanaExplorerUrl:De?.solanaTxHash&&l?l(De.solanaTxHash):void 0,hyperliquidExplorerUrl:De?.hyperliquidTxHash&&u?u(De.hyperliquidTxHash):void 0,onRetry:y.phase==="failed"?ee:void 0,onClose:O,errorMessage:y.phase==="failed"?y.error.message:void 0})]})}function gr({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=i18n.useTranslation(),p=e.phase,a=p==="executing",l=p==="loading",u=p==="error"&&e.steps.length===0;return jsxRuntime.jsxs(ui$1.Card,{className:ui$1.cn("w-full max-w-md",i),children:[jsxRuntime.jsxs(ui$1.CardHeader,{className:"flex flex-col items-start gap-1",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:o("perpDeposit.setup.title")}),jsxRuntime.jsx("p",{className:"text-foreground-500 text-sm",children:o("perpDeposit.setup.description")})]}),jsxRuntime.jsxs(ui$1.CardBody,{className:"gap-3",children:[l&&jsxRuntime.jsx(Ca,{}),u&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!l&&!u&&e.steps.map((c,m)=>jsxRuntime.jsx(va,{rec:c,index:m,isCurrent:e.currentIndex===m,onRetry:r},`${c.step.id}-${m}`)),p==="done"&&jsxRuntime.jsx("p",{className:"text-success text-sm",children:o("perpDeposit.setup.alreadyActive")})]}),jsxRuntime.jsxs(ui$1.CardFooter,{className:"flex justify-between gap-2",children:[n&&jsxRuntime.jsx(ui$1.Button,{variant:"light",onPress:n,isDisabled:a,children:o(p==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsxRuntime.jsx("div",{className:"flex-1"}),u&&s&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:s,children:o("perpDeposit.setup.retry")}),!u&&p!=="done"&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:t,isLoading:a,isDisabled:a||l,children:e.steps.some(c=>c.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function va({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),i=ka(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")}}),o=(()=>{switch(e.step.id){case "approveBuilderFee":{let a=(e.step.params.maxFeeRate/10).toFixed(1);return n("perpDeposit.setup.builderFee.description",{bps:a})}case "setReferrer":return n("perpDeposit.setup.referrer.description",{code:e.step.params.code});case "updateLeverage":return n("perpDeposit.setup.leverage.description")}})(),p=(()=>{switch(e.status){case "pending":return n("perpDeposit.setup.step.pending");case "skipped":return n("perpDeposit.setup.step.skipped");case "running":return n("perpDeposit.setup.step.running");case "done":return n("perpDeposit.setup.step.done");case "error":return n("perpDeposit.setup.step.error")}})();return jsxRuntime.jsxs("div",{className:ui$1.cn("border-divider flex items-start justify-between gap-3 rounded-md border p-3",e.status==="error"&&"border-danger",e.status==="done"&&"border-success/40 bg-success/5",e.status==="skipped"&&"border-default bg-default-100/40"),children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsxRuntime.jsx(Ta,{status:e.status,isCurrent:r}),jsxRuntime.jsx("span",{children:i})]}),jsxRuntime.jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:o}),e.status==="error"&&e.error&&jsxRuntime.jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsxRuntime.jsx("span",{className:ui$1.cn(Da(e.status)),children:p}),e.status==="error"&&s&&jsxRuntime.jsx(ui$1.Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function Ca(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsxRuntime.jsx(ui$1.Spinner,{size:"sm"}),jsxRuntime.jsx("span",{children:e("perpDeposit.setup.loading")})]})}function Ta({status:e,isCurrent:t}){return e==="running"||t?jsxRuntime.jsx(ui$1.Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsxRuntime.jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Da(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 ka(e,t){return t()}function wa({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:p}){let{state:a,runNext:l,runStep:u,reload:c}=$e({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),m=react.useCallback(()=>{l();},[l]),f=react.useCallback(g=>{u(g);},[u]),d=react.useCallback(()=>{c();},[c]);return jsxRuntime.jsx(gr,{state:a,onContinue:m,onRetryStep:f,onReload:d,onDismiss:o,className:p})}exports.CoinInfoNotFoundUI=Ct;exports.CoinInfoSkeletonsUI=Dt;exports.CoinInfoUI=Ot;exports.CoinInfoWidget=zn;exports.DEFAULT_ORDER_BOOK_PRECISION_OPTIONS=fs;exports.DepositConfirmUI=pr;exports.DepositFlowWidget=ba;exports.DepositFormUI=lr;exports.DepositStatusUI=cr;exports.HL_USDC_DECIMALS=_o;exports.HyperliquidApiError=te;exports.HyperliquidInitUI=gr;exports.HyperliquidInitWidget=wa;exports.HyperliquidPerpetualsClient=it;exports.LiberFiApiError=z;exports.LiberFiHttpTransport=re;exports.LiberFiPerpDepositClient=at;exports.LiberFiPerpetualsClient=ot;exports.OpenOrdersEmpty=Zt;exports.OpenOrdersSkeleton=Jt;exports.OpenOrdersUI=Xt;exports.OpenOrdersWidget=Eo;exports.OrderBookUI=Lt;exports.OrderBookWidget=Si;exports.PerpetualsContext=X;exports.PerpetualsProvider=sn;exports.PlaceOrderFormUI=Wt;exports.PlaceOrderFormWidget=go;exports.PositionsEmpty=Co;exports.PositionsSkeleton=Vt;exports.PositionsUI=Gt;exports.PositionsWidget=To;exports.SearchCoinsUI=Nt;exports.SearchCoinsWidget=Vn;exports.TERMINAL_DEPOSIT_STATUSES=ke;exports.TradeHistoryEmpty=ir;exports.TradeHistorySkeleton=nr;exports.TradeHistoryUI=sr;exports.TradeHistoryWidget=Mo;exports.TradesUI=Qt;exports.TradesWidget=Xi;exports.aggregationFromStep=is;exports.cancelOrder=Mr;exports.classifyStep=He;exports.coinsQueryKey=hr;exports.createOrder=Lr;exports.currentDepositBreakdown=Zs;exports.currentDepositStatus=Js;exports.fetchCoins=xr;exports.fetchKlines=Dr;exports.fetchMarket=Pr;exports.fetchMarkets=Cr;exports.fetchOrderBook=wr;exports.fetchOrders=Ur;exports.fetchPerpDepositQuote=Br;exports.fetchPerpDepositStatus=Wr;exports.fetchPositions=Nr;exports.fetchRecentTrades=Rr;exports.fetchTrades=Ar;exports.hlUsdcRawToUsdc=et;exports.initialDepositState=Be;exports.initialSetupState=Ne;exports.isDepositPolling=Xs;exports.isDepositTerminal=Ys;exports.isTerminalDepositLifecycle=en;exports.klinesQueryKey=Tr;exports.lamportsToSol=Le;exports.marketQueryKey=Sr;exports.marketsQueryKey=vr;exports.microUsdcToUsdc=Ho;exports.nextRunnableStep=ze;exports.orderBookQueryKey=kr;exports.ordersQueryKey=Ir;exports.perpDepositQuoteQueryKey=_r;exports.perpDepositStatusQueryKey=zr;exports.positionsQueryKey=Er;exports.recentTradesQueryKey=Or;exports.reduceDepositState=pt;exports.reduceSetupState=Qe;exports.secondsUntil=Me;exports.shortAddress=ar;exports.solToLamports=or;exports.tradesQueryKey=Fr;exports.useCancelOrderMutation=gt;exports.useCandlesSubscription=Cn;exports.useCoinInfo=wt;exports.useCoinsQuery=lt;exports.useCreateOrderMutation=Re;exports.useHyperliquidSetup=$e;exports.useKlinesQuery=cn;exports.useMarketDataSubscription=se;exports.useMarketQuery=we;exports.useMarketsQuery=ut;exports.useOpenOrdersScript=jt;exports.useOrderBookQuery=ct;exports.useOrderBookScript=Ut;exports.useOrdersQuery=mt;exports.usePerpDepositClient=kn;exports.usePerpDepositClientMaybe=ne;exports.usePerpDepositExecute=Pt;exports.usePerpDepositQuote=St;exports.usePerpDepositStatus=vt;exports.usePerpetualsClient=C;exports.usePlaceOrderFormScript=zt;exports.usePositionsQuery=Oe;exports.usePositionsScript=$t;exports.useRecentTradesQuery=dt;exports.useSearchCoinsScript=Et;exports.useTradeHistoryScript=tr;exports.useTradesQuery=ft;exports.useTradesScript=_t;exports.useUserDataSubscription=Ee;exports.version=Ws;//# sourceMappingURL=index.js.map
29
29
  //# sourceMappingURL=index.js.map