@liberfi.io/ui-perpetuals 1.1.71 → 1.1.73
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 +14 -14
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +14 -14
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),i18n=require('@liberfi.io/i18n'),utils=require('@liberfi.io/utils'),ui=require('@liberfi.io/ui'),reactWindow=require('react-window'),hooks=require('@liberfi.io/hooks'),reactHookForm=require('react-hook-form'),walletConnector=require('@liberfi.io/wallet-connector');var so=new Set(["userFills","userFillsByTime","userFunding","userNonFundingLedgerUpdates","frontendOpenOrders","userRateLimit","historicalOrders","userTwapSliceFills","predictedFundings"]);function qr(e){return e&&so.has(e)?20:2}var tn=1,mt=class{capacity;windowMs;tokens;lastRefill;constructor(t={}){this.capacity=t.capacity??1200,this.windowMs=t.windowMs??6e4,this.tokens=this.capacity,this.lastRefill=Date.now();}reset(){this.tokens=this.capacity,this.lastRefill=Date.now();}async waitForToken(t){let r=Math.max(1,Math.floor(t));for(;;){if(this.refill(),this.tokens>=r){this.tokens-=r;return}let s=Math.max(25,this.windowMs-(Date.now()-this.lastRefill));await new Promise(n=>setTimeout(n,s));}}refill(){let t=Date.now();t-this.lastRefill>=this.windowMs&&(this.tokens=this.capacity,this.lastRefill=t);}};function ie(e){return e!==null&&typeof e=="object"?e:{}}function W(e,t="0"){return parseFloat(String(typeof e=="number"?e:e??t))}function no(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 et=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.warn("[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.warn(`[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.warn(`[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=ie(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=ie(t),s=r.channel;this.subscriptions.forEach((n,i)=>{if(this.isChannelMatch(s,n.type,n.param,r))try{let o=this.transformData(n.type,r.data,n.param);n.callback(o);}catch(o){console.error(`[WebSocket] Error in subscription callback (${i}):`,o);}});}isChannelMatch(t,r,s,n){let i=ie(n).data;if(r==="ticker"){if(t!=="activeAssetCtx")return false;let o=s.split("-")[0],a=ie(i).coin;return typeof a=="string"&&a===o}else if(r==="trades"){if(t!=="trades")return false;let o=s.split("-")[0],a=Array.isArray(i)?ie(i[0]).coin:void 0;return typeof a!="string"||a===o}else if(r==="orderBook"){if(t!=="l2Book")return false;let o=s.split("-")[0],a=ie(i).coin;return typeof a=="string"&&a===o}else {if(r==="candle")return t==="candle";if(r==="userFills")return t==="userFills";if(r==="userEvents")return t==="userEvents";if(r==="accountState")return t==="webData2"}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 s=ie(t),i=`${typeof s.coin=="string"?s.coin:r.split("-")[0]}-USDC`,o=ie(s.ctx),a=W(o.midPx??o.markPx),l=W(o.markPx??o.midPx),u=o.prevDayPx?W(o.prevDayPx):a,c=u>0?(a-u)/u*100:0;return {symbol:i,price:a,change24h:c,volume24h:W(o.dayNtlVlm),fundingRate:W(o.funding),openInterest:W(o.openInterest),markPrice:l,indexPrice:W(o.oraclePx??o.midPx)}}transformTradesData(t,r){return Array.isArray(t)?t.map(s=>{let n=ie(s);return {symbol:r,side:n.side==="B"?"buy":"sell",price:W(n.px),quantity:W(n.sz),timestamp:n.time,tradeId:n.tid}}):[]}transformOrderBookData(t,r){let s=ie(t),n=Array.isArray(s.levels)?s.levels:[[],[]],i=Array.isArray(n[0])?n[0]:[],o=Array.isArray(n[1])?n[1]:[],a=l=>{let u=ie(l);return {price:W(u.px),quantity:W(u.sz),count:u.n}};return {symbol:r,bids:i.map(a),asks:o.map(a),timestamp:typeof s.time=="number"?s.time:Date.now()}}transformCandleData(t,r){let[s]=r.split(":"),n=ie(t);return {symbol:s,open:W(n.o),high:W(n.h),low:W(n.l),close:W(n.c),volume:W(n.v),timestamp:W(n.t),closeTimestamp:W(n.T)}}transformUserFillsData(t){return Array.isArray(t)?t.map(r=>{let s=ie(r);return {tradeId:s.tid!=null?String(s.tid):void 0,orderId:s.oid!=null?String(s.oid):void 0,symbol:`${String(s.coin??"")}-USDC`,side:typeof s.dir=="string"&&s.dir.includes("Long")?"long":"short",price:W(s.px),quantity:W(s.sz),fee:W(s.fee),feeCurrency:typeof s.feeToken=="string"?s.feeToken:"USDC",isMaker:s.side==="M",timestamp:s.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}}:t==="accountState"&&(n={method:"subscribe",subscription:{type:"webData2",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}}:t==="accountState"&&(n={method:"unsubscribe",subscription:{type:"webData2",user:r}});n&&this.send(n);}subscribe(t,r,s,n){let i=no(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 rn={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"}},io=60*1e3,oo=1500,ao=1500,Hr=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;assetMetaCache=null;assetMetaPending=null;universeSnapshotCache=null;universeSnapshotPending=null;userStateCache=new Map;userStatePending=new Map;rateLimiter;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||rn[this.environment].api,this._wsEndpoint=t.wsEndpoint||rn[this.environment].ws,this.timeout=t.timeout||3e4,t.rateLimit===false?this.rateLimiter=null:t.rateLimit instanceof mt?this.rateLimiter=t.rateLimit:this.rateLimiter=new mt(t.rateLimit);}weightFor(t,r){if(t.startsWith("/exchange"))return tn;if(t.startsWith("/info")){let s=r&&typeof r=="object"&&"type"in r&&typeof r.type=="string"?r.type:void 0;return qr(s)}return qr(void 0)}async request(t,r){let s=`${this.apiEndpoint}${t}`;this.rateLimiter&&await this.rateLimiter.waitForToken(this.weightFor(t,r));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 instanceof Error&&n.name==="AbortError"?new Te(`Request timeout after ${this.timeout}ms`,408,""):n instanceof Te?n:new Te(`Network error: ${n instanceof Error?n.message:String(n)}`,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(){return (await this.getUniverseSnapshot()).assets.map(r=>r.symbol)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let r=await this.getUniverseSnapshot();if(t&&t.length>0){let s=new Set(t);return r.assets.map(n=>n.market).filter(n=>s.has(n.symbol))}return r.assets.map(s=>s.market)}async getUniverseSnapshot(){let t=Date.now();if(this.universeSnapshotCache&&t-this.universeSnapshotCache.fetchedAt<oo)return this.universeSnapshotCache.snapshot;if(this.universeSnapshotPending)return this.universeSnapshotPending;let r=this.fetchUniverseSnapshot();this.universeSnapshotPending=r;try{let s=await r;return this.universeSnapshotCache={fetchedAt:Date.now(),snapshot:s},s}finally{this.universeSnapshotPending=null;}}async fetchUniverseSnapshot(){let[t,r]=await this.request("/info",{type:"metaAndAssetCtxs"}),s=t.universe.map((i,o)=>{let a=r[o]??{},l=`${i.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx?parseFloat(a.prevDayPx):u,p=c>0?(u-c)/c*100:0,d={symbol:l,price:u,change24h:p,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")},f=typeof i.szDecimals=="number"?{szDecimals:i.szDecimals,maxLeverage:i.maxLeverage}:null;return {coin:i.name,symbol:l,market:d,meta:f}}),n=new Map;for(let i of s)n.set(i.symbol,i);return {assets:s,bySymbol:n,fetchedAt:Date.now()}}async getUserStateSnapshot(t){let r=t.toLowerCase(),s=Date.now(),n=this.userStateCache.get(r);if(n&&s-n.fetchedAt<ao)return n.snapshot;let i=this.userStatePending.get(r);if(i)return i;let o=(async()=>{let[a,l]=await Promise.all([this.request("/info",{type:"clearinghouseState",user:t}),this.request("/info",{type:"frontendOpenOrders",user:t}).catch(()=>{})]);return {clearinghouse:a,openOrders:l,fetchedAt:Date.now()}})();this.userStatePending.set(r,o);try{let a=await o;return this.userStateCache.set(r,{fetchedAt:Date.now(),snapshot:a}),a}finally{this.userStatePending.delete(r);}}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,l,u;i.from!==void 0&&i.to!==void 0?(l=i.from,u=i.to):i.to!==void 0&&a?(u=i.to,l=u-o*a):i.from!==void 0&&a?(l=i.from,u=l+o*a):(u=Date.now(),l=u-o*(a??100));let p=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:u}})).map(d=>({symbol:t,open:parseFloat(d.o),high:parseFloat(d.h),low:parseFloat(d.l),close:parseFloat(d.c),volume:parseFloat(d.v),timestamp:d.t,closeTimestamp:d.T}));return a&&p.length>a&&(p=p.slice(p.length-a)),p}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,l]=o.levels;return {symbol:t,bids:a.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),asks:l.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.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,s]=await Promise.all([this.getUserStateSnapshot(t.userAddress),this.getUniverseSnapshot()]),n=nn(r.clearinghouse,t.symbol),i=sn(s);return n.positions=ln(n.positions,r.openOrders??[],i),n.totalUnrealizedPnl=n.positions.reduce((o,a)=>o+a.unrealizedPnl,0),n}async getActiveAssetLeverage(t){let r=this.symbolToCoin(t.symbol);try{let n=(await this.request("/info",{type:"activeAssetData",coin:r,user:t.userAddress}))?.leverage;return !n||typeof n.value!="number"?null:{value:n.value,type:n.type}}catch(s){if(s instanceof Te&&(s.statusCode===422||s.statusCode===400))return null;throw s}}async getAssetMeta(t){let r=await this.fetchAssetUniverse(),s=this.symbolToCoin(t.symbol);return r.get(s)??null}async fetchAssetUniverse(){let t=Date.now();if(this.assetMetaCache&&t-this.assetMetaCache.fetchedAt<io)return this.assetMetaCache.map;if(this.assetMetaPending)return this.assetMetaPending;let r=(async()=>{let s=await this.request("/info",{type:"meta"}),n=new Map;for(let i of s.universe)!i||typeof i.name!="string"||typeof i.szDecimals=="number"&&n.set(i.name,{szDecimals:i.szDecimals,maxLeverage:i.maxLeverage});return this.assetMetaCache={fetchedAt:Date.now(),map:n},n})();this.assetMetaPending=r;try{return await r}finally{this.assetMetaPending=null;}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let[r,s]=await Promise.all([this.getUserStateSnapshot(t.userAddress).catch(()=>null),this.getUniverseSnapshot().catch(()=>{})]),n=r?.openOrders??[],i={leverageByCoin:an(r?.clearinghouse),markByCoin:s?sn(s):void 0},o=n.map(l=>on(l,i)),a=t.symbol?o.filter(l=>l.symbol===t.symbol):o;return {orders:a,totalCount:a.length,raw:n}}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,dir:n.dir,closedPnl:parseFloat(n.closedPnl||"0")}});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 et(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,i=>s(i))}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)}subscribeAccountState(t,r){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe("accountState",t,s=>{r(po(s));})}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}};function nn(e,t){let r=e.assetPositions.map(o=>{let a=o.position,l=`${a.coin}-USDC`,u=parseFloat(a.szi);if(u===0)return null;let c=parseFloat(a.entryPx),p=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:u>0?"long":"short",quantity:Math.abs(u),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:c,markPrice:c,unrealizedPnl:p,unrealizedPnlPercent:parseFloat(a.returnOnEquity)*100,leverage:a.leverage.value,liquidationPrice:a.liquidationPx?parseFloat(a.liquidationPx):void 0,margin:parseFloat(a.marginUsed),notionalValue:Math.abs(d)}}).filter(o=>o!==null),s=t?r.filter(o=>o.symbol===t):r,n=e.withdrawable,i=typeof n=="string"&&n.length>0?parseFloat(n):parseFloat(e.marginSummary.accountValue)-parseFloat(e.marginSummary.totalMarginUsed);return {positions:s,totalEquity:parseFloat(e.marginSummary.accountValue),availableBalance:i,totalUnrealizedPnl:s.reduce((o,a)=>o+a.unrealizedPnl,0),raw:e}}function lo(e){if(!e.children||e.children.length===0)return {};let t,r;for(let s of e.children){let n=typeof s.orderType=="string"?s.orderType:"",i=s.triggerPx;if(typeof i!="string"||i.length===0)continue;let o=parseFloat(i);!Number.isFinite(o)||o<=0||(/take\s*profit/i.test(n)?t=o:/stop/i.test(n)&&(r=o));}return {takeProfitPrice:t,stopLossPrice:r}}function on(e,t){let r=`${e.coin}-USDC`,s=parseFloat(e.origSz),n=parseFloat(e.sz),i=s-n,o=e.side===true||e.side==="B",a=typeof e.orderType=="string"?e.orderType:"Limit",u=/^market$/i.test(a)?"market":"limit",c=e.isTrigger===true,p;c&&(/take\s*profit/i.test(a)?p="tp":/stop/i.test(a)&&(p="sl"));let d=typeof e.triggerPx=="string"&&e.triggerPx.length>0?parseFloat(e.triggerPx):void 0,f=typeof e.triggerCondition=="string"&&e.triggerCondition!=="N/A"?e.triggerCondition:void 0,{takeProfitPrice:b,stopLossPrice:m}=lo(e),v=t?.leverageByCoin?.get(e.coin),g=t?.markByCoin?.get(e.coin);return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:r,side:o?"long":"short",orderType:u,price:parseFloat(e.limitPx),quantity:s,filledQuantity:i,remainingQuantity:n,status:i>0&&n>0?"partially_filled":"pending",timestamp:e.timestamp,updateTimestamp:e.timestamp,leverage:v,reduceOnly:e.reduceOnly===true,isTrigger:c||void 0,triggerPx:d,triggerType:p,triggerCondition:f,markPrice:g,takeProfitPrice:b,stopLossPrice:m}}function an(e){let t=new Map;if(!e)return t;for(let r of e.assetPositions??[]){let s=r.position?.leverage?.value;typeof s=="number"&&Number.isFinite(s)&&s>0&&t.set(r.position.coin,s);}return t}function uo(e){return e?e.map(t=>({coin:t.coin,total:parseFloat(t.total),totalRaw:t.total,hold:parseFloat(t.hold),entryNotional:t.entryNtl?parseFloat(t.entryNtl):void 0})):[]}function po(e){let t=e.clearinghouseState,r=t?nn(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=uo(e.spotState?.balances),i=e.meta&&e.assetCtxs?fo([e.meta,e.assetCtxs]):null,o=an(t),a=s.map(d=>on(d,{leverageByCoin:o,markByCoin:i??void 0})),l=ln(r.positions,s,i),u=l.reduce((d,f)=>d+f.unrealizedPnl,0),c=e.meta&&e.assetCtxs?co(e.meta,e.assetCtxs,e.serverTime):void 0,p=t?mo(t):void 0;return {positions:l,openOrders:a,spotBalances:n,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:u,serverTime:e.serverTime,leverageByCoin:p,universe:c,raw:e}}function co(e,t,r){let s=e.universe.map((i,o)=>{let a=t[o]??{},l=`${i.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx,p=c?parseFloat(c):u,d=p>0?(u-p)/p*100:0,f={symbol:l,price:u,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")},b=i.szDecimals,m=i.maxLeverage,v=typeof b=="number"?{szDecimals:b,maxLeverage:m}:null;return {coin:i.name,symbol:l,market:f,meta:v}}),n=new Map;for(let i of s)n.set(i.symbol,i);return {assets:s,bySymbol:n,fetchedAt:r??Date.now()}}function mo(e){let t={};for(let r of e.assetPositions??[]){let s=r.position?.leverage;if(!s||typeof s.value!="number")continue;let n=s.type==="isolated"||s.type==="cross"?s.type:"cross";t[r.position.coin]={value:s.value,type:n};}return t}function fo(e){let[t,r]=e,s=new Map;return t.universe.forEach((n,i)=>{let o=r[i];if(!o)return;let a=o.markPx??o.midPx??o.oraclePx;if(typeof a!="string"||a.length===0)return;let l=parseFloat(a);Number.isFinite(l)&&l>0&&s.set(n.name,l);}),s}function sn(e){let t=new Map;for(let r of e.assets){let s=r.market.markPrice&&r.market.markPrice>0?r.market.markPrice:r.market.price;Number.isFinite(s)&&s>0&&t.set(r.coin,s);}return t}function yo(e,t){let r=e.symbol.split("-")[0],s=e.side==="long"?"A":"B",n=s==="B",i,o;for(let a of t){if(a.coin!==r||a.reduceOnly!==true||a.isTrigger!==true||!(a.side===s||a.side===n))continue;let u=typeof a.orderType=="string"?a.orderType:"",c=/take\s*profit/i.test(u),p=/stop/i.test(u);c?(!i||a.timestamp>i.timestamp)&&(i=a):p&&(!o||a.timestamp>o.timestamp)&&(o=a);}return {tp:i?.triggerPx?parseFloat(i.triggerPx):void 0,sl:o?.triggerPx?parseFloat(o.triggerPx):void 0}}function ln(e,t,r){return e.map(s=>{let n={...s},{tp:i,sl:o}=yo(s,t);n.takeProfitPrice=i,n.stopLossPrice=o;let a=s.symbol.split("-")[0],l=r?.get(a);if(l&&Number.isFinite(l)&&l>0){n.markPrice=l;let u=s.side==="long"?1:-1,c=(l-s.entryPrice)*s.quantity*u;n.unrealizedPnl=c,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=c/s.margin*100);}return n})}var Te=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var ft=new Set(["settled","refunded","failed"]);var we=class extends Error{constructor(){super("perpetual wallet disconnected"),this.name="PerpetualDisconnectedError";}},qe=class extends Error{constructor(){super("perpetual order rejected"),this.name="PerpetualRejectedError";}};function go(e={}){let t=e.coins??["BTC-USDC"],r=new Map,s=0,n={symbol:"BTC-USDC",bids:[],asks:[],timestamp:0};return {market:{async getSupportedCoins(){return t},async getMarket(i){return t.includes(i)?{symbol:i,price:0,change24h:0,volume24h:0,fundingRate:0,openInterest:0,markPrice:0}:null},async getMarkets(i){let o=i??t,a=[];for(let l of o){let u=await this.getMarket(l);u&&a.push(u);}return a},async getKlines(){return []},async getOrderBook(){return n},async getRecentTrades(){return []},async getUniverseSnapshot(){return {assets:[],bySymbol:new Map,fetchedAt:0}},async getAssetMeta(){return null}},account:{async getPositions(){return {positions:[]}},async getOpenOrders(){return {orders:[]}},async getTrades(){return {trades:[]}},async getActiveAssetLeverage(){return null}},execution:{async placeOrder(i){if(e.disconnected)throw new we;if(e.rejectOrders)throw new qe;return {orderId:i.clientOrderId??"mem-1",symbol:i.symbol,side:i.side,orderType:i.orderType,status:"pending",timestamp:0}},async cancelOrder(i){if(e.disconnected)throw new we;return {orderId:i.orderId,symbol:i.symbol,status:"success",timestamp:0}}},realtime:{async connectWebSocket(){},disconnectWebSocket(){r.clear();},subscribeMarketData(i,o,a){let l=`m-${s++}`;return r.set(l,a),l},subscribeCandles(i,o,a){let l=`c-${s++}`;return r.set(l,a),l},subscribeUserData(i,o,a){let l=`u-${s++}`;return r.set(l,a),l},subscribeAccountState(i,o){let a=`a-${s++}`;return r.set(a,o),a},unsubscribe(i){r.delete(i);}}}}function bo(e){let t=0,r=new Set,s=null,n=i=>{r.add(i);let o=false;return {unsubscribe(){o||(o=true,r.delete(i),e.realtime.unsubscribe(i));}}};return {get generation(){return t},async connect(){t+=1,await e.realtime.connectWebSocket();},disconnect(){for(let i of [...r])r.delete(i),e.realtime.unsubscribe(i);e.realtime.disconnectWebSocket();},getUniverseSnapshot(){return s||(s=e.market.getUniverseSnapshot().finally(()=>{s=null;})),s},getMarket:i=>e.market.getMarket(i),getPositions:i=>e.account.getPositions(i),subscribeMarketData(i,o,a,l){return n(e.realtime.subscribeMarketData(i,o,a,l))},subscribeCandles(i,o,a){return n(e.realtime.subscribeCandles(i,o,a))},subscriptionCount(){return r.size}}}function ho(e){let t={status:"idle"},r=s=>(t=s,e.onChange?.(s),s);return {snapshot(){return t},async submit(s){if(!e.signer)return r({status:"disconnected",error:new we});r({status:"signing"});try{await e.signer.sign(s);}catch(n){let i=n instanceof Error?n:new Error(String(n));return r({status:"rejected",error:i})}r({status:"submitting"});try{let n=await e.execution.placeOrder(s);return n.status==="rejected"?r({status:"rejected",result:n,error:new qe}):n.status==="pending"?r({status:"pending",result:n}):r({status:"succeeded",result:n})}catch(n){if(n instanceof we)return r({status:"disconnected",error:n});if(n instanceof qe)return r({status:"rejected",error:n});let i=n instanceof Error?n:new Error(String(n));return r({status:"failed",error:i})}}}}var De=react.createContext({});function Po({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(De.Provider,{value:s,children:r})}function R(){let e=react.useContext(De);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function _r(){return ["perps","coins"]}async function Br(e){return await e.getSupportedCoins()}function Et(e={}){let{client:t}=R();return reactQuery.useQuery({queryKey:_r(),queryFn:async()=>Br(t),staleTime:300*1e3,...e})}var un=6e4;function ce(){return ["perps","universe"]}async function Se(e){if(typeof e.getUniverseSnapshot!="function")throw new Error("useUniverseQuery: the active perpetuals client does not implement getUniverseSnapshot()");return e.getUniverseSnapshot()}function xe(e){return typeof e.getUniverseSnapshot=="function"}function pn(e={}){let{client:t}=R(),r=xe(t)&&e.enabled!==false;return reactQuery.useQuery({queryKey:ce(),queryFn:()=>Se(t),refetchInterval:un,staleTime:un/2,...e,enabled:r})}var Rt=6e4;function Qr(e){return ["perps","market",e.symbol]}async function Kr(e,{symbol:t}){return await e.getMarket(t)}function tt(e,t={}){let{client:r}=R(),s=xe(r),n=reactQuery.useQuery({queryKey:ce(),queryFn:()=>Se(r),refetchInterval:Rt,staleTime:Rt/2,enabled:s&&t.enabled!==false&&!!e.symbol,select:o=>o.bySymbol.get(e.symbol)?.market??null}),i=reactQuery.useQuery({queryKey:Qr(e),queryFn:async()=>Kr(r,e),staleTime:Rt/2,refetchInterval:Rt,...t,enabled:!s&&t.enabled!==false&&!!e.symbol});return s?n:i}var At=6e4;function zr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function Wr(e,{symbols:t}={}){return await e.getMarkets(t)}function Ut(e={},t={}){let{client:r}=R(),s=xe(r),n=reactQuery.useQuery({queryKey:ce(),queryFn:()=>Se(r),refetchInterval:At,staleTime:At/2,enabled:s&&t.enabled!==false,select:o=>{if(!e.symbols||e.symbols.length===0)return o.assets.map(l=>l.market);let a=new Set(e.symbols);return o.assets.filter(l=>a.has(l.symbol)).map(l=>l.market)}}),i=reactQuery.useQuery({queryKey:zr(e),queryFn:async()=>Wr(r,e),staleTime:At/2,refetchInterval:At,...t,enabled:!s&&t.enabled!==false});return s?n:i}function $r(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Vr(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function mn(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:$r(e),queryFn:async()=>Vr(r,e),staleTime:30*1e3,...t})}function Gr(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 jr(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function It(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:Gr(e),queryFn:async()=>jr(r,e),staleTime:5*1e3,...t})}function Yr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Xr(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function Mt(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:Yr(e),queryFn:async()=>Xr(r,e),staleTime:5*1e3,...t})}function He(e){return ["perps","positions",e.userAddress??""]}async function Jr(e,t){return await e.getPositions(t)}function Ro(e,t){return {...e,positions:e.positions.filter(r=>r.symbol===t)}}function rt(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:He({userAddress:n}),queryFn:async()=>Jr(r,{userAddress:n}),enabled:s&&!!n,staleTime:10*1e3,select:i?o=>Ro(o,i):void 0,...t})}function _e(e){return ["perps","orders",e.userAddress??""]}async function Zr(e,t){return await e.getOpenOrders(t)}function Uo(e,t){let r=e.orders.filter(s=>s.symbol===t);return {...e,orders:r,totalCount:r.length}}function Nt(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:_e({userAddress:n}),queryFn:async()=>Zr(r,{userAddress:n}),enabled:s&&!!n,staleTime:5*1e3,select:i?o=>Uo(o,i):void 0,...t})}function es(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function ts(e,t){return await e.getTrades(t)}function Lt(e,t={}){let{client:r}=R(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:es(n),queryFn:async()=>ts(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function yt(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function rs(e,t){return await e.getActiveAssetLeverage(t)}function Ft(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:yt({userAddress:n,symbol:i}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return rs(r,{userAddress:n,symbol:i})},enabled:s&&!!n&&!!i,staleTime:30*1e3,...t})}var ss=6e4;function ns(e){return ["perps","assetMeta",e.symbol??""]}async function is(e,t){return await e.getAssetMeta(t)}function st(e,t={}){let{client:r}=R(),{enabled:s=true,symbol:n}=e,i=xe(r),o=reactQuery.useQuery({queryKey:ce(),queryFn:()=>Se(r),refetchInterval:ss,staleTime:ss/2,enabled:i&&s&&!!n,select:l=>n?l.bySymbol.get(n)?.meta??null:null}),a=reactQuery.useQuery({queryKey:ns({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return is(r,{symbol:n})},enabled:!i&&s&&!!n,staleTime:ss,...t});return i?o:a}async function os(e,t){return await e.placeOrder(t)}function qt(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>os(t,r),...e})}async function as(e,t){return await e.cancelOrder(t)}function Ht(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>as(t,r),...e})}function Ee(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=R(),[a,l]=react.useState(null),[u,c]=react.useState(false),[p,d]=react.useState(null),f=react.useRef(null),b=react.useRef(null),m=react.useRef(i);m.current=i;let v=react.useCallback(S=>{let T=m.current;if(!T||T<=0){l(S);return}f.current=S,b.current===null&&(b.current=setTimeout(()=>{if(b.current=null,f.current!==null){let x=f.current;f.current=null,l(x);}},T));},[]),g=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 S=null,T=true;return (async()=>{try{if(await o.connectWebSocket(),!T)return;c(!0),d(null),S=o.subscribeMarketData(t,r,w=>v(w),t==="orderBook"&&n?{aggregation:n}:void 0);}catch(w){T&&(d(w instanceof Error?w:new Error("Connection failed")),c(false));}})(),()=>{if(T=false,S)try{o.unsubscribe(S);}catch(w){console.error("Failed to unsubscribe:",w);}o.disconnectWebSocket(),b.current!==null&&(clearTimeout(b.current),b.current=null),f.current=null,c(false),l(null);}},[o,t,r,s,v,g,n]),{data:a,isConnected:u,error:p}}function yn(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null),p=react.useCallback(d=>{o(d);},[]);return react.useEffect(()=>{if(!s)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),c(null),d=n.subscribeCandles(t,r,p);}catch(m){f&&(c(m instanceof Error?m:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(m){console.error("Failed to unsubscribe:",m);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,p]),{data:i,isConnected:a,error:u}}function gn(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null),p=react.useCallback(d=>{o(d);},[]);return react.useEffect(()=>{if(!s||!r)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),c(null),d=n.subscribeUserData(t,r,m=>p(m));}catch(m){f&&(c(m instanceof Error?m:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(m){console.error("Failed to unsubscribe:",m);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,p]),{data:i,isConnected:a,error:u}}function Be(e){return ["perps","accountState",e.userAddress??""]}function _t(e,t={}){let{enabled:r=true,...s}=e;return reactQuery.useQuery({queryKey:Be(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function bn(e){let{userAddress:t,enabled:r=true}=e,{client:s}=R(),n=reactQuery.useQueryClient(),[i,o]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null);return react.useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let p=null,d=true,f=m=>{if(!d)return;o(m),n.setQueryData(Be({userAddress:t}),m);let v={positions:m.positions,totalEquity:m.totalEquity,availableBalance:m.availableBalance,totalUnrealizedPnl:m.totalUnrealizedPnl,raw:m.raw};n.setQueryData(He({userAddress:t}),v);let g={orders:m.openOrders,totalCount:m.openOrders.length,raw:m.raw};if(n.setQueryData(_e({userAddress:t}),g),m.universe&&n.setQueryData(ce(),m.universe),m.leverageByCoin)for(let[S,T]of Object.entries(m.leverageByCoin))n.setQueryData(yt({userAddress:t,symbol:`${S}-USDC`}),T);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),c(null),p=s.subscribeAccountState(t,f);}catch(m){if(!d)return;l(false),c(m instanceof Error?m:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,p)try{s.unsubscribe(p);}catch(m){console.error("[useAccountStateSubscription] unsubscribe failed:",m);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:i,isConnected:a,error:u}}function hn(e){let{userAddress:t,enabled:r=true,timeoutMs:s=3e3}=e,{client:n}=R(),i=reactQuery.useQueryClient();react.useEffect(()=>{if(!r||!t)return;let o=false,a=setTimeout(()=>{o||i.getQueryData(Be({userAddress:t}))||(async()=>{try{let[u,c]=await Promise.all([n.getPositions({userAddress:t}),n.getOpenOrders({userAddress:t})]);if(o)return;i.setQueryData(He({userAddress:t}),u),i.setQueryData(_e({userAddress:t}),c);}catch(u){process.env.NODE_ENV!=="production"&&console.warn("[useHyperliquidUserBootstrap] fallback REST failed:",u);}})();},s);return ()=>{o=true,clearTimeout(a);}},[n,i,t,r,s]);}function xn(){let e=react.useContext(De);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 Re(){return react.useContext(De)?.depositClient}function ms(e){return ["perps","deposit","quote",e]}async function fs(e,t){return e.quote(t)}function Bt(e,t={}){let r=Re(),s=(t.enabled??!!jo(e))&&!!r;return reactQuery.useQuery({queryKey:ms(e??null),queryFn:async()=>fs(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function jo(e){return !!(e&&e.originChainId&&e.userAddress&&e.hyperliquidRecipient&&e.grossAmount&&e.source)}var Qt={phase:"idle"};function ys(e,t){switch(t.type){case "RESET":return Qt;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,originTxHash:t.originTxHash}: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 Yo(t.status,r)}}}function Yo(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 Xo(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function Jo(e){return e.phase==="submitted"||e.phase==="tracking"}function Zo(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function ea(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 ta(e){return e!==void 0&&ft.has(e)}var de=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},ra=3e4,Qe=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??ra,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 l=await sa(a);throw new de(`HTTP ${a.status} ${a.statusText} from ${t} ${s}`,a.status,l)}return a.status===204?void 0:await a.json()}catch(a){if(a instanceof de)throw a;if(a instanceof Error&&a.name==="AbortError")throw new de(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new de(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(o);}}};async function sa(e){try{return await e.text()}catch{return ""}}function Kt(e){let t=Re(),[r,s]=react.useReducer(ys,Qt),n=ia(e),i=react.useCallback(()=>{s({type:"RESET"});},[]),o=react.useCallback(async a=>{let{quote:l}=a;s({type:"SIGN_START"});let u;try{if(u=await oa(l,n),!u)throw new Error("wallet returned an empty tx hash")}catch(p){let d=vn(p,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),p}s({type:"BROADCAST_START"});let c={userAddress:a.userAddress,hyperliquidRecipient:a.hyperliquidRecipient,originTxHash:u,breakdown:l.breakdown,userId:a.userId,source:a.source,campaign:a.campaign,quoteIssuedAt:l.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 p=await t.submit(c);return s({type:"SUBMIT_OK",intentId:p.intentId,originTxHash:u}),p.intentId}catch(p){let d=vn(p,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),p}},[t,n]);return {state:r,execute:o,reset:i,dispatch:s}}function ia(e){return typeof e=="function"?{solana:e}:e}async function oa(e,t){if(e.kind==="solana"){if(!t.solana)throw new Error("Solana signer is required for solana-origin deposits.");return t.solana(e.serializedTxBase64,{isVersioned:e.isVersioned,sizeBytes:e.sizeBytes})}if(e.kind==="evm"){if(!t.evm)throw new Error("EVM signer is required for evm-origin deposits.");let s=t.evm,n=s.getChainId(),i=e.evmTx.chainId,o=n!==void 0&&n!==i;(o||n===void 0)&&await s.switchChain(i);try{return await s.sendTransaction({chainId:e.evmTx.chainId,to:e.evmTx.to,data:e.evmTx.data,value:e.evmTx.value})}finally{o&&n!==void 0&&await s.switchChain(n).catch(a=>{typeof console<"u"&&console.warn("usePerpDepositExecute: failed to restore chain after EVM deposit",{from:i,to:n,err:a});});}}let r=e;throw new Error(`Unsupported quote kind: ${r.kind}`)}function vn(e,t){if(e instanceof de){let r=aa(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 aa(e){if(e)try{return JSON.parse(e)}catch{return}}function gs(e){return ["perps","deposit","status",e??null]}async function bs(e,t){return e.status(t)}function zt(e,t={}){let r=Re(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:gs(e??void 0),queryFn:async()=>bs(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&ft.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var nt={phase:"idle",steps:[]};function gt(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&ua(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 bt(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?pa(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 nt}}function ht(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 ua(e,t){return e.toLowerCase()===t.toLowerCase()}function pa(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 xt(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,l]=react.useReducer(bt,nt),u=react.useRef(t),c=react.useRef(s),p=react.useRef(i),d=react.useRef(o);u.current=t,c.current=s,p.current=i,d.current=o;let f=react.useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let S=await u.current.getAccountState(r),T=c.current.map(x=>({step:x,status:gt(x,S)}));l({type:"LOAD_SUCCESS",accountState:S,steps:T});}catch(S){let T=On(S);l({type:"LOAD_ERROR",error:T.message}),d.current?.(T,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let b=react.useCallback(async S=>{let T=a.steps[S];if(T){l({type:"RUN_STEP",index:S});try{let x=await da(u.current,T.step);l({type:"STEP_SUCCESS",index:S,txHash:x.txHash,accountState:x.state});}catch(x){let w=On(x);l({type:"STEP_ERROR",index:S,error:w.message}),d.current?.(w,{stepId:T.step.id});}}},[a.steps]),m=react.useCallback(async()=>{let S=ht(a);S!=null&&await b(S);},[a,b]),v=react.useCallback(()=>l({type:"RESET"}),[]),g=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!g.current?(g.current=true,p.current?.(a)):a.phase!=="done"&&(g.current=false);},[a]),{state:a,reload:f,runNext:m,runStep:b,reset:v}}function da(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 On(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function $t(){let{t:e}=i18n.useTranslation();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:e("perpetuals.coinInfo.notAvailable")})})}var Tn="liberfi-perp-shimmer",fa=`
|
|
2
|
-
@keyframes ${
|
|
3
|
-
`;function Ae(){return jsxRuntime.jsx("style",{children:fa})}var hs={backgroundColor:"rgba(255, 255, 255, 0.16)",backgroundImage:"linear-gradient(90deg, rgba(255,255,255,0) 25%, rgba(255,255,255,0.18) 50%, rgba(255,255,255,0) 75%)",backgroundSize:"200% 100%",animation:`${Tn} 1.8s ease-in-out infinite`,borderRadius:6};function me(e){return {...hs,animationDelay:`${e}ms`}}function Vt(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ae,{}),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:ze(0,84,23)}),jsxRuntime.jsx("div",{style:ze(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(Ss,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(Ss,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(Ss,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:ze(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:ze(330,64,17)}),jsxRuntime.jsx("div",{style:ze(360,64,17)})]})]})]})]})]})}function Ss({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:ze(r,e,16)}),jsxRuntime.jsx("div",{style:ze(r+30,t,17)})]})}function ze(e,t,r){return {...me(e),width:t,height:r}}function Gt(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:i,isPending:o}=tt({symbol:e}),{data:a}=Ee({type:"ticker",symbol:e,enabled:!!i});return react.useEffect(()=>{i&&r(i);},[i]),react.useEffect(()=>{if(!a)return;let l=ba(a,e);l&&r(u=>ha(u??i??void 0,l,e));},[a,i,e]),react.useEffect(()=>{let l=()=>{let c=Date.now(),p=3600*1e3,d=c%p,f=p-d;return Math.floor(f/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function ba(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 it(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function ha(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:it(t.price,e?.price??0),change24h:it(t.change24h,e?.change24h??0),volume24h:it(t.volume24h,e?.volume24h??0),fundingRate:it(t.fundingRate,e?.fundingRate??0),openInterest:it(t.openInterest,e?.openInterest??0),markPrice:it(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 va(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 Dn(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatAmountInUsd(e)}function En(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatPriceInUsd(e)}function jt({marketData:e,fundingCountdown:t}){let{t:r}=i18n.useTranslation(),{price:s,change24h:n,indexPrice:i,volume24h:o,openInterest:a,fundingRate:l}=e,u=typeof n=="number"&&Number.isFinite(n)?n:0,c=typeof l=="number"&&Number.isFinite(l)?l:0,p=u>=0,d=u.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:En(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:p?"#C7FF2E":"#F76816"},children:[p?"+":"",d,"%"]})]}),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:r("perpetuals.coinInfo.oraclePrice")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:i?En(i):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.volume24h")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Dn(o)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.openInterest")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Dn(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:r("perpetuals.coinInfo.funding")}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:c>=0?"#C7FF2E":"#F76816"},children:[(c*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:va(t)})]})]})]})]})}function Rn({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Gt(e);return r?jsxRuntime.jsx(Vt,{}):t?jsxRuntime.jsx(jt,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx($t,{})}function Yt({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:i,isPending:o}=Et(),{data:a,isPending:l}=Ut({symbols:i},{enabled:!!i&&i.length>0});react.useEffect(()=>{a&&n(a);},[a]);let u=react.useMemo(()=>{if(!t.trim())return s;let p=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(p))},[s,t]);return {coins:s,isLoading:o||l,searchQuery:t,setSearchQuery:r,filteredCoins:u,handleSelectCoin:p=>{e?.(p);}}}function Un(e){return utils.formatAmountInUsd(e)}function Ea(e){return utils.formatPriceInUsd(e)}function Xt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){let{t:i}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsxRuntime.jsx("div",{style:{padding:"16px 16px 12px"},children:jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsxRuntime.jsx(ui.SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsxRuntime.jsx("input",{type:"text",placeholder:i("perpetuals.searchCoins.placeholder"),value:t,onChange:o=>r(o.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxRuntime.jsxs("div",{className:"flex-1 overflow-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:i("perpetuals.searchCoins.col.token")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:i("perpetuals.searchCoins.col.lastPrice")}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:i("perpetuals.searchCoins.col.change24h")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:i("perpetuals.searchCoins.col.funding8h")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:i("perpetuals.searchCoins.col.volume24h")}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:i("perpetuals.searchCoins.col.openInterest")})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:i("perpetuals.searchCoins.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:i(t?"perpetuals.searchCoins.noCoins":"perpetuals.searchCoins.noCoinsAvailable")})}):e.map(o=>{let a=o.change24h>=0,l=o.change24h.toFixed(2),u=(o.fundingRate*100).toFixed(4),c=o.fundingRate>=0,p=o.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(o.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${p}.svg`,alt:p,className:"rounded-full",style:{width:20,height:20},onError:d=>{let f=d.target;f.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:p})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:Ea(o.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:a?"#C7FF2E":"#F76816",textAlign:"right"},children:[a?"+":"",l,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:c?"#C7FF2E":"#F76816",textAlign:"right"},children:[u,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Un(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Un(o.openInterest*o.price)})]},o.symbol)})]})]})}function Mn({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Yt({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(Xt,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function Cs(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 Fn(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 qn(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 Jt({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:l}=It({symbol:e,maxLevel:t}),u=react.useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,b=s?.asks[0]?.price??a?.asks[0]?.price,m=f&&b?(f+b)/2:b??f??0;return m>0?Math.floor(Math.log10(m)):null},[s,a]),c=react.useMemo(()=>{if(u===null)return;let f=Math.pow(10,u);return Cs(f,i)},[i,u]),{data:p}=Ee({type:"orderBook",symbol:e,enabled:!!a,aggregation:c,throttleMs:100});return react.useEffect(()=>{p?n(p):a&&n(a);},[p,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=Fn(s.bids,i,"bid"),b=Fn(s.asks,i,"ask"),m=f.sort((_,M)=>M.price-_.price).slice(0,t),v=b.sort((_,M)=>_.price-M.price).slice(0,t),g=qn(m),S=qn(v),T=g[0]?.price||0,w=(S[0]?.price||0)-T,H=T>0?w/T*100:0;return {bids:g,asks:S,spread:w,spreadPercentage:H}},[s,i,t]),isLoading:l,precision:i,setPrecision:o}}var _n={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Ma={backgroundColor:"#000000",fontSize:11},Na={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Os={flex:"1 1 0%"},La={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},Fa={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},qa={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},Ha={color:"#F76816",fontWeight:400},_a={color:"#C7FF2E",fontWeight:400},Bn={flex:"1 1 0%",color:"#ffffff"},Ba={flex:"1 1 0%"},Qa={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},Ka={gap:12,fontSize:12,color:"#ffffff"},za={color:"#ffffff"},Wa={color:"#ffffff",fontWeight:500},$a={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},Va={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)"},$n={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},Ga={...$n,color:"#C7FF2E"};function ja(e){return utils.formatPriceInUsd(e)}function Qn(e){return utils.formatAmount(e)}function Kn(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var zn=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",l=react.useMemo(()=>a?{...Fa,width:`${n}%`}:{...qa,width:`${n}%`},[a,n]),u=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:La,onClick:u,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Ba,children:jsxRuntime.jsx("span",{style:a?Ha:_a,children:ja(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Bn,children:Qn(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Bn,children:Qn(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 Ya({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let{t:n}=i18n.useTranslation(),[i,o]=react.useState(false),a=react.useRef(null);react.useEffect(()=>{if(!i)return;let u=c=>{a.current?.contains(c.target)||o(false);};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[i]);let l=react.useMemo(()=>({color:"#6b6b6b",transform:i?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[i]);return jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:Qa,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:Ka,children:[jsxRuntime.jsx("span",{style:za,children:n("perpetuals.orderbook.spread")}),jsxRuntime.jsxs("div",{ref:a,className:"relative",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-white/80 transition-colors",style:$a,onClick:()=>o(u=>!u),"aria-haspopup":"listbox","aria-expanded":i,children:[jsxRuntime.jsx("span",{children:Kn(t)}),jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:l,children:jsxRuntime.jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),i&&jsxRuntime.jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:Va,children:r.map(u=>{let c=u===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":c,className:"cursor-pointer transition-colors",style:c?Ga:$n,onMouseEnter:p=>{p.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(u),o(false);},children:Kn(u)},u)})})]}),jsxRuntime.jsxs("span",{style:Wa,children:[e.toFixed(3),"%"]})]})})}function er({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let{t:a}=i18n.useTranslation(),l=react.useRef(null),u=react.useRef(null),c=react.useRef(true),p=react.useRef(true),d=react.useMemo(()=>[...t].reverse(),[t]);react.useEffect(()=>{let m=l.current;if(!m||!c.current)return;let v=m.scrollHeight;m.scrollTop!==v&&(m.scrollTop=v);},[d]),react.useEffect(()=>{let m=u.current;!m||!p.current||m.scrollTop!==0&&(m.scrollTop=0);},[e]);let f=react.useCallback(()=>{let m=l.current;if(!m)return;let v=m.scrollHeight-m.scrollTop-m.clientHeight;c.current=v<=24;},[]),b=react.useCallback(()=>{let m=u.current;m&&(p.current=m.scrollTop<=24);},[]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Ma,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Na,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Os,children:a("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Os,children:a("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Os,children:a("perpetuals.orderbook.col.total")})]}),jsxRuntime.jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:_n,children:d.map((m,v)=>jsxRuntime.jsx(zn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"ask",onPriceClick:o},`ask-${m.price}-${v}`))}),jsxRuntime.jsx("div",{className:"flex-none",children:jsxRuntime.jsx(Ya,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsxRuntime.jsx("div",{ref:u,onScroll:b,className:"flex-1 min-h-0 overflow-y-auto",style:_n,children:e.map((m,v)=>jsxRuntime.jsx(zn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:o},`bid-${m.price}-${v}`))})]})}var Ts=[1,2,5,10,100,1e3],Xa={backgroundColor:"#000000",fontSize:11},Ja={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},ot={flex:"1 1 0%"},Za={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},el={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function tl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ja,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:ot,children:e("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ot,children:e("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ot,children:e("perpetuals.orderbook.col.total")})]})}function Vn({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Za,children:[jsxRuntime.jsx("div",{style:ot,children:jsxRuntime.jsx("div",{style:{...me(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ot,children:jsxRuntime.jsx("div",{style:{...me(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ot,children:jsxRuntime.jsx("div",{style:{...me(e+60),height:11,width:64}})})]})}function rl(){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(Ae,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Xa,children:[jsxRuntime.jsx(tl,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(Vn,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:el,children:jsxRuntime.jsx("div",{style:{...me(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(Vn,{delay:200+r*40},`bid-${r}`))})]})]})}function sl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:e("perpetuals.orderbook.empty")})})}function jn({symbol:e,maxLevel:t=40,precisionOptions:r=Ts,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:l,spreadPercentage:u,isLoading:c,precision:p,setPrecision:d}=Jt({symbol:e,maxLevel:t,precision:o});return c?jsxRuntime.jsx(rl,{}):a.length===0&&l.length===0?jsxRuntime.jsx(sl,{}):jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(er,{bids:a,asks:l,spreadPercentage:u,precision:p,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var ol=200;function rr({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:i}=Mt({symbol:e,limit:t}),{data:o}=Ee({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(Yn));},[n]);let a=react.useRef([]),l=react.useRef(null),u=react.useRef(t);return u.current=t,react.useEffect(()=>{if(!o)return;let c=al(o);c.length!==0&&(a.current.push(...c),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let p=a.current;a.current=[],p.length!==0&&s(d=>{let f=p.filter(b=>!d.some(m=>m.timestamp===b.timestamp&&m.price===b.price&&m.quantity===b.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,u.current)});},ol)));},[o]),react.useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function al(e){return (Array.isArray(e)?e:[e]).filter(Yn)}function Yn(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 sr=22,Xn=28,Jn=100,Zn=120,yl={backgroundColor:"#000000",fontSize:11},gl={height:Xn,minHeight:Xn,padding:"0 16px",color:"#6b6b6b",fontSize:11},bl={flex:"1 1 0%",maxWidth:Jn},hl={flex:"1 1 0%",marginLeft:20},Sl={flex:"1 1 0%",maxWidth:Zn,textAlign:"right"},xl={height:sr,minHeight:sr,maxHeight:sr,padding:"0 16px"},Pl={flex:"1 1 0%",maxWidth:Jn},vl={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Cl={flex:"1 1 0%",maxWidth:Zn,textAlign:"right",color:"#777A8C"},Ol={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},kl={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function Tl(e){return Number.isFinite(e)?utils.formatPriceInUsd(e):"-"}function wl(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"-"}function Dl(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 El(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Rl({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]),l=react.useMemo(()=>({...n?.side==="buy"?Ol:kl,width:`${El(a)}%`}),[n,a]);if(!n)return null;let u=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:xl,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Pl,children:jsxRuntime.jsx("span",{className:u?"text-bullish":"text-bearish",children:Tl(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:vl,children:wl(a)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Cl,children:Dl(o)})]})})}function nr({trades:e,onTradeClick:t}){let{t:r}=i18n.useTranslation(),s=react.useRef(null),{height:n=0}=hooks.useResizeObserver({ref:s}),i=react.useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:yl,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:gl,children:[jsxRuntime.jsx("div",{style:bl,children:r("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:hl,children:r("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:Sl,children:r("perpetuals.trades.col.age")})]}),jsxRuntime.jsx("div",{ref:s,className:"flex-1 min-h-0",children:n>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:n},rowComponent:Rl,rowCount:e.length,rowHeight:sr,rowProps:i,overscanCount:4})})]})}var Al={backgroundColor:"#000000",fontSize:11},Ul={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},ti={flex:"1 1 0%",maxWidth:100},ri={flex:"1 1 0%",marginLeft:20},si={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Il={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Ml(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ul,children:[jsxRuntime.jsx("div",{style:ti,children:e("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:ri,children:e("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:si,children:e("perpetuals.trades.col.age")})]})}function Nl({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Il,children:[jsxRuntime.jsx("div",{style:ti,children:jsxRuntime.jsx("div",{style:{...me(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:ri,children:jsxRuntime.jsx("div",{style:{...me(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:si,children:jsxRuntime.jsx("div",{style:{...me(e+60),height:11,width:28}})})]})}function Ll(){let e=Array.from({length:12},(t,r)=>r);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ae,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:Al,children:[jsxRuntime.jsx(Ml,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(Nl,{delay:t*35},`trade-${t}`))})]})]})}function Fl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-neutral-400 text-sm",children:e("perpetuals.trades.empty")})})}function ni({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=rr({symbol:e,limit:t});return i?jsxRuntime.jsx(Ll,{}):n.length===0?jsxRuntime.jsx(Fl,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(nr,{trades:n,onTradeClick:r})})}function ii(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function oi(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:ii(s,n)*(e-t)/t*r*100}function vt(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let i=ii(s,n),o=e/r/100;return t*(1+i*o)}function ai(e){if(!Number.isFinite(e)||e<=0)return e;let t=Math.floor(Math.log10(e)),s=10**Math.max(0,4-t);return Math.round(e*s)/s}function li(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var Kl=20;function or({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:o}){let[a,l]=react.useState("long"),[u,c]=react.useState("market"),p=reactHookForm.useForm({defaultValues:{amount:void 0,leverage:Kl,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=tt({symbol:e}),{data:f}=st({symbol:e}),b=f?.szDecimals,m=f?.maxLeverage??r,{mutateAsync:v,isPending:g}=qt({onSuccess:()=>{p.reset(),s?.();},onError:y=>{n?.(y);}}),S=reactQuery.useMutation({mutationFn:async y=>{if(!o)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await o(y)},onSuccess:()=>{p.reset(),s?.();},onError:y=>{n?.(y);}}),T=g||S.isPending,x=p.watch(),{amount:w,leverage:H,price:_}=x,M=d?.price||0,h=react.useMemo(()=>u==="limit"&&_?_:M,[u,_,M]),V=react.useMemo(()=>!w||w<=0||!H?0:w*H,[w,H]),re=react.useMemo(()=>V?V*5e-4:0,[V]),L=react.useMemo(()=>V?V+re:0,[V,re]),A=react.useMemo(()=>{if(!w||!h||!H||H===1||!f?.maxLeverage)return;let y=1/(2*f.maxLeverage),C=(1/H-y)/(a==="long"?1-y:1+y);return a==="long"?h*(1-C):h*(1+C)},[w,h,H,a,f?.maxLeverage]),{data:k}=rt({userAddress:t,symbol:e}),z=k?.totalEquity??0,J=k?.availableBalance??0,Ce=react.useMemo(()=>{let y=k?.positions?.[0];if(!y)return;let C=y.symbol.includes("-")?y.symbol.split("-")[0]:y.symbol;return {side:y.side,quantity:y.quantity,quantityRaw:y.quantityRaw,margin:y.margin,base:C}},[k?.positions]),{data:j}=_t({userAddress:t,enabled:!!t}),Oe=react.useMemo(()=>j?.openOrders?.length?j.openOrders.some(y=>y.symbol===e):false,[j?.openOrders,e]),{data:Fe}=Ft({userAddress:t,symbol:e}),Z=Fe?.value,ke=!t||Z!==void 0,te=react.useRef(null);react.useEffect(()=>{te.current!==e&&Z&&Z>0&&(p.setValue("leverage",Z),te.current=e);},[e,Z,p]),react.useEffect(()=>{te.current=null;},[e]),react.useEffect(()=>{if(!(typeof w!="number"||Number.isNaN(w))){if(w<0){p.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}J>0&&w>J&&p.setValue("amount",J,{shouldValidate:false,shouldDirty:true});}},[w,J,p]);let Je=react.useCallback(async y=>{if(!t)throw new Error("User address is required");if(!y.amount||y.amount<=0)throw new Error("Amount is required");let C=u==="limit"?y.price:void 0,F=y.takeProfitPrice,pe=y.stopLossPrice;if(!F&&y.takeProfitPercent&&y.takeProfitPercent>0&&h&&(F=vt(y.takeProfitPercent,h,y.leverage,a,"tp")),!pe&&y.stopLossPercent&&y.stopLossPercent>0&&h&&(pe=vt(y.stopLossPercent,h,y.leverage,a,"sl")),o){if(!h||h<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(b===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Ze=y.amount*y.leverage/h;await S.mutateAsync({symbol:e,side:a,orderType:u,amount:y.amount,price:C,leverage:y.leverage,takeProfitPrice:F,stopLossPrice:pe,userAddress:t,size:Ze,refPrice:h,szDecimals:b});return}await v({symbol:e,side:a,orderType:u,amount:y.amount,price:C,leverage:y.leverage,takeProfitPrice:F,stopLossPrice:pe,userAddress:t});},[e,a,u,h,b,t,o,S,v]);return {form:p,side:a,orderType:u,setSide:l,setOrderType:c,handleSubmit:Je,isSubmitting:T,currentPrice:h,marketPrice:M,estimatedFee:re,estimatedTotal:L,liquidationPrice:A,availableMargin:J,accountValue:z,currentPosition:Ce,maxLeverage:m,currentLeverage:Z,isLeverageReady:ke,hasOpenOrdersForSymbol:Oe,szDecimals:b,onUpdateLeverage:i}}var se="#C7FF2E",Xl=se,yi="#F76816",ci=yi;function Us(e,t){if(!/^#[0-9a-fA-F]{6}$/.test(e))return e;let r=Math.max(0,Math.min(255,Math.round(t)));return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}var Jl="https://app.hyperliquid.xyz/coins",Zl=10;function Fs(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var eu={...hs,display:"inline-block",width:28,height:14,borderRadius:4};function di(e){return utils.formatAmount(e)}function Is(e){return !Number.isFinite(e)||e<=0?"--":utils.formatPriceInUsd(e)}var Ie=1;function tu(e){let t=Math.max(Ie,Math.floor(e)),r=n=>{let i=Math.round(n);return i<=10?Math.max(Ie,i):Math.round(i/5)*5},s=new Set([Ie,t]);for(let n of [.25,.5,.75]){let i=r(t*n);i>Ie&&i<t&&s.add(i);}return Array.from(s).sort((n,i)=>n-i).map(n=>({value:n,label:`${n}x`}))}function ru({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:i,onConfirm:o,onUpdate:a,onClose:l}){let u=Math.max(Ie,Math.floor(r)),[c,p]=react.useState(Math.max(Ie,Math.min(t,u))),[d,f]=react.useState(false);react.useEffect(()=>{e&&(p(Math.max(Ie,Math.min(t,u))),f(false));},[e,t,u]);let b=react.useMemo(()=>tu(u),[u]),m=react.useCallback(async()=>{if(!d){if(!a){o(c),l();return}f(true);try{await a(c),o(c),l();}catch{f(false);}}},[d,a,c,o,l]),v=walletConnector.useAuthCallback(m),{t:g}=i18n.useTranslation();return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:S=>{d||S||l();},size:"md",hideCloseButton:true,backdrop:"opaque",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.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:g("perpetuals.placeOrder.leverage.title")}),jsxRuntime.jsx("button",{type:"button",onClick:l,disabled:d,"aria-label":g("common.cancel"),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.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-5 pt-2 flex flex-col gap-4",children:[jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[n?jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ci},children:g("perpetuals.placeOrder.leverage.cannotUpdate",{symbol:s})}):jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:g("perpetuals.placeOrder.leverage.desc")}),i&&jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ci},children:g("perpetuals.placeOrder.leverage.ordersAffected",{symbol:s})})]}),jsxRuntime.jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[jsxRuntime.jsx("style",{children:`
|
|
4
|
-
.perp-leverage-slider [data-slot="track"] { background-color:
|
|
1
|
+
'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),i18n=require('@liberfi.io/i18n'),utils=require('@liberfi.io/utils'),ui$1=require('@liberfi.io/ui'),reactWindow=require('react-window'),hooks=require('@liberfi.io/hooks'),reactHookForm=require('react-hook-form'),walletConnector=require('@liberfi.io/wallet-connector');var ai=new Set(["userFills","userFillsByTime","userFunding","userNonFundingLedgerUpdates","frontendOpenOrders","userRateLimit","historicalOrders","userTwapSliceFills","predictedFundings"]);function Hr(e){return e&&ai.has(e)?20:2}var nn=1,mt=class{capacity;windowMs;tokens;lastRefill;constructor(t={}){this.capacity=t.capacity??1200,this.windowMs=t.windowMs??6e4,this.tokens=this.capacity,this.lastRefill=Date.now();}reset(){this.tokens=this.capacity,this.lastRefill=Date.now();}async waitForToken(t){let r=Math.max(1,Math.floor(t));for(;;){if(this.refill(),this.tokens>=r){this.tokens-=r;return}let s=Math.max(25,this.windowMs-(Date.now()-this.lastRefill));await new Promise(n=>setTimeout(n,s));}}refill(){let t=Date.now();t-this.lastRefill>=this.windowMs&&(this.tokens=this.capacity,this.lastRefill=t);}};function oe(e){return e!==null&&typeof e=="object"?e:{}}function z(e,t="0"){return parseFloat(String(typeof e=="number"?e:e??t))}function li(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 Ze=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;connectPromise=null;manuallyDisconnected=false;constructor(t){this.wsEndpoint=t;}async connect(){if(!(this.isConnected&&this.ws?.readyState===WebSocket.OPEN))return this.connectPromise?this.connectPromise:(this.manuallyDisconnected=false,this.connectPromise=new Promise((t,r)=>{let s=false,n=o=>{s||(s=true,this.connectPromise=null,o());};try{let o=new WebSocket(this.wsEndpoint);this.ws=o,o.onopen=()=>{this.ws===o&&(console.warn("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},o.onmessage=i=>{this.ws===o&&this.handleMessage(i.data);},o.onerror=i=>{this.ws===o&&(console.error("[WebSocket] Error:",i),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},o.onclose=i=>{this.ws===o&&(console.warn(`[WebSocket] Closed: ${i.code} - ${i.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${i.code}`))),!this.manuallyDisconnected&&i.code!==1e3&&this.attemptReconnect());};}catch(o){n(()=>r(o));}}),this.connectPromise)}disconnect(){this.manuallyDisconnected=true,this.stopHeartbeat(),this.subscriptions.clear(),this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(1e3,"Normal closure"),this.ws=null),this.isConnected=false,this.isReconnecting=false,this.reconnectAttempts=0;}attemptReconnect(){if(this.isReconnecting)return;if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[WebSocket] Max reconnection attempts reached");return}this.isReconnecting=true,this.reconnectAttempts++;let t=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.warn(`[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=oe(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=oe(t),s=r.channel;this.subscriptions.forEach((n,o)=>{if(this.isChannelMatch(s,n.type,n.param,r))try{let i=this.transformData(n.type,r.data,n.param);n.callback(i);}catch(i){console.error(`[WebSocket] Error in subscription callback (${o}):`,i);}});}isChannelMatch(t,r,s,n){let o=oe(n).data;if(r==="ticker"){if(t!=="activeAssetCtx")return false;let i=s.split("-")[0],a=oe(o).coin;return typeof a=="string"&&a===i}else if(r==="trades"){if(t!=="trades")return false;let i=s.split("-")[0],a=Array.isArray(o)?oe(o[0]).coin:void 0;return typeof a!="string"||a===i}else if(r==="orderBook"){if(t!=="l2Book")return false;let i=s.split("-")[0],a=oe(o).coin;return typeof a=="string"&&a===i}else {if(r==="candle")return t==="candle";if(r==="userFills")return t==="userFills";if(r==="userEvents")return t==="userEvents";if(r==="accountState")return t==="webData2"}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 s=oe(t),o=`${typeof s.coin=="string"?s.coin:r.split("-")[0]}-USDC`,i=oe(s.ctx),a=z(i.midPx??i.markPx),l=z(i.markPx??i.midPx),u=i.prevDayPx?z(i.prevDayPx):a,c=u>0?(a-u)/u*100:0;return {symbol:o,price:a,change24h:c,volume24h:z(i.dayNtlVlm),fundingRate:z(i.funding),openInterest:z(i.openInterest),markPrice:l,indexPrice:z(i.oraclePx??i.midPx)}}transformTradesData(t,r){return Array.isArray(t)?t.map(s=>{let n=oe(s);return {symbol:r,side:n.side==="B"?"buy":"sell",price:z(n.px),quantity:z(n.sz),timestamp:n.time,tradeId:n.tid}}):[]}transformOrderBookData(t,r){let s=oe(t),n=Array.isArray(s.levels)?s.levels:[[],[]],o=Array.isArray(n[0])?n[0]:[],i=Array.isArray(n[1])?n[1]:[],a=l=>{let u=oe(l);return {price:z(u.px),quantity:z(u.sz),count:u.n}};return {symbol:r,bids:o.map(a),asks:i.map(a),timestamp:typeof s.time=="number"?s.time:Date.now()}}transformCandleData(t,r){let[s]=r.split(":"),n=oe(t);return {symbol:s,open:z(n.o),high:z(n.h),low:z(n.l),close:z(n.c),volume:z(n.v),timestamp:z(n.t),closeTimestamp:z(n.T)}}transformUserFillsData(t){return Array.isArray(t)?t.map(r=>{let s=oe(r);return {tradeId:s.tid!=null?String(s.tid):void 0,orderId:s.oid!=null?String(s.oid):void 0,symbol:`${String(s.coin??"")}-USDC`,side:typeof s.dir=="string"&&s.dir.includes("Long")?"long":"short",price:z(s.px),quantity:z(s.sz),fee:z(s.fee),feeCurrency:typeof s.feeToken=="string"?s.feeToken:"USDC",isMaker:s.side==="M",timestamp:s.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 i={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa)),n={method:"subscribe",subscription:i};}else if(t==="candle"){let[o,i]=r.split(":");n={method:"subscribe",subscription:{type:"candle",coin:o.split("-")[0],interval:i}};}else t==="userFills"?n={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"?n={method:"subscribe",subscription:{type:"userEvents",user:r}}:t==="accountState"&&(n={method:"subscribe",subscription:{type:"webData2",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 i={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa)),n={method:"unsubscribe",subscription:i};}else if(t==="candle"){let[o,i]=r.split(":");n={method:"unsubscribe",subscription:{type:"candle",coin:o.split("-")[0],interval:i}};}else t==="userFills"?n={method:"unsubscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"?n={method:"unsubscribe",subscription:{type:"userEvents",user:r}}:t==="accountState"&&(n={method:"unsubscribe",subscription:{type:"webData2",user:r}});n&&this.send(n);}subscribe(t,r,s,n){let o=li(t,r,n);return this.subscriptions.set(o,{type:t,param:r,callback:s,aggregation:n}),this.sendSubscription(t,r,n),o}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 on={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"}},ui=60*1e3,pi=1500,ci=1500,_r=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;assetMetaCache=null;assetMetaPending=null;universeSnapshotCache=null;universeSnapshotPending=null;userStateCache=new Map;userStatePending=new Map;rateLimiter;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||on[this.environment].api,this._wsEndpoint=t.wsEndpoint||on[this.environment].ws,this.timeout=t.timeout||3e4,t.rateLimit===false?this.rateLimiter=null:t.rateLimit instanceof mt?this.rateLimiter=t.rateLimit:this.rateLimiter=new mt(t.rateLimit);}weightFor(t,r){if(t.startsWith("/exchange"))return nn;if(t.startsWith("/info")){let s=r&&typeof r=="object"&&"type"in r&&typeof r.type=="string"?r.type:void 0;return Hr(s)}return Hr(void 0)}async request(t,r){let s=`${this.apiEndpoint}${t}`;this.rateLimiter&&await this.rateLimiter.waitForToken(this.weightFor(t,r));try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(o),!i.ok)throw new Te(`HTTP ${i.status}: ${i.statusText}`,i.status,await i.text());return await i.json()}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Te(`Request timeout after ${this.timeout}ms`,408,""):n instanceof Te?n:new Te(`Network error: ${n instanceof Error?n.message:String(n)}`,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(){return (await this.getUniverseSnapshot()).assets.map(r=>r.symbol)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let r=await this.getUniverseSnapshot();if(t&&t.length>0){let s=new Set(t);return r.assets.map(n=>n.market).filter(n=>s.has(n.symbol))}return r.assets.map(s=>s.market)}async getUniverseSnapshot(){let t=Date.now();if(this.universeSnapshotCache&&t-this.universeSnapshotCache.fetchedAt<pi)return this.universeSnapshotCache.snapshot;if(this.universeSnapshotPending)return this.universeSnapshotPending;let r=this.fetchUniverseSnapshot();this.universeSnapshotPending=r;try{let s=await r;return this.universeSnapshotCache={fetchedAt:Date.now(),snapshot:s},s}finally{this.universeSnapshotPending=null;}}async fetchUniverseSnapshot(){let[t,r]=await this.request("/info",{type:"metaAndAssetCtxs"}),s=t.universe.map((o,i)=>{let a=r[i]??{},l=`${o.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx?parseFloat(a.prevDayPx):u,p=c>0?(u-c)/c*100:0,d={symbol:l,price:u,change24h:p,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")},f=typeof o.szDecimals=="number"?{szDecimals:o.szDecimals,maxLeverage:o.maxLeverage}:null;return {coin:o.name,symbol:l,market:d,meta:f}}),n=new Map;for(let o of s)n.set(o.symbol,o);return {assets:s,bySymbol:n,fetchedAt:Date.now()}}async getUserStateSnapshot(t){let r=t.toLowerCase(),s=Date.now(),n=this.userStateCache.get(r);if(n&&s-n.fetchedAt<ci)return n.snapshot;let o=this.userStatePending.get(r);if(o)return o;let i=(async()=>{let[a,l]=await Promise.all([this.request("/info",{type:"clearinghouseState",user:t}),this.request("/info",{type:"frontendOpenOrders",user:t}).catch(()=>{})]);return {clearinghouse:a,openOrders:l,fetchedAt:Date.now()}})();this.userStatePending.set(r,i);try{let a=await i;return this.userStateCache.set(r,{fetchedAt:Date.now(),snapshot:a}),a}finally{this.userStatePending.delete(r);}}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),o=typeof s=="number"?{limit:s}:s,i=this.parseInterval(r),a=o.limit,l,u;o.from!==void 0&&o.to!==void 0?(l=o.from,u=o.to):o.to!==void 0&&a?(u=o.to,l=u-i*a):o.from!==void 0&&a?(l=o.from,u=l+i*a):(u=Date.now(),l=u-i*(a??100));let p=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:u}})).map(d=>({symbol:t,open:parseFloat(d.o),high:parseFloat(d.h),low:parseFloat(d.l),close:parseFloat(d.c),volume:parseFloat(d.v),timestamp:d.t,closeTimestamp:d.T}));return a&&p.length>a&&(p=p.slice(p.length-a)),p}async getOrderBook(t,r=10,s){let o={type:"l2Book",coin:this.symbolToCoin(t)};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa));let i=await this.request("/info",o),[a,l]=i.levels;return {symbol:t,bids:a.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),asks:l.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),timestamp:i.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(o=>({symbol:t,side:o.side==="B"?"buy":"sell",price:parseFloat(o.px),quantity:parseFloat(o.sz),timestamp:o.time,tradeId:o.tid}))}async placeOrder(t){throw new Error("placeOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async cancelOrder(t){throw new Error("cancelOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async getPositions(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let[r,s]=await Promise.all([this.getUserStateSnapshot(t.userAddress),this.getUniverseSnapshot()]),n=ln(r.clearinghouse,t.symbol),o=an(s);return n.positions=cn(n.positions,r.openOrders??[],o),n.totalUnrealizedPnl=n.positions.reduce((i,a)=>i+a.unrealizedPnl,0),n}async getActiveAssetLeverage(t){let r=this.symbolToCoin(t.symbol);try{let n=(await this.request("/info",{type:"activeAssetData",coin:r,user:t.userAddress}))?.leverage;return !n||typeof n.value!="number"?null:{value:n.value,type:n.type}}catch(s){if(s instanceof Te&&(s.statusCode===422||s.statusCode===400))return null;throw s}}async getAssetMeta(t){let r=await this.fetchAssetUniverse(),s=this.symbolToCoin(t.symbol);return r.get(s)??null}async fetchAssetUniverse(){let t=Date.now();if(this.assetMetaCache&&t-this.assetMetaCache.fetchedAt<ui)return this.assetMetaCache.map;if(this.assetMetaPending)return this.assetMetaPending;let r=(async()=>{let s=await this.request("/info",{type:"meta"}),n=new Map;for(let o of s.universe)!o||typeof o.name!="string"||typeof o.szDecimals=="number"&&n.set(o.name,{szDecimals:o.szDecimals,maxLeverage:o.maxLeverage});return this.assetMetaCache={fetchedAt:Date.now(),map:n},n})();this.assetMetaPending=r;try{return await r}finally{this.assetMetaPending=null;}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let[r,s]=await Promise.all([this.getUserStateSnapshot(t.userAddress).catch(()=>null),this.getUniverseSnapshot().catch(()=>{})]),n=r?.openOrders??[],o={leverageByCoin:pn(r?.clearinghouse),markByCoin:s?an(s):void 0},i=n.map(l=>un(l,o)),a=t.symbol?i.filter(l=>l.symbol===t.symbol):i;return {orders:a,totalCount:a.length,raw:n}}async getTrades(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"userFills",user:t.userAddress}),s=r.map(n=>{let o=`${n.coin}-USDC`,i=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:o,side:i?"long":"short",price:parseFloat(n.px),quantity:parseFloat(n.sz),fee:parseFloat(n.fee||"0"),feeCurrency:n.feeToken||"USDC",isMaker:n.side==="M",timestamp:n.time,dir:n.dir,closedPnl:parseFloat(n.closedPnl||"0")}});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 Ze(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,o=>s(o))}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)}subscribeAccountState(t,r){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe("accountState",t,s=>{r(fi(s));})}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}};function ln(e,t){let r=e.assetPositions.map(i=>{let a=i.position,l=`${a.coin}-USDC`,u=parseFloat(a.szi);if(u===0)return null;let c=parseFloat(a.entryPx),p=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:u>0?"long":"short",quantity:Math.abs(u),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:c,markPrice:c,unrealizedPnl:p,unrealizedPnlPercent:parseFloat(a.returnOnEquity)*100,leverage:a.leverage.value,liquidationPrice:a.liquidationPx?parseFloat(a.liquidationPx):void 0,margin:parseFloat(a.marginUsed),notionalValue:Math.abs(d)}}).filter(i=>i!==null),s=t?r.filter(i=>i.symbol===t):r,n=e.withdrawable,o=typeof n=="string"&&n.length>0?parseFloat(n):parseFloat(e.marginSummary.accountValue)-parseFloat(e.marginSummary.totalMarginUsed);return {positions:s,totalEquity:parseFloat(e.marginSummary.accountValue),availableBalance:o,totalUnrealizedPnl:s.reduce((i,a)=>i+a.unrealizedPnl,0),raw:e}}function di(e){if(!e.children||e.children.length===0)return {};let t,r;for(let s of e.children){let n=typeof s.orderType=="string"?s.orderType:"",o=s.triggerPx;if(typeof o!="string"||o.length===0)continue;let i=parseFloat(o);!Number.isFinite(i)||i<=0||(/take\s*profit/i.test(n)?t=i:/stop/i.test(n)&&(r=i));}return {takeProfitPrice:t,stopLossPrice:r}}function un(e,t){let r=`${e.coin}-USDC`,s=parseFloat(e.origSz),n=parseFloat(e.sz),o=s-n,i=e.side===true||e.side==="B",a=typeof e.orderType=="string"?e.orderType:"Limit",u=/^market$/i.test(a)?"market":"limit",c=e.isTrigger===true,p;c&&(/take\s*profit/i.test(a)?p="tp":/stop/i.test(a)&&(p="sl"));let d=typeof e.triggerPx=="string"&&e.triggerPx.length>0?parseFloat(e.triggerPx):void 0,f=typeof e.triggerCondition=="string"&&e.triggerCondition!=="N/A"?e.triggerCondition:void 0,{takeProfitPrice:g,stopLossPrice:m}=di(e),P=t?.leverageByCoin?.get(e.coin),b=t?.markByCoin?.get(e.coin);return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:r,side:i?"long":"short",orderType:u,price:parseFloat(e.limitPx),quantity:s,filledQuantity:o,remainingQuantity:n,status:o>0&&n>0?"partially_filled":"pending",timestamp:e.timestamp,updateTimestamp:e.timestamp,leverage:P,reduceOnly:e.reduceOnly===true,isTrigger:c||void 0,triggerPx:d,triggerType:p,triggerCondition:f,markPrice:b,takeProfitPrice:g,stopLossPrice:m}}function pn(e){let t=new Map;if(!e)return t;for(let r of e.assetPositions??[]){let s=r.position?.leverage?.value;typeof s=="number"&&Number.isFinite(s)&&s>0&&t.set(r.position.coin,s);}return t}function mi(e){return e?e.map(t=>({coin:t.coin,total:parseFloat(t.total),totalRaw:t.total,hold:parseFloat(t.hold),entryNotional:t.entryNtl?parseFloat(t.entryNtl):void 0})):[]}function fi(e){let t=e.clearinghouseState,r=t?ln(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=mi(e.spotState?.balances),o=e.meta&&e.assetCtxs?bi([e.meta,e.assetCtxs]):null,i=pn(t),a=s.map(d=>un(d,{leverageByCoin:i,markByCoin:o??void 0})),l=cn(r.positions,s,o),u=l.reduce((d,f)=>d+f.unrealizedPnl,0),c=e.meta&&e.assetCtxs?yi(e.meta,e.assetCtxs,e.serverTime):void 0,p=t?gi(t):void 0;return {positions:l,openOrders:a,spotBalances:n,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:u,serverTime:e.serverTime,leverageByCoin:p,universe:c,raw:e}}function yi(e,t,r){let s=e.universe.map((o,i)=>{let a=t[i]??{},l=`${o.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx,p=c?parseFloat(c):u,d=p>0?(u-p)/p*100:0,f={symbol:l,price:u,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")},g=o.szDecimals,m=o.maxLeverage,P=typeof g=="number"?{szDecimals:g,maxLeverage:m}:null;return {coin:o.name,symbol:l,market:f,meta:P}}),n=new Map;for(let o of s)n.set(o.symbol,o);return {assets:s,bySymbol:n,fetchedAt:r??Date.now()}}function gi(e){let t={};for(let r of e.assetPositions??[]){let s=r.position?.leverage;if(!s||typeof s.value!="number")continue;let n=s.type==="isolated"||s.type==="cross"?s.type:"cross";t[r.position.coin]={value:s.value,type:n};}return t}function bi(e){let[t,r]=e,s=new Map;return t.universe.forEach((n,o)=>{let i=r[o];if(!i)return;let a=i.markPx??i.midPx??i.oraclePx;if(typeof a!="string"||a.length===0)return;let l=parseFloat(a);Number.isFinite(l)&&l>0&&s.set(n.name,l);}),s}function an(e){let t=new Map;for(let r of e.assets){let s=r.market.markPrice&&r.market.markPrice>0?r.market.markPrice:r.market.price;Number.isFinite(s)&&s>0&&t.set(r.coin,s);}return t}function hi(e,t){let r=e.symbol.split("-")[0],s=e.side==="long"?"A":"B",n=s==="B",o,i;for(let a of t){if(a.coin!==r||a.reduceOnly!==true||a.isTrigger!==true||!(a.side===s||a.side===n))continue;let u=typeof a.orderType=="string"?a.orderType:"",c=/take\s*profit/i.test(u),p=/stop/i.test(u);c?(!o||a.timestamp>o.timestamp)&&(o=a):p&&(!i||a.timestamp>i.timestamp)&&(i=a);}return {tp:o?.triggerPx?parseFloat(o.triggerPx):void 0,sl:i?.triggerPx?parseFloat(i.triggerPx):void 0}}function cn(e,t,r){return e.map(s=>{let n={...s},{tp:o,sl:i}=hi(s,t);n.takeProfitPrice=o,n.stopLossPrice=i;let a=s.symbol.split("-")[0],l=r?.get(a);if(l&&Number.isFinite(l)&&l>0){n.markPrice=l;let u=s.side==="long"?1:-1,c=(l-s.entryPrice)*s.quantity*u;n.unrealizedPnl=c,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=c/s.margin*100);}return n})}var Te=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var ft=new Set(["settled","refunded","failed"]);var De=class extends Error{constructor(){super("perpetual wallet disconnected"),this.name="PerpetualDisconnectedError";}},qe=class extends Error{constructor(){super("perpetual order rejected"),this.name="PerpetualRejectedError";}};function xi(e={}){let t=e.coins??["BTC-USDC"],r=new Map,s=0,n={symbol:"BTC-USDC",bids:[],asks:[],timestamp:0};return {market:{async getSupportedCoins(){return t},async getMarket(o){return t.includes(o)?{symbol:o,price:0,change24h:0,volume24h:0,fundingRate:0,openInterest:0,markPrice:0}:null},async getMarkets(o){let i=o??t,a=[];for(let l of i){let u=await this.getMarket(l);u&&a.push(u);}return a},async getKlines(){return []},async getOrderBook(){return n},async getRecentTrades(){return []},async getUniverseSnapshot(){return {assets:[],bySymbol:new Map,fetchedAt:0}},async getAssetMeta(){return null}},account:{async getPositions(){return {positions:[]}},async getOpenOrders(){return {orders:[]}},async getTrades(){return {trades:[]}},async getActiveAssetLeverage(){return null}},execution:{async placeOrder(o){if(e.disconnected)throw new De;if(e.rejectOrders)throw new qe;return {orderId:o.clientOrderId??"mem-1",symbol:o.symbol,side:o.side,orderType:o.orderType,status:"pending",timestamp:0}},async cancelOrder(o){if(e.disconnected)throw new De;return {orderId:o.orderId,symbol:o.symbol,status:"success",timestamp:0}}},realtime:{async connectWebSocket(){},disconnectWebSocket(){r.clear();},subscribeMarketData(o,i,a){let l=`m-${s++}`;return r.set(l,a),l},subscribeCandles(o,i,a){let l=`c-${s++}`;return r.set(l,a),l},subscribeUserData(o,i,a){let l=`u-${s++}`;return r.set(l,a),l},subscribeAccountState(o,i){let a=`a-${s++}`;return r.set(a,i),a},unsubscribe(o){r.delete(o);}}}}function Si(e){let t=0,r=new Set,s=null,n=o=>{r.add(o);let i=false;return {unsubscribe(){i||(i=true,r.delete(o),e.realtime.unsubscribe(o));}}};return {get generation(){return t},async connect(){t+=1,await e.realtime.connectWebSocket();},disconnect(){for(let o of [...r])r.delete(o),e.realtime.unsubscribe(o);e.realtime.disconnectWebSocket();},getUniverseSnapshot(){return s||(s=e.market.getUniverseSnapshot().finally(()=>{s=null;})),s},getMarket:o=>e.market.getMarket(o),getPositions:o=>e.account.getPositions(o),subscribeMarketData(o,i,a,l){return n(e.realtime.subscribeMarketData(o,i,a,l))},subscribeCandles(o,i,a){return n(e.realtime.subscribeCandles(o,i,a))},subscriptionCount(){return r.size}}}function vi(e){let t={status:"idle"},r=s=>(t=s,e.onChange?.(s),s);return {snapshot(){return t},async submit(s){if(!e.signer)return r({status:"disconnected",error:new De});r({status:"signing"});try{await e.signer.sign(s);}catch(n){let o=n instanceof Error?n:new Error(String(n));return r({status:"rejected",error:o})}r({status:"submitting"});try{let n=await e.execution.placeOrder(s);return n.status==="rejected"?r({status:"rejected",result:n,error:new qe}):n.status==="pending"?r({status:"pending",result:n}):r({status:"succeeded",result:n})}catch(n){if(n instanceof De)return r({status:"disconnected",error:n});if(n instanceof qe)return r({status:"rejected",error:n});let o=n instanceof Error?n:new Error(String(n));return r({status:"failed",error:o})}}}}var we=react.createContext({});function Oi({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(we.Provider,{value:s,children:r})}function E(){let e=react.useContext(we);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Br(){return ["perps","coins"]}async function Qr(e){return await e.getSupportedCoins()}function Et(e={}){let{client:t}=E();return reactQuery.useQuery({queryKey:Br(),queryFn:async()=>Qr(t),staleTime:300*1e3,...e})}var dn=6e4;function ce(){return ["perps","universe"]}async function xe(e){if(typeof e.getUniverseSnapshot!="function")throw new Error("useUniverseQuery: the active perpetuals client does not implement getUniverseSnapshot()");return e.getUniverseSnapshot()}function Se(e){return typeof e.getUniverseSnapshot=="function"}function mn(e={}){let{client:t}=E(),r=Se(t)&&e.enabled!==false;return reactQuery.useQuery({queryKey:ce(),queryFn:()=>xe(t),refetchInterval:dn,staleTime:dn/2,...e,enabled:r})}var Rt=6e4;function Kr(e){return ["perps","market",e.symbol]}async function Wr(e,{symbol:t}){return await e.getMarket(t)}function et(e,t={}){let{client:r}=E(),s=Se(r),n=reactQuery.useQuery({queryKey:ce(),queryFn:()=>xe(r),refetchInterval:Rt,staleTime:Rt/2,enabled:s&&t.enabled!==false&&!!e.symbol,select:i=>i.bySymbol.get(e.symbol)?.market??null}),o=reactQuery.useQuery({queryKey:Kr(e),queryFn:async()=>Wr(r,e),staleTime:Rt/2,refetchInterval:Rt,...t,enabled:!s&&t.enabled!==false&&!!e.symbol});return s?n:o}var At=6e4;function zr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function $r(e,{symbols:t}={}){return await e.getMarkets(t)}function Ut(e={},t={}){let{client:r}=E(),s=Se(r),n=reactQuery.useQuery({queryKey:ce(),queryFn:()=>xe(r),refetchInterval:At,staleTime:At/2,enabled:s&&t.enabled!==false,select:i=>{if(!e.symbols||e.symbols.length===0)return i.assets.map(l=>l.market);let a=new Set(e.symbols);return i.assets.filter(l=>a.has(l.symbol)).map(l=>l.market)}}),o=reactQuery.useQuery({queryKey:zr(e),queryFn:async()=>$r(r,e),staleTime:At/2,refetchInterval:At,...t,enabled:!s&&t.enabled!==false});return s?n:o}function Vr(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Gr(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function gn(e,t={}){let{client:r}=E();return reactQuery.useQuery({queryKey:Vr(e),queryFn:async()=>Gr(r,e),staleTime:30*1e3,...t})}function jr(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 Yr(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function It(e,t={}){let{client:r}=E();return reactQuery.useQuery({queryKey:jr(e),queryFn:async()=>Yr(r,e),staleTime:5*1e3,...t})}function Xr(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Jr(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function Mt(e,t={}){let{client:r}=E();return reactQuery.useQuery({queryKey:Xr(e),queryFn:async()=>Jr(r,e),staleTime:5*1e3,...t})}function He(e){return ["perps","positions",e.userAddress??""]}async function Zr(e,t){return await e.getPositions(t)}function Ii(e,t){return {...e,positions:e.positions.filter(r=>r.symbol===t)}}function tt(e,t={}){let{client:r}=E(),{enabled:s=true,userAddress:n,symbol:o}=e;return reactQuery.useQuery({queryKey:He({userAddress:n}),queryFn:async()=>Zr(r,{userAddress:n}),enabled:s&&!!n,staleTime:10*1e3,select:o?i=>Ii(i,o):void 0,...t})}function _e(e){return ["perps","orders",e.userAddress??""]}async function es(e,t){return await e.getOpenOrders(t)}function Ni(e,t){let r=e.orders.filter(s=>s.symbol===t);return {...e,orders:r,totalCount:r.length}}function Nt(e,t={}){let{client:r}=E(),{enabled:s=true,userAddress:n,symbol:o}=e;return reactQuery.useQuery({queryKey:_e({userAddress:n}),queryFn:async()=>es(r,{userAddress:n}),enabled:s&&!!n,staleTime:5*1e3,select:o?i=>Ni(i,o):void 0,...t})}function ts(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function rs(e,t){return await e.getTrades(t)}function Lt(e,t={}){let{client:r}=E(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:ts(n),queryFn:async()=>rs(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function yt(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function ss(e,t){return await e.getActiveAssetLeverage(t)}function Ft(e,t={}){let{client:r}=E(),{enabled:s=true,userAddress:n,symbol:o}=e;return reactQuery.useQuery({queryKey:yt({userAddress:n,symbol:o}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return ss(r,{userAddress:n,symbol:o})},enabled:s&&!!n&&!!o,staleTime:30*1e3,...t})}var ns=6e4;function os(e){return ["perps","assetMeta",e.symbol??""]}async function is(e,t){return await e.getAssetMeta(t)}function rt(e,t={}){let{client:r}=E(),{enabled:s=true,symbol:n}=e,o=Se(r),i=reactQuery.useQuery({queryKey:ce(),queryFn:()=>xe(r),refetchInterval:ns,staleTime:ns/2,enabled:o&&s&&!!n,select:l=>n?l.bySymbol.get(n)?.meta??null:null}),a=reactQuery.useQuery({queryKey:os({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return is(r,{symbol:n})},enabled:!o&&s&&!!n,staleTime:ns,...t});return o?i:a}async function as(e,t){return await e.placeOrder(t)}function qt(e={}){let{client:t}=E();return reactQuery.useMutation({mutationFn:async r=>as(t,r),...e})}async function ls(e,t){return await e.cancelOrder(t)}function Ht(e={}){let{client:t}=E();return reactQuery.useMutation({mutationFn:async r=>ls(t,r),...e})}function Ee(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:o}=e,{client:i}=E(),[a,l]=react.useState(null),[u,c]=react.useState(false),[p,d]=react.useState(null),f=react.useRef(null),g=react.useRef(null),m=react.useRef(o);m.current=o;let P=react.useCallback(S=>{let T=m.current;if(!T||T<=0){l(S);return}f.current=S,g.current===null&&(g.current=setTimeout(()=>{if(g.current=null,f.current!==null){let x=f.current;f.current=null,l(x);}},T));},[]),b=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 S=null,T=true;return (async()=>{try{if(await i.connectWebSocket(),!T)return;c(!0),d(null),S=i.subscribeMarketData(t,r,D=>P(D),t==="orderBook"&&n?{aggregation:n}:void 0);}catch(D){T&&(d(D instanceof Error?D:new Error("Connection failed")),c(false));}})(),()=>{if(T=false,S)try{i.unsubscribe(S);}catch(D){console.error("Failed to unsubscribe:",D);}i.disconnectWebSocket(),g.current!==null&&(clearTimeout(g.current),g.current=null),f.current=null,c(false),l(null);}},[i,t,r,s,P,b,n]),{data:a,isConnected:u,error:p}}function hn(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=E(),[o,i]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null),p=react.useCallback(d=>{i(d);},[]);return react.useEffect(()=>{if(!s)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),c(null),d=n.subscribeCandles(t,r,p);}catch(m){f&&(c(m instanceof Error?m:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(m){console.error("Failed to unsubscribe:",m);}n.disconnectWebSocket(),l(false),i(null);}},[n,t,r,s,p]),{data:o,isConnected:a,error:u}}function xn(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=E(),[o,i]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null),p=react.useCallback(d=>{i(d);},[]);return react.useEffect(()=>{if(!s||!r)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),c(null),d=n.subscribeUserData(t,r,m=>p(m));}catch(m){f&&(c(m instanceof Error?m:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(m){console.error("Failed to unsubscribe:",m);}n.disconnectWebSocket(),l(false),i(null);}},[n,t,r,s,p]),{data:o,isConnected:a,error:u}}function Be(e){return ["perps","accountState",e.userAddress??""]}function _t(e,t={}){let{enabled:r=true,...s}=e;return reactQuery.useQuery({queryKey:Be(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function Sn(e){let{userAddress:t,enabled:r=true}=e,{client:s}=E(),n=reactQuery.useQueryClient(),[o,i]=react.useState(null),[a,l]=react.useState(false),[u,c]=react.useState(null);return react.useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let p=null,d=true,f=m=>{if(!d)return;i(m),n.setQueryData(Be({userAddress:t}),m);let P={positions:m.positions,totalEquity:m.totalEquity,availableBalance:m.availableBalance,totalUnrealizedPnl:m.totalUnrealizedPnl,raw:m.raw};n.setQueryData(He({userAddress:t}),P);let b={orders:m.openOrders,totalCount:m.openOrders.length,raw:m.raw};if(n.setQueryData(_e({userAddress:t}),b),m.universe&&n.setQueryData(ce(),m.universe),m.leverageByCoin)for(let[S,T]of Object.entries(m.leverageByCoin))n.setQueryData(yt({userAddress:t,symbol:`${S}-USDC`}),T);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),c(null),p=s.subscribeAccountState(t,f);}catch(m){if(!d)return;l(false),c(m instanceof Error?m:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,p)try{s.unsubscribe(p);}catch(m){console.error("[useAccountStateSubscription] unsubscribe failed:",m);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:o,isConnected:a,error:u}}function vn(e){let{userAddress:t,enabled:r=true,timeoutMs:s=3e3}=e,{client:n}=E(),o=reactQuery.useQueryClient();react.useEffect(()=>{if(!r||!t)return;let i=false,a=setTimeout(()=>{i||o.getQueryData(Be({userAddress:t}))||(async()=>{try{let[u,c]=await Promise.all([n.getPositions({userAddress:t}),n.getOpenOrders({userAddress:t})]);if(i)return;o.setQueryData(He({userAddress:t}),u),o.setQueryData(_e({userAddress:t}),c);}catch(u){process.env.NODE_ENV!=="production"&&console.warn("[useHyperliquidUserBootstrap] fallback REST failed:",u);}})();},s);return ()=>{i=true,clearTimeout(a);}},[n,o,t,r,s]);}function Cn(){let e=react.useContext(we);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 Re(){return react.useContext(we)?.depositClient}function fs(e){return ["perps","deposit","quote",e]}async function ys(e,t){return e.quote(t)}function Bt(e,t={}){let r=Re(),s=(t.enabled??!!Ji(e))&&!!r;return reactQuery.useQuery({queryKey:fs(e??null),queryFn:async()=>ys(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Ji(e){return !!(e&&e.originChainId&&e.userAddress&&e.hyperliquidRecipient&&e.grossAmount&&e.source)}var Qt={phase:"idle"};function gs(e,t){switch(t.type){case "RESET":return Qt;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,originTxHash:t.originTxHash}: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 Zi(t.status,r)}}}function Zi(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 ea(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function ta(e){return e.phase==="submitted"||e.phase==="tracking"}function ra(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function sa(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 na(e){return e!==void 0&&ft.has(e)}var de=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},oa=3e4,Qe=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??oa,this.headers=t.headers,this.defaultQuery=t.defaultQuery,this.fetchImpl=t.fetchImpl??globalThis.fetch.bind(globalThis);}getBaseUrl(){return this.baseUrl}buildUrl(t,r){let s=new URLSearchParams;if(this.defaultQuery)for(let[o,i]of Object.entries(this.defaultQuery))i===void 0||i===""||s.set(o,i);if(r)for(let[o,i]of Object.entries(r))i===void 0||i===""||s.set(o,i);let n=s.toString();return `${this.baseUrl}${t}${n?`?${n}`:""}`}async request(t,r){let s=this.buildUrl(r.path,r.query),n=new AbortController,o=r.timeoutMs??this.timeout,i=setTimeout(()=>n.abort(),o);try{let a=await this.fetchImpl(s,{method:t,headers:{Accept:"application/json",...t==="POST"?{"Content-Type":"application/json"}:{},...this.headers,...r.headers},body:t==="POST"?JSON.stringify(r.body??{}):void 0,signal:n.signal});if(!a.ok){let l=await ia(a);throw new de(`HTTP ${a.status} ${a.statusText} from ${t} ${s}`,a.status,l)}return a.status===204?void 0:await a.json()}catch(a){if(a instanceof de)throw a;if(a instanceof Error&&a.name==="AbortError")throw new de(`Request timeout after ${o}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new de(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(i);}}};async function ia(e){try{return await e.text()}catch{return ""}}function Kt(e){let t=Re(),[r,s]=react.useReducer(gs,Qt),n=la(e),o=react.useCallback(()=>{s({type:"RESET"});},[]),i=react.useCallback(async a=>{let{quote:l}=a;s({type:"SIGN_START"});let u;try{if(u=await ua(l,n),!u)throw new Error("wallet returned an empty tx hash")}catch(p){let d=kn(p,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),p}s({type:"BROADCAST_START"});let c={userAddress:a.userAddress,hyperliquidRecipient:a.hyperliquidRecipient,originTxHash:u,breakdown:l.breakdown,userId:a.userId,source:a.source,campaign:a.campaign,quoteIssuedAt:l.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 p=await t.submit(c);return s({type:"SUBMIT_OK",intentId:p.intentId,originTxHash:u}),p.intentId}catch(p){let d=kn(p,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),p}},[t,n]);return {state:r,execute:i,reset:o,dispatch:s}}function la(e){return typeof e=="function"?{solana:e}:e}async function ua(e,t){if(e.kind==="solana"){if(!t.solana)throw new Error("Solana signer is required for solana-origin deposits.");return t.solana(e.serializedTxBase64,{isVersioned:e.isVersioned,sizeBytes:e.sizeBytes})}if(e.kind==="evm"){if(!t.evm)throw new Error("EVM signer is required for evm-origin deposits.");let s=t.evm,n=s.getChainId(),o=e.evmTx.chainId,i=n!==void 0&&n!==o;(i||n===void 0)&&await s.switchChain(o);try{return await s.sendTransaction({chainId:e.evmTx.chainId,to:e.evmTx.to,data:e.evmTx.data,value:e.evmTx.value})}finally{i&&n!==void 0&&await s.switchChain(n).catch(a=>{typeof console<"u"&&console.warn("usePerpDepositExecute: failed to restore chain after EVM deposit",{from:o,to:n,err:a});});}}let r=e;throw new Error(`Unsupported quote kind: ${r.kind}`)}function kn(e,t){if(e instanceof de){let r=pa(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 pa(e){if(e)try{return JSON.parse(e)}catch{return}}function bs(e){return ["perps","deposit","status",e??null]}async function hs(e,t){return e.status(t)}function Wt(e,t={}){let r=Re(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:bs(e??void 0),queryFn:async()=>hs(r,e),enabled:s,refetchInterval:o=>{let i=o.state.data;return i&&ft.has(i.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var st={phase:"idle",steps:[]};function gt(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&da(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 bt(e,t){switch(t.type){case "START_LOADING":return {phase:"loading",steps:e.steps,accountState:e.accountState};case "LOAD_SUCCESS":return {phase:t.steps.every(s=>s.status==="skipped"||s.status==="done")?"done":"ready",accountState:t.accountState,steps:t.steps};case "LOAD_ERROR":return {phase:"error",steps:e.steps,error:t.error};case "RUN_STEP":return {phase:"executing",steps:e.steps.map((s,n)=>n===t.index?{...s,status:"running",error:void 0}:s),accountState:e.accountState,currentIndex:t.index};case "STEP_SUCCESS":{let r=e.steps.map((o,i)=>i===t.index?{...o,status:"done",txHash:t.txHash,error:void 0}:o),s=t.accountState&&e.accountState?ma(e.accountState,t.accountState):t.accountState??e.accountState;return {phase:r.every(o=>o.status==="skipped"||o.status==="done")?"done":"ready",steps:r,accountState:s,currentIndex:void 0}}case "STEP_ERROR":return {phase:"ready",steps:e.steps.map((s,n)=>n===t.index?{...s,status:"error",error:t.error}:s),accountState:e.accountState,currentIndex:void 0};case "RESET":return st}}function ht(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 da(e,t){return e.toLowerCase()===t.toLowerCase()}function ma(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 St(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:o,onError:i}=e,[a,l]=react.useReducer(bt,st),u=react.useRef(t),c=react.useRef(s),p=react.useRef(o),d=react.useRef(i);u.current=t,c.current=s,p.current=o,d.current=i;let f=react.useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let S=await u.current.getAccountState(r),T=c.current.map(x=>({step:x,status:gt(x,S)}));l({type:"LOAD_SUCCESS",accountState:S,steps:T});}catch(S){let T=Dn(S);l({type:"LOAD_ERROR",error:T.message}),d.current?.(T,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let g=react.useCallback(async S=>{let T=a.steps[S];if(T){l({type:"RUN_STEP",index:S});try{let x=await ya(u.current,T.step);l({type:"STEP_SUCCESS",index:S,txHash:x.txHash,accountState:x.state});}catch(x){let D=Dn(x);l({type:"STEP_ERROR",index:S,error:D.message}),d.current?.(D,{stepId:T.step.id});}}},[a.steps]),m=react.useCallback(async()=>{let S=ht(a);S!=null&&await g(S);},[a,g]),P=react.useCallback(()=>l({type:"RESET"}),[]),b=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!b.current?(b.current=true,p.current?.(a)):a.phase!=="done"&&(b.current=false);},[a]),{state:a,reload:f,runNext:m,runStep:g,reset:P}}function ya(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 Dn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function $t(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-surface-raised border-b border-border-subtle",children:jsxRuntime.jsx("span",{className:"text-text-secondary text-sm",children:e("perpetuals.coinInfo.notAvailable")})})}var En="liberfi-perp-shimmer",ba=`
|
|
2
|
+
@keyframes ${En}{0%{background-position:200% 0}100%{background-position:-200% 0}}
|
|
3
|
+
`;function Ae(){return jsxRuntime.jsx("style",{children:ba})}var xs={backgroundColor:"rgba(255, 255, 255, 0.16)",backgroundImage:"linear-gradient(90deg, rgba(255,255,255,0) 25%, rgba(255,255,255,0.18) 50%, rgba(255,255,255,0) 75%)",backgroundSize:"200% 100%",animation:`${En} 1.8s ease-in-out infinite`,borderRadius:6};function me(e){return {...xs,animationDelay:`${e}ms`}}function Vt(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ae,{}),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:We(0,84,23)}),jsxRuntime.jsx("div",{style:We(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(Ss,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(Ss,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(Ss,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:We(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:We(330,64,17)}),jsxRuntime.jsx("div",{style:We(360,64,17)})]})]})]})]})]})}function Ss({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:We(r,e,16)}),jsxRuntime.jsx("div",{style:We(r+30,t,17)})]})}function We(e,t,r){return {...me(e),width:t,height:r}}function Gt(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:o,isPending:i}=et({symbol:e}),{data:a}=Ee({type:"ticker",symbol:e,enabled:!!o});return react.useEffect(()=>{o&&r(o);},[o]),react.useEffect(()=>{if(!a)return;let l=Sa(a,e);l&&r(u=>va(u??o??void 0,l,e));},[a,o,e]),react.useEffect(()=>{let l=()=>{let c=Date.now(),p=3600*1e3,d=c%p,f=p-d;return Math.floor(f/1e3)};n(l());let u=setInterval(()=>{n(l());},1e3);return ()=>clearInterval(u)},[]),{marketData:t,isLoading:i,fundingCountdown:s}}function Sa(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 nt(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function va(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:nt(t.price,e?.price??0),change24h:nt(t.change24h,e?.change24h??0),volume24h:nt(t.volume24h,e?.volume24h??0),fundingRate:nt(t.fundingRate,e?.fundingRate??0),openInterest:nt(t.openInterest,e?.openInterest??0),markPrice:nt(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 ka(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 An(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatAmountInUsd(e)}function Un(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatPriceInUsd(e)}function jt({marketData:e,fundingCountdown:t}){let{t:r}=i18n.useTranslation(),{price:s,change24h:n,indexPrice:o,volume24h:i,openInterest:a,fundingRate:l}=e,u=typeof n=="number"&&Number.isFinite(n)?n:0,c=typeof l=="number"&&Number.isFinite(l)?l:0,p=u>=0,d=u.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:"var(--color-text-primary)"},children:Un(s)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:p?"var(--color-positive)":"var(--color-negative)"},children:[p?"+":"",d,"%"]})]}),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:"var(--color-text-secondary)",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.oraclePrice")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"var(--color-text-primary)"},children:o?Un(o):"-"})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-secondary)",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.volume24h")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"var(--color-text-primary)"},children:An(i)})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-secondary)",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.openInterest")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"var(--color-text-primary)"},children:An(a*(e.markPrice||s))})]}),jsxRuntime.jsxs("div",{className:"flex flex-col",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-secondary)",lineHeight:"16px",letterSpacing:"-0.12px"},children:r("perpetuals.coinInfo.funding")}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:c>=0?"var(--color-positive)":"var(--color-negative)"},children:[(c*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"var(--color-text-primary)"},children:ka(t)})]})]})]})]})}function In({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Gt(e);return r?jsxRuntime.jsx(Vt,{}):t?jsxRuntime.jsx(jt,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx($t,{})}function Yt({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:o,isPending:i}=Et(),{data:a,isPending:l}=Ut({symbols:o},{enabled:!!o&&o.length>0});react.useEffect(()=>{a&&n(a);},[a]);let u=react.useMemo(()=>{if(!t.trim())return s;let p=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(p))},[s,t]);return {coins:s,isLoading:i||l,searchQuery:t,setSearchQuery:r,filteredCoins:u,handleSelectCoin:p=>{e?.(p);}}}function Nn(e){return utils.formatAmountInUsd(e)}function Ua(e){return utils.formatPriceInUsd(e)}function Xt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){let{t:o}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{backgroundColor:"var(--color-surface-raised)",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 var(--color-border-control)",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:"var(--color-text-muted)"}}),jsxRuntime.jsx("input",{type:"text",placeholder:o("perpetuals.searchCoins.placeholder"),value:t,onChange:i=>r(i.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"var(--color-text-primary)",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 var(--color-border-subtle)",position:"sticky",top:0,backgroundColor:"var(--color-surface-raised)",zIndex:1},children:[jsxRuntime.jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"var(--color-text-muted)"},children:o("perpetuals.searchCoins.col.token")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"var(--color-text-muted)",textAlign:"right"},children:o("perpetuals.searchCoins.col.lastPrice")}),jsxRuntime.jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"var(--color-text-muted)",textAlign:"right"},children:o("perpetuals.searchCoins.col.change24h")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"var(--color-text-muted)",textAlign:"right"},children:o("perpetuals.searchCoins.col.funding8h")}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"var(--color-text-muted)",textAlign:"right"},children:o("perpetuals.searchCoins.col.volume24h")}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"var(--color-text-muted)",textAlign:"right"},children:o("perpetuals.searchCoins.col.openInterest")})]}),n?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:o("perpetuals.searchCoins.loading")})}):e.length===0?jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:o(t?"perpetuals.searchCoins.noCoins":"perpetuals.searchCoins.noCoinsAvailable")})}):e.map(i=>{let a=i.change24h>=0,l=i.change24h.toFixed(2),u=(i.fundingRate*100).toFixed(4),c=i.fundingRate>=0,p=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 var(--color-border-subtle)"},onClick:()=>s(i.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="hsl(var(--heroui-foreground) / 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/${p}.svg`,alt:p,className:"rounded-full",style:{width:20,height:20},onError:d=>{let f=d.target;f.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"var(--color-text-primary)"},children:p})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"var(--color-text-primary)",textAlign:"right"},children:Ua(i.price)}),jsxRuntime.jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:a?"var(--color-positive)":"var(--color-negative)",textAlign:"right"},children:[a?"+":"",l,"%"]}),jsxRuntime.jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:c?"var(--color-positive)":"var(--color-negative)",textAlign:"right"},children:[u,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"var(--color-text-secondary)",textAlign:"right"},children:Nn(i.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"var(--color-text-secondary)",textAlign:"right"},children:Nn(i.openInterest*i.price)})]},i.symbol)})]})]})}function Fn({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:o,handleSelectCoin:i}=Yt({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(Xt,{coins:r,searchQuery:n,onSearchChange:o,onSelectCoin:i,isLoading:s})})}function Os(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,o=null;for(let i of s)i.step<=t+n&&(!o||i.step>o.step)&&(o=i);return o?o.mantissa&&o.mantissa!==1?{nSigFigs:o.nSigFigs,mantissa:o.mantissa}:{nSigFigs:o.nSigFigs}:{nSigFigs:5}}function _n(e,t,r){if(t<=0)return e;let s=new Map,n=r==="ask"?Math.ceil:Math.floor;return e.forEach(o=>{let i=n(o.price/t)*t,a=s.get(i);a?(a.quantity+=o.quantity,o.count&&(a.count=(a.count||0)+o.count)):s.set(i,{price:i,quantity:o.quantity,count:o.count});}),Array.from(s.values())}function Bn(e){let t=0,r=e.map(n=>{let o=n.quantity*n.price;return t+=o,{...n,quantity:o,total:t,percentage:0}}),s=t;return r.map(n=>({...n,percentage:s>0?n.total/s*100:0}))}function Jt({symbol:e,maxLevel:t=20,precision:r=1}){let[s,n]=react.useState(null),[o,i]=react.useState(r);react.useEffect(()=>{i(r);},[r]);let{data:a,isPending:l}=It({symbol:e,maxLevel:t}),u=react.useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,g=s?.asks[0]?.price??a?.asks[0]?.price,m=f&&g?(f+g)/2:g??f??0;return m>0?Math.floor(Math.log10(m)):null},[s,a]),c=react.useMemo(()=>{if(u===null)return;let f=Math.pow(10,u);return Os(f,o)},[o,u]),{data:p}=Ee({type:"orderBook",symbol:e,enabled:!!a,aggregation:c,throttleMs:100});return react.useEffect(()=>{p?n(p):a&&n(a);},[p,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=_n(s.bids,o,"bid"),g=_n(s.asks,o,"ask"),m=f.sort((_,M)=>M.price-_.price).slice(0,t),P=g.sort((_,M)=>_.price-M.price).slice(0,t),b=Bn(m),S=Bn(P),T=b[0]?.price||0,D=(S[0]?.price||0)-T,H=T>0?D/T*100:0;return {bids:b,asks:S,spread:D,spreadPercentage:H}},[s,o,t]),isLoading:l,precision:o,setPrecision:i}}var Kn={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Fa={backgroundColor:"#000000",fontSize:11},qa={height:28,minHeight:28,padding:"0 16px",gap:16,color:"var(--color-text-muted)",fontSize:11},ks={flex:"1 1 0%"},Ha={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},_a={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},Ba={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},Qa={color:"#F76816",fontWeight:400},Ka={color:"#C7FF2E",fontWeight:400},Wn={flex:"1 1 0%",color:"var(--color-text-primary)"},Wa={flex:"1 1 0%"},za={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},$a={gap:12,fontSize:12,color:"var(--color-text-primary)"},Va={color:"var(--color-text-primary)"},Ga={color:"var(--color-text-primary)",fontWeight:500},ja={color:"var(--color-text-primary)",fontWeight:400,background:"none",border:"none",padding:0,gap:4},Ya={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)"},jn={padding:"4px 10px",fontSize:12,color:"var(--color-text-primary)",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},Xa={...jn,color:"#C7FF2E"};function Ja(e){return utils.formatPriceInUsd(e)}function zn(e){return utils.formatAmount(e)}function $n(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var Vn=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:o,onPriceClick:i}){let a=o==="ask",l=react.useMemo(()=>a?{..._a,width:`${n}%`}:{...Ba,width:`${n}%`},[a,n]),u=react.useMemo(()=>i?()=>i(t):void 0,[i,t]);return jsxRuntime.jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Ha,onClick:u,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Wa,children:jsxRuntime.jsx("span",{style:a?Qa:Ka,children:Ja(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Wn,children:zn(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Wn,children:zn(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 Za({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let{t:n}=i18n.useTranslation(),[o,i]=react.useState(false),a=react.useRef(null);react.useEffect(()=>{if(!o)return;let u=c=>{a.current?.contains(c.target)||i(false);};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[o]);let l=react.useMemo(()=>({color:"var(--color-text-muted)",transform:o?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[o]);return jsxRuntime.jsx("div",{className:"flex items-center justify-center",style:za,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:$a,children:[jsxRuntime.jsx("span",{style:Va,children:n("perpetuals.orderbook.spread")}),jsxRuntime.jsxs("div",{ref:a,className:"relative",children:[jsxRuntime.jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-text-primary/80 transition-colors",style:ja,onClick:()=>i(u=>!u),"aria-haspopup":"listbox","aria-expanded":o,children:[jsxRuntime.jsx("span",{children:$n(t)}),jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:l,children:jsxRuntime.jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),o&&jsxRuntime.jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:Ya,children:r.map(u=>{let c=u===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":c,className:"cursor-pointer transition-colors",style:c?Xa:jn,onMouseEnter:p=>{p.currentTarget.style.backgroundColor="hsl(var(--heroui-foreground) / 0.06)";},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(u),i(false);},children:$n(u)},u)})})]}),jsxRuntime.jsxs("span",{style:Ga,children:[e.toFixed(3),"%"]})]})})}function er({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:o,onPriceClick:i}){let{t:a}=i18n.useTranslation(),l=react.useRef(null),u=react.useRef(null),c=react.useRef(true),p=react.useRef(true),d=react.useMemo(()=>[...t].reverse(),[t]);react.useEffect(()=>{let m=l.current;if(!m||!c.current)return;let P=m.scrollHeight;m.scrollTop!==P&&(m.scrollTop=P);},[d]),react.useEffect(()=>{let m=u.current;!m||!p.current||m.scrollTop!==0&&(m.scrollTop=0);},[e]);let f=react.useCallback(()=>{let m=l.current;if(!m)return;let P=m.scrollHeight-m.scrollTop-m.clientHeight;c.current=P<=24;},[]),g=react.useCallback(()=>{let m=u.current;m&&(p.current=m.scrollTop<=24);},[]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Fa,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:qa,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:ks,children:a("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ks,children:a("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ks,children:a("perpetuals.orderbook.col.total")})]}),jsxRuntime.jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:Kn,children:d.map((m,P)=>jsxRuntime.jsx(Vn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"ask",onPriceClick:i},`ask-${m.price}-${P}`))}),jsxRuntime.jsx("div",{className:"flex-none",children:jsxRuntime.jsx(Za,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:o})}),jsxRuntime.jsx("div",{ref:u,onScroll:g,className:"flex-1 min-h-0 overflow-y-auto",style:Kn,children:e.map((m,P)=>jsxRuntime.jsx(Vn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:i},`bid-${m.price}-${P}`))})]})}var Ds=[1,2,5,10,100,1e3],el={backgroundColor:"#000000",fontSize:11},tl={height:28,minHeight:28,padding:"0 16px",gap:16,color:"var(--color-text-muted)",fontSize:11},ot={flex:"1 1 0%"},rl={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},sl={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function nl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:tl,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:ot,children:e("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ot,children:e("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:ot,children:e("perpetuals.orderbook.col.total")})]})}function Yn({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:rl,children:[jsxRuntime.jsx("div",{style:ot,children:jsxRuntime.jsx("div",{style:{...me(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ot,children:jsxRuntime.jsx("div",{style:{...me(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:ot,children:jsxRuntime.jsx("div",{style:{...me(e+60),height:11,width:64}})})]})}function ol(){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(Ae,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:el,children:[jsxRuntime.jsx(nl,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(Yn,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:sl,children:jsxRuntime.jsx("div",{style:{...me(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(Yn,{delay:200+r*40},`bid-${r}`))})]})]})}function il(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-text-secondary text-sm",children:e("perpetuals.orderbook.empty")})})}function Jn({symbol:e,maxLevel:t=40,precisionOptions:r=Ds,defaultPrecision:s,onPriceClick:n,className:o}){let i=s??r[0]??1,{bids:a,asks:l,spreadPercentage:u,isLoading:c,precision:p,setPrecision:d}=Jt({symbol:e,maxLevel:t,precision:i});return c?jsxRuntime.jsx(ol,{}):a.length===0&&l.length===0?jsxRuntime.jsx(il,{}):jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsx(er,{bids:a,asks:l,spreadPercentage:u,precision:p,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var ul=200;function rr({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:o}=Mt({symbol:e,limit:t}),{data:i}=Ee({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(Zn));},[n]);let a=react.useRef([]),l=react.useRef(null),u=react.useRef(t);return u.current=t,react.useEffect(()=>{if(!i)return;let c=pl(i);c.length!==0&&(a.current.push(...c),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let p=a.current;a.current=[],p.length!==0&&s(d=>{let f=p.filter(g=>!d.some(m=>m.timestamp===g.timestamp&&m.price===g.price&&m.quantity===g.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,u.current)});},ul)));},[i]),react.useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:o}}function pl(e){return (Array.isArray(e)?e:[e]).filter(Zn)}function Zn(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 sr=22,eo=28,to=100,ro=120,hl={backgroundColor:"#000000",fontSize:11},xl={height:eo,minHeight:eo,padding:"0 16px",color:"var(--color-text-muted)",fontSize:11},Sl={flex:"1 1 0%",maxWidth:to},vl={flex:"1 1 0%",marginLeft:20},Pl={flex:"1 1 0%",maxWidth:ro,textAlign:"right"},Cl={height:sr,minHeight:sr,maxHeight:sr,padding:"0 16px"},Ol={flex:"1 1 0%",maxWidth:to},kl={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Tl={flex:"1 1 0%",maxWidth:ro,textAlign:"right",color:"#777A8C"},Dl={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},wl={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function El(e){return Number.isFinite(e)?utils.formatPriceInUsd(e):"-"}function Rl(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"-"}function Al(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 Ul(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Il({index:e,style:t,trades:r,onTradeClick:s}){let n=r[e],o=n?.timestamp??Date.now(),i=hooks.useTickAge(o),a=react.useMemo(()=>!n||!Number.isFinite(n.price)||!Number.isFinite(n.quantity)?0:n.price*n.quantity,[n]),l=react.useMemo(()=>({...n?.side==="buy"?Dl:wl,width:`${Ul(a)}%`}),[n,a]);if(!n)return null;let u=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:Cl,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Ol,children:jsxRuntime.jsx("span",{className:u?"text-positive":"text-negative",children:El(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:kl,children:Rl(a)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:Tl,children:Al(i)})]})})}function nr({trades:e,onTradeClick:t}){let{t:r}=i18n.useTranslation(),s=react.useRef(null),{height:n=0}=hooks.useResizeObserver({ref:s}),o=react.useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:hl,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:xl,children:[jsxRuntime.jsx("div",{style:Sl,children:r("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:vl,children:r("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:Pl,children:r("perpetuals.trades.col.age")})]}),jsxRuntime.jsx("div",{ref:s,className:"flex-1 min-h-0",children:n>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:n},rowComponent:Il,rowCount:e.length,rowHeight:sr,rowProps:o,overscanCount:4})})]})}var Ml={backgroundColor:"#000000",fontSize:11},Nl={height:28,minHeight:28,padding:"0 16px",color:"var(--color-text-muted)",fontSize:11},no={flex:"1 1 0%",maxWidth:100},oo={flex:"1 1 0%",marginLeft:20},io={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Ll={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Fl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Nl,children:[jsxRuntime.jsx("div",{style:no,children:e("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:oo,children:e("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:io,children:e("perpetuals.trades.col.age")})]})}function ql({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Ll,children:[jsxRuntime.jsx("div",{style:no,children:jsxRuntime.jsx("div",{style:{...me(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:oo,children:jsxRuntime.jsx("div",{style:{...me(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:io,children:jsxRuntime.jsx("div",{style:{...me(e+60),height:11,width:28}})})]})}function Hl(){let e=Array.from({length:12},(t,r)=>r);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ae,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:Ml,children:[jsxRuntime.jsx(Fl,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(ql,{delay:t*35},`trade-${t}`))})]})]})}function _l(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntime.jsx("span",{className:"text-text-secondary text-sm",children:e("perpetuals.trades.empty")})})}function ao({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:o}=rr({symbol:e,limit:t});return o?jsxRuntime.jsx(Hl,{}):n.length===0?jsxRuntime.jsx(_l,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(nr,{trades:n,onTradeClick:r})})}function lo(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function uo(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:lo(s,n)*(e-t)/t*r*100}function Pt(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let o=lo(s,n),i=e/r/100;return t*(1+o*i)}function po(e){if(!Number.isFinite(e)||e<=0)return e;let t=Math.floor(Math.log10(e)),s=10**Math.max(0,4-t);return Math.round(e*s)/s}function co(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var $l=20;function ir({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:i}){let[a,l]=react.useState("long"),[u,c]=react.useState("market"),p=reactHookForm.useForm({defaultValues:{amount:void 0,leverage:$l,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=et({symbol:e}),{data:f}=rt({symbol:e}),g=f?.szDecimals,m=f?.maxLeverage??r,{mutateAsync:P,isPending:b}=qt({onSuccess:()=>{p.reset(),s?.();},onError:y=>{n?.(y);}}),S=reactQuery.useMutation({mutationFn:async y=>{if(!i)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await i(y)},onSuccess:()=>{p.reset(),s?.();},onError:y=>{n?.(y);}}),T=b||S.isPending,x=p.watch(),{amount:D,leverage:H,price:_}=x,M=d?.price||0,h=react.useMemo(()=>u==="limit"&&_?_:M,[u,_,M]),V=react.useMemo(()=>!D||D<=0||!H?0:D*H,[D,H]),re=react.useMemo(()=>V?V*5e-4:0,[V]),L=react.useMemo(()=>V?V+re:0,[V,re]),A=react.useMemo(()=>{if(!D||!h||!H||H===1||!f?.maxLeverage)return;let y=1/(2*f.maxLeverage),C=(1/H-y)/(a==="long"?1-y:1+y);return a==="long"?h*(1-C):h*(1+C)},[D,h,H,a,f?.maxLeverage]),{data:k}=tt({userAddress:t,symbol:e}),W=k?.totalEquity??0,J=k?.availableBalance??0,Ce=react.useMemo(()=>{let y=k?.positions?.[0];if(!y)return;let C=y.symbol.includes("-")?y.symbol.split("-")[0]:y.symbol;return {side:y.side,quantity:y.quantity,quantityRaw:y.quantityRaw,margin:y.margin,base:C}},[k?.positions]),{data:j}=_t({userAddress:t,enabled:!!t}),Oe=react.useMemo(()=>j?.openOrders?.length?j.openOrders.some(y=>y.symbol===e):false,[j?.openOrders,e]),{data:Fe}=Ft({userAddress:t,symbol:e}),Z=Fe?.value,ke=!t||Z!==void 0,te=react.useRef(null);react.useEffect(()=>{te.current!==e&&Z&&Z>0&&(p.setValue("leverage",Z),te.current=e);},[e,Z,p]),react.useEffect(()=>{te.current=null;},[e]),react.useEffect(()=>{if(!(typeof D!="number"||Number.isNaN(D))){if(D<0){p.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}J>0&&D>J&&p.setValue("amount",J,{shouldValidate:false,shouldDirty:true});}},[D,J,p]);let Xe=react.useCallback(async y=>{if(!t)throw new Error("User address is required");if(!y.amount||y.amount<=0)throw new Error("Amount is required");let C=u==="limit"?y.price:void 0,F=y.takeProfitPrice,pe=y.stopLossPrice;if(!F&&y.takeProfitPercent&&y.takeProfitPercent>0&&h&&(F=Pt(y.takeProfitPercent,h,y.leverage,a,"tp")),!pe&&y.stopLossPercent&&y.stopLossPercent>0&&h&&(pe=Pt(y.stopLossPercent,h,y.leverage,a,"sl")),i){if(!h||h<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(g===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Je=y.amount*y.leverage/h;await S.mutateAsync({symbol:e,side:a,orderType:u,amount:y.amount,price:C,leverage:y.leverage,takeProfitPrice:F,stopLossPrice:pe,userAddress:t,size:Je,refPrice:h,szDecimals:g});return}await P({symbol:e,side:a,orderType:u,amount:y.amount,price:C,leverage:y.leverage,takeProfitPrice:F,stopLossPrice:pe,userAddress:t});},[e,a,u,h,g,t,i,S,P]);return {form:p,side:a,orderType:u,setSide:l,setOrderType:c,handleSubmit:Xe,isSubmitting:T,currentPrice:h,marketPrice:M,estimatedFee:re,estimatedTotal:L,liquidationPrice:A,availableMargin:J,accountValue:W,currentPosition:Ce,maxLeverage:m,currentLeverage:Z,isLeverageReady:ke,hasOpenOrdersForSymbol:Oe,szDecimals:g,onUpdateLeverage:o}}function So(e){return `${e}x`}var se=ui$1.themeSemanticColors.action.primary,tu=ui$1.themeSemanticColors.market.positive,yo=ui$1.themeSemanticColors.market.negative,go=ui$1.themeSemanticColors.status.danger;function Is(e,t){if(!/^#[0-9a-fA-F]{6}$/.test(e))return e;let r=Math.max(0,Math.min(255,Math.round(t)));return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}var ru="https://app.hyperliquid.xyz/coins",su=10;function qs(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var nu={...xs,display:"inline-block",width:28,height:14,borderRadius:4};function bo(e){return utils.formatAmount(e)}function Ms(e){return !Number.isFinite(e)||e<=0?"--":utils.formatPriceInUsd(e)}var Ie=1;function ou(e){let t=Math.max(Ie,Math.floor(e)),r=n=>{let o=Math.round(n);return o<=10?Math.max(Ie,o):Math.round(o/5)*5},s=new Set([Ie,t]);for(let n of [.25,.5,.75]){let o=r(t*n);o>Ie&&o<t&&s.add(o);}return Array.from(s).sort((n,o)=>n-o).map(n=>({value:n,label:`${n}x`}))}function iu({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:o,onConfirm:i,onUpdate:a,onClose:l}){let u=Math.max(Ie,Math.floor(r)),[c,p]=react.useState(Math.max(Ie,Math.min(t,u))),[d,f]=react.useState(false);react.useEffect(()=>{e&&(p(Math.max(Ie,Math.min(t,u))),f(false));},[e,t,u]);let g=react.useMemo(()=>ou(u),[u]),m=react.useCallback(async()=>{if(!d){if(!a){i(c),l();return}f(true);try{await a(c),i(c),l();}catch{f(false);}}},[d,a,c,i,l]),P=walletConnector.useAuthCallback(m),{t:b}=i18n.useTranslation();return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:S=>{d||S||l();},size:"md",hideCloseButton:true,backdrop:"opaque",classNames:{base:`${ui$1.THEMED_MODAL_BASE_CLASS} 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-text-primary m-0",children:b("perpetuals.placeOrder.leverage.title")}),jsxRuntime.jsx("button",{type:"button",onClick:l,disabled:d,"aria-label":b("common.cancel"),className:"p-1 rounded-[10px] hover:bg-surface-strong/50 text-text-secondary hover:text-text-primary 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.jsxs("div",{className:"flex flex-col gap-1",children:[n?jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:go},children:b("perpetuals.placeOrder.leverage.cannotUpdate",{symbol:s})}):jsxRuntime.jsx("p",{className:"text-[13px] text-text-secondary leading-[18px] m-0",children:b("perpetuals.placeOrder.leverage.desc")}),o&&jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:go},children:b("perpetuals.placeOrder.leverage.ordersAffected",{symbol:s})})]}),jsxRuntime.jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[jsxRuntime.jsx("style",{children:`
|
|
4
|
+
.perp-leverage-slider [data-slot="track"] { background-color: hsl(var(--heroui-foreground) / 0.08) !important; }
|
|
5
5
|
.perp-leverage-slider [data-slot="filler"] { background-color: ${se} !important; }
|
|
6
6
|
.perp-leverage-slider [data-slot="thumb"] { background-color: ${se} !important; }
|
|
7
7
|
.perp-leverage-slider [data-slot="thumb"]::after { background-color: ${se} !important; }
|
|
8
|
-
.perp-leverage-slider [data-slot="mark"] { color:
|
|
9
|
-
`}),jsxRuntime.jsx(ui.Slider,{value:[c],onChange:S=>p(Array.isArray(S)?S[0]:S),isDisabled:d||n,minValue:Ie,maxValue:u,step:1,marks:b,"aria-label":"Leverage"})]}),jsxRuntime.jsxs("div",{className:"text-sm text-white font-medium",children:[g("perpetuals.placeOrder.leverage.label")," ",c,"x"]}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{v();},disabled:d||n,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:[d&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),g(n?"perpetuals.placeOrder.leverage.failed":d?"perpetuals.placeOrder.leverage.updating":"perpetuals.placeOrder.leverage.update")]})]})]})})})}function su({methods:e}){let{t}=i18n.useTranslation(),r=e.watch("amount"),s=typeof r=="number"&&Number.isFinite(r)?r:void 0,[n,i]=react.useState(()=>s!==void 0?String(s):""),o=react.useRef(null);react.useEffect(()=>{let u=typeof document<"u"&&document.activeElement===o.current;i(c=>{let p=parseFloat(c),d=Number.isFinite(p)&&p===s;if(u&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(u=>{let c=Fs(u.target.value);if(i(c),c===""||c==="."){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let p=Number(c);Number.isFinite(p)&&e.setValue("amount",p,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(u=>{(u.key==="-"||u.key==="+"||u.key==="e"||u.key==="E")&&(u.preventDefault(),u.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:o,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:"amount",placeholder:"0.0 USDC","aria-label":t("perpetuals.placeOrder.buyAmount"),className:"flex-1 min-w-0 bg-transparent border-none outline-none w-full",style:{color:"#ffffff",fontSize:18,lineHeight:"23px",fontVariantNumeric:"tabular-nums",padding:0},value:n,onChange:a,onKeyDownCapture:l})}function nu({methods:e,placeholder:t}){let r=e.watch("price"),s=typeof r=="number"&&Number.isFinite(r)?r:void 0,[n,i]=react.useState(()=>s!==void 0?String(s):""),o=react.useRef(null);react.useEffect(()=>{let u=typeof document<"u"&&document.activeElement===o.current;i(c=>{let p=parseFloat(c),d=Number.isFinite(p)&&p===s;if(u&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(u=>{let c=Fs(u.target.value);if(i(c),c===""||c==="."){e.setValue("price",void 0,{shouldValidate:false,shouldDirty:true});return}let p=Number(c);Number.isFinite(p)&&e.setValue("price",p,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(u=>{(u.key==="-"||u.key==="+"||u.key==="e"||u.key==="E")&&(u.preventDefault(),u.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:o,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:"price",placeholder:t,"aria-label":"Limit price",className:"flex-1 min-w-0 bg-transparent border-none outline-none w-full",style:{color:"#ffffff",fontSize:18,lineHeight:"23px",fontVariantNumeric:"tabular-nums",padding:0},value:n,onChange:a,onKeyDownCapture:l})}function mi(e){return Number.isFinite(e)?String(e):""}function ar({methods:e,field:t,placeholder:r,refPrice:s,leverage:n,side:i}){let o=t.startsWith("takeProfit")?"tp":"sl",a=t==="takeProfitPrice"||t==="stopLossPrice",l=(()=>{switch(t){case "takeProfitPrice":return "takeProfitPercent";case "takeProfitPercent":return "takeProfitPrice";case "stopLossPrice":return "stopLossPercent";case "stopLossPercent":return "stopLossPrice"}})(),u=e.watch(t),c=typeof u=="number"&&Number.isFinite(u)?u:void 0,[p,d]=react.useState(()=>c!==void 0?mi(c):""),f=react.useRef(null);react.useEffect(()=>{let v=typeof document<"u"&&document.activeElement===f.current;d(g=>{let S=parseFloat(g),T=Number.isFinite(S)&&S===c;if(v&&T)return g;let x=c!==void 0?mi(c):"";return g===x?g:x});},[c]);let b=react.useCallback(v=>{let g=Fs(v.target.value);if(d(g),g===""||g==="."){e.setValue(t,void 0,{shouldValidate:false,shouldDirty:true}),e.setValue(l,void 0,{shouldValidate:false,shouldDirty:false});return}let S=Number(g);if(!Number.isFinite(S)||(e.setValue(t,S,{shouldValidate:false,shouldDirty:true}),!s||s<=0||!n||n<=0))return;let T=a?oi(S,s,n,i,o):vt(S,s,n,i,o);if(T===void 0||!Number.isFinite(T))return;let x=a?li(T):ai(T);e.setValue(l,x,{shouldValidate:false,shouldDirty:false});},[e,t,l,a,s,n,i,o]),m=react.useCallback(v=>{(v.key==="-"||v.key==="+"||v.key==="e"||v.key==="E")&&(v.preventDefault(),v.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:f,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:t,placeholder:r,"aria-label":t,className:"w-full bg-transparent outline-none",style:{color:"#ffffff",fontSize:12,height:32,padding:"0 8px",border:"1px solid #1c1c1c",borderRadius:4,fontVariantNumeric:"tabular-nums"},value:p,onChange:b,onKeyDownCapture:m})}function ur({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:i,isSubmitting:o,symbol:a,currentPrice:l,marketPrice:u,liquidationPrice:c,availableMargin:p,accountValue:d,currentPosition:f,maxLeverage:b,isLeverageReady:m=true,hasOpenOrdersForSymbol:v=false,szDecimals:g,onAddFunds:S,onUpdateLeverage:T}){let{t:x}=i18n.useTranslation(),w=react.useCallback(()=>{S?.();},[S]),H=walletConnector.useAuthCallback(w),_=walletConnector.useAuthCallback(i),[M,h]=react.useState(false),[V,re]=react.useState(false),L=e.watch("leverage")||20,A=e.watch("amount"),k=typeof A=="number"&&Number.isFinite(A)?A:0,z=k>0,J=e.watch("price"),Ce=typeof J=="number"&&Number.isFinite(J)&&J>0,j=a.split("-")[0],Oe=react.useMemo(()=>{if(!p||p<=0||!z)return 0;let C=k/p*100;return Number.isFinite(C)?Math.max(0,Math.min(100,C)):0},[z,k,p]),Fe=react.useCallback(C=>{if(p<=0)return;let F=Math.max(0,Math.min(100,C))/100;if(F===0){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let pe=Number((p*F).toFixed(4));e.setValue("amount",pe,{shouldValidate:false,shouldDirty:true});},[p,e]),Z=react.useMemo(()=>!z||!l||l<=0?0:k*L/l,[z,k,L,l]),ke=react.useMemo(()=>Zl/Math.max(1,L),[L]),te=react.useMemo(()=>p<=0?{label:x("perpetuals.placeOrder.btn.addFunds"),kind:"deposit",disabled:!S}:z?k<ke?{label:x("perpetuals.placeOrder.err.tooSmall"),kind:"invalid",disabled:true}:r==="limit"&&!Ce?{label:x("perpetuals.placeOrder.err.invalidLimit"),kind:"invalid",disabled:true}:{label:`${x(t==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${j}-USD`,kind:"submit",disabled:o}:{label:x("perpetuals.placeOrder.err.invalidAmount"),kind:"invalid",disabled:true},[p,z,k,ke,r,Ce,t,j,o,S,x]),Je=react.useCallback(()=>{te.kind==="deposit"&&H();},[te.kind,H]),y=C=>!Number.isFinite(C)||C<=0?"0":typeof g=="number"&&g>=0?C.toFixed(g):C>=1e3?C.toFixed(2):C>=1?C.toFixed(4):C.toFixed(6);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsx(Ae,{}),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.StyledTooltip,{content:x("perpetuals.placeOrder.tooltip.long"),placement:"top",delay:200,closeDelay:0,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"?se:"transparent",color:t==="long"?"#000000":"#b5b5b5",fontWeight:t==="long"?500:400,border:"none"},onClick:()=>s("long"),children:x("perpetuals.placeOrder.long")})}),jsxRuntime.jsx(ui.StyledTooltip,{content:x("perpetuals.placeOrder.tooltip.short"),placement:"top",delay:200,closeDelay:0,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:x("perpetuals.placeOrder.short")})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:x("perpetuals.placeOrder.market")},{key:"limit",label:x("perpetuals.placeOrder.limit")}].map(C=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===C.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===C.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(C.key),children:C.label})},C.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer flex items-center gap-1.5 px-3 py-1.5 rounded-[10px] transition-colors text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800/40 focus:outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#C7FF2E] disabled:cursor-progress",style:{fontSize:12,fontWeight:400},onClick:()=>h(true),disabled:!m,children:[jsxRuntime.jsx("span",{children:x("perpetuals.placeOrder.leverage.label")}),m?jsxRuntime.jsxs("span",{children:[L,"x"]}):jsxRuntime.jsx("span",{"aria-hidden":"true",style:eu})]})]}),jsxRuntime.jsx(ui.RHForm,{methods:e,onSubmit:_,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[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:x("perpetuals.placeOrder.buyAmount")}),jsxRuntime.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#ffffff"},children:j})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8,minHeight:24},children:[jsxRuntime.jsx(su,{methods:e}),jsxRuntime.jsxs("div",{className:"flex items-center shrink-0",style:{gap:6},children:[jsxRuntime.jsx("img",{src:`${Jl}/${j}.svg`,alt:j,width:18,height:18,className:"rounded-full",style:{width:18,height:18},onError:C=>{C.target.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:18,lineHeight:"23px",color:"#b5b5b5",fontVariantNumeric:"tabular-nums"},children:y(Z)})]})]})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
|
|
8
|
+
.perp-leverage-slider [data-slot="mark"] { color: var(--color-text-muted) !important; }
|
|
9
|
+
`}),jsxRuntime.jsx(ui$1.Slider,{value:[c],onChange:S=>p(Array.isArray(S)?S[0]:S),isDisabled:d||n,minValue:Ie,maxValue:u,step:1,marks:g,"aria-label":b("perpetuals.placeOrder.leverage.label")})]}),jsxRuntime.jsxs("div",{className:"text-sm text-text-primary font-medium",children:[b("perpetuals.placeOrder.leverage.label")," ",So(c)]}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{P();},disabled:d||n,className:"cursor-pointer mt-1 w-full h-12 rounded-[12px] font-medium text-text-inverse bg-action-primary hover:bg-action-primary-hover active:bg-action-primary-pressed transition-colors flex items-center justify-center gap-2 disabled:bg-surface-emphasis disabled:text-text-muted disabled:cursor-not-allowed",children:[d&&jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}),b(n?"perpetuals.placeOrder.leverage.failed":d?"perpetuals.placeOrder.leverage.updating":"perpetuals.placeOrder.leverage.update")]})]})]})})})}function au({methods:e}){let{t}=i18n.useTranslation(),r=e.watch("amount"),s=typeof r=="number"&&Number.isFinite(r)?r:void 0,[n,o]=react.useState(()=>s!==void 0?String(s):""),i=react.useRef(null);react.useEffect(()=>{let u=typeof document<"u"&&document.activeElement===i.current;o(c=>{let p=parseFloat(c),d=Number.isFinite(p)&&p===s;if(u&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(u=>{let c=qs(u.target.value);if(o(c),c===""||c==="."){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let p=Number(c);Number.isFinite(p)&&e.setValue("amount",p,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(u=>{(u.key==="-"||u.key==="+"||u.key==="e"||u.key==="E")&&(u.preventDefault(),u.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:i,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:"amount",placeholder:"0.0 USDC","aria-label":t("perpetuals.placeOrder.buyAmount"),className:"flex-1 min-w-0 bg-transparent border-none outline-none w-full",style:{color:"var(--color-text-primary)",fontSize:18,lineHeight:"23px",fontVariantNumeric:"tabular-nums",padding:0},value:n,onChange:a,onKeyDownCapture:l})}function lu({methods:e,placeholder:t,ariaLabel:r}){let s=e.watch("price"),n=typeof s=="number"&&Number.isFinite(s)?s:void 0,[o,i]=react.useState(()=>n!==void 0?String(n):""),a=react.useRef(null);react.useEffect(()=>{let c=typeof document<"u"&&document.activeElement===a.current;i(p=>{let d=parseFloat(p),f=Number.isFinite(d)&&d===n;if(c&&f)return p;let g=n!==void 0?String(n):"";return p===g?p:g});},[n]);let l=react.useCallback(c=>{let p=qs(c.target.value);if(i(p),p===""||p==="."){e.setValue("price",void 0,{shouldValidate:false,shouldDirty:true});return}let d=Number(p);Number.isFinite(d)&&e.setValue("price",d,{shouldValidate:false,shouldDirty:true});},[e]),u=react.useCallback(c=>{(c.key==="-"||c.key==="+"||c.key==="e"||c.key==="E")&&(c.preventDefault(),c.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:a,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:"price",placeholder:t,"aria-label":r,className:"flex-1 min-w-0 bg-transparent border-none outline-none w-full",style:{color:"var(--color-text-primary)",fontSize:18,lineHeight:"23px",fontVariantNumeric:"tabular-nums",padding:0},value:o,onChange:l,onKeyDownCapture:u})}function ho(e){return Number.isFinite(e)?String(e):""}function ar({methods:e,field:t,placeholder:r,refPrice:s,leverage:n,side:o}){let i=t.startsWith("takeProfit")?"tp":"sl",a=t==="takeProfitPrice"||t==="stopLossPrice",l=(()=>{switch(t){case "takeProfitPrice":return "takeProfitPercent";case "takeProfitPercent":return "takeProfitPrice";case "stopLossPrice":return "stopLossPercent";case "stopLossPercent":return "stopLossPrice"}})(),u=e.watch(t),c=typeof u=="number"&&Number.isFinite(u)?u:void 0,[p,d]=react.useState(()=>c!==void 0?ho(c):""),f=react.useRef(null);react.useEffect(()=>{let P=typeof document<"u"&&document.activeElement===f.current;d(b=>{let S=parseFloat(b),T=Number.isFinite(S)&&S===c;if(P&&T)return b;let x=c!==void 0?ho(c):"";return b===x?b:x});},[c]);let g=react.useCallback(P=>{let b=qs(P.target.value);if(d(b),b===""||b==="."){e.setValue(t,void 0,{shouldValidate:false,shouldDirty:true}),e.setValue(l,void 0,{shouldValidate:false,shouldDirty:false});return}let S=Number(b);if(!Number.isFinite(S)||(e.setValue(t,S,{shouldValidate:false,shouldDirty:true}),!s||s<=0||!n||n<=0))return;let T=a?uo(S,s,n,o,i):Pt(S,s,n,o,i);if(T===void 0||!Number.isFinite(T))return;let x=a?co(T):po(T);e.setValue(l,x,{shouldValidate:false,shouldDirty:false});},[e,t,l,a,s,n,o,i]),m=react.useCallback(P=>{(P.key==="-"||P.key==="+"||P.key==="e"||P.key==="E")&&(P.preventDefault(),P.stopPropagation());},[]);return jsxRuntime.jsx("input",{ref:f,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,name:t,placeholder:r,"aria-label":t,className:"w-full bg-transparent outline-none",style:{color:"var(--color-text-primary)",fontSize:12,height:32,padding:"0 8px",border:"1px solid var(--color-border-subtle)",borderRadius:4,fontVariantNumeric:"tabular-nums"},value:p,onChange:g,onKeyDownCapture:m})}function pr({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:o,isSubmitting:i,symbol:a,currentPrice:l,marketPrice:u,liquidationPrice:c,availableMargin:p,accountValue:d,currentPosition:f,maxLeverage:g,isLeverageReady:m=true,hasOpenOrdersForSymbol:P=false,szDecimals:b,onAddFunds:S,onUpdateLeverage:T}){let{t:x}=i18n.useTranslation(),D=react.useCallback(()=>{S?.();},[S]),H=walletConnector.useAuthCallback(D),_=walletConnector.useAuthCallback(o),[M,h]=react.useState(false),[V,re]=react.useState(false),L=e.watch("leverage")||20,A=e.watch("amount"),k=typeof A=="number"&&Number.isFinite(A)?A:0,W=k>0,J=e.watch("price"),Ce=typeof J=="number"&&Number.isFinite(J)&&J>0,j=a.split("-")[0],Oe=react.useMemo(()=>{if(!p||p<=0||!W)return 0;let C=k/p*100;return Number.isFinite(C)?Math.max(0,Math.min(100,C)):0},[W,k,p]),Fe=react.useCallback(C=>{if(p<=0)return;let F=Math.max(0,Math.min(100,C))/100;if(F===0){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let pe=Number((p*F).toFixed(4));e.setValue("amount",pe,{shouldValidate:false,shouldDirty:true});},[p,e]),Z=react.useMemo(()=>!W||!l||l<=0?0:k*L/l,[W,k,L,l]),ke=react.useMemo(()=>su/Math.max(1,L),[L]),te=react.useMemo(()=>p<=0?{label:x("perpetuals.placeOrder.btn.addFunds"),kind:"deposit",disabled:!S}:W?k<ke?{label:x("perpetuals.placeOrder.err.tooSmall"),kind:"invalid",disabled:true}:r==="limit"&&!Ce?{label:x("perpetuals.placeOrder.err.invalidLimit"),kind:"invalid",disabled:true}:{label:`${x(t==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${j}-USD`,kind:"submit",disabled:i}:{label:x("perpetuals.placeOrder.err.invalidAmount"),kind:"invalid",disabled:true},[p,W,k,ke,r,Ce,t,j,i,S,x]),Xe=react.useCallback(()=>{te.kind==="deposit"&&H();},[te.kind,H]),y=C=>!Number.isFinite(C)||C<=0?"0":typeof b=="number"&&b>=0?C.toFixed(b):C>=1e3?C.toFixed(2):C>=1?C.toFixed(4):C.toFixed(6);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"var(--color-surface-base)"},children:[jsxRuntime.jsx(Ae,{}),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 var(--color-border-subtle)",borderRadius:8,padding:4,gap:4},children:[jsxRuntime.jsx(ui$1.StyledTooltip,{content:x("perpetuals.placeOrder.tooltip.long"),placement:"top",delay:200,closeDelay:0,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"?se:"transparent",color:t==="long"?"var(--color-text-inverse)":"var(--color-text-secondary)",fontWeight:t==="long"?500:400,border:"none"},onClick:()=>s("long"),children:x("perpetuals.placeOrder.long")})}),jsxRuntime.jsx(ui$1.StyledTooltip,{content:x("perpetuals.placeOrder.tooltip.short"),placement:"top",delay:200,closeDelay:0,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"?yo:"transparent",color:t==="short"?"var(--color-text-inverse)":"var(--color-text-secondary)",fontWeight:t==="short"?500:400,border:"none"},onClick:()=>s("short"),children:x("perpetuals.placeOrder.short")})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:x("perpetuals.placeOrder.market")},{key:"limit",label:x("perpetuals.placeOrder.limit")}].map(C=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===C.key?"2px solid var(--color-text-primary)":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===C.key?"var(--color-text-primary)":"var(--color-text-secondary)",border:"none"},onClick:()=>n(C.key),children:C.label})},C.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer flex items-center gap-1.5 px-3 py-1.5 rounded-[10px] transition-colors text-text-muted hover:text-text-primary hover:bg-surface-interactive/40 focus:outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-progress",style:{fontSize:12,fontWeight:400},onClick:()=>h(true),disabled:!m,children:[jsxRuntime.jsx("span",{children:x("perpetuals.placeOrder.leverage.label")}),m?jsxRuntime.jsx("span",{children:So(L)}):jsxRuntime.jsx("span",{"aria-hidden":"true",style:nu})]})]}),jsxRuntime.jsx(ui$1.RHForm,{methods:e,onSubmit:_,children:jsxRuntime.jsxs("div",{className:"space-y-3 w-full",children:[jsxRuntime.jsxs("div",{className:"perp-buy-amt",style:{borderRadius:4,padding:8,backgroundColor:"var(--color-surface-raised)",border:"1px solid var(--color-border-subtle)",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:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.buyAmount")}),jsxRuntime.jsx("span",{style:{fontSize:14,fontWeight:500,color:"var(--color-text-primary)"},children:j})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8,minHeight:24},children:[jsxRuntime.jsx(au,{methods:e}),jsxRuntime.jsxs("div",{className:"flex items-center shrink-0",style:{gap:6},children:[jsxRuntime.jsx("img",{src:`${ru}/${j}.svg`,alt:j,width:18,height:18,className:"rounded-full",style:{width:18,height:18},onError:C=>{C.target.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:18,lineHeight:"23px",color:"var(--color-text-secondary)",fontVariantNumeric:"tabular-nums"},children:y(Z)})]})]})]}),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; }
|
|
13
|
-
.perp-order-form .group input { color:
|
|
14
|
-
.perp-slider { -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer; width: 100%; height: 16px; --pct: 0%; --fill: ${se}; --track:
|
|
13
|
+
.perp-order-form .group input { color: var(--color-text-primary) !important; }
|
|
14
|
+
.perp-slider { -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer; width: 100%; height: 16px; --pct: 0%; --fill: ${se}; --track: var(--color-border-subtle); }
|
|
15
15
|
.perp-slider::-webkit-slider-runnable-track {
|
|
16
16
|
height: 4px; border-radius: 2px;
|
|
17
17
|
background: linear-gradient(to right, var(--fill) 0, var(--fill) var(--pct), var(--track) var(--pct), var(--track) 100%);
|
|
18
18
|
}
|
|
19
19
|
.perp-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; border-radius: 50%; background: ${se}; margin-top: -4px; border: none; box-shadow: 0 0 0 2px rgba(0,0,0,0.6); }
|
|
20
|
-
.perp-slider::-moz-range-track { height: 4px; border-radius: 2px; background:
|
|
20
|
+
.perp-slider::-moz-range-track { height: 4px; border-radius: 2px; background: var(--color-border-subtle); border: none; }
|
|
21
21
|
.perp-slider::-moz-range-progress { height: 4px; border-radius: 2px; background: ${se}; }
|
|
22
22
|
.perp-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: ${se}; border: none; box-shadow: 0 0 0 2px rgba(0,0,0,0.6); }
|
|
23
23
|
.perp-slider:disabled { cursor: not-allowed; opacity: 0.5; }
|
|
24
|
-
.perp-side-tab[data-active="false"]:hover { background-color:
|
|
25
|
-
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(Oe),onChange:C=>Fe(Number(C.target.value)),min:0,max:100,step:1,disabled:p<=0,className:"perp-slider",style:{"--pct":`${Math.round(Oe)}%`}}),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%"})]})]}),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:x("perpetuals.placeOrder.limitPrice")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:u&&u>0?x("perpetuals.placeOrder.currentPrice",{price:Is(u)}):"--"})]}),jsxRuntime.jsx(nu,{methods:e,placeholder:u&&u>0?Is(u):"$0.0"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",style:{marginTop:16},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>re(C=>!C),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:V?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:V&&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:x("perpetuals.placeOrder.tpsl")})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsxs("span",{children:[x("perpetuals.placeOrder.estLiqPrice")," "]}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:c?Is(c):"--"})]})]}),V&&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:x("perpetuals.placeOrder.tpPrice")}),jsxRuntime.jsx(ar,{methods:e,field:"takeProfitPrice",placeholder:x("perpetuals.placeOrder.enterTpPrice"),refPrice:l,leverage:L,side:t})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsxRuntime.jsx(ar,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:L,side:t})]})]}),V&&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:x("perpetuals.placeOrder.slPrice")}),jsxRuntime.jsx(ar,{methods:e,field:"stopLossPrice",placeholder:x("perpetuals.placeOrder.enterSlPrice"),refPrice:l,leverage:L,side:t})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsxRuntime.jsx(ar,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:L,side:t})]})]}),(()=>{let C=te.kind==="submit",F=C?"submit":"button",Ze=C?t==="long"?Xl:yi:te.kind==="deposit"?se:"rgba(63,63,70,0.6)",ro=te.kind==="invalid"?"#71717a":"#000000",en=C&&o;return jsxRuntime.jsxs("button",{type:F,disabled:te.disabled,onClick:C?void 0:Je,className:"w-full transition-colors disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{marginTop:16,height:40,fontSize:14,fontWeight:600,color:ro,backgroundColor:Ze,borderRadius:9999,border:"none",cursor:te.disabled?"not-allowed":"pointer",opacity:te.disabled?.9:1},children:[en&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),en?x("perpetuals.placeOrder.btn.placing"):te.label]})})(),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:x("perpetuals.placeOrder.availableMargin")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{H();},disabled:!S,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:Us(se,26),color:se,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:S?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:C=>{S&&(C.currentTarget.style.backgroundColor=Us(se,51));},onMouseLeave:C=>{S&&(C.currentTarget.style.backgroundColor=Us(se,26));},children:[di(p)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:x("perpetuals.placeOrder.perpsAccountValue")}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[di(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:x("perpetuals.placeOrder.currentPosition")}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?`${x(f.side==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${f.quantityRaw??String(f.quantity)} ${f.base} (${f.margin.toFixed(2)} USDC)`:"--"})]})]})]})})]}),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:x("perpetuals.placeOrder.poweredBy")}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:C=>{let F=C.target;F.style.display="none";}})]})}),jsxRuntime.jsx(ru,{isOpen:M,initialLeverage:L,maxLeverage:b,coinName:f?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!f,hasOpenOrders:v,onConfirm:C=>e.setValue("leverage",C),onUpdate:T,onClose:()=>h(false)})]})}function bi({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,onPlaceOrder:a,className:l}){let{form:u,side:c,orderType:p,setSide:d,setOrderType:f,handleSubmit:b,isSubmitting:m,currentPrice:v,marketPrice:g,estimatedFee:S,estimatedTotal:T,liquidationPrice:x,availableMargin:w,accountValue:H,currentPosition:_,maxLeverage:M,isLeverageReady:h,hasOpenOrdersForSymbol:V,szDecimals:re,onUpdateLeverage:L}=or({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:a});return jsxRuntime.jsx("div",{className:l,children:jsxRuntime.jsx(ur,{methods:u,side:c,orderType:p,onSideChange:d,onOrderTypeChange:f,onSubmit:b,isSubmitting:m,symbol:e,currentPrice:v,marketPrice:g,estimatedFee:S,estimatedTotal:T,liquidationPrice:x,availableMargin:w,accountValue:H,currentPosition:_,maxLeverage:M,isLeverageReady:h,hasOpenOrdersForSymbol:V,szDecimals:re,onAddFunds:i,onUpdateLeverage:L})})}var Ot="#C7FF2E";function Bs(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}function pr({isOpen:e,position:t,closeType:r,isSubmitting:s,onClose:n,onConfirm:i}){let{t:o}=i18n.useTranslation(),a=t?Math.abs(t.quantity):0,l=t?.quantityRaw??String(a),u=t?.symbol.split("-")[0]??"",c=t?.side==="long",p=o(c?"perpetuals.positions.long":"perpetuals.positions.short"),[d,f]=react.useState(""),[b,m]=react.useState("100"),[v,g]=react.useState(""),S=react.useRef(null),T=react.useRef(null),x=react.useRef(null);react.useEffect(()=>{if(e&&t){let y=Math.abs(t.quantity);f(t.quantityRaw??String(y)),m("100"),g("");}},[e,t]);let w=react.useMemo(()=>{let y=parseFloat(d);return Number.isFinite(y)&&y>0?y:0},[d]);react.useMemo(()=>{let y=parseFloat(b);return Number.isFinite(y)?Math.max(0,Math.min(100,y)):0},[b]);let _=react.useMemo(()=>{if(a<=0||w<=0)return 0;let y=w/a*100;return Math.max(0,Math.min(100,y))},[w,a]),M=react.useCallback(y=>{let C=Bs(y.target.value),F=parseFloat(C);if(Number.isFinite(F)&&F>a&&a>0){f(t?.quantityRaw??String(a)),m("100");return}if(f(C),Number.isFinite(F)&&a>0){let pe=Math.round(F/a*100);m(String(Math.min(100,pe)));}else (C===""||C===".")&&m("0");},[a,t?.quantityRaw]),h=react.useCallback(()=>{let y=parseFloat(d);!Number.isFinite(y)||y<=0?(f("0"),m("0")):y>a&&a>0&&(f(t?.quantityRaw??String(a)),m("100"));},[d,a,t?.quantityRaw]),V=react.useCallback(y=>{let C=Bs(y.target.value),F=parseFloat(C);if(Number.isFinite(F)&&F>100){m("100"),a>0&&f(t?.quantityRaw??String(a));return}if(m(C),Number.isFinite(F)&&a>0){let pe=Math.max(0,Math.min(100,F)),Ze=a*(pe/100);f(Ze>0?String(Number(Ze.toPrecision(6))):"0");}else (C===""||C===".")&&f("0");},[a,t?.quantityRaw]),re=react.useCallback(()=>{let y=parseFloat(b);!Number.isFinite(y)||y<0?(m("0"),f("0")):y>100&&(m("100"),a>0&&f(t?.quantityRaw??String(a)));},[b,a,t?.quantityRaw]),L=react.useCallback(y=>{let C=Number(y.target.value);if(m(String(C)),a>0){let F=a*(C/100);f(C===100?t?.quantityRaw??String(a):F>0?String(Number(F.toPrecision(6))):"0");}},[a,t?.quantityRaw]),A=react.useCallback(y=>{g(Bs(y.target.value));},[]),k=react.useCallback(y=>{(y.key==="-"||y.key==="+"||y.key==="e"||y.key==="E")&&(y.preventDefault(),y.stopPropagation());},[]),z=r==="limit",J=parseFloat(v),Ce=z&&Number.isFinite(J)&&J>0,j=w>0&&(!z||Ce)&&!s,Oe=react.useCallback(async()=>{j&&await i(w,z?J:void 0);},[j,i,w,z,J]),Fe=walletConnector.useAuthCallback(Oe),Z=z?o("perpetuals.positions.close.limitTitle",{side:p,size:l,symbol:u}):o("perpetuals.positions.close.marketTitle",{side:p,size:l,symbol:u}),ke=o(z?"perpetuals.positions.close.limitDesc":"perpetuals.positions.close.marketDesc"),te=o(z?"perpetuals.positions.close.confirmLimit":"perpetuals.positions.close.confirmMarket"),Je=t?.markPrice&&t.markPrice>0?String(t.markPrice):"";return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:y=>{s||y||n();},size:"md",hideCloseButton:true,backdrop:"opaque",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.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-sm font-semibold text-white m-0",children:Z}),jsxRuntime.jsx("button",{type:"button",onClick:n,disabled: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 disabled:cursor-not-allowed disabled:opacity-50",children:jsxRuntime.jsx(ui.XCloseIcon,{width:16,height:16})})]}),jsxRuntime.jsxs("div",{className:"px-5 pb-5 pt-1 flex flex-col gap-4",children:[jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:ke}),z&&jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:o("perpetuals.positions.close.price")}),jsxRuntime.jsx("input",{ref:x,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,placeholder:Je?o("perpetuals.positions.close.currentPrice",{price:Je}):"0.0",value:v,onChange:A,onKeyDownCapture:k,className:"w-full bg-transparent outline-none",style:{color:"#ffffff",fontSize:14,height:40,padding:"0 12px",border:"1px solid rgba(39,39,42,0.8)",borderRadius:8,fontVariantNumeric:"tabular-nums"}})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:o("perpetuals.positions.close.size")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"%"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-1",style:{border:"1px solid rgba(39,39,42,0.8)",borderRadius:8,height:40,padding:"0 12px"},children:[jsxRuntime.jsx("input",{ref:S,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:d,onChange:M,onBlur:h,onKeyDownCapture:k,className:"flex-1 min-w-0 bg-transparent border-none outline-none",style:{color:"#ffffff",fontSize:14,fontVariantNumeric:"tabular-nums",padding:0}}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginLeft:8,flexShrink:0},children:"$"})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{border:"1px solid rgba(39,39,42,0.8)",borderRadius:8,height:40,padding:"0 12px",width:80},children:[jsxRuntime.jsx("input",{ref:T,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:b,onChange:V,onBlur:re,onKeyDownCapture:k,className:"flex-1 min-w-0 bg-transparent border-none outline-none text-right",style:{color:"#ffffff",fontSize:14,fontVariantNumeric:"tabular-nums",padding:0}}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginLeft:4,flexShrink:0},children:"%"})]})]}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginTop:2},children:o("perpetuals.positions.close.maxSize",{size:l,symbol:u})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
|
|
24
|
+
.perp-side-tab[data-active="false"]:hover { background-color: hsl(var(--heroui-foreground) / 0.12) !important; color: var(--color-text-primary) !important; }
|
|
25
|
+
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(Oe),onChange:C=>Fe(Number(C.target.value)),min:0,max:100,step:1,disabled:p<=0,className:"perp-slider",style:{"--pct":`${Math.round(Oe)}%`}}),jsxRuntime.jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"var(--color-text-secondary)",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%"})]})]}),r==="limit"&&jsxRuntime.jsxs("div",{className:"perp-price-box",style:{borderRadius:4,padding:8,backgroundColor:"var(--color-surface-raised)",border:"1px solid var(--color-border-subtle)",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:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.limitPrice")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:u&&u>0?x("perpetuals.placeOrder.currentPrice",{price:Ms(u)}):"--"})]}),jsxRuntime.jsx(lu,{methods:e,ariaLabel:x("perpetuals.placeOrder.limitPrice"),placeholder:u&&u>0?Ms(u):"$0.0"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",style:{marginTop:16},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsxRuntime.jsx("div",{onClick:()=>re(C=>!C),style:{width:16,height:16,borderRadius:4,border:"1px solid var(--color-border-control)",backgroundColor:V?se:"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:V&&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:"var(--color-text-inverse)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"var(--color-text-secondary)"},children:x("perpetuals.placeOrder.tpsl")})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"var(--color-text-muted)"},children:[jsxRuntime.jsxs("span",{children:[x("perpetuals.placeOrder.estLiqPrice")," "]}),jsxRuntime.jsx("span",{style:{color:"var(--color-text-secondary)"},children:c?Ms(c):"--"})]})]}),V&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:2,display:"block"},children:x("perpetuals.placeOrder.tpPrice")}),jsxRuntime.jsx(ar,{methods:e,field:"takeProfitPrice",placeholder:x("perpetuals.placeOrder.enterTpPrice"),refPrice:l,leverage:L,side:t})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:2,display:"block"},children:x("perpetuals.placeOrder.tpPercent")}),jsxRuntime.jsx(ar,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:L,side:t})]})]}),V&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:2,display:"block"},children:x("perpetuals.placeOrder.slPrice")}),jsxRuntime.jsx(ar,{methods:e,field:"stopLossPrice",placeholder:x("perpetuals.placeOrder.enterSlPrice"),refPrice:l,leverage:L,side:t})]}),jsxRuntime.jsxs("div",{style:{width:70},children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:2,display:"block"},children:x("perpetuals.placeOrder.slPercent")}),jsxRuntime.jsx(ar,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:L,side:t})]})]}),(()=>{let C=te.kind==="submit",F=C?"submit":"button",Je=C?t==="long"?tu:yo:te.kind==="deposit"?se:"var(--color-surface-emphasis)",ii=te.kind==="invalid"?"var(--color-text-disabled)":"var(--color-text-inverse)",sn=C&&i;return jsxRuntime.jsxs("button",{type:F,disabled:te.disabled,onClick:C?void 0:Xe,className:"w-full transition-colors disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{marginTop:16,height:40,fontSize:14,fontWeight:600,color:ii,backgroundColor:Je,borderRadius:9999,border:"none",cursor:te.disabled?"not-allowed":"pointer",opacity:te.disabled?.9:1},children:[sn&&jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}),sn?x("perpetuals.placeOrder.btn.placing"):te.label]})})(),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:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.availableMargin")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{H();},disabled:!S,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:Is(se,26),color:se,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:S?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:C=>{S&&(C.currentTarget.style.backgroundColor=Is(se,51));},onMouseLeave:C=>{S&&(C.currentTarget.style.backgroundColor=Is(se,26));},children:[bo(p)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.perpsAccountValue")}),jsxRuntime.jsxs("span",{style:{color:"var(--color-text-secondary)",fontSize:12},children:[bo(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.currentPosition")}),jsxRuntime.jsx("span",{style:{color:"var(--color-text-secondary)",fontSize:12},children:f?`${x(f.side==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${f.quantityRaw??String(f.quantity)} ${f.base} (${f.margin.toFixed(2)} USDC)`:"--"})]})]})]})})]}),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:"var(--color-text-muted)"},children:x("perpetuals.placeOrder.poweredBy")}),jsxRuntime.jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:C=>{let F=C.target;F.style.display="none";}})]})}),jsxRuntime.jsx(iu,{isOpen:M,initialLeverage:L,maxLeverage:g,coinName:f?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!f,hasOpenOrders:P,onConfirm:C=>e.setValue("leverage",C),onUpdate:T,onClose:()=>h(false)})]})}function Po({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:o,onUpdateLeverage:i,onPlaceOrder:a,className:l}){let{form:u,side:c,orderType:p,setSide:d,setOrderType:f,handleSubmit:g,isSubmitting:m,currentPrice:P,marketPrice:b,estimatedFee:S,estimatedTotal:T,liquidationPrice:x,availableMargin:D,accountValue:H,currentPosition:_,maxLeverage:M,isLeverageReady:h,hasOpenOrdersForSymbol:V,szDecimals:re,onUpdateLeverage:L}=ir({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:a});return jsxRuntime.jsx("div",{className:l,children:jsxRuntime.jsx(pr,{methods:u,side:c,orderType:p,onSideChange:d,onOrderTypeChange:f,onSubmit:g,isSubmitting:m,symbol:e,currentPrice:P,marketPrice:b,estimatedFee:S,estimatedTotal:T,liquidationPrice:x,availableMargin:D,accountValue:H,currentPosition:_,maxLeverage:M,isLeverageReady:h,hasOpenOrdersForSymbol:V,szDecimals:re,onAddFunds:o,onUpdateLeverage:L})})}var Ot=ui$1.themeSemanticColors.action.primary;function Qs(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}function cr({isOpen:e,position:t,closeType:r,isSubmitting:s,onClose:n,onConfirm:o}){let{t:i}=i18n.useTranslation(),a=t?Math.abs(t.quantity):0,l=t?.quantityRaw??String(a),u=t?.symbol.split("-")[0]??"",c=t?.side==="long",p=i(c?"perpetuals.positions.long":"perpetuals.positions.short"),[d,f]=react.useState(""),[g,m]=react.useState("100"),[P,b]=react.useState(""),S=react.useRef(null),T=react.useRef(null),x=react.useRef(null);react.useEffect(()=>{if(e&&t){let y=Math.abs(t.quantity);f(t.quantityRaw??String(y)),m("100"),b("");}},[e,t]);let D=react.useMemo(()=>{let y=parseFloat(d);return Number.isFinite(y)&&y>0?y:0},[d]);react.useMemo(()=>{let y=parseFloat(g);return Number.isFinite(y)?Math.max(0,Math.min(100,y)):0},[g]);let _=react.useMemo(()=>{if(a<=0||D<=0)return 0;let y=D/a*100;return Math.max(0,Math.min(100,y))},[D,a]),M=react.useCallback(y=>{let C=Qs(y.target.value),F=parseFloat(C);if(Number.isFinite(F)&&F>a&&a>0){f(t?.quantityRaw??String(a)),m("100");return}if(f(C),Number.isFinite(F)&&a>0){let pe=Math.round(F/a*100);m(String(Math.min(100,pe)));}else (C===""||C===".")&&m("0");},[a,t?.quantityRaw]),h=react.useCallback(()=>{let y=parseFloat(d);!Number.isFinite(y)||y<=0?(f("0"),m("0")):y>a&&a>0&&(f(t?.quantityRaw??String(a)),m("100"));},[d,a,t?.quantityRaw]),V=react.useCallback(y=>{let C=Qs(y.target.value),F=parseFloat(C);if(Number.isFinite(F)&&F>100){m("100"),a>0&&f(t?.quantityRaw??String(a));return}if(m(C),Number.isFinite(F)&&a>0){let pe=Math.max(0,Math.min(100,F)),Je=a*(pe/100);f(Je>0?String(Number(Je.toPrecision(6))):"0");}else (C===""||C===".")&&f("0");},[a,t?.quantityRaw]),re=react.useCallback(()=>{let y=parseFloat(g);!Number.isFinite(y)||y<0?(m("0"),f("0")):y>100&&(m("100"),a>0&&f(t?.quantityRaw??String(a)));},[g,a,t?.quantityRaw]),L=react.useCallback(y=>{let C=Number(y.target.value);if(m(String(C)),a>0){let F=a*(C/100);f(C===100?t?.quantityRaw??String(a):F>0?String(Number(F.toPrecision(6))):"0");}},[a,t?.quantityRaw]),A=react.useCallback(y=>{b(Qs(y.target.value));},[]),k=react.useCallback(y=>{(y.key==="-"||y.key==="+"||y.key==="e"||y.key==="E")&&(y.preventDefault(),y.stopPropagation());},[]),W=r==="limit",J=parseFloat(P),Ce=W&&Number.isFinite(J)&&J>0,j=D>0&&(!W||Ce)&&!s,Oe=react.useCallback(async()=>{j&&await o(D,W?J:void 0);},[j,o,D,W,J]),Fe=walletConnector.useAuthCallback(Oe),Z=W?i("perpetuals.positions.close.limitTitle",{side:p,size:l,symbol:u}):i("perpetuals.positions.close.marketTitle",{side:p,size:l,symbol:u}),ke=i(W?"perpetuals.positions.close.limitDesc":"perpetuals.positions.close.marketDesc"),te=i(W?"perpetuals.positions.close.confirmLimit":"perpetuals.positions.close.confirmMarket"),Xe=t?.markPrice&&t.markPrice>0?String(t.markPrice):"";return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:y=>{s||y||n();},size:"md",hideCloseButton:true,backdrop:"opaque",classNames:{base:`${ui$1.THEMED_MODAL_BASE_CLASS} 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-sm font-semibold text-text-primary m-0",children:Z}),jsxRuntime.jsx("button",{type:"button",onClick:n,disabled:s,"aria-label":i("common.close"),className:"p-1 rounded-[10px] hover:bg-surface-strong/50 text-text-secondary hover:text-text-primary 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-1 flex flex-col gap-4",children:[jsxRuntime.jsx("p",{className:"text-[13px] text-text-secondary leading-[18px] m-0",children:ke}),W&&jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:i("perpetuals.positions.close.price")}),jsxRuntime.jsx("input",{ref:x,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,placeholder:Xe?i("perpetuals.positions.close.currentPrice",{price:Xe}):"0.0",value:P,onChange:A,onKeyDownCapture:k,className:"w-full bg-transparent outline-none",style:{color:"var(--color-text-primary)",fontSize:14,height:40,padding:"0 12px",border:"1px solid var(--color-border-control)",borderRadius:8,fontVariantNumeric:"tabular-nums"}})]}),jsxRuntime.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:i("perpetuals.positions.close.size")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)"},children:"%"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-1",style:{border:"1px solid var(--color-border-control)",borderRadius:8,height:40,padding:"0 12px"},children:[jsxRuntime.jsx("input",{ref:S,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:d,onChange:M,onBlur:h,onKeyDownCapture:k,className:"flex-1 min-w-0 bg-transparent border-none outline-none",style:{color:"var(--color-text-primary)",fontSize:14,fontVariantNumeric:"tabular-nums",padding:0}}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginLeft:8,flexShrink:0},children:"$"})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{border:"1px solid var(--color-border-control)",borderRadius:8,height:40,padding:"0 12px",width:80},children:[jsxRuntime.jsx("input",{ref:T,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:g,onChange:V,onBlur:re,onKeyDownCapture:k,className:"flex-1 min-w-0 bg-transparent border-none outline-none text-right",style:{color:"var(--color-text-primary)",fontSize:14,fontVariantNumeric:"tabular-nums",padding:0}}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginLeft:4,flexShrink:0},children:"%"})]})]}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",marginTop:2},children:i("perpetuals.positions.close.maxSize",{size:l,symbol:u})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
|
|
26
26
|
.perp-close-slider { -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer; width: 100%; height: 16px; --pct: 0%; --fill: ${Ot}; --track: rgba(39,39,42,0.8); }
|
|
27
27
|
.perp-close-slider::-webkit-slider-runnable-track {
|
|
28
28
|
height: 4px; border-radius: 2px;
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
.perp-close-slider::-moz-range-progress { height: 4px; border-radius: 2px; background: ${Ot}; }
|
|
34
34
|
.perp-close-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: ${Ot}; border: none; box-shadow: 0 0 0 2px rgba(0,0,0,0.6); }
|
|
35
35
|
.perp-close-slider:disabled { cursor: not-allowed; opacity: 0.5; }
|
|
36
|
-
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(_),onChange:L,min:0,max:100,step:1,disabled:a<=0,className:"perp-close-slider",style:{"--pct":`${Math.round(_)}%`}}),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("button",{type:"button",onClick:()=>{Fe();},disabled:!j,className:"w-full transition-colors disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{marginTop:4,height:44,fontSize:14,fontWeight:600,color:"#000000",backgroundColor:j?Ot:"rgba(63,63,70,0.6)",borderRadius:9999,border:"none",cursor:j?"pointer":"not-allowed",opacity:j?1:.9},children:[s&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),s?"Closing...":te]})]})]})})})}function dr({userAddress:e,onCloseSuccess:t,onCloseError:r,onPlaceOrder:s}){let[n,i]=react.useState(false),[o,a]=react.useState(null),[l,u]=react.useState("market"),{data:c}=st({symbol:o?.symbol}),{mutateAsync:p,isPending:d}=reactQuery.useMutation({mutationFn:async g=>{if(!s)throw new Error("onPlaceOrder is not configured; cannot submit close order");return await s(g)},onSuccess:()=>{i(false),a(null),t?.();},onError:g=>{r?.(g);}}),f=react.useCallback(g=>{a(g),u("market"),i(true);},[]),b=react.useCallback(g=>{a(g),u("limit"),i(true);},[]),m=react.useCallback(()=>{d||(i(false),a(null));},[d]),v=react.useCallback(async(g,S)=>{if(!o||!e)throw new Error("Position and user address are required");let T=o.side==="long"?"short":"long",x=l==="limit"?"limit":"market",w=o.markPrice||o.entryPrice,H=c?.szDecimals??5;await p({symbol:o.symbol,side:T,orderType:x,amount:g*w,price:x==="limit"?S:void 0,leverage:o.leverage,reduceOnly:true,userAddress:e,size:g,refPrice:w,szDecimals:H});},[o,e,l,c,p]);return {isModalOpen:n,selectedPosition:o,closeType:l,isClosing:d,openMarketClose:f,openLimitClose:b,handleConfirm:v,closeModal:m}}function xi(e,t){switch(t){case "asset":return e.symbol.split("-")[0];case "position":return Math.abs(e.quantity);case "value":return e.notionalValue;case "entry":return e.entryPrice;case "mark":return e.markPrice;case "liq":return e.liquidationPrice??null;case "marginPnl":return e.margin}}function fu(e,t,r,s){let n=xi(e,r),i=xi(t,r);if(n===null&&i===null)return 0;if(n===null)return 1;if(i===null)return -1;let o;return typeof n=="string"&&typeof i=="string"?o=n.localeCompare(i):o=n-i,s==="asc"?o:-o}function mr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}){let[i,o]=react.useState("marginPnl"),[a,l]=react.useState("desc"),u=react.useCallback(v=>{o(g=>g===v?(l(S=>S==="asc"?"desc":"asc"),g):(l("asc"),v));},[]),{data:c,isLoading:p,error:d}=rt({userAddress:e,symbol:t},{enabled:!!e}),f=dr({userAddress:e,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}),b=react.useMemo(()=>c?.positions??[],[c]);return {positions:react.useMemo(()=>i?[...b].sort((v,g)=>fu(v,g,i,a)):b,[b,i,a]),isLoading:p,error:d,sortKey:i,sortDir:a,onSort:u,closePosition:f}}var bu={start:"justify-start",center:"justify-center",end:"justify-end"},ge={minHeight:28,maxHeight:28},fr={minHeight:36,maxHeight:36},at={backgroundColor:"rgba(255, 255, 255, 0.06)"};function oe(e){return e===void 0||!Number.isFinite(e)?"--":utils.formatPriceInUsd(e)}function Ge(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"--"}function yr(e){return Number.isFinite(e)?utils.formatAmountInUsd(e,{showPlusGtThanZero:true}):"--"}function Oi(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function lt(e,t){return t||(Number.isFinite(e)?utils.formatAmount(e):"--")}function gr(e){if(e===void 0||!Number.isFinite(e))return "--";let t=new Date(e);if(Number.isNaN(t.getTime()))return "--";let r=t.getFullYear(),s=t.getMonth()+1,n=t.getDate(),i=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0");return `${r}/${s}/${n} ${i}:${o}:${a}`}function N({style:e,children:t,sortKey:r,activeSortKey:s,sortDir:n,onSort:i,align:o="start"}){let l=r!==void 0&&r===s?n==="asc"?" \u2191":" \u2193":"",u=r!==void 0&&i!==void 0,c=bu[o],p=jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-500",children:[t,l]});return u?jsxRuntime.jsx("button",{type:"button",onClick:()=>i?.(r),style:e,className:ui.cn("flex flex-row items-center cursor-pointer hover:text-foreground",c),children:p}):jsxRuntime.jsx("div",{style:e,className:ui.cn("flex flex-row items-center",c),children:p})}var X={asset:{flex:"0.8 1 0%"},position:{flex:"1.2 1 0%"},value:{flex:"0.8 1 0%"},entry:{flex:"0.8 1 0%"},mark:{flex:"0.8 1 0%"},liq:{flex:"0.8 1 0%"},marginPnl:{flex:"1.5 1 0%"},tpsl:{flex:"0.8 1 0%"},close:{flex:"0.8 1 0%"}},br={minWidth:1e3};function hr({positions:e,sortKey:t,sortDir:r,onSort:s,onMarketClose:n,onLimitClose:i,isClosing:o,className:a}){let{t:l}=i18n.useTranslation(),u=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:X.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.asset")}),jsxRuntime.jsx(N,{style:X.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.position")}),jsxRuntime.jsx(N,{style:X.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.positionValue")}),jsxRuntime.jsx(N,{style:X.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.entryPrice")}),jsxRuntime.jsx(N,{style:X.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.markPrice")}),jsxRuntime.jsx(N,{style:X.liq,sortKey:"liq",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui.StyledTooltip,{content:l("perpetuals.positions.tooltip.liqPrice"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsxs("span",{className:"border-b border-dashed border-default-500/40",children:[jsxRuntime.jsx("span",{className:"hidden sm:inline",children:l("perpetuals.positions.col.liqPrice")}),jsxRuntime.jsx("span",{className:"inline sm:hidden",children:l("perpetuals.positions.col.liqPriceShort")})]})})}),jsxRuntime.jsx(N,{style:X.marginPnl,sortKey:"marginPnl",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui.StyledTooltip,{content:l("perpetuals.positions.tooltip.marginPnl"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:l("perpetuals.positions.col.marginPnl")})})}),jsxRuntime.jsx(N,{style:X.tpsl,align:"center",children:l("perpetuals.positions.col.tpsl")}),jsxRuntime.jsx(N,{style:X.close,align:"end",children:l("perpetuals.positions.col.close")})]});return e.length===0?jsxRuntime.jsx("div",{className:ui.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",a),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...br,...ge},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:br,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:l("perpetuals.positions.empty")})]})}):jsxRuntime.jsx("div",{className:ui.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",a),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...br,...ge},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:br,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((c,p)=>jsxRuntime.jsx(Su,{position:c,striped:p%2===1,isClosing:o,onMarketClose:n,onLimitClose:i},c.symbol))})]})})}function Su({position:e,striped:t,isClosing:r,onMarketClose:s,onLimitClose:n}){let{t:i}=i18n.useTranslation(),o=e.symbol.split("-")[0],a=e.side==="long",l=i(a?"perpetuals.positions.long":"perpetuals.positions.short"),u=a?"text-bullish":"text-bearish",p=e.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t?at:void 0,children:jsxRuntime.jsxs("div",{style:fr,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsxs("div",{style:X.asset,className:"flex flex-row items-center justify-start gap-1.5",children:[jsxRuntime.jsx("img",{alt:o,src:`https://app.hyperliquid.xyz/coins/${o}.svg`,className:"rounded-full",style:{width:16,height:16},onError:d=>{d.currentTarget.style.display="none";}}),jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:o})]}),jsxRuntime.jsxs("div",{style:X.position,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",u),children:l}),jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-700",children:[lt(e.quantity,e.quantityRaw)," ",o]})]}),jsxRuntime.jsx("div",{style:X.value,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ge(e.notionalValue)})}),jsxRuntime.jsx("div",{style:X.entry,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:oe(e.entryPrice)})}),jsxRuntime.jsx("div",{style:X.mark,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:oe(e.markPrice)})}),jsxRuntime.jsx("div",{style:X.liq,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:oe(e.liquidationPrice)})}),jsxRuntime.jsxs("div",{style:X.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ge(e.margin)}),jsxRuntime.jsxs("span",{className:ui.cn("text-xs font-medium",p),children:["(",yr(e.unrealizedPnl)," /"," ",Oi(e.unrealizedPnlPercent),")"]})]}),jsxRuntime.jsxs("div",{style:{...X.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsxRuntime.jsx("span",{className:"pr-1 text-right text-xs font-normal text-default-700",children:e.takeProfitPrice!==void 0?oe(e.takeProfitPrice):"--"}),jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-500",children:"/"}),jsxRuntime.jsx("span",{className:"pl-1 text-left text-xs font-normal text-default-700",children:e.stopLossPrice!==void 0?oe(e.stopLossPrice):"--"})]}),jsxRuntime.jsxs("div",{style:X.close,className:"flex flex-row items-center justify-end gap-2",children:[jsxRuntime.jsx("button",{type:"button",onClick:()=>s(e),disabled:r,className:ui.cn("text-xs font-medium text-bearish","transition-opacity duration-150 ease-in-out","hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"),children:i("perpetuals.positions.close.market")}),jsxRuntime.jsx("button",{type:"button",onClick:()=>n(e),disabled:r,className:ui.cn("text-xs font-medium text-bearish","transition-opacity duration-150 ease-in-out","hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"),children:i("perpetuals.positions.close.limit")})]})]})})}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 wi(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open positions"})}function Di({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n,className:i}){let{positions:o,isLoading:a,sortKey:l,sortDir:u,onSort:c,closePosition:p}=mr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n});return a?jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(Sr,{})}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(hr,{positions:o,sortKey:l,sortDir:u,onSort:c,onMarketClose:p.openMarketClose,onLimitClose:p.openLimitClose,isClosing:p.isClosing,className:i}),jsxRuntime.jsx(pr,{isOpen:p.isModalOpen,position:p.selectedPosition,closeType:p.closeType,isSubmitting:p.isClosing,onClose:p.closeModal,onConfirm:p.handleConfirm})]})}function Ri(e,t){switch(t){case "time":return e.timestamp;case "size":return e.quantity;case "asset":return e.symbol.split("-")[0];case "direction":return e.side;case "type":return e.orderType;case "leverage":return e.leverage??null;case "orderValue":return e.isTrigger?null:e.price*e.quantity;case "executePrice":return e.isTrigger?null:e.price;case "currentPrice":return e.markPrice??null}}function Cu(e,t,r,s){let n=Ri(e,r),i=Ri(t,r);if(n===null&&i===null)return 0;if(n===null)return 1;if(i===null)return -1;let o;return typeof n=="string"&&typeof i=="string"?o=n.localeCompare(i):o=n-i,s==="asc"?o:-o}function vr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}){let[o,a]=react.useState("time"),[l,u]=react.useState("desc"),c=react.useCallback(A=>{a(k=>k===A?(u(z=>z==="asc"?"desc":"asc"),k):(u("asc"),A));},[]),{data:p,isLoading:d,error:f}=Nt({userAddress:e,symbol:t},{enabled:!!e}),b=react.useRef(new Set),[,m]=react.useState(0),v=react.useCallback(()=>m(A=>A+1),[]),g=react.useCallback(A=>{b.current.add(A),v();},[v]),S=react.useCallback(A=>{b.current.delete(A),v();},[v]),[T,x]=react.useState(false),{mutateAsync:w,isPending:H}=Ht({onSuccess:()=>{r?.();},onError:A=>{s?.(A);}}),_=react.useCallback(async A=>{if(n)try{let k=await n(A);return r?.(),k}catch(k){throw s?.(k instanceof Error?k:new Error(String(k))),k}if(i)try{let[k]=await i([A]);if(!k)throw new Error("cancelOrders returned no result");return r?.(),k}catch(k){throw s?.(k instanceof Error?k:new Error(String(k))),k}return w(A)},[n,i,w,r,s]),M=react.useMemo(()=>p?.orders??[],[p]),h=react.useMemo(()=>o?[...M].sort((A,k)=>Cu(A,k,o,l)):M,[M,o,l]),V=react.useCallback(async A=>{if(!e)throw new Error("User address is required");g(A.orderId);try{await _({orderId:A.orderId,symbol:A.symbol,userAddress:e});}finally{S(A.orderId);}},[e,_,g,S]),re=react.useCallback(async()=>{if(!e)throw new Error("User address is required");if(M.length!==0){x(true);try{let A=M.map(k=>({orderId:k.orderId,symbol:k.symbol,userAddress:e}));if(i){try{await i(A);for(let k=0;k<A.length;k++)r?.();}catch(k){s?.(k instanceof Error?k:new Error(String(k)));}return}await Promise.allSettled(A.map(k=>_(k)));}finally{x(false);}}},[e,M,i,_,r,s]),L=b.current.size>0||T||H;return {orders:h,isLoading:d,error:f,sortKey:o,sortDir:l,onSort:c,handleCancelOrder:V,handleCancelAll:re,isCanceling:L,cancelingOrderIds:b.current,isCancelingAll:T}}var q={time:{flex:"1 1 0%",maxWidth:160},size:{flex:"1 1 0%",maxWidth:80},asset:{flex:"1 1 0%",maxWidth:70},direction:{flex:"1 1 0%",maxWidth:70},type:{flex:"1 1 0%",maxWidth:160},leverage:{flex:"1 1 0%",maxWidth:80},orderValue:{flex:"1 1 0%",maxWidth:100},executePrice:{flex:"1 1 0%",maxWidth:100},currentPrice:{flex:"1 1 0%",maxWidth:100},triggerCondition:{flex:"1 1 0%"},tpsl:{flex:"1 1 0%",maxWidth:120},cancel:{flex:"1 1 0%",maxWidth:70}},Cr={minWidth:1100};function ku(e,t){let r=e.orderType==="limit";return e.isTrigger?e.triggerType==="tp"?r?"Take Profit Limit":"Take Profit Market":e.triggerType==="sl"?r?"Stop Limit":"Stop Market":r?"Limit":t:r?"Limit":t}function Or({orders:e,sortKey:t,sortDir:r,onSort:s,onCancelOrder:n,onCancelAll:i,cancelingOrderIds:o,isCancelingAll:a,className:l}){let{t:u}=i18n.useTranslation(),c=u("perpetuals.openOrders.market"),p=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:q.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.time")}),jsxRuntime.jsx(N,{style:q.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.size")}),jsxRuntime.jsx(N,{style:q.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.asset")}),jsxRuntime.jsx(N,{style:q.direction,sortKey:"direction",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.direction")}),jsxRuntime.jsx(N,{style:q.type,sortKey:"type",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.type")}),jsxRuntime.jsx(N,{style:q.leverage,sortKey:"leverage",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui.StyledTooltip,{content:u("perpetuals.openOrders.tooltip.leverage"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:u("perpetuals.openOrders.col.leverage")})})}),jsxRuntime.jsx(N,{style:q.orderValue,sortKey:"orderValue",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.orderValue")}),jsxRuntime.jsx(N,{style:q.executePrice,sortKey:"executePrice",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.executePrice")}),jsxRuntime.jsx(N,{style:q.currentPrice,sortKey:"currentPrice",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.currentPrice")}),jsxRuntime.jsx(N,{style:q.triggerCondition,children:u("perpetuals.openOrders.col.triggerCondition")}),jsxRuntime.jsx(N,{style:q.tpsl,align:"center",children:u("perpetuals.openOrders.col.tpsl")}),jsxRuntime.jsx("div",{style:q.cancel,className:"flex flex-row items-center justify-center",children:jsxRuntime.jsx("button",{type:"button",onClick:i,disabled:a||e.length===0,className:ui.cn("inline-flex min-w-[60px] items-center justify-center gap-1","text-xs font-medium text-bearish","cursor-pointer transition-colors duration-150","hover:text-bearish/80 disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),children:a?jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}):u("perpetuals.openOrders.col.cancelAll")})})]});return e.length===0?jsxRuntime.jsx("div",{className:ui.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",l),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...Cr,...ge},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:Cr,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:u("perpetuals.openOrders.empty")})]})}):jsxRuntime.jsx("div",{className:ui.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",l),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...Cr,...ge},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:Cr,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((d,f)=>jsxRuntime.jsx(Tu,{order:d,striped:f%2===1,isThisRowCanceling:o.has(d.orderId),isBatchCanceling:a,marketLabel:c,onCancel:n},d.orderId))})]})})}function Tu({order:e,striped:t,isThisRowCanceling:r,isBatchCanceling:s,marketLabel:n,onCancel:i}){let{t:o}=i18n.useTranslation(),a=e.symbol.split("-")[0],l=e.side==="long",u=o(l?"perpetuals.openOrders.long":"perpetuals.openOrders.short"),c=l?"text-bullish":"text-bearish",p=ku(e,n),d=e.isTrigger?n:Ge(e.price*e.quantity),f=e.isTrigger?n:oe(e.price);return jsxRuntime.jsx("div",{style:t?at:void 0,children:jsxRuntime.jsxs("div",{style:fr,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsx("div",{style:q.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:gr(e.timestamp)})}),jsxRuntime.jsx("div",{style:q.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:lt(e.quantity)})}),jsxRuntime.jsx("div",{style:q.asset,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:a})}),jsxRuntime.jsx("div",{style:q.direction,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",c),children:u})}),jsxRuntime.jsx("div",{style:q.type,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:p})}),jsxRuntime.jsx("div",{style:q.leverage,className:"flex flex-row items-center justify-start",children:e.leverage!==void 0?jsxRuntime.jsxs("span",{className:ui.cn("inline-flex flex-row items-center justify-start gap-1","rounded p-1 bg-default-200/50","text-xs font-normal text-default-700"),style:{height:18},children:[e.leverage,"x"]}):jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-500",children:"--"})}),jsxRuntime.jsx("div",{style:q.orderValue,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:d})}),jsxRuntime.jsx("div",{style:q.executePrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:f})}),jsxRuntime.jsx("div",{style:q.currentPrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:oe(e.markPrice)})}),jsxRuntime.jsx("div",{style:q.triggerCondition,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:e.triggerCondition??"--"})}),jsxRuntime.jsxs("div",{style:{...q.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsxRuntime.jsx("span",{className:"pr-1 text-right text-xs font-normal text-default-700",children:e.takeProfitPrice!==void 0?oe(e.takeProfitPrice):"--"}),jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-500",children:"/"}),jsxRuntime.jsx("span",{className:"pl-1 text-left text-xs font-normal text-default-700",children:e.stopLossPrice!==void 0?oe(e.stopLossPrice):"--"})]}),jsxRuntime.jsx("div",{style:q.cancel,className:"flex flex-row items-center justify-end gap-1",children:jsxRuntime.jsx("button",{type:"button",onClick:()=>i(e),disabled:r||s,"aria-label":o("perpetuals.openOrders.cancelOne.aria"),"aria-busy":r||void 0,className:ui.cn("inline-flex items-center justify-center rounded p-1","cursor-pointer text-bearish transition-colors duration-150 ease-in-out","hover:bg-bearish/10","disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),style:{height:24,width:24},children:r?jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current",style:{transform:"scale(0.6)"}}):jsxRuntime.jsx("svg",{viewBox:"0 0 14 14",width:12,height:12,fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round","aria-hidden":"true",children:jsxRuntime.jsx("path",{d:"M3 3 L11 11 M11 3 L3 11"})})})})]})})}function Ii(){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 Mi(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open orders"})}function Ni({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i,className:o}){let{t:a}=i18n.useTranslation(),{orders:l,sortKey:u,sortDir:c,onSort:p,handleCancelOrder:d,handleCancelAll:f,cancelingOrderIds:b,isCancelingAll:m}=vr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}),[v,g]=react.useState(false),S=react.useCallback(()=>{l.length!==0&&g(true);},[l.length]),T=react.useCallback(()=>{m||g(false);},[m]),x=react.useCallback(async()=>{try{await f();}finally{g(false);}},[f]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Or,{className:o,orders:l,sortKey:u,sortDir:c,onSort:p,onCancelOrder:d,onCancelAll:S,cancelingOrderIds:b,isCancelingAll:m}),jsxRuntime.jsx(ui.StyledModal,{isOpen:v,onOpenChange:w=>{m||w||T();},size:"md",hideCloseButton:true,backdrop:"opaque",classNames:{base:ui.cn("!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.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:a("perpetuals.openOrders.cancelAll.confirmTitle")}),jsxRuntime.jsx("button",{type:"button",onClick:T,disabled:m,"aria-label":"Close",className:ui.cn("p-1 rounded-[10px] cursor-pointer","hover:bg-[rgba(39,39,42,0.5)]","text-zinc-400 hover:text-white transition-colors","disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),children:jsxRuntime.jsx(ui.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:a("perpetuals.openOrders.cancelAll.confirmBody")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{x();},disabled:m,className:ui.cn("cursor-pointer mt-1 w-full h-12 rounded-[12px]","font-medium text-white","bg-bearish hover:bg-bearish/90 active:bg-bearish/80","transition-colors flex items-center justify-center gap-2","disabled:bg-[#3f3f46] disabled:text-zinc-500 disabled:cursor-not-allowed","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),children:[m&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),a(m?"perpetuals.openOrders.cancelAll.confirming":"perpetuals.openOrders.cancelAll.confirm")]})]})]})})})]})}function qi(e,t){switch(t){case "time":return e.timestamp;case "size":return e.quantity;case "asset":return e.symbol.split("-")[0];case "description":return e.dir??null;case "price":return e.price;case "tradeValue":return e.price*e.quantity;case "closedPnl":return e.closedPnl??null}}function Nu(e,t,r,s){let n=qi(e,r),i=qi(t,r);if(n===null&&i===null)return 0;if(n===null)return 1;if(i===null)return -1;let o;return typeof n=="string"&&typeof i=="string"?o=n.localeCompare(i):o=n-i,s==="asc"?o:-o}function kr({userAddress:e,symbol:t}){let[r,s]=react.useState("time"),[n,i]=react.useState("desc"),o=react.useCallback(d=>{s(f=>f===d?(i(b=>b==="asc"?"desc":"asc"),f):(i("desc"),d));},[]),{data:a,isLoading:l,error:u}=Lt({userAddress:e,symbol:t},{enabled:!!e,staleTime:5e3}),c=react.useMemo(()=>a?.trades??[],[a]);return {trades:react.useMemo(()=>[...c].sort((d,f)=>Nu(d,f,r,n)),[c,r,n]),isLoading:l,error:u,sortKey:r,sortDir:n,onSort:o}}var ne={time:{flex:"1 1 0%",maxWidth:200},size:{flex:"1 1 0%",maxWidth:80},asset:{flex:"1 1 0%",maxWidth:100},description:{flex:"1 1 0%",maxWidth:300},price:{flex:"1 1 0%"},tradeValue:{flex:"1 1 0%"},closedPnl:{flex:"1 1 0%"}},$s={minWidth:1100},Bu=48,Hi={minHeight:36,maxHeight:36,padding:"0 16px"};function Qu(e){return e?!!(/^Open\s+Long\b/i.test(e)||/^Close\s+Short\b/i.test(e)):false}function wr({trades:e,sortKey:t,sortDir:r,onSort:s,className:n}){let{t:i}=i18n.useTranslation(),o=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:ne.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.time")}),jsxRuntime.jsx(N,{style:ne.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.size")}),jsxRuntime.jsx(N,{style:ne.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.asset")}),jsxRuntime.jsx(N,{style:ne.description,sortKey:"description",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.description")}),jsxRuntime.jsx(N,{style:ne.price,sortKey:"price",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.price")}),jsxRuntime.jsx(N,{style:ne.tradeValue,sortKey:"tradeValue",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.tradeValue")}),jsxRuntime.jsx(N,{style:ne.closedPnl,sortKey:"closedPnl",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.closedPnl")})]});return jsxRuntime.jsx("div",{className:ui.cn("flex h-full w-full min-w-0 flex-col overflow-hidden bg-transparent",n),children:jsxRuntime.jsxs("div",{className:"flex flex-1 min-h-0 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...$s,...ge},className:"flex flex-none flex-col",children:o}),e.length===0?jsxRuntime.jsx("div",{style:$s,className:"flex flex-1 min-h-0 flex-col items-center justify-center py-6 text-xs text-default-700",children:i("perpetuals.tradeHistory.empty")}):jsxRuntime.jsx(Ku,{trades:e})]})})}function Ku({trades:e}){let t=react.useRef(null),{height:r=0}=hooks.useResizeObserver({ref:t}),s=react.useMemo(()=>({trades:e}),[e]);return jsxRuntime.jsx("div",{ref:t,style:$s,className:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:r>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:r},rowComponent:zu,rowCount:e.length,rowHeight:Bu,rowProps:s,overscanCount:4})})}function zu({index:e,style:t,trades:r}){let s=r[e];if(!s)return null;let n=e%2===1,i=s.symbol.split("-")[0],o=s.price*s.quantity,a=s.closedPnl??0,l=Qu(s.dir),u=s.dir??"",c=l?"text-bullish":"text-bearish",p=a>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:n?{...Hi,...at}:Hi,className:"flex flex-1 flex-row items-center justify-start",children:[jsxRuntime.jsx("div",{style:ne.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-500",children:gr(s.timestamp)})}),jsxRuntime.jsx("div",{style:ne.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:lt(s.quantity)})}),jsxRuntime.jsx("div",{style:ne.asset,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:i})}),jsxRuntime.jsx("div",{style:ne.description,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui.cn("text-xs font-normal",c),children:u})}),jsxRuntime.jsx("div",{style:ne.price,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"font-normal text-default-700",style:{fontSize:11,lineHeight:"16px"},children:oe(s.price)})}),jsxRuntime.jsx("div",{style:ne.tradeValue,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ge(o)})}),jsxRuntime.jsx("div",{style:ne.closedPnl,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",p),children:yr(a)})})]})})}function _i(){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 Bi(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No trades"})}function Qi({userAddress:e,symbol:t,className:r}){let{trades:s,sortKey:n,sortDir:i,onSort:o}=kr({userAddress:e,symbol:t});return jsxRuntime.jsx(wr,{className:r,trades:s,sortKey:n,sortDir:i,onSort:o})}var $u=1000000000n,Ki=8,Vu=10n**BigInt(8);function ct(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Wi(r,$u,t)}function Tt(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return Wi(r,Vu,t)}var zi=Tt;function Dr(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 Wi(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),l=(o*a+t/2n)/t;l>=a&&(i+=1n,l=0n);let u=l.toString().padStart(r,"0");return u=u.replace(/0+$/,""),u?`${s?"-":""}${i.toString()}.${u}`:`${s?"-":""}${i.toString()}`}function dt(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function Er(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:l}=i18n.useTranslation(),u=t?Date.parse(t.expiresAt):0,[c,p]=react.useState(()=>u?dt(u):0);return react.useEffect(()=>{if(!e||!u)return;p(dt(u));let d=setInterval(()=>{let f=dt(u);p(f),f===0&&(o?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,u,o]),jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:d=>!d&&i(),hideCloseButton:true,backdrop:"opaque",children:jsxRuntime.jsxs(ui.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui.ModalHeader,{children:l("perpDeposit.confirm.title")}),jsxRuntime.jsxs(ui.ModalBody,{children:[t?jsxRuntime.jsx(rp,{breakdown:t.breakdown}):jsxRuntime.jsx("div",{className:"flex h-32 items-center justify-center",children:jsxRuntime.jsx(ui.Spinner,{})}),t&&!s&&jsxRuntime.jsx("div",{className:"text-default-500 mt-4 text-xs",children:l("perpDeposit.confirm.expiresIn",{seconds:c})}),s&&jsxRuntime.jsx("div",{className:"text-warning-500 mt-4 text-xs",children:l("perpDeposit.confirm.expired")}),a&&jsxRuntime.jsx("div",{className:"text-danger mt-4 text-xs",children:a})]}),jsxRuntime.jsxs(ui.ModalFooter,{className:"flex justify-between gap-2",children:[jsxRuntime.jsx(ui.Button,{variant:"flat",color:"default",onPress:i,isDisabled:r,children:l("perpDeposit.confirm.cancel")}),jsxRuntime.jsx(ui.Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:l("perpDeposit.confirm.cta")})]})]})})}function rp({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(Rr,{label:t("perpDeposit.confirm.send"),value:`${ct(e.grossLamports)} SOL`}),jsxRuntime.jsx(Rr,{label:t("perpDeposit.confirm.receive"),value:`${Tt(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(Rr,{label:t("perpDeposit.confirm.platformFee"),value:`${ct(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(Rr,{label:t("perpDeposit.confirm.relayFee"),value:`${ct(e.relayDepositLamports,6)} SOL`,muted:true})]})}function Rr({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 Ur({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:l,className:u}){let{t:c}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui.cn("flex flex-col gap-4",u),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:c("perpDeposit.amount")}),n&&jsxRuntime.jsx("span",{className:"text-xs text-default-500",children:c("perpDeposit.amount.balance",{balance:n})})]}),jsxRuntime.jsx("div",{className:"relative",children:jsxRuntime.jsx(ui.Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:c("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:c("perpDeposit.amount.unit")}),n&&l&&jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"primary",onPress:l,isDisabled:i,children:c("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:c("perpDeposit.recipient")}),jsxRuntime.jsx(ui.Input,{id:"perp-deposit-recipient",type:"text",placeholder:c("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:i,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}var Yi="#C7FF2E";function Ir({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:l}=i18n.useTranslation(),u=dp(t),c=t==="failed"?a||(r?.lastError?.message?l("perpDeposit.status.failed",{message:r.lastError.message}):l("perpDeposit.status.failed",{message:""})):t==="succeeded"?l("perpDeposit.status.settled"):t==="refunded"?l("perpDeposit.status.refunded"):r?.status==="broadcasted"?l("perpDeposit.status.broadcasted"):r?.status==="relay_waiting"?l("perpDeposit.status.relay_waiting"):r?.status==="relay_pending"?l("perpDeposit.status.relay_pending"):r?.status==="stuck"?l("perpDeposit.status.stuck"):l("perpDeposit.status.broadcasted"),p=t==="failed"&&!!i;return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:d=>!d&&o(),size:"md",hideCloseButton:true,backdrop:"opaque",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.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:l("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":l("perpDeposit.status.close"),children:jsxRuntime.jsx(ui.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(pp,{variant:u}),jsxRuntime.jsx("p",{className:ui.cn("text-sm leading-relaxed max-w-[320px]",mp(u)),children:c})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(ji,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(ji,{href:n,label:l("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxRuntime.jsxs("div",{className:ui.cn("px-5 pb-5 pt-2 flex gap-2",p?"justify-between":"justify-end"),children:[p&&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:l("perpDeposit.status.tryAgain")}),jsxRuntime.jsx("button",{type:"button",onClick:o,className:ui.cn("cursor-pointer h-10 rounded-[10px] font-medium transition-colors flex items-center justify-center",p?"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:l("perpDeposit.status.close")})]})]})})})}function ji({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:[Er(r,6,4),jsxRuntime.jsx(bp,{})]})]})}function pp({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(cp,{})}):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(fp,{className:"w-8 h-8",style:{color:Yi}})}):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(yp,{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(gp,{className:"w-8 h-8 text-rose-400"})})}function cp(){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:Yi,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsxRuntime.jsx("style",{children:`
|
|
36
|
+
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(_),onChange:L,min:0,max:100,step:1,disabled:a<=0,className:"perp-close-slider",style:{"--pct":`${Math.round(_)}%`}}),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("button",{type:"button",onClick:()=>{Fe();},disabled:!j,className:"w-full transition-colors disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{marginTop:4,height:44,fontSize:14,fontWeight:600,color:"#000000",backgroundColor:j?Ot:"hsl(var(--heroui-content4) / 0.6)",borderRadius:9999,border:"none",cursor:j?"pointer":"not-allowed",opacity:j?1:.9},children:[s&&jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}),s?"Closing...":te]})]})]})})})}function mr({userAddress:e,onCloseSuccess:t,onCloseError:r,onPlaceOrder:s}){let[n,o]=react.useState(false),[i,a]=react.useState(null),[l,u]=react.useState("market"),{data:c}=rt({symbol:i?.symbol}),{mutateAsync:p,isPending:d}=reactQuery.useMutation({mutationFn:async b=>{if(!s)throw new Error("onPlaceOrder is not configured; cannot submit close order");return await s(b)},onSuccess:()=>{o(false),a(null),t?.();},onError:b=>{r?.(b);}}),f=react.useCallback(b=>{a(b),u("market"),o(true);},[]),g=react.useCallback(b=>{a(b),u("limit"),o(true);},[]),m=react.useCallback(()=>{d||(o(false),a(null));},[d]),P=react.useCallback(async(b,S)=>{if(!i||!e)throw new Error("Position and user address are required");let T=i.side==="long"?"short":"long",x=l==="limit"?"limit":"market",D=i.markPrice||i.entryPrice,H=c?.szDecimals??5;await p({symbol:i.symbol,side:T,orderType:x,amount:b*D,price:x==="limit"?S:void 0,leverage:i.leverage,reduceOnly:true,userAddress:e,size:b,refPrice:D,szDecimals:H});},[i,e,l,c,p]);return {isModalOpen:n,selectedPosition:i,closeType:l,isClosing:d,openMarketClose:f,openLimitClose:g,handleConfirm:P,closeModal:m}}function ko(e,t){switch(t){case "asset":return e.symbol.split("-")[0];case "position":return Math.abs(e.quantity);case "value":return e.notionalValue;case "entry":return e.entryPrice;case "mark":return e.markPrice;case "liq":return e.liquidationPrice??null;case "marginPnl":return e.margin}}function Su(e,t,r,s){let n=ko(e,r),o=ko(t,r);if(n===null&&o===null)return 0;if(n===null)return 1;if(o===null)return -1;let i;return typeof n=="string"&&typeof o=="string"?i=n.localeCompare(o):i=n-o,s==="asc"?i:-i}function fr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}){let[o,i]=react.useState("marginPnl"),[a,l]=react.useState("desc"),u=react.useCallback(P=>{i(b=>b===P?(l(S=>S==="asc"?"desc":"asc"),b):(l("asc"),P));},[]),{data:c,isLoading:p,error:d}=tt({userAddress:e,symbol:t},{enabled:!!e}),f=mr({userAddress:e,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}),g=react.useMemo(()=>c?.positions??[],[c]);return {positions:react.useMemo(()=>o?[...g].sort((P,b)=>Su(P,b,o,a)):g,[g,o,a]),isLoading:p,error:d,sortKey:o,sortDir:a,onSort:u,closePosition:f}}var Cu={start:"justify-start",center:"justify-center",end:"justify-end"},ge={minHeight:28,maxHeight:28},yr={minHeight:36,maxHeight:36},it={backgroundColor:"rgba(255, 255, 255, 0.06)"};function ie(e){return e===void 0||!Number.isFinite(e)?"--":utils.formatPriceInUsd(e)}function Ge(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"--"}function gr(e){return Number.isFinite(e)?utils.formatAmountInUsd(e,{showPlusGtThanZero:true}):"--"}function Eo(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function at(e,t){return t||(Number.isFinite(e)?utils.formatAmount(e):"--")}function br(e){if(e===void 0||!Number.isFinite(e))return "--";let t=new Date(e);if(Number.isNaN(t.getTime()))return "--";let r=t.getFullYear(),s=t.getMonth()+1,n=t.getDate(),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0");return `${r}/${s}/${n} ${o}:${i}:${a}`}function N({style:e,children:t,sortKey:r,activeSortKey:s,sortDir:n,onSort:o,align:i="start"}){let l=r!==void 0&&r===s?n==="asc"?" \u2191":" \u2193":"",u=r!==void 0&&o!==void 0,c=Cu[i],p=jsxRuntime.jsxs("span",{className:"text-xs font-normal text-text-muted",children:[t,l]});return u?jsxRuntime.jsx("button",{type:"button",onClick:()=>o?.(r),style:e,className:ui$1.cn("flex flex-row items-center cursor-pointer hover:text-foreground",c),children:p}):jsxRuntime.jsx("div",{style:e,className:ui$1.cn("flex flex-row items-center",c),children:p})}var X={asset:{flex:"0.8 1 0%"},position:{flex:"1.2 1 0%"},value:{flex:"0.8 1 0%"},entry:{flex:"0.8 1 0%"},mark:{flex:"0.8 1 0%"},liq:{flex:"0.8 1 0%"},marginPnl:{flex:"1.5 1 0%"},tpsl:{flex:"0.8 1 0%"},close:{flex:"0.8 1 0%"}},hr={minWidth:1e3};function xr({positions:e,sortKey:t,sortDir:r,onSort:s,onMarketClose:n,onLimitClose:o,isClosing:i,className:a}){let{t:l}=i18n.useTranslation(),u=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:X.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.asset")}),jsxRuntime.jsx(N,{style:X.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.position")}),jsxRuntime.jsx(N,{style:X.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.positionValue")}),jsxRuntime.jsx(N,{style:X.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.entryPrice")}),jsxRuntime.jsx(N,{style:X.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.markPrice")}),jsxRuntime.jsx(N,{style:X.liq,sortKey:"liq",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui$1.StyledTooltip,{content:l("perpetuals.positions.tooltip.liqPrice"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsxs("span",{className:"border-b border-dashed border-default-500/40",children:[jsxRuntime.jsx("span",{className:"hidden sm:inline",children:l("perpetuals.positions.col.liqPrice")}),jsxRuntime.jsx("span",{className:"inline sm:hidden",children:l("perpetuals.positions.col.liqPriceShort")})]})})}),jsxRuntime.jsx(N,{style:X.marginPnl,sortKey:"marginPnl",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui$1.StyledTooltip,{content:l("perpetuals.positions.tooltip.marginPnl"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:l("perpetuals.positions.col.marginPnl")})})}),jsxRuntime.jsx(N,{style:X.tpsl,align:"center",children:l("perpetuals.positions.col.tpsl")}),jsxRuntime.jsx(N,{style:X.close,align:"end",children:l("perpetuals.positions.col.close")})]});return e.length===0?jsxRuntime.jsx("div",{className:ui$1.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",a),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...hr,...ge},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:hr,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-text-secondary",children:l("perpetuals.positions.empty")})]})}):jsxRuntime.jsx("div",{className:ui$1.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",a),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...hr,...ge},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:hr,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((c,p)=>jsxRuntime.jsx(ku,{position:c,striped:p%2===1,isClosing:i,onMarketClose:n,onLimitClose:o},c.symbol))})]})})}function ku({position:e,striped:t,isClosing:r,onMarketClose:s,onLimitClose:n}){let{t:o}=i18n.useTranslation(),i=e.symbol.split("-")[0],a=e.side==="long",l=o(a?"perpetuals.positions.long":"perpetuals.positions.short"),u=a?"text-positive":"text-negative",p=e.unrealizedPnl>=0?"text-positive":"text-negative";return jsxRuntime.jsx("div",{style:t?it:void 0,children:jsxRuntime.jsxs("div",{style:yr,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsxs("div",{style:X.asset,className:"flex flex-row items-center justify-start gap-1.5",children:[jsxRuntime.jsx("img",{alt:i,src:`https://app.hyperliquid.xyz/coins/${i}.svg`,className:"rounded-full",style:{width:16,height:16},onError:d=>{d.currentTarget.style.display="none";}}),jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:i})]}),jsxRuntime.jsxs("div",{style:X.position,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:ui$1.cn("text-xs font-medium",u),children:l}),jsxRuntime.jsxs("span",{className:"text-xs font-normal text-text-secondary",children:[at(e.quantity,e.quantityRaw)," ",i]})]}),jsxRuntime.jsx("div",{style:X.value,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:Ge(e.notionalValue)})}),jsxRuntime.jsx("div",{style:X.entry,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:ie(e.entryPrice)})}),jsxRuntime.jsx("div",{style:X.mark,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:X.liq,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:ie(e.liquidationPrice)})}),jsxRuntime.jsxs("div",{style:X.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:Ge(e.margin)}),jsxRuntime.jsxs("span",{className:ui$1.cn("text-xs font-medium",p),children:["(",gr(e.unrealizedPnl)," /"," ",Eo(e.unrealizedPnlPercent),")"]})]}),jsxRuntime.jsxs("div",{style:{...X.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsxRuntime.jsx("span",{className:"pr-1 text-right text-xs font-normal text-text-secondary",children:e.takeProfitPrice!==void 0?ie(e.takeProfitPrice):"--"}),jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-muted",children:"/"}),jsxRuntime.jsx("span",{className:"pl-1 text-left text-xs font-normal text-text-secondary",children:e.stopLossPrice!==void 0?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsxs("div",{style:X.close,className:"flex flex-row items-center justify-end gap-2",children:[jsxRuntime.jsx("button",{type:"button",onClick:()=>s(e),disabled:r,className:ui$1.cn("text-xs font-medium text-negative","transition-opacity duration-150 ease-in-out","hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"),children:o("perpetuals.positions.close.market")}),jsxRuntime.jsx("button",{type:"button",onClick:()=>n(e),disabled:r,className:ui$1.cn("text-xs font-medium text-negative","transition-opacity duration-150 ease-in-out","hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"),children:o("perpetuals.positions.close.limit")})]})]})})}function Sr(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"})]})}function Ao(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-text-secondary",children:e("perpetuals.positions.empty")})}function Uo({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n,className:o}){let{positions:i,isLoading:a,sortKey:l,sortDir:u,onSort:c,closePosition:p}=fr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n});return a?jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsx(Sr,{})}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(xr,{positions:i,sortKey:l,sortDir:u,onSort:c,onMarketClose:p.openMarketClose,onLimitClose:p.openLimitClose,isClosing:p.isClosing,className:o}),jsxRuntime.jsx(cr,{isOpen:p.isModalOpen,position:p.selectedPosition,closeType:p.closeType,isSubmitting:p.isClosing,onClose:p.closeModal,onConfirm:p.handleConfirm})]})}function Mo(e,t){switch(t){case "time":return e.timestamp;case "size":return e.quantity;case "asset":return e.symbol.split("-")[0];case "direction":return e.side;case "type":return e.orderType;case "leverage":return e.leverage??null;case "orderValue":return e.isTrigger?null:e.price*e.quantity;case "executePrice":return e.isTrigger?null:e.price;case "currentPrice":return e.markPrice??null}}function Eu(e,t,r,s){let n=Mo(e,r),o=Mo(t,r);if(n===null&&o===null)return 0;if(n===null)return 1;if(o===null)return -1;let i;return typeof n=="string"&&typeof o=="string"?i=n.localeCompare(o):i=n-o,s==="asc"?i:-i}function Cr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:o}){let[i,a]=react.useState("time"),[l,u]=react.useState("desc"),c=react.useCallback(A=>{a(k=>k===A?(u(W=>W==="asc"?"desc":"asc"),k):(u("asc"),A));},[]),{data:p,isLoading:d,error:f}=Nt({userAddress:e,symbol:t},{enabled:!!e}),g=react.useRef(new Set),[,m]=react.useState(0),P=react.useCallback(()=>m(A=>A+1),[]),b=react.useCallback(A=>{g.current.add(A),P();},[P]),S=react.useCallback(A=>{g.current.delete(A),P();},[P]),[T,x]=react.useState(false),{mutateAsync:D,isPending:H}=Ht({onSuccess:()=>{r?.();},onError:A=>{s?.(A);}}),_=react.useCallback(async A=>{if(n)try{let k=await n(A);return r?.(),k}catch(k){throw s?.(k instanceof Error?k:new Error(String(k))),k}if(o)try{let[k]=await o([A]);if(!k)throw new Error("cancelOrders returned no result");return r?.(),k}catch(k){throw s?.(k instanceof Error?k:new Error(String(k))),k}return D(A)},[n,o,D,r,s]),M=react.useMemo(()=>p?.orders??[],[p]),h=react.useMemo(()=>i?[...M].sort((A,k)=>Eu(A,k,i,l)):M,[M,i,l]),V=react.useCallback(async A=>{if(!e)throw new Error("User address is required");b(A.orderId);try{await _({orderId:A.orderId,symbol:A.symbol,userAddress:e});}finally{S(A.orderId);}},[e,_,b,S]),re=react.useCallback(async()=>{if(!e)throw new Error("User address is required");if(M.length!==0){x(true);try{let A=M.map(k=>({orderId:k.orderId,symbol:k.symbol,userAddress:e}));if(o){try{await o(A);for(let k=0;k<A.length;k++)r?.();}catch(k){s?.(k instanceof Error?k:new Error(String(k)));}return}await Promise.allSettled(A.map(k=>_(k)));}finally{x(false);}}},[e,M,o,_,r,s]),L=g.current.size>0||T||H;return {orders:h,isLoading:d,error:f,sortKey:i,sortDir:l,onSort:c,handleCancelOrder:V,handleCancelAll:re,isCanceling:L,cancelingOrderIds:g.current,isCancelingAll:T}}function Au(e){return `${e}x`}var q={time:{flex:"1 1 0%",maxWidth:160},size:{flex:"1 1 0%",maxWidth:80},asset:{flex:"1 1 0%",maxWidth:70},direction:{flex:"1 1 0%",maxWidth:70},type:{flex:"1 1 0%",maxWidth:160},leverage:{flex:"1 1 0%",maxWidth:80},orderValue:{flex:"1 1 0%",maxWidth:100},executePrice:{flex:"1 1 0%",maxWidth:100},currentPrice:{flex:"1 1 0%",maxWidth:100},triggerCondition:{flex:"1 1 0%"},tpsl:{flex:"1 1 0%",maxWidth:120},cancel:{flex:"1 1 0%",maxWidth:70}},Or={minWidth:1100};function Uu(e,t){let r=e.orderType==="limit";return e.isTrigger?e.triggerType==="tp"?r?"Take Profit Limit":"Take Profit Market":e.triggerType==="sl"?r?"Stop Limit":"Stop Market":r?"Limit":t:r?"Limit":t}function kr({orders:e,sortKey:t,sortDir:r,onSort:s,onCancelOrder:n,onCancelAll:o,cancelingOrderIds:i,isCancelingAll:a,className:l}){let{t:u}=i18n.useTranslation(),c=u("perpetuals.openOrders.market"),p=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:q.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.time")}),jsxRuntime.jsx(N,{style:q.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.size")}),jsxRuntime.jsx(N,{style:q.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.asset")}),jsxRuntime.jsx(N,{style:q.direction,sortKey:"direction",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.direction")}),jsxRuntime.jsx(N,{style:q.type,sortKey:"type",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.type")}),jsxRuntime.jsx(N,{style:q.leverage,sortKey:"leverage",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui$1.StyledTooltip,{content:u("perpetuals.openOrders.tooltip.leverage"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:u("perpetuals.openOrders.col.leverage")})})}),jsxRuntime.jsx(N,{style:q.orderValue,sortKey:"orderValue",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.orderValue")}),jsxRuntime.jsx(N,{style:q.executePrice,sortKey:"executePrice",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.executePrice")}),jsxRuntime.jsx(N,{style:q.currentPrice,sortKey:"currentPrice",activeSortKey:t,sortDir:r,onSort:s,children:u("perpetuals.openOrders.col.currentPrice")}),jsxRuntime.jsx(N,{style:q.triggerCondition,children:u("perpetuals.openOrders.col.triggerCondition")}),jsxRuntime.jsx(N,{style:q.tpsl,align:"center",children:u("perpetuals.openOrders.col.tpsl")}),jsxRuntime.jsx("div",{style:q.cancel,className:"flex flex-row items-center justify-center",children:jsxRuntime.jsx("button",{type:"button",onClick:o,disabled:a||e.length===0,className:ui$1.cn("inline-flex min-w-[60px] items-center justify-center gap-1","text-xs font-medium text-negative","cursor-pointer transition-colors duration-150","hover:text-negative/80 disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),children:a?jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}):u("perpetuals.openOrders.col.cancelAll")})})]});return e.length===0?jsxRuntime.jsx("div",{className:ui$1.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",l),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...Or,...ge},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:Or,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-text-secondary",children:u("perpetuals.openOrders.empty")})]})}):jsxRuntime.jsx("div",{className:ui$1.cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",l),children:jsxRuntime.jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...Or,...ge},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:Or,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((d,f)=>jsxRuntime.jsx(Iu,{order:d,striped:f%2===1,isThisRowCanceling:i.has(d.orderId),isBatchCanceling:a,marketLabel:c,onCancel:n},d.orderId))})]})})}function Iu({order:e,striped:t,isThisRowCanceling:r,isBatchCanceling:s,marketLabel:n,onCancel:o}){let{t:i}=i18n.useTranslation(),a=e.symbol.split("-")[0],l=e.side==="long",u=i(l?"perpetuals.openOrders.long":"perpetuals.openOrders.short"),c=l?"text-positive":"text-negative",p=Uu(e,n),d=e.isTrigger?n:Ge(e.price*e.quantity),f=e.isTrigger?n:ie(e.price);return jsxRuntime.jsx("div",{style:t?it:void 0,children:jsxRuntime.jsxs("div",{style:yr,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsx("div",{style:q.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:br(e.timestamp)})}),jsxRuntime.jsx("div",{style:q.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:at(e.quantity)})}),jsxRuntime.jsx("div",{style:q.asset,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:a})}),jsxRuntime.jsx("div",{style:q.direction,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui$1.cn("text-xs font-medium",c),children:u})}),jsxRuntime.jsx("div",{style:q.type,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:p})}),jsxRuntime.jsx("div",{style:q.leverage,className:"flex flex-row items-center justify-start",children:e.leverage!==void 0?jsxRuntime.jsx("span",{className:ui$1.cn("inline-flex flex-row items-center justify-start gap-1","rounded p-1 bg-default-200/50","text-xs font-normal text-text-secondary"),style:{height:18},children:Au(e.leverage)}):jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-muted",children:"--"})}),jsxRuntime.jsx("div",{style:q.orderValue,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:d})}),jsxRuntime.jsx("div",{style:q.executePrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:f})}),jsxRuntime.jsx("div",{style:q.currentPrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:q.triggerCondition,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:e.triggerCondition??"--"})}),jsxRuntime.jsxs("div",{style:{...q.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsxRuntime.jsx("span",{className:"pr-1 text-right text-xs font-normal text-text-secondary",children:e.takeProfitPrice!==void 0?ie(e.takeProfitPrice):"--"}),jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-muted",children:"/"}),jsxRuntime.jsx("span",{className:"pl-1 text-left text-xs font-normal text-text-secondary",children:e.stopLossPrice!==void 0?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsx("div",{style:q.cancel,className:"flex flex-row items-center justify-end gap-1",children:jsxRuntime.jsx("button",{type:"button",onClick:()=>o(e),disabled:r||s,"aria-label":i("perpetuals.openOrders.cancelOne.aria"),"aria-busy":r||void 0,className:ui$1.cn("inline-flex items-center justify-center rounded p-1","cursor-pointer text-negative transition-colors duration-150 ease-in-out","hover:bg-negative/10","disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),style:{height:24,width:24},children:r?jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current",style:{transform:"scale(0.6)"}}):jsxRuntime.jsx("svg",{viewBox:"0 0 14 14",width:12,height:12,fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round","aria-hidden":"true",children:jsxRuntime.jsx("path",{d:"M3 3 L11 11 M11 3 L3 11"})})})})]})})}function Lo(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"})]})}function Fo(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-text-secondary",children:e("perpetuals.openOrders.empty")})}function qo({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:o,className:i}){let{t:a}=i18n.useTranslation(),{orders:l,sortKey:u,sortDir:c,onSort:p,handleCancelOrder:d,handleCancelAll:f,cancelingOrderIds:g,isCancelingAll:m}=Cr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:o}),[P,b]=react.useState(false),S=react.useCallback(()=>{l.length!==0&&b(true);},[l.length]),T=react.useCallback(()=>{m||b(false);},[m]),x=react.useCallback(async()=>{try{await f();}finally{b(false);}},[f]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(kr,{className:i,orders:l,sortKey:u,sortDir:c,onSort:p,onCancelOrder:d,onCancelAll:S,cancelingOrderIds:g,isCancelingAll:m}),jsxRuntime.jsx(ui$1.StyledModal,{isOpen:P,onOpenChange:D=>{m||D||T();},size:"md",hideCloseButton:true,backdrop:"opaque",classNames:{base:ui$1.cn("!bg-surface-interactive !rounded-[14px] !border !border-border-subtle","!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-text-primary m-0",children:a("perpetuals.openOrders.cancelAll.confirmTitle")}),jsxRuntime.jsx("button",{type:"button",onClick:T,disabled:m,"aria-label":a("common.close"),className:ui$1.cn("p-1 rounded-[10px] cursor-pointer","hover:bg-surface-strong/50","text-text-secondary hover:text-text-primary transition-colors","disabled:cursor-not-allowed disabled:opacity-50","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),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-text-secondary leading-[18px] m-0",children:a("perpetuals.openOrders.cancelAll.confirmBody")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{x();},disabled:m,className:ui$1.cn("cursor-pointer mt-1 w-full h-12 rounded-[12px]","font-medium text-text-primary","bg-negative hover:bg-negative/90 active:bg-negative/80","transition-colors flex items-center justify-center gap-2","disabled:bg-surface-emphasis disabled:text-text-muted disabled:cursor-not-allowed","outline-none focus:outline-none focus-visible:outline-none","focus:ring-0 focus-visible:ring-0"),children:[m&&jsxRuntime.jsx(ui$1.Spinner,{size:"sm",color:"current"}),a(m?"perpetuals.openOrders.cancelAll.confirming":"perpetuals.openOrders.cancelAll.confirm")]})]})]})})})]})}function Bo(e,t){switch(t){case "time":return e.timestamp;case "size":return e.quantity;case "asset":return e.symbol.split("-")[0];case "description":return e.dir??null;case "price":return e.price;case "tradeValue":return e.price*e.quantity;case "closedPnl":return e.closedPnl??null}}function Qu(e,t,r,s){let n=Bo(e,r),o=Bo(t,r);if(n===null&&o===null)return 0;if(n===null)return 1;if(o===null)return -1;let i;return typeof n=="string"&&typeof o=="string"?i=n.localeCompare(o):i=n-o,s==="asc"?i:-i}function Tr({userAddress:e,symbol:t}){let[r,s]=react.useState("time"),[n,o]=react.useState("desc"),i=react.useCallback(d=>{s(f=>f===d?(o(g=>g==="asc"?"desc":"asc"),f):(o("desc"),d));},[]),{data:a,isLoading:l,error:u}=Lt({userAddress:e,symbol:t},{enabled:!!e,staleTime:5e3}),c=react.useMemo(()=>a?.trades??[],[a]);return {trades:react.useMemo(()=>[...c].sort((d,f)=>Qu(d,f,r,n)),[c,r,n]),isLoading:l,error:u,sortKey:r,sortDir:n,onSort:i}}var ne={time:{flex:"1 1 0%",maxWidth:200},size:{flex:"1 1 0%",maxWidth:80},asset:{flex:"1 1 0%",maxWidth:100},description:{flex:"1 1 0%",maxWidth:300},price:{flex:"1 1 0%"},tradeValue:{flex:"1 1 0%"},closedPnl:{flex:"1 1 0%"}},js={minWidth:1100},Vu=48,Qo={minHeight:36,maxHeight:36,padding:"0 16px"};function Gu(e){return e?!!(/^Open\s+Long\b/i.test(e)||/^Close\s+Short\b/i.test(e)):false}function wr({trades:e,sortKey:t,sortDir:r,onSort:s,className:n}){let{t:o}=i18n.useTranslation(),i=jsxRuntime.jsxs("div",{style:ge,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(N,{style:ne.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.time")}),jsxRuntime.jsx(N,{style:ne.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.size")}),jsxRuntime.jsx(N,{style:ne.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.asset")}),jsxRuntime.jsx(N,{style:ne.description,sortKey:"description",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.description")}),jsxRuntime.jsx(N,{style:ne.price,sortKey:"price",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.price")}),jsxRuntime.jsx(N,{style:ne.tradeValue,sortKey:"tradeValue",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.tradeValue")}),jsxRuntime.jsx(N,{style:ne.closedPnl,sortKey:"closedPnl",activeSortKey:t,sortDir:r,onSort:s,children:o("perpetuals.tradeHistory.col.closedPnl")})]});return jsxRuntime.jsx("div",{className:ui$1.cn("flex h-full w-full min-w-0 flex-col overflow-hidden bg-transparent",n),children:jsxRuntime.jsxs("div",{className:"flex flex-1 min-h-0 flex-col overflow-x-auto",children:[jsxRuntime.jsx("div",{style:{...js,...ge},className:"flex flex-none flex-col",children:i}),e.length===0?jsxRuntime.jsx("div",{style:js,className:"flex flex-1 min-h-0 flex-col items-center justify-center py-6 text-xs text-text-secondary",children:o("perpetuals.tradeHistory.empty")}):jsxRuntime.jsx(ju,{trades:e})]})})}function ju({trades:e}){let t=react.useRef(null),{height:r=0}=hooks.useResizeObserver({ref:t}),s=react.useMemo(()=>({trades:e}),[e]);return jsxRuntime.jsx("div",{ref:t,style:js,className:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:r>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:r},rowComponent:Yu,rowCount:e.length,rowHeight:Vu,rowProps:s,overscanCount:4})})}function Yu({index:e,style:t,trades:r}){let s=r[e];if(!s)return null;let n=e%2===1,o=s.symbol.split("-")[0],i=s.price*s.quantity,a=s.closedPnl??0,l=Gu(s.dir),u=s.dir??"",c=l?"text-positive":"text-negative",p=a>=0?"text-positive":"text-negative";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:n?{...Qo,...it}:Qo,className:"flex flex-1 flex-row items-center justify-start",children:[jsxRuntime.jsx("div",{style:ne.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-muted",children:br(s.timestamp)})}),jsxRuntime.jsx("div",{style:ne.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:at(s.quantity)})}),jsxRuntime.jsx("div",{style:ne.asset,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-medium text-foreground",children:o})}),jsxRuntime.jsx("div",{style:ne.description,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui$1.cn("text-xs font-normal",c),children:u})}),jsxRuntime.jsx("div",{style:ne.price,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"font-normal text-text-secondary",style:{fontSize:11,lineHeight:"16px"},children:ie(s.price)})}),jsxRuntime.jsx("div",{style:ne.tradeValue,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-text-secondary",children:Ge(i)})}),jsxRuntime.jsx("div",{style:ne.closedPnl,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui$1.cn("text-xs font-medium",p),children:gr(a)})})]})})}function Wo(){return jsxRuntime.jsxs("div",{className:"w-full space-y-4 p-4",children:[jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"}),jsxRuntime.jsx("div",{className:"h-4 bg-surface-interactive rounded w-full animate-pulse"})]})}function zo(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-text-secondary",children:e("perpetuals.tradeHistory.empty")})}function $o({userAddress:e,symbol:t,className:r}){let{trades:s,sortKey:n,sortDir:o,onSort:i}=Tr({userAddress:e,symbol:t});return jsxRuntime.jsx(wr,{className:r,trades:s,sortKey:n,sortDir:o,onSort:i})}var Ju=1000000000n,Vo=8,Zu=10n**BigInt(8);function ct(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return jo(r,Ju,t)}function Tt(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return jo(r,Zu,t)}var Go=Tt;function Er(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 jo(e,t,r){let s=e<0n,n=s?-e:e,o=n/t,i=n%t;if(r<=0)return i*2n>=t&&(o+=1n),`${s?"-":""}${o.toString()}`;let a=10n**BigInt(r),l=(i*a+t/2n)/t;l>=a&&(o+=1n,l=0n);let u=l.toString().padStart(r,"0");return u=u.replace(/0+$/,""),u?`${s?"-":""}${o.toString()}.${u}`:`${s?"-":""}${o.toString()}`}function dt(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function Rr(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function Ur({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:o,onExpire:i,error:a}){let{t:l}=i18n.useTranslation(),u=t?Date.parse(t.expiresAt):0,[c,p]=react.useState(()=>u?dt(u):0);return react.useEffect(()=>{if(!e||!u)return;p(dt(u));let d=setInterval(()=>{let f=dt(u);p(f),f===0&&(i?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,u,i]),jsxRuntime.jsx(ui$1.Modal,{isOpen:e,onOpenChange:d=>!d&&o(),hideCloseButton:true,backdrop:"opaque",children:jsxRuntime.jsxs(ui$1.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui$1.ModalHeader,{children:l("perpDeposit.confirm.title")}),jsxRuntime.jsxs(ui$1.ModalBody,{children:[t?jsxRuntime.jsx(lp,{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-text-muted mt-4 text-xs",children:l("perpDeposit.confirm.expiresIn",{seconds:c})}),s&&jsxRuntime.jsx("div",{className:"text-warning-500 mt-4 text-xs",children:l("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:o,isDisabled:r,children:l("perpDeposit.confirm.cancel")}),jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:l("perpDeposit.confirm.cta")})]})]})})}function lp({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(Ar,{label:t("perpDeposit.confirm.send"),value:`${ct(e.grossLamports)} SOL`}),jsxRuntime.jsx(Ar,{label:t("perpDeposit.confirm.receive"),value:`${Tt(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(Ar,{label:t("perpDeposit.confirm.platformFee"),value:`${ct(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(Ar,{label:t("perpDeposit.confirm.relayFee"),value:`${ct(e.relayDepositLamports,6)} SOL`,muted:true})]})}function Ar({label:e,value:t,highlight:r,muted:s}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("dt",{className:"text-text-muted",children:e}),jsxRuntime.jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-text-muted text-xs":"text-foreground",children:t})]})}function Ir({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:o,amountError:i,recipientError:a,onMax:l,className:u}){let{t:c}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui$1.cn("flex flex-col gap-4",u),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:c("perpDeposit.amount")}),n&&jsxRuntime.jsx("span",{className:"text-xs text-text-muted",children:c("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:c("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:o,isInvalid:!!i,errorMessage:i,endContent:jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-text-muted text-sm",children:c("perpDeposit.amount.unit")}),n&&l&&jsxRuntime.jsx(ui$1.Button,{size:"sm",variant:"flat",color:"primary",onPress:l,isDisabled:o,children:c("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:c("perpDeposit.recipient")}),jsxRuntime.jsx(ui$1.Input,{id:"perp-deposit-recipient",type:"text",placeholder:c("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:o,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}var ei="#C7FF2E";function Mr({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:o,onClose:i,errorMessage:a}){let{t:l}=i18n.useTranslation(),u=xp(t),c=t==="failed"?a||(r?.lastError?.message?l("perpDeposit.status.failed",{message:r.lastError.message}):l("perpDeposit.status.failed",{message:""})):t==="succeeded"?l("perpDeposit.status.settled"):t==="refunded"?l("perpDeposit.status.refunded"):r?.status==="broadcasted"?l("perpDeposit.status.broadcasted"):r?.status==="relay_waiting"?l("perpDeposit.status.relay_waiting"):r?.status==="relay_pending"?l("perpDeposit.status.relay_pending"):r?.status==="stuck"?l("perpDeposit.status.stuck"):l("perpDeposit.status.broadcasted"),p=t==="failed"&&!!o;return jsxRuntime.jsx(ui$1.StyledModal,{isOpen:e,onOpenChange:d=>!d&&i(),size:"md",hideCloseButton:true,backdrop:"opaque",classNames:{base:`${ui$1.THEMED_MODAL_BASE_CLASS} 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-text-primary",children:l("perpDeposit.status.title")})}),jsxRuntime.jsx("button",{type:"button",onClick:i,className:"cursor-pointer p-1 rounded-[10px] hover:bg-surface-strong/50 text-text-secondary hover:text-text-primary transition-colors","aria-label":l("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-surface-base border border-border-subtle px-4 py-6 flex flex-col items-center text-center gap-4",children:[jsxRuntime.jsx(bp,{variant:u}),jsxRuntime.jsx("p",{className:ui$1.cn("text-sm leading-relaxed max-w-[320px]",Sp(u)),children:c})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(Zo,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(Zo,{href:n,label:l("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxRuntime.jsxs("div",{className:ui$1.cn("px-5 pb-5 pt-2 flex gap-2",p?"justify-between":"justify-end"),children:[p&&jsxRuntime.jsx("button",{type:"button",onClick:o,className:"cursor-pointer flex-1 h-10 rounded-[10px] font-medium text-text-inverse bg-action-primary hover:bg-action-primary-hover active:bg-action-primary-pressed transition-colors flex items-center justify-center",children:l("perpDeposit.status.tryAgain")}),jsxRuntime.jsx("button",{type:"button",onClick:i,className:ui$1.cn("cursor-pointer h-10 rounded-[10px] font-medium transition-colors flex items-center justify-center",p?"flex-1 bg-surface-strong hover:bg-surface-emphasis text-text-primary":"px-6 bg-surface-strong hover:bg-surface-emphasis text-text-primary"),children:l("perpDeposit.status.close")})]})]})})})}function Zo({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-surface-base border border-border-subtle hover:border-positive/40 transition-colors",children:[jsxRuntime.jsx("span",{className:"text-xs text-text-secondary group-hover:text-text-primary transition-colors",children:t}),jsxRuntime.jsxs("span",{className:"flex items-center gap-1.5 text-xs tabular-nums text-text-secondary group-hover:text-brand-primary transition-colors",children:[Rr(r,6,4),jsxRuntime.jsx(Op,{})]})]})}function bp({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(hp,{})}):e==="success"?jsxRuntime.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-positive/12",children:jsxRuntime.jsx(vp,{className:"w-8 h-8",style:{color:ei}})}):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(Pp,{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(Cp,{className:"w-8 h-8 text-rose-400"})})}function hp(){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:"hsl(var(--heroui-foreground) / 0.08)",strokeWidth:"4"}),jsxRuntime.jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:ei,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsxRuntime.jsx("style",{children:`
|
|
37
37
|
.lfi-perp-deposit-spinner {
|
|
38
38
|
animation: lfi-perp-deposit-spin 0.9s linear infinite;
|
|
39
39
|
transform-origin: center;
|
|
@@ -41,6 +41,6 @@
|
|
|
41
41
|
@keyframes lfi-perp-deposit-spin {
|
|
42
42
|
to { transform: rotate(360deg); }
|
|
43
43
|
}
|
|
44
|
-
`})]})}function dp(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function mp(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 fp(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 yp(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 gp(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 bp(){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 Zi({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:u,buildHyperliquidExplorerUrl:c,onSettled:p,onError:d,className:f}){let{t:b}=i18n.useTranslation(),[m,v]=react.useState(""),[g,S]=react.useState(n??""),T=react.useMemo(()=>{if(m&&(!/^\d+(\.\d+)?$/.test(m.trim())||Number(m)<=0))return b("perpDeposit.error.amountInvalid")},[m,b]),x=react.useMemo(()=>{if(g)return l?l(g):void 0},[g,l]),w=react.useMemo(()=>T?"":Dr(m),[m,T]),H=792703809,_=react.useMemo(()=>!w||w==="0"||x||!g?null:{originChainId:H,userAddress:e,hyperliquidRecipient:g,grossAmount:w,source:r},[w,g,x,r,e]),M=Bt(_,{enabled:!!_}),{state:h,execute:V,reset:re,dispatch:L}=Kt(i),A=h.phase==="submitted"||h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"?h.intentId:void 0,k=zt(A,{enabled:!!A&&h.phase!=="succeeded"&&h.phase!=="refunded"&&h.phase!=="failed"});react.useEffect(()=>{k.data&&L({type:"STATUS_UPDATE",status:k.data});},[k.data,L]),react.useEffect(()=>{h.phase==="succeeded"?p?.(h.intentId):h.phase==="failed"&&d?.(h.intentId,h.error.message);},[h,p,d]);let z=react.useCallback(()=>{M.data&&(L({type:"QUOTE_REQUEST"}),L({type:"QUOTE_RECEIVED",quote:M.data}));},[L,M.data]),J=react.useCallback(async()=>{if(h.phase==="ready_to_sign")try{await V({quote:h.quote,userAddress:e,hyperliquidRecipient:g,userId:t,source:r,campaign:s});}catch{}},[h,V,e,g,t,r,s]),Ce=react.useCallback(()=>{L({type:"QUOTE_EXPIRED"});},[L]),j=react.useCallback(async()=>{L({type:"RESET"}),await M.refetch();},[L,M]),Oe=h.phase==="ready_to_sign"||h.phase==="signing"||h.phase==="broadcasting"||h.phase==="expired",Fe=h.phase==="submitted"||h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"&&!!h.intentId,Z=h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"?h.status:void 0,ke=!M.data||M.isFetching||!!T||!!x||!_;return jsxRuntime.jsxs(ui.Card,{className:f,children:[jsxRuntime.jsxs(ui.CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:b("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:b("perpDeposit.description")})]}),jsxRuntime.jsx(Ur,{amount:m,onAmountChange:v,recipient:g,onRecipientChange:S,balanceSol:o,onMax:a,amountError:T,recipientError:x,disabled:h.phase!=="idle"&&h.phase!=="expired"&&h.phase!=="failed"}),jsxRuntime.jsx(ui.Button,{color:"primary",isDisabled:ke,isLoading:M.isFetching,onPress:z,children:M.isFetching?b("perpDeposit.gettingQuote"):b("perpDeposit.confirmQuote")}),M.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:b("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(Ar,{isOpen:Oe,quote:h.phase==="ready_to_sign"||h.phase==="signing"||h.phase==="broadcasting"||h.phase==="expired"?h.quote:void 0,isExecuting:h.phase==="signing"||h.phase==="broadcasting",isExpired:h.phase==="expired",onConfirm:J,onCancel:re,onExpire:Ce}),jsxRuntime.jsx(Ir,{isOpen:Fe,phase:h.phase,status:Z,solanaExplorerUrl:Z?.solanaTxHash&&u?u(Z.solanaTxHash):void 0,hyperliquidExplorerUrl:Z?.hyperliquidTxHash&&c?c(Z.hyperliquidTxHash):void 0,onRetry:h.phase==="failed"?j:void 0,onClose:re,errorMessage:h.phase==="failed"?h.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,l=a==="executing",u=a==="loading",c=a==="error"&&e.steps.length===0;return jsxRuntime.jsxs(ui.Card,{className:ui.cn("w-full max-w-md",i),children:[jsxRuntime.jsxs(ui.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.CardBody,{className:"gap-3",children:[u&&jsxRuntime.jsx(Dp,{}),c&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!u&&!c&&e.steps.map((p,d)=>jsxRuntime.jsx(wp,{rec:p,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${p.step.id}-${d}`)),a==="done"&&jsxRuntime.jsx("p",{className:"text-success text-sm",children:o("perpDeposit.setup.alreadyActive")})]}),jsxRuntime.jsxs(ui.CardFooter,{className:"flex justify-between gap-2",children:[n&&jsxRuntime.jsx(ui.Button,{variant:"light",onPress:n,isDisabled:l,children:o(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsxRuntime.jsx("div",{className:"flex-1"}),c&&s&&jsxRuntime.jsx(ui.Button,{color:"primary",onPress:s,children:o("perpDeposit.setup.retry")}),!c&&a!=="done"&&jsxRuntime.jsx(ui.Button,{color:"primary",onPress:t,isLoading:l,isDisabled:l||u,children:e.steps.some(p=>p.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function wp({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),i=Ap(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 l=(e.step.params.maxFeeRate/10).toFixed(1);return n("perpDeposit.setup.builderFee.description",{bps:l})}case "setReferrer":return n("perpDeposit.setup.referrer.description",{code:e.step.params.code});case "updateLeverage":return n("perpDeposit.setup.leverage.description")}})(),a=(()=>{switch(e.status){case "pending":return n("perpDeposit.setup.step.pending");case "skipped":return n("perpDeposit.setup.step.skipped");case "running":return n("perpDeposit.setup.step.running");case "done":return n("perpDeposit.setup.step.done");case "error":return n("perpDeposit.setup.step.error")}})();return jsxRuntime.jsxs("div",{className:ui.cn("border-divider flex items-start justify-between gap-3 rounded-md border p-3",e.status==="error"&&"border-danger",e.status==="done"&&"border-success/40 bg-success/5",e.status==="skipped"&&"border-default bg-default-100/40"),children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsxRuntime.jsx(Ep,{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.cn(Rp(e.status)),children:a}),e.status==="error"&&s&&jsxRuntime.jsx(ui.Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function Dp(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsxRuntime.jsx(ui.Spinner,{size:"sm"}),jsxRuntime.jsx("span",{children:e("perpDeposit.setup.loading")})]})}function Ep({status:e,isCurrent:t}){return e==="running"||t?jsxRuntime.jsx(ui.Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsxRuntime.jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsxRuntime.jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Rp(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 Ap(e,t){return t()}function to({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:l,runNext:u,runStep:c,reload:p}=xt({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),d=react.useCallback(()=>{u();},[u]),f=react.useCallback(m=>{c(m);},[c]),b=react.useCallback(()=>{p();},[p]);return jsxRuntime.jsx(Fr,{state:l,onContinue:d,onRetryStep:f,onReload:b,onDismiss:o,className:a})}var Ip="wss://api.hyperliquid.xyz/ws",Js=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 Qe({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??Ip,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 de&&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 getUniverseSnapshot(){let r=(await this.getMarkets()).map(n=>({coin:n.symbol.split("-")[0],symbol:n.symbol,market:n,meta:null})),s=new Map;for(let n of r)s.set(n.symbol,n);return {assets:r,bySymbol:s,fetchedAt:Date.now()}}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 getActiveAssetLeverage(t){return null}async getAssetMeta(t){return null}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 et(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}`,n=>s(n))}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 Zs=class{transport;constructor(t){this.transport="transport"in t?t.transport:new Qe(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`})}};
|
|
45
|
-
exports.ClosePositionModal=
|
|
44
|
+
`})]})}function xp(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function Sp(e){switch(e){case "success":return "text-text-primary";case "warning":return "text-amber-200";case "error":return "text-rose-300";default:return "text-text-primary"}}function vp(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 Pp(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 Cp(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 Op(){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 si({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:o,balanceSol:i,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:u,buildHyperliquidExplorerUrl:c,onSettled:p,onError:d,className:f}){let{t:g}=i18n.useTranslation(),[m,P]=react.useState(""),[b,S]=react.useState(n??""),T=react.useMemo(()=>{if(m&&(!/^\d+(\.\d+)?$/.test(m.trim())||Number(m)<=0))return g("perpDeposit.error.amountInvalid")},[m,g]),x=react.useMemo(()=>{if(b)return l?l(b):void 0},[b,l]),D=react.useMemo(()=>T?"":Er(m),[m,T]),H=792703809,_=react.useMemo(()=>!D||D==="0"||x||!b?null:{originChainId:H,userAddress:e,hyperliquidRecipient:b,grossAmount:D,source:r},[D,b,x,r,e]),M=Bt(_,{enabled:!!_}),{state:h,execute:V,reset:re,dispatch:L}=Kt(o),A=h.phase==="submitted"||h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"?h.intentId:void 0,k=Wt(A,{enabled:!!A&&h.phase!=="succeeded"&&h.phase!=="refunded"&&h.phase!=="failed"});react.useEffect(()=>{k.data&&L({type:"STATUS_UPDATE",status:k.data});},[k.data,L]),react.useEffect(()=>{h.phase==="succeeded"?p?.(h.intentId):h.phase==="failed"&&d?.(h.intentId,h.error.message);},[h,p,d]);let W=react.useCallback(()=>{M.data&&(L({type:"QUOTE_REQUEST"}),L({type:"QUOTE_RECEIVED",quote:M.data}));},[L,M.data]),J=react.useCallback(async()=>{if(h.phase==="ready_to_sign")try{await V({quote:h.quote,userAddress:e,hyperliquidRecipient:b,userId:t,source:r,campaign:s});}catch{}},[h,V,e,b,t,r,s]),Ce=react.useCallback(()=>{L({type:"QUOTE_EXPIRED"});},[L]),j=react.useCallback(async()=>{L({type:"RESET"}),await M.refetch();},[L,M]),Oe=h.phase==="ready_to_sign"||h.phase==="signing"||h.phase==="broadcasting"||h.phase==="expired",Fe=h.phase==="submitted"||h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"&&!!h.intentId,Z=h.phase==="tracking"||h.phase==="succeeded"||h.phase==="refunded"||h.phase==="failed"?h.status:void 0,ke=!M.data||M.isFetching||!!T||!!x||!_;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:g("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-text-muted text-sm",children:g("perpDeposit.description")})]}),jsxRuntime.jsx(Ir,{amount:m,onAmountChange:P,recipient:b,onRecipientChange:S,balanceSol:i,onMax:a,amountError:T,recipientError:x,disabled:h.phase!=="idle"&&h.phase!=="expired"&&h.phase!=="failed"}),jsxRuntime.jsx(ui$1.Button,{color:"primary",isDisabled:ke,isLoading:M.isFetching,onPress:W,children:M.isFetching?g("perpDeposit.gettingQuote"):g("perpDeposit.confirmQuote")}),M.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:g("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(Ur,{isOpen:Oe,quote:h.phase==="ready_to_sign"||h.phase==="signing"||h.phase==="broadcasting"||h.phase==="expired"?h.quote:void 0,isExecuting:h.phase==="signing"||h.phase==="broadcasting",isExpired:h.phase==="expired",onConfirm:J,onCancel:re,onExpire:Ce}),jsxRuntime.jsx(Mr,{isOpen:Fe,phase:h.phase,status:Z,solanaExplorerUrl:Z?.solanaTxHash&&u?u(Z.solanaTxHash):void 0,hyperliquidExplorerUrl:Z?.hyperliquidTxHash&&c?c(Z.hyperliquidTxHash):void 0,onRetry:h.phase==="failed"?j:void 0,onClose:re,errorMessage:h.phase==="failed"?h.error.message:void 0})]})}var Mp="\u2713";function qr({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:o}){let{t:i}=i18n.useTranslation(),a=e.phase,l=a==="executing",u=a==="loading",c=a==="error"&&e.steps.length===0;return jsxRuntime.jsxs(ui$1.Card,{className:ui$1.cn("w-full max-w-md",o),children:[jsxRuntime.jsxs(ui$1.CardHeader,{className:"flex flex-col items-start gap-1",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold",children:i("perpDeposit.setup.title")}),jsxRuntime.jsx("p",{className:"text-foreground-500 text-sm",children:i("perpDeposit.setup.description")})]}),jsxRuntime.jsxs(ui$1.CardBody,{className:"gap-3",children:[u&&jsxRuntime.jsx(Lp,{}),c&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:i("perpDeposit.setup.loadFailed",{message:e.error??""})}),!u&&!c&&e.steps.map((p,d)=>jsxRuntime.jsx(Np,{rec:p,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${p.step.id}-${d}`)),a==="done"&&jsxRuntime.jsx("p",{className:"text-success text-sm",children:i("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:l,children:i(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsxRuntime.jsx("div",{className:"flex-1"}),c&&s&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:s,children:i("perpDeposit.setup.retry")}),!c&&a!=="done"&&jsxRuntime.jsx(ui$1.Button,{color:"primary",onPress:t,isLoading:l,isDisabled:l||u,children:e.steps.some(p=>p.status==="done")?i("perpDeposit.setup.continue"):i("perpDeposit.setup.cta")})]})]})}function Np({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),o=Hp(e.step.id,()=>{switch(e.step.id){case "approveBuilderFee":return n("perpDeposit.setup.builderFee.label");case "setReferrer":return n("perpDeposit.setup.referrer.label");case "updateLeverage":return n("perpDeposit.setup.leverage.label")}}),i=(()=>{switch(e.step.id){case "approveBuilderFee":{let l=(e.step.params.maxFeeRate/10).toFixed(1);return n("perpDeposit.setup.builderFee.description",{bps:l})}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(Fp,{status:e.status,isCurrent:r}),jsxRuntime.jsx("span",{children:o})]}),jsxRuntime.jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:i}),e.status==="error"&&e.error&&jsxRuntime.jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsxRuntime.jsx("span",{className:ui$1.cn(qp(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 Lp(){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 Fp({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:Mp}):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 qp(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 Hp(e,t){return t()}function oi({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:o,onDismiss:i,className:a}){let{state:l,runNext:u,runStep:c,reload:p}=St({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:o}),d=react.useCallback(()=>{u();},[u]),f=react.useCallback(m=>{c(m);},[c]),g=react.useCallback(()=>{p();},[p]);return jsxRuntime.jsx(qr,{state:l,onContinue:d,onRetryStep:f,onReload:g,onDismiss:i,className:a})}var Bp="wss://api.hyperliquid.xyz/ws",tn=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 Qe({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??Bp,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 de&&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 getUniverseSnapshot(){let r=(await this.getMarkets()).map(n=>({coin:n.symbol.split("-")[0],symbol:n.symbol,market:n,meta:null})),s=new Map;for(let n of r)s.set(n.symbol,n);return {assets:r,bySymbol:s,fetchedAt:Date.now()}}async getKlines(t,r,s=100){let n=typeof s=="number"?{limit:s}:s,o={interval:r};return n.limit!==void 0&&(o.limit=String(n.limit)),n.from!==void 0&&(o.start=String(n.from)),n.to!==void 0&&(o.end=String(n.to)),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:o})}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 getActiveAssetLeverage(t){return null}async getAssetMeta(t){return null}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 Ze(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}`,n=>s(n))}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 rn=class{transport;constructor(t){this.transport="transport"in t?t.transport:new Qe(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`})}};
|
|
45
|
+
exports.ClosePositionModal=cr;exports.CoinInfoNotFoundUI=$t;exports.CoinInfoSkeletonsUI=Vt;exports.CoinInfoUI=jt;exports.CoinInfoWidget=In;exports.DEFAULT_ORDER_BOOK_PRECISION_OPTIONS=Ds;exports.DepositConfirmUI=Ur;exports.DepositFlowWidget=si;exports.DepositFormUI=Ir;exports.DepositStatusUI=Mr;exports.HL_USDC_DECIMALS=Vo;exports.HyperliquidApiError=Te;exports.HyperliquidInitUI=qr;exports.HyperliquidInitWidget=oi;exports.HyperliquidPerpetualsClient=_r;exports.LiberFiApiError=de;exports.LiberFiHttpTransport=Qe;exports.LiberFiPerpDepositClient=rn;exports.LiberFiPerpetualsClient=tn;exports.OpenOrdersEmpty=Fo;exports.OpenOrdersSkeleton=Lo;exports.OpenOrdersUI=kr;exports.OpenOrdersWidget=qo;exports.OrderBookUI=er;exports.OrderBookWidget=Jn;exports.PerpetualDisconnectedError=De;exports.PerpetualRejectedError=qe;exports.PerpetualsContext=we;exports.PerpetualsProvider=Oi;exports.PlaceOrderFormUI=pr;exports.PlaceOrderFormWidget=Po;exports.PositionsEmpty=Ao;exports.PositionsSkeleton=Sr;exports.PositionsUI=xr;exports.PositionsWidget=Uo;exports.SearchCoinsUI=Xt;exports.SearchCoinsWidget=Fn;exports.TERMINAL_DEPOSIT_STATUSES=ft;exports.TradeHistoryEmpty=zo;exports.TradeHistorySkeleton=Wo;exports.TradeHistoryUI=wr;exports.TradeHistoryWidget=$o;exports.TradesUI=nr;exports.TradesWidget=ao;exports.accountStateQueryKey=Be;exports.activeAssetLeverageQueryKey=yt;exports.aggregationFromStep=Os;exports.assetMetaQueryKey=os;exports.cancelOrder=ls;exports.classifyStep=gt;exports.coinsQueryKey=Br;exports.createInMemoryPerpetualCapabilities=xi;exports.createOrder=as;exports.createPerpetualDataRuntime=Si;exports.createPerpetualExecutionRuntime=vi;exports.currentDepositBreakdown=sa;exports.currentDepositStatus=ra;exports.fetchActiveAssetLeverage=ss;exports.fetchAssetMeta=is;exports.fetchCoins=Qr;exports.fetchKlines=Gr;exports.fetchMarket=Wr;exports.fetchMarkets=$r;exports.fetchOrderBook=Yr;exports.fetchOrders=es;exports.fetchPerpDepositQuote=ys;exports.fetchPerpDepositStatus=hs;exports.fetchPositions=Zr;exports.fetchRecentTrades=Jr;exports.fetchTrades=rs;exports.fetchUniverse=xe;exports.hlUsdcRawToUsdc=Tt;exports.initialDepositState=Qt;exports.initialSetupState=st;exports.isDepositPolling=ta;exports.isDepositTerminal=ea;exports.isTerminalDepositLifecycle=na;exports.klinesQueryKey=Vr;exports.lamportsToSol=ct;exports.marketQueryKey=Kr;exports.marketsQueryKey=zr;exports.microUsdcToUsdc=Go;exports.nextRunnableStep=ht;exports.orderBookQueryKey=jr;exports.ordersQueryKey=_e;exports.perpDepositQuoteQueryKey=fs;exports.perpDepositStatusQueryKey=bs;exports.positionsQueryKey=He;exports.recentTradesQueryKey=Xr;exports.reduceDepositState=gs;exports.reduceSetupState=bt;exports.secondsUntil=dt;exports.shortAddress=Rr;exports.solToLamports=Er;exports.supportsUniverseSnapshot=Se;exports.tradesQueryKey=ts;exports.universeQueryKey=ce;exports.useAccountStateQuery=_t;exports.useAccountStateSubscription=Sn;exports.useActiveAssetLeverageQuery=Ft;exports.useAssetMetaQuery=rt;exports.useCancelOrderMutation=Ht;exports.useCandlesSubscription=hn;exports.useClosePosition=mr;exports.useCoinInfo=Gt;exports.useCoinsQuery=Et;exports.useCreateOrderMutation=qt;exports.useHyperliquidSetup=St;exports.useHyperliquidUserBootstrap=vn;exports.useKlinesQuery=gn;exports.useMarketDataSubscription=Ee;exports.useMarketQuery=et;exports.useMarketsQuery=Ut;exports.useOpenOrdersScript=Cr;exports.useOrderBookQuery=It;exports.useOrderBookScript=Jt;exports.useOrdersQuery=Nt;exports.usePerpDepositClient=Cn;exports.usePerpDepositClientMaybe=Re;exports.usePerpDepositExecute=Kt;exports.usePerpDepositQuote=Bt;exports.usePerpDepositStatus=Wt;exports.usePerpetualsClient=E;exports.usePlaceOrderFormScript=ir;exports.usePositionsQuery=tt;exports.usePositionsScript=fr;exports.useRecentTradesQuery=Mt;exports.useSearchCoinsScript=Yt;exports.useTradeHistoryScript=Tr;exports.useTradesQuery=Lt;exports.useTradesScript=rr;exports.useUniverseQuery=mn;exports.useUserDataSubscription=xn;//# sourceMappingURL=index.js.map
|
|
46
46
|
//# sourceMappingURL=index.js.map
|