@liberfi.io/ui-perpetuals 1.1.24 → 1.1.26
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 +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),i18n=require('@liberfi.io/i18n'),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 Ei=new Set(["userFills","userFillsByTime","userFunding","userNonFundingLedgerUpdates","frontendOpenOrders","userRateLimit","historicalOrders","userTwapSliceFills","predictedFundings"]);function Gt(e){return e&&Ei.has(e)?20:2}var Os=1,st=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 Ri(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 Ve=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;connectPromise=null;manuallyDisconnected=false;constructor(t){this.wsEndpoint=t;}async connect(){if(!(this.isConnected&&this.ws?.readyState===WebSocket.OPEN))return this.connectPromise?this.connectPromise:(this.manuallyDisconnected=false,this.connectPromise=new Promise((t,r)=>{let s=false,n=i=>{s||(s=true,this.connectPromise=null,i());};try{let i=new WebSocket(this.wsEndpoint);this.ws=i,i.onopen=()=>{this.ws===i&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},i.onmessage=o=>{this.ws===i&&this.handleMessage(o.data);},i.onerror=o=>{this.ws===i&&(console.error("[WebSocket] Error:",o),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},i.onclose=o=>{this.ws===i&&(console.log(`[WebSocket] Closed: ${o.code} - ${o.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${o.code}`))),!this.manuallyDisconnected&&o.code!==1e3&&this.attemptReconnect());};}catch(i){n(()=>r(i));}}),this.connectPromise)}disconnect(){this.manuallyDisconnected=true,this.stopHeartbeat(),this.subscriptions.clear(),this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(1e3,"Normal closure"),this.ws=null),this.isConnected=false,this.isReconnecting=false,this.reconnectAttempts=0;}attemptReconnect(){if(this.isReconnecting)return;if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[WebSocket] Max reconnection attempts reached");return}this.isReconnecting=true,this.reconnectAttempts++;let t=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[WebSocket] Reconnecting in ${t}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=window.setTimeout(()=>{this.connect().then(()=>{this.resubscribeAll();}).catch(r=>{console.error("[WebSocket] Reconnection failed:",r),this.isReconnecting=false;});},t);}startHeartbeat(){this.heartbeatInterval=window.setInterval(()=>{this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.send({method:"ping"});},this.pingInterval);}stopHeartbeat(){this.heartbeatInterval!==null&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}send(t){this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(JSON.stringify(t)):this.messageQueue.push(t);}flushMessageQueue(){for(;this.messageQueue.length>0;){let t=this.messageQueue.shift();t&&this.send(t);}}resubscribeAll(){this.subscriptions.forEach(t=>{this.sendSubscription(t.type,t.param,t.aggregation);});}handleMessage(t){try{let r=JSON.parse(t);r.channel?this.handleChannelMessage(r):r.method;}catch(r){console.error("[WebSocket] Failed to parse message:",r,t);}}handleChannelMessage(t){let r=t.channel;this.subscriptions.forEach((s,n)=>{if(this.isChannelMatch(r,s.type,s.param,t))try{let i=this.transformData(s.type,t.data,s.param);s.callback(i);}catch(i){console.error(`[WebSocket] Error in subscription callback (${n}):`,i);}});}isChannelMatch(t,r,s,n){if(r==="ticker"){if(t!=="activeAssetCtx")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else if(r==="trades"){if(t!=="trades")return false;let i=s.split("-")[0],o=Array.isArray(n?.data)?n.data[0]?.coin:void 0;return typeof o!="string"||o===i}else if(r==="orderBook"){if(t!=="l2Book")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else {if(r==="candle")return t==="candle";if(r==="userFills")return t==="userFills";if(r==="userEvents")return t==="userEvents";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 n=`${t?.coin??r.split("-")[0]}-USDC`,i=t?.ctx??{},o=parseFloat(i.midPx??i.markPx??"0"),a=parseFloat(i.markPx??i.midPx??"0"),l=i.prevDayPx?parseFloat(i.prevDayPx):o,p=l>0?(o-l)/l*100:0;return {symbol:n,price:o,change24h:p,volume24h:parseFloat(i.dayNtlVlm??"0"),fundingRate:parseFloat(i.funding??"0"),openInterest:parseFloat(i.openInterest??"0"),markPrice:a,indexPrice:parseFloat(i.oraclePx??i.midPx??"0")}}transformTradesData(t,r){return Array.isArray(t)?t.map(s=>({symbol:r,side:s.side==="B"?"buy":"sell",price:parseFloat(s.px),quantity:parseFloat(s.sz),timestamp:s.time,tradeId:s.tid})):[]}transformOrderBookData(t,r){let[s,n]=t.levels||[[],[]];return {symbol:r,bids:s.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),asks:n.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),timestamp:t.time||Date.now()}}transformCandleData(t,r){let[s]=r.split(":");return {symbol:s,open:parseFloat(t.o),high:parseFloat(t.h),low:parseFloat(t.l),close:parseFloat(t.c),volume:parseFloat(t.v),timestamp:t.t,closeTimestamp:t.T}}transformUserFillsData(t){return Array.isArray(t)?t.map(r=>({tradeId:r.tid?.toString(),orderId:r.oid?.toString(),symbol:`${r.coin}-USDC`,side:r.dir?.includes("Long")?"long":"short",price:parseFloat(r.px),quantity:parseFloat(r.sz),fee:parseFloat(r.fee||"0"),feeCurrency:r.feeToken||"USDC",isMaker:r.side==="M",timestamp:r.time})):[]}transformUserEventsData(t){return t}sendSubscription(t,r,s){let n;if(t==="ticker")n={method:"subscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"subscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"subscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"?n={method:"subscribe",subscription:{type:"userEvents",user:r}}: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=Ri(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 Ts={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"}},Ai=60*1e3,Ni=1500,Ui=1500,jt=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||Ts[this.environment].api,this._wsEndpoint=t.wsEndpoint||Ts[this.environment].ws,this.timeout=t.timeout||3e4,t.rateLimit===false?this.rateLimiter=null:t.rateLimit instanceof st?this.rateLimiter=t.rateLimit:this.rateLimiter=new st(t.rateLimit);}weightFor(t,r){if(t.startsWith("/exchange"))return Os;if(t.startsWith("/info")){let s=r&&typeof r=="object"&&typeof r.type=="string"?r.type:void 0;return Gt(s)}return Gt(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 Ce(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new Ce(`Request timeout after ${this.timeout}ms`,408,""):n instanceof Ce?n:new Ce(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){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<Ni)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`,p=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx?parseFloat(a.prevDayPx):p,u=c>0?(p-c)/c*100:0,d={symbol:l,price:p,change24h:u,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<Ui)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,p;i.from!==void 0&&i.to!==void 0?(l=i.from,p=i.to):i.to!==void 0&&a?(p=i.to,l=p-o*a):i.from!==void 0&&a?(l=i.from,p=l+o*a):(p=Date.now(),l=p-o*(a??100));let u=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:p}})).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&&u.length>a&&(u=u.slice(u.length-a)),u}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(p=>({price:parseFloat(p.px),quantity:parseFloat(p.sz),count:p.n})),asks:l.slice(0,r).map(p=>({price:parseFloat(p.px),quantity:parseFloat(p.sz),count:p.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=ws(r.clearinghouse,t.symbol),i=Ds(s);return n.positions=Rs(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 Ce&&(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<Ai)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:Es(r?.clearinghouse),markByCoin:s?Ds(s):void 0},o=n.map(l=>ks(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 Ve(this._wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s,n){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(t,r,s,n?.aggregation)}subscribeCandles(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=`${t}:${r}`;return this.wsManager.subscribe("candle",n,s)}subscribeUserData(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=t==="fills"?"userFills":"userEvents";return this.wsManager.subscribe(n,r,s)}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 ws(e,t){let r=e.assetPositions.map(o=>{let a=o.position,l=`${a.coin}-USDC`,p=parseFloat(a.szi);if(p===0)return null;let c=parseFloat(a.entryPx),u=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:p>0?"long":"short",quantity:Math.abs(p),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:c,markPrice:c,unrealizedPnl:u,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 Mi(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 ks(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",p=/^market$/i.test(a)?"market":"limit",c=e.isTrigger===true,u;c&&(/take\s*profit/i.test(a)?u="tp":/stop/i.test(a)&&(u="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:y,stopLossPrice:m}=Mi(e),v=t?.leverageByCoin?.get(e.coin),b=t?.markByCoin?.get(e.coin);return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:r,side:o?"long":"short",orderType:p,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:u,triggerCondition:f,markPrice:b,takeProfitPrice:y,stopLossPrice:m}}function Es(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 Ii(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?ws(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=Ii(e.spotState?.balances),i=e.meta&&e.assetCtxs?Hi([e.meta,e.assetCtxs]):null,o=Es(t),a=s.map(d=>ks(d,{leverageByCoin:o,markByCoin:i??void 0})),l=Rs(r.positions,s,i),p=l.reduce((d,f)=>d+f.unrealizedPnl,0),c=e.meta&&e.assetCtxs?Li(e.meta,e.assetCtxs,e.serverTime):void 0,u=t?qi(t):void 0;return {positions:l,openOrders:a,spotBalances:n,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:p,serverTime:e.serverTime,leverageByCoin:u,universe:c,raw:e}}function Li(e,t,r){let s=e.universe.map((i,o)=>{let a=t[o]??{},l=`${i.name}-USDC`,p=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx,u=c?parseFloat(c):p,d=u>0?(p-u)/u*100:0,f={symbol:l,price:p,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")},y=i.szDecimals,m=i.maxLeverage,v=typeof y=="number"?{szDecimals:y,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 qi(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 Hi(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 Ds(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 _i(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 p=typeof a.orderType=="string"?a.orderType:"",c=/take\s*profit/i.test(p),u=/stop/i.test(p);c?(!i||a.timestamp>i.timestamp)&&(i=a):u&&(!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 Rs(e,t,r){return e.map(s=>{let n={...s},{tp:i,sl:o}=_i(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 p=s.side==="long"?1:-1,c=(l-s.entryPrice)*s.quantity*p;n.unrealizedPnl=c,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=c/s.margin*100);}return n})}var Ce=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var ue=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Bi=3e4,Ie=class{baseUrl;timeout;headers;defaultQuery;fetchImpl;constructor(t){if(!t.baseUrl)throw new Error("LiberFiHttpTransport: `baseUrl` is required (e.g. https://api.liberfi.io/perpetuals).");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.timeout=t.timeout??Bi,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 Qi(a);throw new ue(`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 ue)throw a;if(a instanceof Error&&a.name==="AbortError")throw new ue(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new ue(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(o);}}};async function Qi(e){try{return await e.text()}catch{return ""}}var Ki="wss://api.hyperliquid.xyz/ws",Yt=class{transport;wsEndpoint;signTypedData;wsManager=null;wsRefCount=0;constructor(t){if(t.transport)this.transport=t.transport;else {if(!t.baseUrl)throw new Error("LiberFiPerpetualsClient: either `baseUrl` or a pre-built `transport` is required.");this.transport=new Ie({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??Ki,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 ue&&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 Ve(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s,n){return this.requireWS().subscribe(t,r,s,n?.aggregation)}subscribeCandles(t,r,s){return this.requireWS().subscribe("candle",`${t}:${r}`,s)}subscribeUserData(t,r,s){let n=t==="fills"?"userFills":"userEvents";return this.requireWS().subscribe(n,r,s)}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}requireWS(){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager}};var Xt=class{transport;constructor(t){this.transport="transport"in t?t.transport:new Ie(t);}getBaseUrl(){return this.transport.getBaseUrl()}async quote(t){return this.transport.request("POST",{path:"/v1/deposits/quote",body:t})}async submit(t){return this.transport.request("POST",{path:"/v1/deposits/submit",body:t})}async status(t){if(!t)throw new Error("intentId is required");return this.transport.request("GET",{path:`/v1/deposits/${encodeURIComponent(t)}`})}async refresh(t){if(!t)throw new Error("intentId is required");return this.transport.request("POST",{path:`/v1/deposits/${encodeURIComponent(t)}/refresh`})}};var nt=new Set(["settled","refunded","failed"]);var xt={phase:"idle"};function Jt(e,t){switch(t.type){case "RESET":return xt;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 Wi(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function $i(e){return e.phase==="submitted"||e.phase==="tracking"}function Vi(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Gi(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 ji(e){return e!==void 0&&nt.has(e)}var Oe=react.createContext({});function Ji({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(Oe.Provider,{value:s,children:r})}function R(){let e=react.useContext(Oe);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function As(){return ["perps","coins"]}async function Ns(e){return await e.getSupportedCoins()}function Zt(e={}){let{client:t}=R();return reactQuery.useQuery({queryKey:As(),queryFn:async()=>Ns(t),staleTime:300*1e3,...e})}var Us=6e4;function ye(){return ["perps","universe"]}async function Te(e){if(typeof e.getUniverseSnapshot!="function")throw new Error("useUniverseQuery: the active perpetuals client does not implement getUniverseSnapshot()");return e.getUniverseSnapshot()}function De(e){return typeof e.getUniverseSnapshot=="function"}function so(e={}){let{client:t}=R(),r=De(t)&&e.enabled!==false;return reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(t),refetchInterval:Us,staleTime:Us/2,...e,enabled:r})}var St=6e4;function Is(e){return ["perps","market",e.symbol]}async function Fs(e,{symbol:t}){return await e.getMarket(t)}function it(e,t={}){let{client:r}=R(),s=De(r),n=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:St,staleTime:St/2,enabled:s&&t.enabled!==false&&!!e.symbol,select:o=>o.bySymbol.get(e.symbol)?.market??null}),i=reactQuery.useQuery({queryKey:Is(e),queryFn:async()=>Fs(r,e),staleTime:St/2,refetchInterval:St,...t,enabled:!s&&t.enabled!==false&&!!e.symbol});return s?n:i}var vt=6e4;function qs(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function Hs(e,{symbols:t}={}){return await e.getMarkets(t)}function er(e={},t={}){let{client:r}=R(),s=De(r),n=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:vt,staleTime:vt/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:qs(e),queryFn:async()=>Hs(r,e),staleTime:vt/2,refetchInterval:vt,...t,enabled:!s&&t.enabled!==false});return s?n:i}function _s(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Bs(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function io(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:_s(e),queryFn:async()=>Bs(r,e),staleTime:30*1e3,...t})}function Qs(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 Ks(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function tr(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:Qs(e),queryFn:async()=>Ks(r,e),staleTime:5*1e3,...t})}function zs(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Ws(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function rr(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:zs(e),queryFn:async()=>Ws(r,e),staleTime:5*1e3,...t})}function Ge(e){return ["perps","positions",e.userAddress??""]}async function $s(e,t){return await e.getPositions(t)}function po(e,t){return {...e,positions:e.positions.filter(r=>r.symbol===t)}}function ot(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:Ge({userAddress:n}),queryFn:async()=>$s(r,{userAddress:n}),enabled:s&&!!n,staleTime:10*1e3,select:i?o=>po(o,i):void 0,...t})}function je(e){return ["perps","orders",e.userAddress??""]}async function Vs(e,t){return await e.getOpenOrders(t)}function co(e,t){let r=e.orders.filter(s=>s.symbol===t);return {...e,orders:r,totalCount:r.length}}function sr(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:je({userAddress:n}),queryFn:async()=>Vs(r,{userAddress:n}),enabled:s&&!!n,staleTime:5*1e3,select:i?o=>co(o,i):void 0,...t})}function Gs(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function js(e,t){return await e.getTrades(t)}function nr(e,t={}){let{client:r}=R(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Gs(n),queryFn:async()=>js(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function Pt(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function Ys(e,t){return await e.getActiveAssetLeverage(t)}function ir(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:Pt({userAddress:n,symbol:i}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return Ys(r,{userAddress:n,symbol:i})},enabled:s&&!!n&&!!i,staleTime:30*1e3,...t})}var or=6e4;function Js(e){return ["perps","assetMeta",e.symbol??""]}async function Zs(e,t){return await e.getAssetMeta(t)}function at(e,t={}){let{client:r}=R(),{enabled:s=true,symbol:n}=e,i=De(r),o=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:or,staleTime:or/2,enabled:i&&s&&!!n,select:l=>n?l.bySymbol.get(n)?.meta??null:null}),a=reactQuery.useQuery({queryKey:Js({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return Zs(r,{symbol:n})},enabled:!i&&s&&!!n,staleTime:or,...t});return i?o:a}async function en(e,t){return await e.placeOrder(t)}function ar(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>en(t,r),...e})}async function tn(e,t){return await e.cancelOrder(t)}function lr(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>tn(t,r),...e})}function Fe(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=R(),[a,l]=react.useState(null),[p,c]=react.useState(false),[u,d]=react.useState(null),f=react.useRef(null),y=react.useRef(null),m=react.useRef(i);m.current=i;let v=react.useCallback(P=>{let C=m.current;if(!C||C<=0){l(P);return}f.current=P,y.current===null&&(y.current=setTimeout(()=>{if(y.current=null,f.current!==null){let A=f.current;f.current=null,l(A);}},C));},[]),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 P=null,C=true;return (async()=>{try{if(await o.connectWebSocket(),!C)return;c(!0),d(null),P=o.subscribeMarketData(t,r,v,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(h){C&&(d(h instanceof Error?h:new Error("Connection failed")),c(false));}})(),()=>{if(C=false,P)try{o.unsubscribe(P);}catch(h){console.error("Failed to unsubscribe:",h);}o.disconnectWebSocket(),y.current!==null&&(clearTimeout(y.current),y.current=null),f.current=null,c(false),l(null);}},[o,t,r,s,v,b]),{data:a,isConnected:p,error:u}}function vo(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null),u=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,u);}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,u]),{data:i,isConnected:a,error:p}}function Oo(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null),u=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,u);}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,u]),{data:i,isConnected:a,error:p}}function Ye(e){return ["perps","accountState",e.userAddress??""]}function mr(e,t={}){let{enabled:r=true,...s}=e;return reactQuery.useQuery({queryKey:Ye(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function ko(e){let{userAddress:t,enabled:r=true}=e,{client:s}=R(),n=reactQuery.useQueryClient(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null);return react.useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let u=null,d=true,f=m=>{if(!d)return;o(m),n.setQueryData(Ye({userAddress:t}),m);let v={positions:m.positions,totalEquity:m.totalEquity,availableBalance:m.availableBalance,totalUnrealizedPnl:m.totalUnrealizedPnl,raw:m.raw};n.setQueryData(Ge({userAddress:t}),v);let b={orders:m.openOrders,totalCount:m.openOrders.length,raw:m.raw};if(n.setQueryData(je({userAddress:t}),b),m.universe&&n.setQueryData(ye(),m.universe),m.leverageByCoin)for(let[P,C]of Object.entries(m.leverageByCoin))n.setQueryData(Pt({userAddress:t,symbol:`${P}-USDC`}),C);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),c(null),u=s.subscribeAccountState(t,f);}catch(m){if(!d)return;l(false),c(m instanceof Error?m:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,u)try{s.unsubscribe(u);}catch(m){console.error("[useAccountStateSubscription] unsubscribe failed:",m);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:i,isConnected:a,error:p}}function Ao(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(Ye({userAddress:t}))||(async()=>{try{let[p,c]=await Promise.all([n.getPositions({userAddress:t}),n.getOpenOrders({userAddress:t})]);if(o)return;i.setQueryData(Ge({userAddress:t}),p),i.setQueryData(je({userAddress:t}),c);}catch(p){process.env.NODE_ENV!=="production"&&console.warn("[useHyperliquidUserBootstrap] fallback REST failed:",p);}})();},s);return ()=>{o=true,clearTimeout(a);}},[n,i,t,r,s]);}function No(){let e=react.useContext(Oe);if(!e||!e.client)throw new Error("usePerpDepositClient must be used within a <PerpetualsProvider>.");if(!e.depositClient)throw new Error("usePerpDepositClient: <PerpetualsProvider> was rendered without a `depositClient` prop. Pass a `LiberFiPerpDepositClient` instance to enable the deposit flow.");return e.depositClient}function Le(){return react.useContext(Oe)?.depositClient}function sn(e){return ["perps","deposit","quote",e]}async function nn(e,t){return e.quote(t)}function yr(e,t={}){let r=Le(),s=(t.enabled??!!Mo(e))&&!!r;return reactQuery.useQuery({queryKey:sn(e??null),queryFn:async()=>nn(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Mo(e){return !!(e&&e.originChainId&&e.userAddress&&e.hyperliquidRecipient&&e.grossAmount&&e.source)}function gr(e){let t=Le(),[r,s]=react.useReducer(Jt,xt),n=Fo(e),i=react.useCallback(()=>{s({type:"RESET"});},[]),o=react.useCallback(async a=>{let{quote:l}=a;s({type:"SIGN_START"});let p;try{if(p=await Lo(l,n),!p)throw new Error("wallet returned an empty tx hash")}catch(u){let d=an(u,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),u}s({type:"BROADCAST_START"});let c={userAddress:a.userAddress,hyperliquidRecipient:a.hyperliquidRecipient,originTxHash:p,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 u=await t.submit(c);return s({type:"SUBMIT_OK",intentId:u.intentId,originTxHash:p}),u.intentId}catch(u){let d=an(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,n.solana,n.evm]);return {state:r,execute:o,reset:i,dispatch:s}}function Fo(e){return typeof e=="function"?{solana:e}:e}async function Lo(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 an(e,t){if(e instanceof ue){let r=qo(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 qo(e){if(e)try{return JSON.parse(e)}catch{return}}function ln(e){return ["perps","deposit","status",e??null]}async function pn(e,t){return e.status(t)}function br(e,t={}){let r=Le(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:ln(e??void 0),queryFn:async()=>pn(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&nt.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var lt={phase:"idle",steps:[]};function Ct(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&_o(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 Ot(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?Bo(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 lt}}function Tt(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 _o(e,t){return e.toLowerCase()===t.toLowerCase()}function Bo(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 wt(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,l]=react.useReducer(Ot,lt),p=react.useRef(t),c=react.useRef(s),u=react.useRef(i),d=react.useRef(o);p.current=t,c.current=s,u.current=i,d.current=o;let f=react.useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let P=await p.current.getAccountState(r),C=c.current.map(A=>({step:A,status:Ct(A,P)}));l({type:"LOAD_SUCCESS",accountState:P,steps:C});}catch(P){let C=cn(P);l({type:"LOAD_ERROR",error:C.message}),d.current?.(C,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let y=react.useCallback(async P=>{let C=a.steps[P];if(C){l({type:"RUN_STEP",index:P});try{let A=await Ko(p.current,C.step);l({type:"STEP_SUCCESS",index:P,txHash:A.txHash,accountState:A.state});}catch(A){let h=cn(A);l({type:"STEP_ERROR",index:P,error:h.message}),d.current?.(h,{stepId:C.step.id});}}},[a.steps]),m=react.useCallback(async()=>{let P=Tt(a);P!=null&&await y(P);},[a,y]),v=react.useCallback(()=>l({type:"RESET"}),[]),b=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!b.current?(b.current=true,u.current?.(a)):a.phase!=="done"&&(b.current=false);},[a]),{state:a,reload:f,runNext:m,runStep:y,reset:v}}function Ko(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 cn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function hr(){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 mn="liberfi-perp-shimmer",Wo=`
|
|
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 Ri=new Set(["userFills","userFillsByTime","userFunding","userNonFundingLedgerUpdates","frontendOpenOrders","userRateLimit","historicalOrders","userTwapSliceFills","predictedFundings"]);function Gt(e){return e&&Ri.has(e)?20:2}var Os=1,st=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 Ai(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 Ve=class{ws=null;wsEndpoint;subscriptions=new Map;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;heartbeatInterval=null;messageQueue=[];isConnected=false;pingInterval=3e4;reconnectTimeout=null;isReconnecting=false;connectPromise=null;manuallyDisconnected=false;constructor(t){this.wsEndpoint=t;}async connect(){if(!(this.isConnected&&this.ws?.readyState===WebSocket.OPEN))return this.connectPromise?this.connectPromise:(this.manuallyDisconnected=false,this.connectPromise=new Promise((t,r)=>{let s=false,n=i=>{s||(s=true,this.connectPromise=null,i());};try{let i=new WebSocket(this.wsEndpoint);this.ws=i,i.onopen=()=>{this.ws===i&&(console.log("[WebSocket] Connected to Hyperliquid"),this.isConnected=!0,this.reconnectAttempts=0,this.isReconnecting=!1,this.startHeartbeat(),this.flushMessageQueue(),n(t));},i.onmessage=o=>{this.ws===i&&this.handleMessage(o.data);},i.onerror=o=>{this.ws===i&&(console.error("[WebSocket] Error:",o),this.isConnected=!1,n(()=>r(new Error("WebSocket connection failed"))));},i.onclose=o=>{this.ws===i&&(console.log(`[WebSocket] Closed: ${o.code} - ${o.reason||"No reason provided"}`),this.isConnected=!1,this.stopHeartbeat(),this.connectPromise=null,s||n(()=>r(new Error(`WebSocket closed before connection was established: ${o.code}`))),!this.manuallyDisconnected&&o.code!==1e3&&this.attemptReconnect());};}catch(i){n(()=>r(i));}}),this.connectPromise)}disconnect(){this.manuallyDisconnected=true,this.stopHeartbeat(),this.subscriptions.clear(),this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(1e3,"Normal closure"),this.ws=null),this.isConnected=false,this.isReconnecting=false,this.reconnectAttempts=0;}attemptReconnect(){if(this.isReconnecting)return;if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[WebSocket] Max reconnection attempts reached");return}this.isReconnecting=true,this.reconnectAttempts++;let t=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[WebSocket] Reconnecting in ${t}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=window.setTimeout(()=>{this.connect().then(()=>{this.resubscribeAll();}).catch(r=>{console.error("[WebSocket] Reconnection failed:",r),this.isReconnecting=false;});},t);}startHeartbeat(){this.heartbeatInterval=window.setInterval(()=>{this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.send({method:"ping"});},this.pingInterval);}stopHeartbeat(){this.heartbeatInterval!==null&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}send(t){this.isConnected&&this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(JSON.stringify(t)):this.messageQueue.push(t);}flushMessageQueue(){for(;this.messageQueue.length>0;){let t=this.messageQueue.shift();t&&this.send(t);}}resubscribeAll(){this.subscriptions.forEach(t=>{this.sendSubscription(t.type,t.param,t.aggregation);});}handleMessage(t){try{let r=JSON.parse(t);r.channel?this.handleChannelMessage(r):r.method;}catch(r){console.error("[WebSocket] Failed to parse message:",r,t);}}handleChannelMessage(t){let r=t.channel;this.subscriptions.forEach((s,n)=>{if(this.isChannelMatch(r,s.type,s.param,t))try{let i=this.transformData(s.type,t.data,s.param);s.callback(i);}catch(i){console.error(`[WebSocket] Error in subscription callback (${n}):`,i);}});}isChannelMatch(t,r,s,n){if(r==="ticker"){if(t!=="activeAssetCtx")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else if(r==="trades"){if(t!=="trades")return false;let i=s.split("-")[0],o=Array.isArray(n?.data)?n.data[0]?.coin:void 0;return typeof o!="string"||o===i}else if(r==="orderBook"){if(t!=="l2Book")return false;let i=s.split("-")[0],o=n?.data?.coin;return typeof o=="string"&&o===i}else {if(r==="candle")return t==="candle";if(r==="userFills")return t==="userFills";if(r==="userEvents")return t==="userEvents";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 n=`${t?.coin??r.split("-")[0]}-USDC`,i=t?.ctx??{},o=parseFloat(i.midPx??i.markPx??"0"),a=parseFloat(i.markPx??i.midPx??"0"),l=i.prevDayPx?parseFloat(i.prevDayPx):o,p=l>0?(o-l)/l*100:0;return {symbol:n,price:o,change24h:p,volume24h:parseFloat(i.dayNtlVlm??"0"),fundingRate:parseFloat(i.funding??"0"),openInterest:parseFloat(i.openInterest??"0"),markPrice:a,indexPrice:parseFloat(i.oraclePx??i.midPx??"0")}}transformTradesData(t,r){return Array.isArray(t)?t.map(s=>({symbol:r,side:s.side==="B"?"buy":"sell",price:parseFloat(s.px),quantity:parseFloat(s.sz),timestamp:s.time,tradeId:s.tid})):[]}transformOrderBookData(t,r){let[s,n]=t.levels||[[],[]];return {symbol:r,bids:s.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),asks:n.map(i=>({price:parseFloat(i.px),quantity:parseFloat(i.sz),count:i.n})),timestamp:t.time||Date.now()}}transformCandleData(t,r){let[s]=r.split(":");return {symbol:s,open:parseFloat(t.o),high:parseFloat(t.h),low:parseFloat(t.l),close:parseFloat(t.c),volume:parseFloat(t.v),timestamp:t.t,closeTimestamp:t.T}}transformUserFillsData(t){return Array.isArray(t)?t.map(r=>({tradeId:r.tid?.toString(),orderId:r.oid?.toString(),symbol:`${r.coin}-USDC`,side:r.dir?.includes("Long")?"long":"short",price:parseFloat(r.px),quantity:parseFloat(r.sz),fee:parseFloat(r.fee||"0"),feeCurrency:r.feeToken||"USDC",isMaker:r.side==="M",timestamp:r.time})):[]}transformUserEventsData(t){return t}sendSubscription(t,r,s){let n;if(t==="ticker")n={method:"subscribe",subscription:{type:"activeAssetCtx",coin:r.split("-")[0]}};else if(t==="trades")n={method:"subscribe",subscription:{type:"trades",coin:r.split("-")[0]}};else if(t==="orderBook"){let o={type:"l2Book",coin:r.split("-")[0]};s?.nSigFigs!==void 0&&(o.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(o.mantissa=s.mantissa)),n={method:"subscribe",subscription:o};}else if(t==="candle"){let[i,o]=r.split(":");n={method:"subscribe",subscription:{type:"candle",coin:i.split("-")[0],interval:o}};}else t==="userFills"?n={method:"subscribe",subscription:{type:"userFills",user:r}}:t==="userEvents"?n={method:"subscribe",subscription:{type:"userEvents",user:r}}: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=Ai(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 Ts={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"}},Ni=60*1e3,Ui=1500,Ii=1500,jt=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||Ts[this.environment].api,this._wsEndpoint=t.wsEndpoint||Ts[this.environment].ws,this.timeout=t.timeout||3e4,t.rateLimit===false?this.rateLimiter=null:t.rateLimit instanceof st?this.rateLimiter=t.rateLimit:this.rateLimiter=new st(t.rateLimit);}weightFor(t,r){if(t.startsWith("/exchange"))return Os;if(t.startsWith("/info")){let s=r&&typeof r=="object"&&typeof r.type=="string"?r.type:void 0;return Gt(s)}return Gt(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 Ce(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new Ce(`Request timeout after ${this.timeout}ms`,408,""):n instanceof Ce?n:new Ce(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){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<Ui)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`,p=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx?parseFloat(a.prevDayPx):p,u=c>0?(p-c)/c*100:0,d={symbol:l,price:p,change24h:u,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<Ii)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,p;i.from!==void 0&&i.to!==void 0?(l=i.from,p=i.to):i.to!==void 0&&a?(p=i.to,l=p-o*a):i.from!==void 0&&a?(l=i.from,p=l+o*a):(p=Date.now(),l=p-o*(a??100));let u=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:p}})).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&&u.length>a&&(u=u.slice(u.length-a)),u}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(p=>({price:parseFloat(p.px),quantity:parseFloat(p.sz),count:p.n})),asks:l.slice(0,r).map(p=>({price:parseFloat(p.px),quantity:parseFloat(p.sz),count:p.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=ws(r.clearinghouse,t.symbol),i=Ds(s);return n.positions=Rs(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 Ce&&(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<Ni)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:Es(r?.clearinghouse),markByCoin:s?Ds(s):void 0},o=n.map(l=>ks(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 Ve(this._wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s,n){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager.subscribe(t,r,s,n?.aggregation)}subscribeCandles(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=`${t}:${r}`;return this.wsManager.subscribe("candle",n,s)}subscribeUserData(t,r,s){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");let n=t==="fills"?"userFills":"userEvents";return this.wsManager.subscribe(n,r,s)}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 ws(e,t){let r=e.assetPositions.map(o=>{let a=o.position,l=`${a.coin}-USDC`,p=parseFloat(a.szi);if(p===0)return null;let c=parseFloat(a.entryPx),u=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:p>0?"long":"short",quantity:Math.abs(p),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:c,markPrice:c,unrealizedPnl:u,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 Mi(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 ks(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",p=/^market$/i.test(a)?"market":"limit",c=e.isTrigger===true,u;c&&(/take\s*profit/i.test(a)?u="tp":/stop/i.test(a)&&(u="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:y,stopLossPrice:m}=Mi(e),v=t?.leverageByCoin?.get(e.coin),b=t?.markByCoin?.get(e.coin);return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:r,side:o?"long":"short",orderType:p,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:u,triggerCondition:f,markPrice:b,takeProfitPrice:y,stopLossPrice:m}}function Es(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 Li(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?ws(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=Li(e.spotState?.balances),i=e.meta&&e.assetCtxs?_i([e.meta,e.assetCtxs]):null,o=Es(t),a=s.map(d=>ks(d,{leverageByCoin:o,markByCoin:i??void 0})),l=Rs(r.positions,s,i),p=l.reduce((d,f)=>d+f.unrealizedPnl,0),c=e.meta&&e.assetCtxs?qi(e.meta,e.assetCtxs,e.serverTime):void 0,u=t?Hi(t):void 0;return {positions:l,openOrders:a,spotBalances:n,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:p,serverTime:e.serverTime,leverageByCoin:u,universe:c,raw:e}}function qi(e,t,r){let s=e.universe.map((i,o)=>{let a=t[o]??{},l=`${i.name}-USDC`,p=parseFloat(a.midPx||a.markPx||"0"),c=a.prevDayPx,u=c?parseFloat(c):p,d=u>0?(p-u)/u*100:0,f={symbol:l,price:p,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")},y=i.szDecimals,m=i.maxLeverage,v=typeof y=="number"?{szDecimals:y,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 Hi(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 _i(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 Ds(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 Bi(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 p=typeof a.orderType=="string"?a.orderType:"",c=/take\s*profit/i.test(p),u=/stop/i.test(p);c?(!i||a.timestamp>i.timestamp)&&(i=a):u&&(!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 Rs(e,t,r){return e.map(s=>{let n={...s},{tp:i,sl:o}=Bi(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 p=s.side==="long"?1:-1,c=(l-s.entryPrice)*s.quantity*p;n.unrealizedPnl=c,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=c/s.margin*100);}return n})}var Ce=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var ue=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Qi=3e4,Me=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??Qi,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 Ki(a);throw new ue(`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 ue)throw a;if(a instanceof Error&&a.name==="AbortError")throw new ue(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new ue(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(o);}}};async function Ki(e){try{return await e.text()}catch{return ""}}var zi="wss://api.hyperliquid.xyz/ws",Yt=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 Me({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??zi,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 ue&&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 Ve(this.wsEndpoint)),!this.wsManager.isConnectedNow()&&await this.wsManager.connect();}disconnectWebSocket(){this.wsRefCount=Math.max(0,this.wsRefCount-1),this.wsRefCount===0&&this.wsManager&&(this.wsManager.disconnect(),this.wsManager=null);}subscribeMarketData(t,r,s,n){return this.requireWS().subscribe(t,r,s,n?.aggregation)}subscribeCandles(t,r,s){return this.requireWS().subscribe("candle",`${t}:${r}`,s)}subscribeUserData(t,r,s){let n=t==="fills"?"userFills":"userEvents";return this.requireWS().subscribe(n,r,s)}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}requireWS(){if(!this.wsManager)throw new Error("WebSocket not connected. Call connectWebSocket() first.");return this.wsManager}};var Xt=class{transport;constructor(t){this.transport="transport"in t?t.transport:new Me(t);}getBaseUrl(){return this.transport.getBaseUrl()}async quote(t){return this.transport.request("POST",{path:"/v1/deposits/quote",body:t})}async submit(t){return this.transport.request("POST",{path:"/v1/deposits/submit",body:t})}async status(t){if(!t)throw new Error("intentId is required");return this.transport.request("GET",{path:`/v1/deposits/${encodeURIComponent(t)}`})}async refresh(t){if(!t)throw new Error("intentId is required");return this.transport.request("POST",{path:`/v1/deposits/${encodeURIComponent(t)}/refresh`})}};var nt=new Set(["settled","refunded","failed"]);var xt={phase:"idle"};function Jt(e,t){switch(t.type){case "RESET":return xt;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 Wi(t.status,r)}}}function Wi(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 $i(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function Vi(e){return e.phase==="submitted"||e.phase==="tracking"}function Gi(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function ji(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 Yi(e){return e!==void 0&&nt.has(e)}var Oe=react.createContext({});function Zi({client:e,depositClient:t,children:r}){let s=react.useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsxRuntime.jsx(Oe.Provider,{value:s,children:r})}function R(){let e=react.useContext(Oe);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function As(){return ["perps","coins"]}async function Ns(e){return await e.getSupportedCoins()}function Zt(e={}){let{client:t}=R();return reactQuery.useQuery({queryKey:As(),queryFn:async()=>Ns(t),staleTime:300*1e3,...e})}var Us=6e4;function ye(){return ["perps","universe"]}async function Te(e){if(typeof e.getUniverseSnapshot!="function")throw new Error("useUniverseQuery: the active perpetuals client does not implement getUniverseSnapshot()");return e.getUniverseSnapshot()}function De(e){return typeof e.getUniverseSnapshot=="function"}function no(e={}){let{client:t}=R(),r=De(t)&&e.enabled!==false;return reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(t),refetchInterval:Us,staleTime:Us/2,...e,enabled:r})}var St=6e4;function Ms(e){return ["perps","market",e.symbol]}async function Ls(e,{symbol:t}){return await e.getMarket(t)}function it(e,t={}){let{client:r}=R(),s=De(r),n=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:St,staleTime:St/2,enabled:s&&t.enabled!==false&&!!e.symbol,select:o=>o.bySymbol.get(e.symbol)?.market??null}),i=reactQuery.useQuery({queryKey:Ms(e),queryFn:async()=>Ls(r,e),staleTime:St/2,refetchInterval:St,...t,enabled:!s&&t.enabled!==false&&!!e.symbol});return s?n:i}var vt=6e4;function qs(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function Hs(e,{symbols:t}={}){return await e.getMarkets(t)}function er(e={},t={}){let{client:r}=R(),s=De(r),n=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:vt,staleTime:vt/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:qs(e),queryFn:async()=>Hs(r,e),staleTime:vt/2,refetchInterval:vt,...t,enabled:!s&&t.enabled!==false});return s?n:i}function _s(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function Bs(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function oo(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:_s(e),queryFn:async()=>Bs(r,e),staleTime:30*1e3,...t})}function Qs(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 Ks(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function tr(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:Qs(e),queryFn:async()=>Ks(r,e),staleTime:5*1e3,...t})}function zs(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function Ws(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function rr(e,t={}){let{client:r}=R();return reactQuery.useQuery({queryKey:zs(e),queryFn:async()=>Ws(r,e),staleTime:5*1e3,...t})}function Ge(e){return ["perps","positions",e.userAddress??""]}async function $s(e,t){return await e.getPositions(t)}function uo(e,t){return {...e,positions:e.positions.filter(r=>r.symbol===t)}}function ot(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:Ge({userAddress:n}),queryFn:async()=>$s(r,{userAddress:n}),enabled:s&&!!n,staleTime:10*1e3,select:i?o=>uo(o,i):void 0,...t})}function je(e){return ["perps","orders",e.userAddress??""]}async function Vs(e,t){return await e.getOpenOrders(t)}function mo(e,t){let r=e.orders.filter(s=>s.symbol===t);return {...e,orders:r,totalCount:r.length}}function sr(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:je({userAddress:n}),queryFn:async()=>Vs(r,{userAddress:n}),enabled:s&&!!n,staleTime:5*1e3,select:i?o=>mo(o,i):void 0,...t})}function Gs(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function js(e,t){return await e.getTrades(t)}function nr(e,t={}){let{client:r}=R(),{enabled:s=true,...n}=e;return reactQuery.useQuery({queryKey:Gs(n),queryFn:async()=>js(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function Pt(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function Ys(e,t){return await e.getActiveAssetLeverage(t)}function ir(e,t={}){let{client:r}=R(),{enabled:s=true,userAddress:n,symbol:i}=e;return reactQuery.useQuery({queryKey:Pt({userAddress:n,symbol:i}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return Ys(r,{userAddress:n,symbol:i})},enabled:s&&!!n&&!!i,staleTime:30*1e3,...t})}var or=6e4;function Js(e){return ["perps","assetMeta",e.symbol??""]}async function Zs(e,t){return await e.getAssetMeta(t)}function at(e,t={}){let{client:r}=R(),{enabled:s=true,symbol:n}=e,i=De(r),o=reactQuery.useQuery({queryKey:ye(),queryFn:()=>Te(r),refetchInterval:or,staleTime:or/2,enabled:i&&s&&!!n,select:l=>n?l.bySymbol.get(n)?.meta??null:null}),a=reactQuery.useQuery({queryKey:Js({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return Zs(r,{symbol:n})},enabled:!i&&s&&!!n,staleTime:or,...t});return i?o:a}async function en(e,t){return await e.placeOrder(t)}function ar(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>en(t,r),...e})}async function tn(e,t){return await e.cancelOrder(t)}function lr(e={}){let{client:t}=R();return reactQuery.useMutation({mutationFn:async r=>tn(t,r),...e})}function Le(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=R(),[a,l]=react.useState(null),[p,c]=react.useState(false),[u,d]=react.useState(null),f=react.useRef(null),y=react.useRef(null),m=react.useRef(i);m.current=i;let v=react.useCallback(P=>{let C=m.current;if(!C||C<=0){l(P);return}f.current=P,y.current===null&&(y.current=setTimeout(()=>{if(y.current=null,f.current!==null){let A=f.current;f.current=null,l(A);}},C));},[]),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 P=null,C=true;return (async()=>{try{if(await o.connectWebSocket(),!C)return;c(!0),d(null),P=o.subscribeMarketData(t,r,v,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(h){C&&(d(h instanceof Error?h:new Error("Connection failed")),c(false));}})(),()=>{if(C=false,P)try{o.unsubscribe(P);}catch(h){console.error("Failed to unsubscribe:",h);}o.disconnectWebSocket(),y.current!==null&&(clearTimeout(y.current),y.current=null),f.current=null,c(false),l(null);}},[o,t,r,s,v,b]),{data:a,isConnected:p,error:u}}function Po(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null),u=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,u);}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,u]),{data:i,isConnected:a,error:p}}function To(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=R(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null),u=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,u);}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,u]),{data:i,isConnected:a,error:p}}function Ye(e){return ["perps","accountState",e.userAddress??""]}function mr(e,t={}){let{enabled:r=true,...s}=e;return reactQuery.useQuery({queryKey:Ye(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function Eo(e){let{userAddress:t,enabled:r=true}=e,{client:s}=R(),n=reactQuery.useQueryClient(),[i,o]=react.useState(null),[a,l]=react.useState(false),[p,c]=react.useState(null);return react.useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let u=null,d=true,f=m=>{if(!d)return;o(m),n.setQueryData(Ye({userAddress:t}),m);let v={positions:m.positions,totalEquity:m.totalEquity,availableBalance:m.availableBalance,totalUnrealizedPnl:m.totalUnrealizedPnl,raw:m.raw};n.setQueryData(Ge({userAddress:t}),v);let b={orders:m.openOrders,totalCount:m.openOrders.length,raw:m.raw};if(n.setQueryData(je({userAddress:t}),b),m.universe&&n.setQueryData(ye(),m.universe),m.leverageByCoin)for(let[P,C]of Object.entries(m.leverageByCoin))n.setQueryData(Pt({userAddress:t,symbol:`${P}-USDC`}),C);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),c(null),u=s.subscribeAccountState(t,f);}catch(m){if(!d)return;l(false),c(m instanceof Error?m:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,u)try{s.unsubscribe(u);}catch(m){console.error("[useAccountStateSubscription] unsubscribe failed:",m);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:i,isConnected:a,error:p}}function No(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(Ye({userAddress:t}))||(async()=>{try{let[p,c]=await Promise.all([n.getPositions({userAddress:t}),n.getOpenOrders({userAddress:t})]);if(o)return;i.setQueryData(Ge({userAddress:t}),p),i.setQueryData(je({userAddress:t}),c);}catch(p){process.env.NODE_ENV!=="production"&&console.warn("[useHyperliquidUserBootstrap] fallback REST failed:",p);}})();},s);return ()=>{o=true,clearTimeout(a);}},[n,i,t,r,s]);}function Uo(){let e=react.useContext(Oe);if(!e||!e.client)throw new Error("usePerpDepositClient must be used within a <PerpetualsProvider>.");if(!e.depositClient)throw new Error("usePerpDepositClient: <PerpetualsProvider> was rendered without a `depositClient` prop. Pass a `LiberFiPerpDepositClient` instance to enable the deposit flow.");return e.depositClient}function Fe(){return react.useContext(Oe)?.depositClient}function sn(e){return ["perps","deposit","quote",e]}async function nn(e,t){return e.quote(t)}function yr(e,t={}){let r=Fe(),s=(t.enabled??!!Mo(e))&&!!r;return reactQuery.useQuery({queryKey:sn(e??null),queryFn:async()=>nn(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Mo(e){return !!(e&&e.originChainId&&e.userAddress&&e.hyperliquidRecipient&&e.grossAmount&&e.source)}function gr(e){let t=Fe(),[r,s]=react.useReducer(Jt,xt),n=Fo(e),i=react.useCallback(()=>{s({type:"RESET"});},[]),o=react.useCallback(async a=>{let{quote:l}=a;s({type:"SIGN_START"});let p;try{if(p=await qo(l,n),!p)throw new Error("wallet returned an empty tx hash")}catch(u){let d=an(u,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:d}),u}s({type:"BROADCAST_START"});let c={userAddress:a.userAddress,hyperliquidRecipient:a.hyperliquidRecipient,originTxHash:p,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 u=await t.submit(c);return s({type:"SUBMIT_OK",intentId:u.intentId,originTxHash:p}),u.intentId}catch(u){let d=an(u,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:d}),u}},[t,n.solana,n.evm]);return {state:r,execute:o,reset:i,dispatch:s}}function Fo(e){return typeof e=="function"?{solana:e}:e}async function qo(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 an(e,t){if(e instanceof ue){let r=Ho(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 Ho(e){if(e)try{return JSON.parse(e)}catch{return}}function ln(e){return ["perps","deposit","status",e??null]}async function pn(e,t){return e.status(t)}function br(e,t={}){let r=Fe(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return reactQuery.useQuery({queryKey:ln(e??void 0),queryFn:async()=>pn(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&nt.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var lt={phase:"idle",steps:[]};function Ct(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Bo(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 Ot(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?Qo(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 lt}}function Tt(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 Bo(e,t){return e.toLowerCase()===t.toLowerCase()}function Qo(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 wt(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,l]=react.useReducer(Ot,lt),p=react.useRef(t),c=react.useRef(s),u=react.useRef(i),d=react.useRef(o);p.current=t,c.current=s,u.current=i,d.current=o;let f=react.useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let P=await p.current.getAccountState(r),C=c.current.map(A=>({step:A,status:Ct(A,P)}));l({type:"LOAD_SUCCESS",accountState:P,steps:C});}catch(P){let C=cn(P);l({type:"LOAD_ERROR",error:C.message}),d.current?.(C,{});}}},[r]);react.useEffect(()=>{n&&r&&f();},[n,r,f]);let y=react.useCallback(async P=>{let C=a.steps[P];if(C){l({type:"RUN_STEP",index:P});try{let A=await zo(p.current,C.step);l({type:"STEP_SUCCESS",index:P,txHash:A.txHash,accountState:A.state});}catch(A){let h=cn(A);l({type:"STEP_ERROR",index:P,error:h.message}),d.current?.(h,{stepId:C.step.id});}}},[a.steps]),m=react.useCallback(async()=>{let P=Tt(a);P!=null&&await y(P);},[a,y]),v=react.useCallback(()=>l({type:"RESET"}),[]),b=react.useRef(false);return react.useEffect(()=>{a.phase==="done"&&!b.current?(b.current=true,u.current?.(a)):a.phase!=="done"&&(b.current=false);},[a]),{state:a,reload:f,runNext:m,runStep:y,reset:v}}function zo(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 cn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function hr(){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 mn="liberfi-perp-shimmer",$o=`
|
|
2
2
|
@keyframes ${mn}{0%{background-position:200% 0}100%{background-position:-200% 0}}
|
|
3
|
-
`;function we(){return jsxRuntime.jsx("style",{children:Wo})}var xr={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:`${mn} 1.8s ease-in-out infinite`,borderRadius:6};function ce(e){return {...xr,animationDelay:`${e}ms`}}function vr(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(we,{}),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:He(0,84,23)}),jsxRuntime.jsx("div",{style:He(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(Sr,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(Sr,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(Sr,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:He(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:He(330,64,17)}),jsxRuntime.jsx("div",{style:He(360,64,17)})]})]})]})]})]})}function Sr({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:He(r,e,16)}),jsxRuntime.jsx("div",{style:He(r+30,t,17)})]})}function He(e,t,r){return {...ce(e),width:t,height:r}}function Cr(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:i,isPending:o}=it({symbol:e}),{data:a,isConnected:l}=Fe({type:"ticker",symbol:e,enabled:!!i});return react.useEffect(()=>{i&&r(i);},[i]),react.useEffect(()=>{if(!a)return;let p=Go(a,e);p&&r(c=>jo(c??i??void 0,p,e));},[a,i,e]),react.useEffect(()=>{let p=()=>{let u=Date.now(),d=3600*1e3,f=u%d,y=d-f;return Math.floor(y/1e3)};n(p());let c=setInterval(()=>{n(p());},1e3);return ()=>clearInterval(c)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function Go(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 Xe(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function jo(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:Xe(t.price,e?.price??0),change24h:Xe(t.change24h,e?.change24h??0),volume24h:Xe(t.volume24h,e?.volume24h??0),fundingRate:Xe(t.fundingRate,e?.fundingRate??0),openInterest:Xe(t.openInterest,e?.openInterest??0),markPrice:Xe(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 Xo(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 yn(e,t=2){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e9?`$${(e/1e9).toFixed(t)}B`:e>=1e6?`$${(e/1e6).toFixed(t)}M`:e>=1e3?`$${(e/1e3).toFixed(t)}K`:`$${e.toFixed(t)}`}function gn(e){return typeof e!="number"||!Number.isFinite(e)?"-":e>=1e3?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e>=1?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):e.toFixed(6)}function Or({marketData:e,fundingCountdown:t}){let{t:r}=i18n.useTranslation(),{symbol:s,price:n,change24h:i,indexPrice:o,volume24h:a,openInterest:l,fundingRate:p}=e,c=typeof i=="number"&&Number.isFinite(i)?i:0,u=typeof p=="number"&&Number.isFinite(p)?p:0,d=c>=0,f=c.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:gn(n)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",f,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap: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:o?gn(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.volume24h")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:yn(a,0)})]}),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:yn(l*(e.markPrice||n))})]}),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:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Xo(t)})]})]})]})]})}function Jo({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Cr(e);return r?jsxRuntime.jsx(vr,{}):t?jsxRuntime.jsx(Or,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx(hr,{})}function Dr({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:i,isPending:o}=Zt(),{data:a,isPending:l}=er({symbols:i},{enabled:!!i&&i.length>0});react.useEffect(()=>{a&&n(a);},[a]);let p=react.useMemo(()=>{if(!t.trim())return s;let u=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(u))},[s,t]);return {coins:s,isLoading:o||l,searchQuery:t,setSearchQuery:r,filteredCoins:p,handleSelectCoin:u=>{e?.(u);}}}function hn(e,t=2){return e>=1e9?`$${(e/1e9).toFixed(t)}B`:e>=1e6?`$${(e/1e6).toFixed(t)}M`:e>=1e3?`$${(e/1e3).toFixed(t)}K`:`$${e.toFixed(t)}`}function sa(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function wr({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),p=(o.fundingRate*100).toFixed(4),c=o.fundingRate>=0,u=o.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(o.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:d=>{let f=d.target;f.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:sa(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:[p,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:hn(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:hn(o.openInterest*o.price)})]},o.symbol)})]})]})}function na({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Dr({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(wr,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function On(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 Pn(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 Cn(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 Er({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}=tr({symbol:e,maxLevel:t}),p=react.useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,y=s?.asks[0]?.price??a?.asks[0]?.price,m=f&&y?(f+y)/2:y??f??0;return m>0?Math.floor(Math.log10(m)):null},[s,a]),c=react.useMemo(()=>{if(p===null)return;let f=Math.pow(10,p);return On(f,i)},[i,p]),{data:u}=Fe({type:"orderBook",symbol:e,enabled:!!a,aggregation:c,throttleMs:100});return react.useEffect(()=>{u?n(u):a&&n(a);},[u,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=Pn(s.bids,i,"bid"),y=Pn(s.asks,i,"ask"),m=f.sort((F,M)=>M.price-F.price).slice(0,t),v=y.sort((F,M)=>F.price-M.price).slice(0,t),b=Cn(m),P=Cn(v),C=b[0]?.price||0,h=(P[0]?.price||0)-C,z=C>0?h/C*100:0;return {bids:b,asks:P,spread:h,spreadPercentage:z}},[s,i,t]),isLoading:l,precision:i,setPrecision:o}}var Dn={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},aa={backgroundColor:"#000000",fontSize:11},la={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Rr={flex:"1 1 0%"},pa={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ua={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},ca={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},da={color:"#F76816",fontWeight:400},ma={color:"#C7FF2E",fontWeight:400},wn={flex:"1 1 0%",color:"#ffffff"},fa={flex:"1 1 0%"},ya={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},ga={gap:12,fontSize:12,color:"#ffffff"},ba={color:"#ffffff"},ha={color:"#ffffff",fontWeight:500},xa={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},Sa={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)"},Nn={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},va={...Nn,color:"#C7FF2E"};function Pa(e){return e>=1e3?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e>=1?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):e.toFixed(6)}function kn(e){return Math.round(e).toLocaleString("en-US")}function En(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var Rn=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",l=react.useMemo(()=>a?{...ua,width:`${n}%`}:{...ca,width:`${n}%`},[a,n]),p=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:pa,onClick:p,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:fa,children:jsxRuntime.jsx("span",{style:a?da:ma,children:Pa(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:wn,children:kn(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:wn,children:kn(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 Ca({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 p=c=>{a.current?.contains(c.target)||o(false);};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[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:ya,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:ga,children:[jsxRuntime.jsx("span",{style:ba,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:xa,onClick:()=>o(p=>!p),"aria-haspopup":"listbox","aria-expanded":i,children:[jsxRuntime.jsx("span",{children:En(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:Sa,children:r.map(p=>{let c=p===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":c,className:"cursor-pointer transition-colors",style:c?va:Nn,onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(p),o(false);},children:En(p)},p)})})]}),jsxRuntime.jsxs("span",{style:ha,children:[e.toFixed(3),"%"]})]})})}function Nr({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let{t:a}=i18n.useTranslation(),l=react.useRef(null),p=react.useRef(null),c=react.useRef(true),u=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=p.current;!m||!u.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;},[]),y=react.useCallback(()=>{let m=p.current;m&&(u.current=m.scrollTop<=24);},[]);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:aa,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:la,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Rr,children:a("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Rr,children:a("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Rr,children:a("perpetuals.orderbook.col.total")})]}),jsxRuntime.jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:Dn,children:d.map((m,v)=>jsxRuntime.jsx(Rn,{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(Ca,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsxRuntime.jsx("div",{ref:p,onScroll:y,className:"flex-1 min-h-0 overflow-y-auto",style:Dn,children:e.map((m,v)=>jsxRuntime.jsx(Rn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:o},`bid-${m.price}-${v}`))})]})}var In=[1,2,5,10,100,1e3],Oa={backgroundColor:"#000000",fontSize:11},Ta={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Je={flex:"1 1 0%"},Da={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},wa={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function ka(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Ta,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Je,children:e("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Je,children:e("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Je,children:e("perpetuals.orderbook.col.total")})]})}function Un({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Da,children:[jsxRuntime.jsx("div",{style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e+60),height:11,width:64}})})]})}function Ea(){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(we,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Oa,children:[jsxRuntime.jsx(ka,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(Un,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:wa,children:jsxRuntime.jsx("div",{style:{...ce(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(Un,{delay:200+r*40},`bid-${r}`))})]})]})}function Ra(){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 Aa({symbol:e,maxLevel:t=40,precisionOptions:r=In,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:l,spreadPercentage:p,isLoading:c,precision:u,setPrecision:d}=Er({symbol:e,maxLevel:t,precision:o});return c?jsxRuntime.jsx(Ea,{}):a.length===0&&l.length===0?jsxRuntime.jsx(Ra,{}):jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(Nr,{bids:a,asks:l,spreadPercentage:p,precision:u,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var Ma=200;function Ir({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:i}=rr({symbol:e,limit:t}),{data:o}=Fe({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(Fn));},[n]);let a=react.useRef([]),l=react.useRef(null),p=react.useRef(t);return p.current=t,react.useEffect(()=>{if(!o)return;let c=Ia(o);c.length!==0&&(a.current.push(...c),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let u=a.current;a.current=[],u.length!==0&&s(d=>{let f=u.filter(y=>!d.some(m=>m.timestamp===y.timestamp&&m.price===y.price&&m.quantity===y.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,p.current)});},Ma)));},[o]),react.useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function Ia(e){return (Array.isArray(e)?e:[e]).filter(Fn)}function Fn(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 Rt=22,Ln=28,qn=100,Hn=120,Ba={backgroundColor:"#000000",fontSize:11},Qa={height:Ln,minHeight:Ln,padding:"0 16px",color:"#6b6b6b",fontSize:11},Ka={flex:"1 1 0%",maxWidth:qn},za={flex:"1 1 0%",marginLeft:20},Wa={flex:"1 1 0%",maxWidth:Hn,textAlign:"right"},$a={height:Rt,minHeight:Rt,maxHeight:Rt,padding:"0 16px"},Va={flex:"1 1 0%",maxWidth:qn},Ga={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},ja={flex:"1 1 0%",maxWidth:Hn,textAlign:"right",color:"#777A8C"},Ya={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},Xa={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function Ja(e){return Number.isFinite(e)?e>=1e3?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e>=1?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:4}):e.toFixed(6):"-"}function Za(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"-"}function el(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 tl(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"?Ya:Xa,width:`${tl(a)}%`}),[n,a]);if(!n)return null;let p=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:$a,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Va,children:jsxRuntime.jsx("span",{className:p?"text-bullish":"text-bearish",children:Ja(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:Ga,children:Za(a)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:ja,children:el(o)})]})})}function qr({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:Ba,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Qa,children:[jsxRuntime.jsx("div",{style:Ka,children:r("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:za,children:r("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:Wa,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:Rt,rowProps:i,overscanCount:4})})]})}var sl={backgroundColor:"#000000",fontSize:11},nl={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},Bn={flex:"1 1 0%",maxWidth:100},Qn={flex:"1 1 0%",marginLeft:20},Kn={flex:"1 1 0%",maxWidth:120,textAlign:"right"},il={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function ol(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:nl,children:[jsxRuntime.jsx("div",{style:Bn,children:e("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:Qn,children:e("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:Kn,children:e("perpetuals.trades.col.age")})]})}function al({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:il,children:[jsxRuntime.jsx("div",{style:Bn,children:jsxRuntime.jsx("div",{style:{...ce(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:Qn,children:jsxRuntime.jsx("div",{style:{...ce(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Kn,children:jsxRuntime.jsx("div",{style:{...ce(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(we,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:sl,children:[jsxRuntime.jsx(ol,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(al,{delay:t*35},`trade-${t}`))})]})]})}function pl(){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 ul({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=Ir({symbol:e,limit:t});return i?jsxRuntime.jsx(ll,{}):n.length===0?jsxRuntime.jsx(pl,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(qr,{trades:n,onTradeClick:r})})}function zn(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function Wn(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:zn(s,n)*(e-t)/t*r*100}function ct(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let i=zn(s,n),o=e/r/100;return t*(1+i*o)}function $n(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 Vn(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var gl=20;function _r({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:o}){let[a,l]=react.useState("long"),[p,c]=react.useState("market"),u=reactHookForm.useForm({defaultValues:{amount:void 0,leverage:gl,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=it({symbol:e}),{data:f}=at({symbol:e}),y=f?.szDecimals,m=f?.maxLeverage??r,{mutateAsync:v,isPending:b}=ar({onSuccess:()=>{u.reset(),s?.();},onError:g=>{n?.(g);}}),P=reactQuery.useMutation({mutationFn:async g=>{if(!o)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await o(g)},onSuccess:()=>{u.reset(),s?.();},onError:g=>{n?.(g);}}),C=b||P.isPending,A=u.watch(),{amount:h,leverage:z,price:F}=A,M=d?.price||0,x=react.useMemo(()=>p==="limit"&&F?F:M,[p,F,M]),G=react.useMemo(()=>!h||h<=0||!z?0:h*z,[h,z]),X=react.useMemo(()=>G?G*5e-4:0,[G]),W=react.useMemo(()=>G?G+X:0,[G,X]),w=react.useMemo(()=>{if(!h||!x||!z||z===1||!f?.maxLeverage)return;let g=1/(2*f.maxLeverage),q=(1/z-g)/(a==="long"?1-g:1+g);return a==="long"?x*(1-q):x*(1+q)},[h,x,z,a,f?.maxLeverage]),{data:D}=ot({userAddress:t,symbol:e}),B=D?.totalEquity??0,$=D?.availableBalance??0,he=react.useMemo(()=>{let g=D?.positions?.[0];if(!g)return;let q=g.symbol.includes("-")?g.symbol.split("-")[0]:g.symbol;return {side:g.side,quantity:g.quantity,quantityRaw:g.quantityRaw,margin:g.margin,base:q}},[D?.positions]),{data:ee}=mr({userAddress:t,enabled:!!t}),pe=react.useMemo(()=>ee?.openOrders?.length?ee.openOrders.some(g=>g.symbol===e):false,[ee?.openOrders,e]),{data:ve}=ir({userAddress:t,symbol:e}),J=ve?.value,Ue=!t||J!==void 0,Pe=react.useRef(null);react.useEffect(()=>{Pe.current!==e&&J&&J>0&&(u.setValue("leverage",J),Pe.current=e);},[e,J,u]),react.useEffect(()=>{Pe.current=null;},[e]),react.useEffect(()=>{if(!(typeof h!="number"||Number.isNaN(h))){if(h<0){u.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}$>0&&h>$&&u.setValue("amount",$,{shouldValidate:false,shouldDirty:true});}},[h,$,u]);let re=react.useCallback(async g=>{if(!t)throw new Error("User address is required");if(!g.amount||g.amount<=0)throw new Error("Amount is required");let q=p==="limit"?g.price:void 0,O=g.takeProfitPrice,te=g.stopLossPrice;if(!O&&g.takeProfitPercent&&g.takeProfitPercent>0&&x&&(O=ct(g.takeProfitPercent,x,g.leverage,a,"tp")),!te&&g.stopLossPercent&&g.stopLossPercent>0&&x&&(te=ct(g.stopLossPercent,x,g.leverage,a,"sl")),o){if(!x||x<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(y===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Me=g.amount*g.leverage/x;await P.mutateAsync({symbol:e,side:a,orderType:p,amount:g.amount,price:q,leverage:g.leverage,takeProfitPrice:O,stopLossPrice:te,userAddress:t,size:Me,refPrice:x,szDecimals:y});return}await v({symbol:e,side:a,orderType:p,amount:g.amount,price:q,leverage:g.leverage,takeProfitPrice:O,stopLossPrice:te,userAddress:t});},[e,a,p,x,y,t,o,P,v]);return {form:u,side:a,orderType:p,setSide:l,setOrderType:c,handleSubmit:re,isSubmitting:C,currentPrice:x,marketPrice:M,estimatedFee:X,estimatedTotal:W,liquidationPrice:w,availableMargin:$,accountValue:B,currentPosition:he,maxLeverage:m,currentLeverage:J,isLeverageReady:Ue,hasOpenOrdersForSymbol:pe,szDecimals:y,onUpdateLeverage:i}}var se="#C7FF2E",Pl=se,ei="#F76816",Yn=ei;function Br(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 Cl="https://app.hyperliquid.xyz/coins",Ol=10;function $r(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var Tl={...xr,display:"inline-block",width:28,height:14,borderRadius:4};function Xn(e,t=2){return e.toFixed(t)}function Qr(e){if(!Number.isFinite(e)||e<=0)return "--";let t=Math.floor(Math.log10(e)),r=Math.max(0,4-t);return `$${new Intl.NumberFormat("en-US",{minimumFractionDigits:r,maximumFractionDigits:r}).format(e)}`}var Ee=1;function Dl(e){let t=Math.max(Ee,Math.floor(e)),r=n=>{let i=Math.round(n);return i<=10?Math.max(Ee,i):Math.round(i/5)*5},s=new Set([Ee,t]);for(let n of [.25,.5,.75]){let i=r(t*n);i>Ee&&i<t&&s.add(i);}return Array.from(s).sort((n,i)=>n-i).map(n=>({value:n,label:`${n}x`}))}function wl({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:i,onConfirm:o,onUpdate:a,onClose:l}){let p=Math.max(Ee,Math.floor(r)),[c,u]=react.useState(Math.max(Ee,Math.min(t,p))),[d,f]=react.useState(false);react.useEffect(()=>{e&&(u(Math.max(Ee,Math.min(t,p))),f(false));},[e,t,p]);let y=react.useMemo(()=>Dl(p),[p]),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:b}=i18n.useTranslation();return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:P=>{d||P||l();},size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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: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-[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:Yn},children:b("perpetuals.placeOrder.leverage.cannotUpdate",{symbol:s})}):jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:b("perpetuals.placeOrder.leverage.desc")}),i&&jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:Yn},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:`
|
|
3
|
+
`;function we(){return jsxRuntime.jsx("style",{children:$o})}var xr={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:`${mn} 1.8s ease-in-out infinite`,borderRadius:6};function ce(e){return {...xr,animationDelay:`${e}ms`}}function vr(){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(we,{}),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:He(0,84,23)}),jsxRuntime.jsx("div",{style:He(60,52,16)})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxRuntime.jsx(Sr,{labelWidth:72,valueWidth:64,delay:120}),jsxRuntime.jsx(Sr,{labelWidth:72,valueWidth:48,delay:180}),jsxRuntime.jsx(Sr,{labelWidth:84,valueWidth:56,delay:240}),jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:He(300,132,16)}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{style:He(330,64,17)}),jsxRuntime.jsx("div",{style:He(360,64,17)})]})]})]})]})]})}function Sr({labelWidth:e,valueWidth:t,delay:r}){return jsxRuntime.jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsxRuntime.jsx("div",{style:He(r,e,16)}),jsxRuntime.jsx("div",{style:He(r+30,t,17)})]})}function He(e,t,r){return {...ce(e),width:t,height:r}}function Cr(e){let[t,r]=react.useState(),[s,n]=react.useState(0),{data:i,isPending:o}=it({symbol:e}),{data:a,isConnected:l}=Le({type:"ticker",symbol:e,enabled:!!i});return react.useEffect(()=>{i&&r(i);},[i]),react.useEffect(()=>{if(!a)return;let p=jo(a,e);p&&r(c=>Yo(c??i??void 0,p,e));},[a,i,e]),react.useEffect(()=>{let p=()=>{let u=Date.now(),d=3600*1e3,f=u%d,y=d-f;return Math.floor(y/1e3)};n(p());let c=setInterval(()=>{n(p());},1e3);return ()=>clearInterval(c)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function jo(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 Xe(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Yo(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:Xe(t.price,e?.price??0),change24h:Xe(t.change24h,e?.change24h??0),volume24h:Xe(t.volume24h,e?.volume24h??0),fundingRate:Xe(t.fundingRate,e?.fundingRate??0),openInterest:Xe(t.openInterest,e?.openInterest??0),markPrice:Xe(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 ea(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 yn(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatAmountInUsd(e)}function gn(e){return typeof e!="number"||!Number.isFinite(e)?"-":utils.formatPriceInUsd(e)}function Or({marketData:e,fundingCountdown:t}){let{t:r}=i18n.useTranslation(),{symbol:s,price:n,change24h:i,indexPrice:o,volume24h:a,openInterest:l,fundingRate:p}=e,c=typeof i=="number"&&Number.isFinite(i)?i:0,u=typeof p=="number"&&Number.isFinite(p)?p:0,d=c>=0,f=c.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:gn(n)}),jsxRuntime.jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:d?"#C7FF2E":"#F76816"},children:[d?"+":"",f,"%"]})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap: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:o?gn(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.volume24h")}),jsxRuntime.jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:yn(a)})]}),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:yn(l*(e.markPrice||n))})]}),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:u>=0?"#C7FF2E":"#F76816"},children:[(u*100).toFixed(5),"%"]}),jsxRuntime.jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:ea(t)})]})]})]})]})}function ta({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Cr(e);return r?jsxRuntime.jsx(vr,{}):t?jsxRuntime.jsx(Or,{marketData:t,fundingCountdown:s}):jsxRuntime.jsx(hr,{})}function Dr({onSelectCoin:e}={}){let[t,r]=react.useState(""),[s,n]=react.useState([]),{data:i,isPending:o}=Zt(),{data:a,isPending:l}=er({symbols:i},{enabled:!!i&&i.length>0});react.useEffect(()=>{a&&n(a);},[a]);let p=react.useMemo(()=>{if(!t.trim())return s;let u=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(u))},[s,t]);return {coins:s,isLoading:o||l,searchQuery:t,setSearchQuery:r,filteredCoins:p,handleSelectCoin:u=>{e?.(u);}}}function hn(e){return utils.formatAmountInUsd(e)}function la(e){return utils.formatPriceInUsd(e)}function wr({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),p=(o.fundingRate*100).toFixed(4),c=o.fundingRate>=0,u=o.symbol.split("-")[0];return jsxRuntime.jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(o.symbol),onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent";},children:[jsxRuntime.jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsxRuntime.jsx("img",{src:`https://app.hyperliquid.xyz/coins/${u}.svg`,alt:u,className:"rounded-full",style:{width:20,height:20},onError:d=>{let f=d.target;f.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:u})]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:la(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:[p,"%"]}),jsxRuntime.jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:hn(o.volume24h)}),jsxRuntime.jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:hn(o.openInterest*o.price)})]},o.symbol)})]})]})}function pa({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Dr({onSelectCoin:e});return jsxRuntime.jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsxRuntime.jsx(wr,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function On(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 Pn(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 Cn(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 Er({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}=tr({symbol:e,maxLevel:t}),p=react.useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,y=s?.asks[0]?.price??a?.asks[0]?.price,m=f&&y?(f+y)/2:y??f??0;return m>0?Math.floor(Math.log10(m)):null},[s,a]),c=react.useMemo(()=>{if(p===null)return;let f=Math.pow(10,p);return On(f,i)},[i,p]),{data:u}=Le({type:"orderBook",symbol:e,enabled:!!a,aggregation:c,throttleMs:100});return react.useEffect(()=>{u?n(u):a&&n(a);},[u,a]),{...react.useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=Pn(s.bids,i,"bid"),y=Pn(s.asks,i,"ask"),m=f.sort((L,I)=>I.price-L.price).slice(0,t),v=y.sort((L,I)=>L.price-I.price).slice(0,t),b=Cn(m),P=Cn(v),C=b[0]?.price||0,h=(P[0]?.price||0)-C,z=C>0?h/C*100:0;return {bids:b,asks:P,spread:h,spreadPercentage:z}},[s,i,t]),isLoading:l,precision:i,setPrecision:o}}var Dn={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},fa={backgroundColor:"#000000",fontSize:11},ya={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Rr={flex:"1 1 0%"},ga={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ba={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},ha={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},xa={color:"#F76816",fontWeight:400},Sa={color:"#C7FF2E",fontWeight:400},wn={flex:"1 1 0%",color:"#ffffff"},va={flex:"1 1 0%"},Pa={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},Ca={gap:12,fontSize:12,color:"#ffffff"},Oa={color:"#ffffff"},Ta={color:"#ffffff",fontWeight:500},Da={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},wa={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)"},Nn={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},ka={...Nn,color:"#C7FF2E"};function Ea(e){return utils.formatPriceInUsd(e)}function kn(e){return utils.formatAmount(e)}function En(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var Rn=react.memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",l=react.useMemo(()=>a?{...ba,width:`${n}%`}:{...ha,width:`${n}%`},[a,n]),p=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:ga,onClick:p,children:[jsxRuntime.jsx("div",{className:"absolute left-0 top-0",style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:va,children:jsxRuntime.jsx("span",{style:a?xa:Sa,children:Ea(t)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:wn,children:kn(r)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:wn,children:kn(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 Ra({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 p=c=>{a.current?.contains(c.target)||o(false);};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[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:Pa,children:jsxRuntime.jsxs("div",{className:"flex items-center",style:Ca,children:[jsxRuntime.jsx("span",{style:Oa,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:Da,onClick:()=>o(p=>!p),"aria-haspopup":"listbox","aria-expanded":i,children:[jsxRuntime.jsx("span",{children:En(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:wa,children:r.map(p=>{let c=p===t;return jsxRuntime.jsx("button",{type:"button",role:"option","aria-selected":c,className:"cursor-pointer transition-colors",style:c?ka:Nn,onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(p),o(false);},children:En(p)},p)})})]}),jsxRuntime.jsxs("span",{style:Ta,children:[e.toFixed(3),"%"]})]})})}function Nr({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let{t:a}=i18n.useTranslation(),l=react.useRef(null),p=react.useRef(null),c=react.useRef(true),u=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=p.current;!m||!u.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;},[]),y=react.useCallback(()=>{let m=p.current;m&&(u.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:ya,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Rr,children:a("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Rr,children:a("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Rr,children:a("perpetuals.orderbook.col.total")})]}),jsxRuntime.jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:Dn,children:d.map((m,v)=>jsxRuntime.jsx(Rn,{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(Ra,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsxRuntime.jsx("div",{ref:p,onScroll:y,className:"flex-1 min-h-0 overflow-y-auto",style:Dn,children:e.map((m,v)=>jsxRuntime.jsx(Rn,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:o},`bid-${m.price}-${v}`))})]})}var Mn=[1,2,5,10,100,1e3],Aa={backgroundColor:"#000000",fontSize:11},Na={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},Je={flex:"1 1 0%"},Ua={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},Ia={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function Ma(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Na,children:[jsxRuntime.jsx("div",{className:"flex items-center",style:Je,children:e("perpetuals.orderbook.col.price")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Je,children:e("perpetuals.orderbook.col.amount")}),jsxRuntime.jsx("div",{className:"flex items-center justify-end",style:Je,children:e("perpetuals.orderbook.col.total")})]})}function Un({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:Ua,children:[jsxRuntime.jsx("div",{style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e),height:11,width:56}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Je,children:jsxRuntime.jsx("div",{style:{...ce(e+60),height:11,width:64}})})]})}function La(){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(we,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full min-h-0",style:Aa,children:[jsxRuntime.jsx(Ma,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsxRuntime.jsx(Un,{delay:r*40},`ask-${r}`))}),jsxRuntime.jsx("div",{className:"flex-none flex items-center justify-center",style:Ia,children:jsxRuntime.jsx("div",{style:{...ce(0),width:96,height:12}})}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsxRuntime.jsx(Un,{delay:200+r*40},`bid-${r}`))})]})]})}function Fa(){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 qa({symbol:e,maxLevel:t=40,precisionOptions:r=Mn,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:l,spreadPercentage:p,isLoading:c,precision:u,setPrecision:d}=Er({symbol:e,maxLevel:t,precision:o});return c?jsxRuntime.jsx(La,{}):a.length===0&&l.length===0?jsxRuntime.jsx(Fa,{}):jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(Nr,{bids:a,asks:l,spreadPercentage:p,precision:u,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var Ba=200;function Mr({symbol:e,limit:t=50}){let[r,s]=react.useState([]),{data:n,isPending:i}=rr({symbol:e,limit:t}),{data:o}=Le({type:"trades",symbol:e,enabled:!!n});react.useEffect(()=>{n&&s(n.filter(Ln));},[n]);let a=react.useRef([]),l=react.useRef(null),p=react.useRef(t);return p.current=t,react.useEffect(()=>{if(!o)return;let c=Qa(o);c.length!==0&&(a.current.push(...c),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let u=a.current;a.current=[],u.length!==0&&s(d=>{let f=u.filter(y=>!d.some(m=>m.timestamp===y.timestamp&&m.price===y.price&&m.quantity===y.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,p.current)});},Ba)));},[o]),react.useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function Qa(e){return (Array.isArray(e)?e:[e]).filter(Ln)}function Ln(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 Rt=22,Fn=28,qn=100,Hn=120,Ya={backgroundColor:"#000000",fontSize:11},Xa={height:Fn,minHeight:Fn,padding:"0 16px",color:"#6b6b6b",fontSize:11},Ja={flex:"1 1 0%",maxWidth:qn},Za={flex:"1 1 0%",marginLeft:20},el={flex:"1 1 0%",maxWidth:Hn,textAlign:"right"},tl={height:Rt,minHeight:Rt,maxHeight:Rt,padding:"0 16px"},rl={flex:"1 1 0%",maxWidth:qn},sl={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},nl={flex:"1 1 0%",maxWidth:Hn,textAlign:"right",color:"#777A8C"},il={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},ol={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function al(e){return Number.isFinite(e)?utils.formatPriceInUsd(e):"-"}function ll(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"-"}function pl(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 cl({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"?il:ol,width:`${ul(a)}%`}),[n,a]);if(!n)return null;let p=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:tl,onClick:s?()=>s(n):void 0,children:[jsxRuntime.jsx("div",{style:l}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:rl,children:jsxRuntime.jsx("span",{className:p?"text-bullish":"text-bearish",children:al(n.price)})}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center",style:sl,children:ll(a)}),jsxRuntime.jsx("div",{className:"relative z-10 flex items-center justify-end",style:nl,children:pl(o)})]})})}function qr({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:Ya,children:[jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:Xa,children:[jsxRuntime.jsx("div",{style:Ja,children:r("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:Za,children:r("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:el,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:cl,rowCount:e.length,rowHeight:Rt,rowProps:i,overscanCount:4})})]})}var dl={backgroundColor:"#000000",fontSize:11},ml={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},Bn={flex:"1 1 0%",maxWidth:100},Qn={flex:"1 1 0%",marginLeft:20},Kn={flex:"1 1 0%",maxWidth:120,textAlign:"right"},fl={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function yl(){let{t:e}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:"flex items-center flex-none",style:ml,children:[jsxRuntime.jsx("div",{style:Bn,children:e("perpetuals.trades.col.price")}),jsxRuntime.jsx("div",{style:Qn,children:e("perpetuals.trades.col.size")}),jsxRuntime.jsx("div",{style:Kn,children:e("perpetuals.trades.col.age")})]})}function gl({delay:e}){return jsxRuntime.jsxs("div",{className:"flex items-center",style:fl,children:[jsxRuntime.jsx("div",{style:Bn,children:jsxRuntime.jsx("div",{style:{...ce(e),height:11,width:56}})}),jsxRuntime.jsx("div",{style:Qn,children:jsxRuntime.jsx("div",{style:{...ce(e+30),height:11,width:64}})}),jsxRuntime.jsx("div",{className:"flex justify-end",style:Kn,children:jsxRuntime.jsx("div",{style:{...ce(e+60),height:11,width:28}})})]})}function bl(){let e=Array.from({length:12},(t,r)=>r);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(we,{}),jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:dl,children:[jsxRuntime.jsx(yl,{}),jsxRuntime.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsxRuntime.jsx(gl,{delay:t*35},`trade-${t}`))})]})]})}function hl(){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 xl({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=Mr({symbol:e,limit:t});return i?jsxRuntime.jsx(bl,{}):n.length===0?jsxRuntime.jsx(hl,{}):jsxRuntime.jsx("div",{className:s,children:jsxRuntime.jsx(qr,{trades:n,onTradeClick:r})})}function zn(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function Wn(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:zn(s,n)*(e-t)/t*r*100}function ct(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let i=zn(s,n),o=e/r/100;return t*(1+i*o)}function $n(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 Vn(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var Tl=20;function _r({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:o}){let[a,l]=react.useState("long"),[p,c]=react.useState("market"),u=reactHookForm.useForm({defaultValues:{amount:void 0,leverage:Tl,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=it({symbol:e}),{data:f}=at({symbol:e}),y=f?.szDecimals,m=f?.maxLeverage??r,{mutateAsync:v,isPending:b}=ar({onSuccess:()=>{u.reset(),s?.();},onError:g=>{n?.(g);}}),P=reactQuery.useMutation({mutationFn:async g=>{if(!o)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await o(g)},onSuccess:()=>{u.reset(),s?.();},onError:g=>{n?.(g);}}),C=b||P.isPending,A=u.watch(),{amount:h,leverage:z,price:L}=A,I=d?.price||0,x=react.useMemo(()=>p==="limit"&&L?L:I,[p,L,I]),G=react.useMemo(()=>!h||h<=0||!z?0:h*z,[h,z]),X=react.useMemo(()=>G?G*5e-4:0,[G]),W=react.useMemo(()=>G?G+X:0,[G,X]),w=react.useMemo(()=>{if(!h||!x||!z||z===1||!f?.maxLeverage)return;let g=1/(2*f.maxLeverage),q=(1/z-g)/(a==="long"?1-g:1+g);return a==="long"?x*(1-q):x*(1+q)},[h,x,z,a,f?.maxLeverage]),{data:D}=ot({userAddress:t,symbol:e}),B=D?.totalEquity??0,$=D?.availableBalance??0,he=react.useMemo(()=>{let g=D?.positions?.[0];if(!g)return;let q=g.symbol.includes("-")?g.symbol.split("-")[0]:g.symbol;return {side:g.side,quantity:g.quantity,quantityRaw:g.quantityRaw,margin:g.margin,base:q}},[D?.positions]),{data:ee}=mr({userAddress:t,enabled:!!t}),pe=react.useMemo(()=>ee?.openOrders?.length?ee.openOrders.some(g=>g.symbol===e):false,[ee?.openOrders,e]),{data:ve}=ir({userAddress:t,symbol:e}),J=ve?.value,Ue=!t||J!==void 0,Pe=react.useRef(null);react.useEffect(()=>{Pe.current!==e&&J&&J>0&&(u.setValue("leverage",J),Pe.current=e);},[e,J,u]),react.useEffect(()=>{Pe.current=null;},[e]),react.useEffect(()=>{if(!(typeof h!="number"||Number.isNaN(h))){if(h<0){u.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}$>0&&h>$&&u.setValue("amount",$,{shouldValidate:false,shouldDirty:true});}},[h,$,u]);let re=react.useCallback(async g=>{if(!t)throw new Error("User address is required");if(!g.amount||g.amount<=0)throw new Error("Amount is required");let q=p==="limit"?g.price:void 0,O=g.takeProfitPrice,te=g.stopLossPrice;if(!O&&g.takeProfitPercent&&g.takeProfitPercent>0&&x&&(O=ct(g.takeProfitPercent,x,g.leverage,a,"tp")),!te&&g.stopLossPercent&&g.stopLossPercent>0&&x&&(te=ct(g.stopLossPercent,x,g.leverage,a,"sl")),o){if(!x||x<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(y===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Ie=g.amount*g.leverage/x;await P.mutateAsync({symbol:e,side:a,orderType:p,amount:g.amount,price:q,leverage:g.leverage,takeProfitPrice:O,stopLossPrice:te,userAddress:t,size:Ie,refPrice:x,szDecimals:y});return}await v({symbol:e,side:a,orderType:p,amount:g.amount,price:q,leverage:g.leverage,takeProfitPrice:O,stopLossPrice:te,userAddress:t});},[e,a,p,x,y,t,o,P,v]);return {form:u,side:a,orderType:p,setSide:l,setOrderType:c,handleSubmit:re,isSubmitting:C,currentPrice:x,marketPrice:I,estimatedFee:X,estimatedTotal:W,liquidationPrice:w,availableMargin:$,accountValue:B,currentPosition:he,maxLeverage:m,currentLeverage:J,isLeverageReady:Ue,hasOpenOrdersForSymbol:pe,szDecimals:y,onUpdateLeverage:i}}var se="#C7FF2E",Ul=se,ei="#F76816",Yn=ei;function Br(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 Il="https://app.hyperliquid.xyz/coins",Ml=10;function $r(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var Ll={...xr,display:"inline-block",width:28,height:14,borderRadius:4};function Xn(e){return utils.formatAmount(e)}function Qr(e){return !Number.isFinite(e)||e<=0?"--":utils.formatPriceInUsd(e)}var Ee=1;function Fl(e){let t=Math.max(Ee,Math.floor(e)),r=n=>{let i=Math.round(n);return i<=10?Math.max(Ee,i):Math.round(i/5)*5},s=new Set([Ee,t]);for(let n of [.25,.5,.75]){let i=r(t*n);i>Ee&&i<t&&s.add(i);}return Array.from(s).sort((n,i)=>n-i).map(n=>({value:n,label:`${n}x`}))}function ql({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:i,onConfirm:o,onUpdate:a,onClose:l}){let p=Math.max(Ee,Math.floor(r)),[c,u]=react.useState(Math.max(Ee,Math.min(t,p))),[d,f]=react.useState(false);react.useEffect(()=>{e&&(u(Math.max(Ee,Math.min(t,p))),f(false));},[e,t,p]);let y=react.useMemo(()=>Fl(p),[p]),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:b}=i18n.useTranslation();return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:P=>{d||P||l();},size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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: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-[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:Yn},children:b("perpetuals.placeOrder.leverage.cannotUpdate",{symbol:s})}):jsxRuntime.jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:b("perpetuals.placeOrder.leverage.desc")}),i&&jsxRuntime.jsx("p",{className:"text-[13px] leading-[18px] m-0",style:{color:Yn},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
4
|
.perp-leverage-slider [data-slot="track"] { background-color: rgba(255,255,255,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
8
|
.perp-leverage-slider [data-slot="mark"] { color: #6b6b6b !important; }
|
|
9
|
-
`}),jsxRuntime.jsx(ui.Slider,{value:[c],onChange:P=>u(Array.isArray(P)?P[0]:P),isDisabled:d||n,minValue:Ee,maxValue:p,step:1,marks:y,"aria-label":"Leverage"})]}),jsxRuntime.jsxs("div",{className:"text-sm text-white font-medium",children:[b("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"}),b(n?"perpetuals.placeOrder.leverage.failed":d?"perpetuals.placeOrder.leverage.updating":"perpetuals.placeOrder.leverage.update")]})]})]})})})}function kl({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 p=typeof document<"u"&&document.activeElement===o.current;i(c=>{let u=parseFloat(c),d=Number.isFinite(u)&&u===s;if(p&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(p=>{let c=$r(p.target.value);if(i(c),c===""||c==="."){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let u=Number(c);Number.isFinite(u)&&e.setValue("amount",u,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(p=>{(p.key==="-"||p.key==="+"||p.key==="e"||p.key==="E")&&(p.preventDefault(),p.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 El({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 p=typeof document<"u"&&document.activeElement===o.current;i(c=>{let u=parseFloat(c),d=Number.isFinite(u)&&u===s;if(p&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(p=>{let c=$r(p.target.value);if(i(c),c===""||c==="."){e.setValue("price",void 0,{shouldValidate:false,shouldDirty:true});return}let u=Number(c);Number.isFinite(u)&&e.setValue("price",u,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(p=>{(p.key==="-"||p.key==="+"||p.key==="e"||p.key==="E")&&(p.preventDefault(),p.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 Jn(e){return Number.isFinite(e)?String(e):""}function Nt({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"}})(),p=e.watch(t),c=typeof p=="number"&&Number.isFinite(p)?p:void 0,[u,d]=react.useState(()=>c!==void 0?Jn(c):""),f=react.useRef(null);react.useEffect(()=>{let v=typeof document<"u"&&document.activeElement===f.current;d(b=>{let P=parseFloat(b),C=Number.isFinite(P)&&P===c;if(v&&C)return b;let A=c!==void 0?Jn(c):"";return b===A?b:A});},[c]);let y=react.useCallback(v=>{let b=$r(v.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 P=Number(b);if(!Number.isFinite(P)||(e.setValue(t,P,{shouldValidate:false,shouldDirty:true}),!s||s<=0||!n||n<=0))return;let C=a?Wn(P,s,n,i,o):ct(P,s,n,i,o);if(C===void 0||!Number.isFinite(C))return;let A=a?Vn(C):$n(C);e.setValue(l,A,{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:u,onChange:y,onKeyDownCapture:m})}function Vr({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:i,isSubmitting:o,symbol:a,currentPrice:l,marketPrice:p,estimatedFee:c,liquidationPrice:u,availableMargin:d,accountValue:f,currentPosition:y,maxLeverage:m,isLeverageReady:v=true,hasOpenOrdersForSymbol:b=false,szDecimals:P,onAddFunds:C,onUpdateLeverage:A}){let{t:h}=i18n.useTranslation(),z=react.useCallback(()=>{C?.();},[C]),F=walletConnector.useAuthCallback(z),M=walletConnector.useAuthCallback(i),[x,G]=react.useState(false),[X,W]=react.useState(false),w=e.watch("leverage")||20,D=e.watch("amount"),B=typeof D=="number"&&Number.isFinite(D)?D:0,$=B>0,he=e.watch("price"),ee=typeof he=="number"&&Number.isFinite(he)&&he>0,pe=a.split("-")[0],ve=react.useMemo(()=>{if(!d||d<=0||!$)return 0;let O=B/d*100;return Number.isFinite(O)?Math.max(0,Math.min(100,O)):0},[$,B,d]),J=react.useCallback(O=>{if(d<=0)return;let te=Math.max(0,Math.min(100,O))/100;if(te===0){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let Me=Number((d*te).toFixed(4));e.setValue("amount",Me,{shouldValidate:false,shouldDirty:true});},[d,e]),Ue=react.useMemo(()=>!$||!l||l<=0?0:B*w/l,[$,B,w,l]),Pe=react.useMemo(()=>Ol/Math.max(1,w),[w]),re=react.useMemo(()=>d<=0?{label:h("perpetuals.placeOrder.btn.addFunds"),kind:"deposit",disabled:!C}:$?B<Pe?{label:h("perpetuals.placeOrder.err.tooSmall"),kind:"invalid",disabled:true}:r==="limit"&&!ee?{label:h("perpetuals.placeOrder.err.invalidLimit"),kind:"invalid",disabled:true}:{label:`${h(t==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${pe}-USD`,kind:"submit",disabled:o}:{label:h("perpetuals.placeOrder.err.invalidAmount"),kind:"invalid",disabled:true},[d,$,B,Pe,r,ee,t,pe,o,C,h]),g=react.useCallback(()=>{re.kind==="deposit"&&F();},[re.kind,F]),q=O=>!Number.isFinite(O)||O<=0?"0":typeof P=="number"&&P>=0?O.toFixed(P):O>=1e3?O.toFixed(2):O>=1?O.toFixed(4):O.toFixed(6);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsx(we,{}),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:h("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:h("perpetuals.placeOrder.long")})}),jsxRuntime.jsx(ui.StyledTooltip,{content:h("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:h("perpetuals.placeOrder.short")})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:h("perpetuals.placeOrder.market")},{key:"limit",label:h("perpetuals.placeOrder.limit")}].map(O=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===O.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===O.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(O.key),children:O.label})},O.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer flex items-center gap-1.5 px-3 py-1.5 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:()=>G(true),disabled:!v,children:[jsxRuntime.jsx("span",{children:h("perpetuals.placeOrder.leverage.label")}),v?jsxRuntime.jsxs("span",{children:[w,"x"]}):jsxRuntime.jsx("span",{"aria-hidden":"true",style:Tl})]})]}),jsxRuntime.jsx(ui.RHForm,{methods:e,onSubmit:M,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:h("perpetuals.placeOrder.buyAmount")}),jsxRuntime.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#ffffff"},children:pe})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8,minHeight:24},children:[jsxRuntime.jsx(kl,{methods:e}),jsxRuntime.jsxs("div",{className:"flex items-center shrink-0",style:{gap:6},children:[jsxRuntime.jsx("img",{src:`${Cl}/${pe}.svg`,alt:pe,width:18,height:18,className:"rounded-full",style:{width:18,height:18},onError:O=>{O.target.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:18,lineHeight:"23px",color:"#b5b5b5",fontVariantNumeric:"tabular-nums"},children:q(Ue)})]})]})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
|
|
9
|
+
`}),jsxRuntime.jsx(ui.Slider,{value:[c],onChange:P=>u(Array.isArray(P)?P[0]:P),isDisabled:d||n,minValue:Ee,maxValue:p,step:1,marks:y,"aria-label":"Leverage"})]}),jsxRuntime.jsxs("div",{className:"text-sm text-white font-medium",children:[b("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"}),b(n?"perpetuals.placeOrder.leverage.failed":d?"perpetuals.placeOrder.leverage.updating":"perpetuals.placeOrder.leverage.update")]})]})]})})})}function Hl({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 p=typeof document<"u"&&document.activeElement===o.current;i(c=>{let u=parseFloat(c),d=Number.isFinite(u)&&u===s;if(p&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(p=>{let c=$r(p.target.value);if(i(c),c===""||c==="."){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let u=Number(c);Number.isFinite(u)&&e.setValue("amount",u,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(p=>{(p.key==="-"||p.key==="+"||p.key==="e"||p.key==="E")&&(p.preventDefault(),p.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 _l({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 p=typeof document<"u"&&document.activeElement===o.current;i(c=>{let u=parseFloat(c),d=Number.isFinite(u)&&u===s;if(p&&d)return c;let f=s!==void 0?String(s):"";return c===f?c:f});},[s]);let a=react.useCallback(p=>{let c=$r(p.target.value);if(i(c),c===""||c==="."){e.setValue("price",void 0,{shouldValidate:false,shouldDirty:true});return}let u=Number(c);Number.isFinite(u)&&e.setValue("price",u,{shouldValidate:false,shouldDirty:true});},[e]),l=react.useCallback(p=>{(p.key==="-"||p.key==="+"||p.key==="e"||p.key==="E")&&(p.preventDefault(),p.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 Jn(e){return Number.isFinite(e)?String(e):""}function Nt({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"}})(),p=e.watch(t),c=typeof p=="number"&&Number.isFinite(p)?p:void 0,[u,d]=react.useState(()=>c!==void 0?Jn(c):""),f=react.useRef(null);react.useEffect(()=>{let v=typeof document<"u"&&document.activeElement===f.current;d(b=>{let P=parseFloat(b),C=Number.isFinite(P)&&P===c;if(v&&C)return b;let A=c!==void 0?Jn(c):"";return b===A?b:A});},[c]);let y=react.useCallback(v=>{let b=$r(v.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 P=Number(b);if(!Number.isFinite(P)||(e.setValue(t,P,{shouldValidate:false,shouldDirty:true}),!s||s<=0||!n||n<=0))return;let C=a?Wn(P,s,n,i,o):ct(P,s,n,i,o);if(C===void 0||!Number.isFinite(C))return;let A=a?Vn(C):$n(C);e.setValue(l,A,{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:u,onChange:y,onKeyDownCapture:m})}function Vr({methods:e,side:t,orderType:r,onSideChange:s,onOrderTypeChange:n,onSubmit:i,isSubmitting:o,symbol:a,currentPrice:l,marketPrice:p,estimatedFee:c,liquidationPrice:u,availableMargin:d,accountValue:f,currentPosition:y,maxLeverage:m,isLeverageReady:v=true,hasOpenOrdersForSymbol:b=false,szDecimals:P,onAddFunds:C,onUpdateLeverage:A}){let{t:h}=i18n.useTranslation(),z=react.useCallback(()=>{C?.();},[C]),L=walletConnector.useAuthCallback(z),I=walletConnector.useAuthCallback(i),[x,G]=react.useState(false),[X,W]=react.useState(false),w=e.watch("leverage")||20,D=e.watch("amount"),B=typeof D=="number"&&Number.isFinite(D)?D:0,$=B>0,he=e.watch("price"),ee=typeof he=="number"&&Number.isFinite(he)&&he>0,pe=a.split("-")[0],ve=react.useMemo(()=>{if(!d||d<=0||!$)return 0;let O=B/d*100;return Number.isFinite(O)?Math.max(0,Math.min(100,O)):0},[$,B,d]),J=react.useCallback(O=>{if(d<=0)return;let te=Math.max(0,Math.min(100,O))/100;if(te===0){e.setValue("amount",void 0,{shouldValidate:false,shouldDirty:true});return}let Ie=Number((d*te).toFixed(4));e.setValue("amount",Ie,{shouldValidate:false,shouldDirty:true});},[d,e]),Ue=react.useMemo(()=>!$||!l||l<=0?0:B*w/l,[$,B,w,l]),Pe=react.useMemo(()=>Ml/Math.max(1,w),[w]),re=react.useMemo(()=>d<=0?{label:h("perpetuals.placeOrder.btn.addFunds"),kind:"deposit",disabled:!C}:$?B<Pe?{label:h("perpetuals.placeOrder.err.tooSmall"),kind:"invalid",disabled:true}:r==="limit"&&!ee?{label:h("perpetuals.placeOrder.err.invalidLimit"),kind:"invalid",disabled:true}:{label:`${h(t==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${pe}-USD`,kind:"submit",disabled:o}:{label:h("perpetuals.placeOrder.err.invalidAmount"),kind:"invalid",disabled:true},[d,$,B,Pe,r,ee,t,pe,o,C,h]),g=react.useCallback(()=>{re.kind==="deposit"&&L();},[re.kind,L]),q=O=>!Number.isFinite(O)||O<=0?"0":typeof P=="number"&&P>=0?O.toFixed(P):O>=1e3?O.toFixed(2):O>=1?O.toFixed(4):O.toFixed(6);return jsxRuntime.jsxs("div",{className:"flex flex-col h-full",style:{backgroundColor:"#000000"},children:[jsxRuntime.jsx(we,{}),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:h("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:h("perpetuals.placeOrder.long")})}),jsxRuntime.jsx(ui.StyledTooltip,{content:h("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:h("perpetuals.placeOrder.short")})})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxRuntime.jsx("div",{className:"flex",children:[{key:"market",label:h("perpetuals.placeOrder.market")},{key:"limit",label:h("perpetuals.placeOrder.limit")}].map(O=>jsxRuntime.jsx("div",{style:{height:32,display:"flex",alignItems:"center",borderBottom:r===O.key?"2px solid #ffffff":"2px solid transparent",padding:"2px 0 0",cursor:"pointer"},children:jsxRuntime.jsx("button",{type:"button",className:"cursor-pointer transition-colors",style:{padding:"0 8px",fontSize:12,fontWeight:500,backgroundColor:"transparent",color:r===O.key?"#ffffff":"#b5b5b5",border:"none"},onClick:()=>n(O.key),children:O.label})},O.key))}),jsxRuntime.jsx("div",{className:"flex-1"}),jsxRuntime.jsxs("button",{type:"button",className:"cursor-pointer flex items-center gap-1.5 px-3 py-1.5 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:()=>G(true),disabled:!v,children:[jsxRuntime.jsx("span",{children:h("perpetuals.placeOrder.leverage.label")}),v?jsxRuntime.jsxs("span",{children:[w,"x"]}):jsxRuntime.jsx("span",{"aria-hidden":"true",style:Ll})]})]}),jsxRuntime.jsx(ui.RHForm,{methods:e,onSubmit:I,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:h("perpetuals.placeOrder.buyAmount")}),jsxRuntime.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#ffffff"},children:pe})]}),jsxRuntime.jsxs("div",{className:"flex items-center",style:{gap:8,minHeight:24},children:[jsxRuntime.jsx(Hl,{methods:e}),jsxRuntime.jsxs("div",{className:"flex items-center shrink-0",style:{gap:6},children:[jsxRuntime.jsx("img",{src:`${Il}/${pe}.svg`,alt:pe,width:18,height:18,className:"rounded-full",style:{width:18,height:18},onError:O=>{O.target.style.display="none";}}),jsxRuntime.jsx("span",{style:{fontSize:18,lineHeight:"23px",color:"#b5b5b5",fontVariantNumeric:"tabular-nums"},children:q(Ue)})]})]})]}),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; }
|
|
@@ -22,7 +22,7 @@
|
|
|
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
24
|
.perp-side-tab[data-active="false"]:hover { background-color: rgba(255,255,255,0.12) !important; color: #ffffff !important; }
|
|
25
|
-
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(ve),onChange:O=>J(Number(O.target.value)),min:0,max:100,step:1,disabled:d<=0,className:"perp-slider",style:{"--pct":`${Math.round(ve)}%`}}),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:h("perpetuals.placeOrder.limitPrice")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:p&&p>0?h("perpetuals.placeOrder.currentPrice",{price:Qr(p)}):"--"})]}),jsxRuntime.jsx(El,{methods:e,placeholder:p&&p>0?Qr(p):"$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:()=>W(O=>!O),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:X?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:X&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:h("perpetuals.placeOrder.tpsl")})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsxs("span",{children:[h("perpetuals.placeOrder.estLiqPrice")," "]}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?Qr(u):"--"})]})]}),X&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:h("perpetuals.placeOrder.tpPrice")}),jsxRuntime.jsx(Nt,{methods:e,field:"takeProfitPrice",placeholder:h("perpetuals.placeOrder.enterTpPrice"),refPrice:l,leverage:w,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(Nt,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:w,side:t})]})]}),X&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:h("perpetuals.placeOrder.slPrice")}),jsxRuntime.jsx(Nt,{methods:e,field:"stopLossPrice",placeholder:h("perpetuals.placeOrder.enterSlPrice"),refPrice:l,leverage:w,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(Nt,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:w,side:t})]})]}),(()=>{let O=re.kind==="submit",te=O?"submit":"button",wi=O?t==="long"?Pl:ei:re.kind==="deposit"?se:"rgba(63,63,70,0.6)",ki=re.kind==="invalid"?"#71717a":"#000000",Cs=O&&o;return jsxRuntime.jsxs("button",{type:te,disabled:re.disabled,onClick:O?void 0:g,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:ki,backgroundColor:wi,borderRadius:9999,border:"none",cursor:re.disabled?"not-allowed":"pointer",opacity:re.disabled?.9:1},children:[Cs&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),Cs?h("perpetuals.placeOrder.btn.placing"):re.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:h("perpetuals.placeOrder.availableMargin")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{F();},disabled:!C,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:Br(se,26),color:se,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:C?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:O=>{C&&(O.currentTarget.style.backgroundColor=Br(se,51));},onMouseLeave:O=>{C&&(O.currentTarget.style.backgroundColor=Br(se,26));},children:[Xn(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:h("perpetuals.placeOrder.perpsAccountValue")}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[Xn(f)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:h("perpetuals.placeOrder.currentPosition")}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:y?`${h(y.side==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${y.quantityRaw??String(y.quantity)} ${y.base} (${y.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:h("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:O=>{let te=O.target;te.style.display="none";}})]})}),jsxRuntime.jsx(wl,{isOpen:x,initialLeverage:w,maxLeverage:m,coinName:y?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!y,hasOpenOrders:b,onConfirm:O=>e.setValue("leverage",O),onUpdate:A,onClose:()=>G(false)})]})}function Rl({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,onPlaceOrder:a,className:l}){let{form:p,side:c,orderType:u,setSide:d,setOrderType:f,handleSubmit:y,isSubmitting:m,currentPrice:v,marketPrice:b,estimatedFee:P,estimatedTotal:C,liquidationPrice:A,availableMargin:h,accountValue:z,currentPosition:F,maxLeverage:M,isLeverageReady:x,hasOpenOrdersForSymbol:G,szDecimals:X,onUpdateLeverage:W}=_r({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:a});return jsxRuntime.jsx("div",{className:l,children:jsxRuntime.jsx(Vr,{methods:p,side:c,orderType:u,onSideChange:d,onOrderTypeChange:f,onSubmit:y,isSubmitting:m,symbol:e,currentPrice:v,marketPrice:b,estimatedFee:P,estimatedTotal:C,liquidationPrice:A,availableMargin:h,accountValue:z,currentPosition:F,maxLeverage:M,isLeverageReady:x,hasOpenOrdersForSymbol:G,szDecimals:X,onAddFunds:i,onUpdateLeverage:W})})}var mt="#C7FF2E";function Xr(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}function Jr({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),p=t?.symbol.split("-")[0]??"",c=t?.side==="long",u=o(c?"perpetuals.positions.long":"perpetuals.positions.short"),[d,f]=react.useState(""),[y,m]=react.useState("100"),[v,b]=react.useState(""),P=react.useRef(null),C=react.useRef(null),A=react.useRef(null);react.useEffect(()=>{if(e&&t){let g=Math.abs(t.quantity);f(t.quantityRaw??String(g)),m("100"),b("");}},[e,t]);let h=react.useMemo(()=>{let g=parseFloat(d);return Number.isFinite(g)&&g>0?g:0},[d]);react.useMemo(()=>{let g=parseFloat(y);return Number.isFinite(g)?Math.max(0,Math.min(100,g)):0},[y]);let F=react.useMemo(()=>{if(a<=0||h<=0)return 0;let g=h/a*100;return Math.max(0,Math.min(100,g))},[h,a]),M=react.useCallback(g=>{let q=Xr(g.target.value),O=parseFloat(q);if(Number.isFinite(O)&&O>a&&a>0){f(t?.quantityRaw??String(a)),m("100");return}if(f(q),Number.isFinite(O)&&a>0){let te=Math.round(O/a*100);m(String(Math.min(100,te)));}else (q===""||q===".")&&m("0");},[a,t?.quantityRaw]),x=react.useCallback(()=>{let g=parseFloat(d);!Number.isFinite(g)||g<=0?(f("0"),m("0")):g>a&&a>0&&(f(t?.quantityRaw??String(a)),m("100"));},[d,a,t?.quantityRaw]),G=react.useCallback(g=>{let q=Xr(g.target.value),O=parseFloat(q);if(Number.isFinite(O)&&O>100){m("100"),a>0&&f(t?.quantityRaw??String(a));return}if(m(q),Number.isFinite(O)&&a>0){let te=Math.max(0,Math.min(100,O)),Me=a*(te/100);f(Me>0?String(Number(Me.toPrecision(6))):"0");}else (q===""||q===".")&&f("0");},[a,t?.quantityRaw]),X=react.useCallback(()=>{let g=parseFloat(y);!Number.isFinite(g)||g<0?(m("0"),f("0")):g>100&&(m("100"),a>0&&f(t?.quantityRaw??String(a)));},[y,a,t?.quantityRaw]),W=react.useCallback(g=>{let q=Number(g.target.value);if(m(String(q)),a>0){let O=a*(q/100);f(q===100?t?.quantityRaw??String(a):O>0?String(Number(O.toPrecision(6))):"0");}},[a,t?.quantityRaw]),w=react.useCallback(g=>{b(Xr(g.target.value));},[]),D=react.useCallback(g=>{(g.key==="-"||g.key==="+"||g.key==="e"||g.key==="E")&&(g.preventDefault(),g.stopPropagation());},[]),B=r==="limit",$=parseFloat(v),he=B&&Number.isFinite($)&&$>0,ee=h>0&&(!B||he)&&!s,pe=react.useCallback(async()=>{ee&&await i(h,B?$:void 0);},[ee,i,h,B,$]),ve=walletConnector.useAuthCallback(pe),J=B?o("perpetuals.positions.close.limitTitle",{side:u,size:l,symbol:p}):o("perpetuals.positions.close.marketTitle",{side:u,size:l,symbol:p}),Ue=o(B?"perpetuals.positions.close.limitDesc":"perpetuals.positions.close.marketDesc"),Pe=o(B?"perpetuals.positions.close.confirmLimit":"perpetuals.positions.close.confirmMarket"),re=t?.markPrice&&t.markPrice>0?String(t.markPrice):"";return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:g=>{s||g||n();},size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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:J}),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:Ue}),B&&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:A,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,placeholder:re?o("perpetuals.positions.close.currentPrice",{price:re}):"0.0",value:v,onChange:w,onKeyDownCapture:D,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:P,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:d,onChange:M,onBlur:x,onKeyDownCapture:D,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:C,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:y,onChange:G,onBlur:X,onKeyDownCapture:D,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:p})})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("style",{children:`
|
|
25
|
+
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(ve),onChange:O=>J(Number(O.target.value)),min:0,max:100,step:1,disabled:d<=0,className:"perp-slider",style:{"--pct":`${Math.round(ve)}%`}}),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:h("perpetuals.placeOrder.limitPrice")}),jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:p&&p>0?h("perpetuals.placeOrder.currentPrice",{price:Qr(p)}):"--"})]}),jsxRuntime.jsx(_l,{methods:e,placeholder:p&&p>0?Qr(p):"$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:()=>W(O=>!O),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:X?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:X&&jsxRuntime.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsxRuntime.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsxRuntime.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:h("perpetuals.placeOrder.tpsl")})]}),jsxRuntime.jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsxRuntime.jsxs("span",{children:[h("perpetuals.placeOrder.estLiqPrice")," "]}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5"},children:u?Qr(u):"--"})]})]}),X&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:h("perpetuals.placeOrder.tpPrice")}),jsxRuntime.jsx(Nt,{methods:e,field:"takeProfitPrice",placeholder:h("perpetuals.placeOrder.enterTpPrice"),refPrice:l,leverage:w,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(Nt,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:w,side:t})]})]}),X&&jsxRuntime.jsxs("div",{className:"flex",style:{gap:8},children:[jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:h("perpetuals.placeOrder.slPrice")}),jsxRuntime.jsx(Nt,{methods:e,field:"stopLossPrice",placeholder:h("perpetuals.placeOrder.enterSlPrice"),refPrice:l,leverage:w,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(Nt,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:w,side:t})]})]}),(()=>{let O=re.kind==="submit",te=O?"submit":"button",ki=O?t==="long"?Ul:ei:re.kind==="deposit"?se:"rgba(63,63,70,0.6)",Ei=re.kind==="invalid"?"#71717a":"#000000",Cs=O&&o;return jsxRuntime.jsxs("button",{type:te,disabled:re.disabled,onClick:O?void 0:g,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:Ei,backgroundColor:ki,borderRadius:9999,border:"none",cursor:re.disabled?"not-allowed":"pointer",opacity:re.disabled?.9:1},children:[Cs&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),Cs?h("perpetuals.placeOrder.btn.placing"):re.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:h("perpetuals.placeOrder.availableMargin")}),jsxRuntime.jsxs("button",{type:"button",onClick:()=>{L();},disabled:!C,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:Br(se,26),color:se,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:C?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:O=>{C&&(O.currentTarget.style.backgroundColor=Br(se,51));},onMouseLeave:O=>{C&&(O.currentTarget.style.backgroundColor=Br(se,26));},children:[Xn(d)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:h("perpetuals.placeOrder.perpsAccountValue")}),jsxRuntime.jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[Xn(f)," USDC"]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{style:{color:"#6b6b6b"},children:h("perpetuals.placeOrder.currentPosition")}),jsxRuntime.jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:y?`${h(y.side==="long"?"perpetuals.placeOrder.long":"perpetuals.placeOrder.short")} ${y.quantityRaw??String(y.quantity)} ${y.base} (${y.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:h("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:O=>{let te=O.target;te.style.display="none";}})]})}),jsxRuntime.jsx(ql,{isOpen:x,initialLeverage:w,maxLeverage:m,coinName:y?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!y,hasOpenOrders:b,onConfirm:O=>e.setValue("leverage",O),onUpdate:A,onClose:()=>G(false)})]})}function Bl({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,onPlaceOrder:a,className:l}){let{form:p,side:c,orderType:u,setSide:d,setOrderType:f,handleSubmit:y,isSubmitting:m,currentPrice:v,marketPrice:b,estimatedFee:P,estimatedTotal:C,liquidationPrice:A,availableMargin:h,accountValue:z,currentPosition:L,maxLeverage:I,isLeverageReady:x,hasOpenOrdersForSymbol:G,szDecimals:X,onUpdateLeverage:W}=_r({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:a});return jsxRuntime.jsx("div",{className:l,children:jsxRuntime.jsx(Vr,{methods:p,side:c,orderType:u,onSideChange:d,onOrderTypeChange:f,onSubmit:y,isSubmitting:m,symbol:e,currentPrice:v,marketPrice:b,estimatedFee:P,estimatedTotal:C,liquidationPrice:A,availableMargin:h,accountValue:z,currentPosition:L,maxLeverage:I,isLeverageReady:x,hasOpenOrdersForSymbol:G,szDecimals:X,onAddFunds:i,onUpdateLeverage:W})})}var mt="#C7FF2E";function Xr(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}function Jr({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),p=t?.symbol.split("-")[0]??"",c=t?.side==="long",u=o(c?"perpetuals.positions.long":"perpetuals.positions.short"),[d,f]=react.useState(""),[y,m]=react.useState("100"),[v,b]=react.useState(""),P=react.useRef(null),C=react.useRef(null),A=react.useRef(null);react.useEffect(()=>{if(e&&t){let g=Math.abs(t.quantity);f(t.quantityRaw??String(g)),m("100"),b("");}},[e,t]);let h=react.useMemo(()=>{let g=parseFloat(d);return Number.isFinite(g)&&g>0?g:0},[d]);react.useMemo(()=>{let g=parseFloat(y);return Number.isFinite(g)?Math.max(0,Math.min(100,g)):0},[y]);let L=react.useMemo(()=>{if(a<=0||h<=0)return 0;let g=h/a*100;return Math.max(0,Math.min(100,g))},[h,a]),I=react.useCallback(g=>{let q=Xr(g.target.value),O=parseFloat(q);if(Number.isFinite(O)&&O>a&&a>0){f(t?.quantityRaw??String(a)),m("100");return}if(f(q),Number.isFinite(O)&&a>0){let te=Math.round(O/a*100);m(String(Math.min(100,te)));}else (q===""||q===".")&&m("0");},[a,t?.quantityRaw]),x=react.useCallback(()=>{let g=parseFloat(d);!Number.isFinite(g)||g<=0?(f("0"),m("0")):g>a&&a>0&&(f(t?.quantityRaw??String(a)),m("100"));},[d,a,t?.quantityRaw]),G=react.useCallback(g=>{let q=Xr(g.target.value),O=parseFloat(q);if(Number.isFinite(O)&&O>100){m("100"),a>0&&f(t?.quantityRaw??String(a));return}if(m(q),Number.isFinite(O)&&a>0){let te=Math.max(0,Math.min(100,O)),Ie=a*(te/100);f(Ie>0?String(Number(Ie.toPrecision(6))):"0");}else (q===""||q===".")&&f("0");},[a,t?.quantityRaw]),X=react.useCallback(()=>{let g=parseFloat(y);!Number.isFinite(g)||g<0?(m("0"),f("0")):g>100&&(m("100"),a>0&&f(t?.quantityRaw??String(a)));},[y,a,t?.quantityRaw]),W=react.useCallback(g=>{let q=Number(g.target.value);if(m(String(q)),a>0){let O=a*(q/100);f(q===100?t?.quantityRaw??String(a):O>0?String(Number(O.toPrecision(6))):"0");}},[a,t?.quantityRaw]),w=react.useCallback(g=>{b(Xr(g.target.value));},[]),D=react.useCallback(g=>{(g.key==="-"||g.key==="+"||g.key==="e"||g.key==="E")&&(g.preventDefault(),g.stopPropagation());},[]),B=r==="limit",$=parseFloat(v),he=B&&Number.isFinite($)&&$>0,ee=h>0&&(!B||he)&&!s,pe=react.useCallback(async()=>{ee&&await i(h,B?$:void 0);},[ee,i,h,B,$]),ve=walletConnector.useAuthCallback(pe),J=B?o("perpetuals.positions.close.limitTitle",{side:u,size:l,symbol:p}):o("perpetuals.positions.close.marketTitle",{side:u,size:l,symbol:p}),Ue=o(B?"perpetuals.positions.close.limitDesc":"perpetuals.positions.close.marketDesc"),Pe=o(B?"perpetuals.positions.close.confirmLimit":"perpetuals.positions.close.confirmMarket"),re=t?.markPrice&&t.markPrice>0?String(t.markPrice):"";return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:g=>{s||g||n();},size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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:J}),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:Ue}),B&&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:A,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,placeholder:re?o("perpetuals.positions.close.currentPrice",{price:re}):"0.0",value:v,onChange:w,onKeyDownCapture:D,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:P,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:d,onChange:I,onBlur:x,onKeyDownCapture:D,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:C,type:"text",inputMode:"decimal",pattern:"[0-9.]*",autoComplete:"off",autoCorrect:"off",spellCheck:false,value:y,onChange:G,onBlur:X,onKeyDownCapture:D,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:p})})]}),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: ${mt}; --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: ${mt}; }
|
|
34
34
|
.perp-close-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: ${mt}; 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(F),onChange:W,min:0,max:100,step:1,disabled:a<=0,className:"perp-close-slider",style:{"--pct":`${Math.round(F)}%`}}),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:()=>{ve();},disabled:!ee,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:ee?mt:"rgba(63,63,70,0.6)",borderRadius:9999,border:"none",cursor:ee?"pointer":"not-allowed",opacity:ee?1:.9},children:[s&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),s?"Closing...":Pe]})]})]})})})}function es({userAddress:e,onCloseSuccess:t,onCloseError:r,onPlaceOrder:s}){let[n,i]=react.useState(false),[o,a]=react.useState(null),[l,p]=react.useState("market"),{data:c}=at({symbol:o?.symbol}),{mutateAsync:u,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:()=>{i(false),a(null),t?.();},onError:b=>{r?.(b);}}),f=react.useCallback(b=>{a(b),p("market"),i(true);},[]),y=react.useCallback(b=>{a(b),p("limit"),i(true);},[]),m=react.useCallback(()=>{d||(i(false),a(null));},[d]),v=react.useCallback(async(b,P)=>{if(!o||!e)throw new Error("Position and user address are required");let C=o.side==="long"?"short":"long",A=l==="limit"?"limit":"market",h=o.markPrice||o.entryPrice,z=c?.szDecimals??5;await u({symbol:o.symbol,side:C,orderType:A,amount:b*h,price:A==="limit"?P:void 0,leverage:o.leverage,reduceOnly:true,userAddress:e,size:b,refPrice:h,szDecimals:z});},[o,e,l,c,u]);return {isModalOpen:n,selectedPosition:o,closeType:l,isClosing:d,openMarketClose:f,openLimitClose:y,handleConfirm:v,closeModal:m}}function ni(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 _l(e,t,r,s){let n=ni(e,r),i=ni(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 ts({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}){let[i,o]=react.useState("marginPnl"),[a,l]=react.useState("desc"),p=react.useCallback(v=>{o(b=>b===v?(l(P=>P==="asc"?"desc":"asc"),b):(l("asc"),v));},[]),{data:c,isLoading:u,error:d}=ot({userAddress:e,symbol:t},{enabled:!!e}),f=es({userAddress:e,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}),y=react.useMemo(()=>c?.positions??[],[c]);return {positions:react.useMemo(()=>i?[...y].sort((v,b)=>_l(v,b,i,a)):y,[y,i,a]),isLoading:u,error:d,sortKey:i,sortDir:a,onSort:p,closePosition:f}}var Bl={start:"justify-start",center:"justify-center",end:"justify-end"},fe={minHeight:28,maxHeight:28},It={minHeight:36,maxHeight:36},Ze={backgroundColor:"rgba(255, 255, 255, 0.06)"};function ie(e){if(e===void 0||!Number.isFinite(e))return "--";let t=Math.abs(e),r;return t>=1e4?r=0:t>=1e3?r=1:t>=1?r=2:t>=.01?r=4:r=6,"$"+e.toLocaleString("en-US",{minimumFractionDigits:r,maximumFractionDigits:r})}function Ke(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function Ft(e){return Number.isFinite(e)?Math.abs(e)<.005?"+$0":(e>=0?"+":"-")+"$"+Math.abs(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function ai(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function et(e,t){return t||(Number.isFinite(e)?e.toFixed(5).replace(/\.?0+$/,""):"--")}function Lt(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 I({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":"",p=r!==void 0&&i!==void 0,c=Bl[o],u=jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-500",children:[t,l]});return p?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:u}):jsxRuntime.jsx("div",{style:e,className:ui.cn("flex flex-row items-center",c),children:u})}var Y={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%"}},qt={minWidth:1e3};function rs({positions:e,sortKey:t,sortDir:r,onSort:s,onMarketClose:n,onLimitClose:i,isClosing:o,className:a}){let{t:l}=i18n.useTranslation(),p=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(I,{style:Y.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.asset")}),jsxRuntime.jsx(I,{style:Y.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.position")}),jsxRuntime.jsx(I,{style:Y.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.positionValue")}),jsxRuntime.jsx(I,{style:Y.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.entryPrice")}),jsxRuntime.jsx(I,{style:Y.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.markPrice")}),jsxRuntime.jsx(I,{style:Y.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(I,{style:Y.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(I,{style:Y.tpsl,align:"center",children:l("perpetuals.positions.col.tpsl")}),jsxRuntime.jsx(I,{style:Y.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:{...qt,...fe},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:qt,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:{...qt,...fe},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:qt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((c,u)=>jsxRuntime.jsx(Kl,{position:c,striped:u%2===1,isClosing:o,onMarketClose:n,onLimitClose:i},c.symbol))})]})})}function Kl({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"),p=a?"text-bullish":"text-bearish",u=e.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t?Ze:void 0,children:jsxRuntime.jsxs("div",{style:It,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsxs("div",{style:Y.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:Y.position,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",p),children:l}),jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-700",children:[et(e.quantity,e.quantityRaw)," ",o]})]}),jsxRuntime.jsx("div",{style:Y.value,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ke(e.notionalValue)})}),jsxRuntime.jsx("div",{style:Y.entry,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.entryPrice)})}),jsxRuntime.jsx("div",{style:Y.mark,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:Y.liq,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.liquidationPrice)})}),jsxRuntime.jsxs("div",{style:Y.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ke(e.margin)}),jsxRuntime.jsxs("span",{className:ui.cn("text-xs font-medium",u),children:["(",Ft(e.unrealizedPnl)," /"," ",ai(e.unrealizedPnlPercent),")"]})]}),jsxRuntime.jsxs("div",{style:{...Y.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?ie(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?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsxs("div",{style:Y.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 ss(){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 zl(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open positions"})}function Wl({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n,className:i}){let{positions:o,isLoading:a,sortKey:l,sortDir:p,onSort:c,closePosition:u}=ts({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n});return a?jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(ss,{})}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(rs,{positions:o,sortKey:l,sortDir:p,onSort:c,onMarketClose:u.openMarketClose,onLimitClose:u.openLimitClose,isClosing:u.isClosing,className:i}),jsxRuntime.jsx(Jr,{isOpen:u.isModalOpen,position:u.selectedPosition,closeType:u.closeType,isSubmitting:u.isClosing,onClose:u.closeModal,onConfirm:u.handleConfirm})]})}function ci(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 jl(e,t,r,s){let n=ci(e,r),i=ci(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 ns({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}){let[o,a]=react.useState("time"),[l,p]=react.useState("desc"),c=react.useCallback(w=>{a(D=>D===w?(p(B=>B==="asc"?"desc":"asc"),D):(p("asc"),w));},[]),{data:u,isLoading:d,error:f}=sr({userAddress:e,symbol:t},{enabled:!!e}),y=react.useRef(new Set),[,m]=react.useState(0),v=react.useCallback(()=>m(w=>w+1),[]),b=react.useCallback(w=>{y.current.add(w),v();},[v]),P=react.useCallback(w=>{y.current.delete(w),v();},[v]),[C,A]=react.useState(false),{mutateAsync:h,isPending:z}=lr({onSuccess:()=>{r?.();},onError:w=>{s?.(w);}}),F=react.useCallback(async w=>{if(n)try{let D=await n(w);return r?.(),D}catch(D){throw s?.(D instanceof Error?D:new Error(String(D))),D}if(i)try{let[D]=await i([w]);if(!D)throw new Error("cancelOrders returned no result");return r?.(),D}catch(D){throw s?.(D instanceof Error?D:new Error(String(D))),D}return h(w)},[n,i,h,r,s]),M=react.useMemo(()=>u?.orders??[],[u]),x=react.useMemo(()=>o?[...M].sort((w,D)=>jl(w,D,o,l)):M,[M,o,l]),G=react.useCallback(async w=>{if(!e)throw new Error("User address is required");b(w.orderId);try{await F({orderId:w.orderId,symbol:w.symbol,userAddress:e});}finally{P(w.orderId);}},[e,F,b,P]),X=react.useCallback(async()=>{if(!e)throw new Error("User address is required");if(M.length!==0){A(true);try{let w=M.map(D=>({orderId:D.orderId,symbol:D.symbol,userAddress:e}));if(i){try{await i(w);for(let D=0;D<w.length;D++)r?.();}catch(D){s?.(D instanceof Error?D:new Error(String(D)));}return}await Promise.allSettled(w.map(D=>F(D)));}finally{A(false);}}},[e,M,i,F,r,s]),W=y.current.size>0||C||z;return {orders:x,isLoading:d,error:f,sortKey:o,sortDir:l,onSort:c,handleCancelOrder:G,handleCancelAll:X,isCanceling:W,cancelingOrderIds:y.current,isCancelingAll:C}}var L={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}},Bt={minWidth:1100};function Xl(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 is({orders:e,sortKey:t,sortDir:r,onSort:s,onCancelOrder:n,onCancelAll:i,cancelingOrderIds:o,isCancelingAll:a,className:l}){let{t:p}=i18n.useTranslation(),c=p("perpetuals.openOrders.market"),u=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(I,{style:L.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.time")}),jsxRuntime.jsx(I,{style:L.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.size")}),jsxRuntime.jsx(I,{style:L.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.asset")}),jsxRuntime.jsx(I,{style:L.direction,sortKey:"direction",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.direction")}),jsxRuntime.jsx(I,{style:L.type,sortKey:"type",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.type")}),jsxRuntime.jsx(I,{style:L.leverage,sortKey:"leverage",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui.StyledTooltip,{content:p("perpetuals.openOrders.tooltip.leverage"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:p("perpetuals.openOrders.col.leverage")})})}),jsxRuntime.jsx(I,{style:L.orderValue,sortKey:"orderValue",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.orderValue")}),jsxRuntime.jsx(I,{style:L.executePrice,sortKey:"executePrice",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.executePrice")}),jsxRuntime.jsx(I,{style:L.currentPrice,sortKey:"currentPrice",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.currentPrice")}),jsxRuntime.jsx(I,{style:L.triggerCondition,children:p("perpetuals.openOrders.col.triggerCondition")}),jsxRuntime.jsx(I,{style:L.tpsl,align:"center",children:p("perpetuals.openOrders.col.tpsl")}),jsxRuntime.jsx("div",{style:L.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"}):p("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:{...Bt,...fe},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:Bt,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:p("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:{...Bt,...fe},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:Bt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((d,f)=>jsxRuntime.jsx(Jl,{order:d,striped:f%2===1,isThisRowCanceling:o.has(d.orderId),isBatchCanceling:a,marketLabel:c,onCancel:n},d.orderId))})]})})}function Jl({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",p=o(l?"perpetuals.openOrders.long":"perpetuals.openOrders.short"),c=l?"text-bullish":"text-bearish",u=Xl(e,n),d=e.isTrigger?n:Ke(e.price*e.quantity),f=e.isTrigger?n:ie(e.price);return jsxRuntime.jsx("div",{style:t?Ze:void 0,children:jsxRuntime.jsxs("div",{style:It,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsx("div",{style:L.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Lt(e.timestamp)})}),jsxRuntime.jsx("div",{style:L.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:et(e.quantity)})}),jsxRuntime.jsx("div",{style:L.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:L.direction,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",c),children:p})}),jsxRuntime.jsx("div",{style:L.type,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:u})}),jsxRuntime.jsx("div",{style:L.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:L.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:L.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:L.currentPrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:L.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:{...L.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?ie(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?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsx("div",{style:L.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 Zl(){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 ep(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open orders"})}function ap({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i,className:o}){let{t:a}=i18n.useTranslation(),{orders:l,sortKey:p,sortDir:c,onSort:u,handleCancelOrder:d,handleCancelAll:f,cancelingOrderIds:y,isCancelingAll:m}=ns({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}),[v,b]=react.useState(false),P=react.useCallback(()=>{l.length!==0&&b(true);},[l.length]),C=react.useCallback(()=>{m||b(false);},[m]),A=react.useCallback(async()=>{try{await f();}finally{b(false);}},[f]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(is,{className:o,orders:l,sortKey:p,sortDir:c,onSort:u,onCancelOrder:d,onCancelAll:P,cancelingOrderIds:y,isCancelingAll:m}),jsxRuntime.jsx(ui.StyledModal,{isOpen:v,onOpenChange:h=>{m||h||C();},size:"md",hideCloseButton:true,backdrop:"blur",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:C,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:()=>{A();},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 gi(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 up(e,t,r,s){let n=gi(e,r),i=gi(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 ls({userAddress:e,symbol:t}){let[r,s]=react.useState("time"),[n,i]=react.useState("desc"),o=react.useCallback(d=>{s(f=>f===d?(i(y=>y==="asc"?"desc":"asc"),f):(i("desc"),d));},[]),{data:a,isLoading:l,error:p}=nr({userAddress:e,symbol:t},{enabled:!!e,staleTime:5e3}),c=react.useMemo(()=>a?.trades??[],[a]);return {trades:react.useMemo(()=>[...c].sort((d,f)=>up(d,f,r,n)),[c,r,n]),isLoading:l,error:p,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%"}},us={minWidth:1100},gp=48,bi={minHeight:36,maxHeight:36,padding:"0 16px"};function bp(e){return e?!!(/^Open\s+Long\b/i.test(e)||/^Close\s+Short\b/i.test(e)):false}function cs({trades:e,sortKey:t,sortDir:r,onSort:s,className:n}){let{t:i}=i18n.useTranslation(),o=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(I,{style:ne.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.time")}),jsxRuntime.jsx(I,{style:ne.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.size")}),jsxRuntime.jsx(I,{style:ne.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.asset")}),jsxRuntime.jsx(I,{style:ne.description,sortKey:"description",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.description")}),jsxRuntime.jsx(I,{style:ne.price,sortKey:"price",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.price")}),jsxRuntime.jsx(I,{style:ne.tradeValue,sortKey:"tradeValue",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.tradeValue")}),jsxRuntime.jsx(I,{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:{...us,...fe},className:"flex flex-none flex-col",children:o}),e.length===0?jsxRuntime.jsx("div",{style:us,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(hp,{trades:e})]})})}function hp({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:us,className:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:r>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:r},rowComponent:xp,rowCount:e.length,rowHeight:gp,rowProps:s,overscanCount:4})})}function xp({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=bp(s.dir),p=s.dir??"",c=l?"text-bullish":"text-bearish",u=a>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:n?{...bi,...Ze}:bi,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:Lt(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:et(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:p})}),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: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-default-700",children:Ke(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",u),children:Ft(a)})})]})})}function Sp(){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 vp(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No trades"})}function Pp({userAddress:e,symbol:t,className:r}){let{trades:s,sortKey:n,sortDir:i,onSort:o}=ls({userAddress:e,symbol:t});return jsxRuntime.jsx(cs,{className:r,trades:s,sortKey:n,sortDir:i,onSort:o})}var Op=1000000000n,Tp=8,Dp=10n**BigInt(8);function yt(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return hi(r,Op,t)}function Kt(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return hi(r,Dp,t)}var wp=Kt;function ds(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 hi(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 p=l.toString().padStart(r,"0");return p=p.replace(/0+$/,""),p?`${s?"-":""}${i.toString()}.${p}`:`${s?"-":""}${i.toString()}`}function gt(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function ms(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function fs({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:a}){let{t:l}=i18n.useTranslation(),p=t?Date.parse(t.expiresAt):0,[c,u]=react.useState(()=>p?gt(p):0);return react.useEffect(()=>{if(!e||!p)return;u(gt(p));let d=setInterval(()=>{let f=gt(p);u(f),f===0&&(o?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,p,o]),jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:d=>!d&&i(),hideCloseButton:true,backdrop:"blur",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(Fp,{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 Fp({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.send"),value:`${yt(e.grossLamports)} SOL`}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.receive"),value:`${Kt(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.platformFee"),value:`${yt(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.relayFee"),value:`${yt(e.relayDepositLamports,6)} SOL`,muted:true})]})}function zt({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 ys({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:l,className:p}){let{t:c}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui.cn("flex flex-col gap-4",p),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 Ci="#C7FF2E";function bs({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:l}=i18n.useTranslation(),p=$p(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"),u=t==="failed"&&!!i;return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:d=>!d&&o(),size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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(zp,{variant:p}),jsxRuntime.jsx("p",{className:ui.cn("text-sm leading-relaxed max-w-[320px]",Vp(p)),children:c})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(Pi,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(Pi,{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",u?"justify-between":"justify-end"),children:[u&&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",u?"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 Pi({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:[ms(r,6,4),jsxRuntime.jsx(Xp,{})]})]})}function zp({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(Wp,{})}):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(Gp,{className:"w-8 h-8",style:{color:Ci}})}):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(jp,{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(Yp,{className:"w-8 h-8 text-rose-400"})})}function Wp(){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:Ci,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsxRuntime.jsx("style",{children:`
|
|
36
|
+
`}),jsxRuntime.jsx("input",{type:"range",value:Math.round(L),onChange:W,min:0,max:100,step:1,disabled:a<=0,className:"perp-close-slider",style:{"--pct":`${Math.round(L)}%`}}),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:()=>{ve();},disabled:!ee,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:ee?mt:"rgba(63,63,70,0.6)",borderRadius:9999,border:"none",cursor:ee?"pointer":"not-allowed",opacity:ee?1:.9},children:[s&&jsxRuntime.jsx(ui.Spinner,{size:"sm",color:"current"}),s?"Closing...":Pe]})]})]})})})}function es({userAddress:e,onCloseSuccess:t,onCloseError:r,onPlaceOrder:s}){let[n,i]=react.useState(false),[o,a]=react.useState(null),[l,p]=react.useState("market"),{data:c}=at({symbol:o?.symbol}),{mutateAsync:u,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:()=>{i(false),a(null),t?.();},onError:b=>{r?.(b);}}),f=react.useCallback(b=>{a(b),p("market"),i(true);},[]),y=react.useCallback(b=>{a(b),p("limit"),i(true);},[]),m=react.useCallback(()=>{d||(i(false),a(null));},[d]),v=react.useCallback(async(b,P)=>{if(!o||!e)throw new Error("Position and user address are required");let C=o.side==="long"?"short":"long",A=l==="limit"?"limit":"market",h=o.markPrice||o.entryPrice,z=c?.szDecimals??5;await u({symbol:o.symbol,side:C,orderType:A,amount:b*h,price:A==="limit"?P:void 0,leverage:o.leverage,reduceOnly:true,userAddress:e,size:b,refPrice:h,szDecimals:z});},[o,e,l,c,u]);return {isModalOpen:n,selectedPosition:o,closeType:l,isClosing:d,openMarketClose:f,openLimitClose:y,handleConfirm:v,closeModal:m}}function ni(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 Xl(e,t,r,s){let n=ni(e,r),i=ni(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 ts({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}){let[i,o]=react.useState("marginPnl"),[a,l]=react.useState("desc"),p=react.useCallback(v=>{o(b=>b===v?(l(P=>P==="asc"?"desc":"asc"),b):(l("asc"),v));},[]),{data:c,isLoading:u,error:d}=ot({userAddress:e,symbol:t},{enabled:!!e}),f=es({userAddress:e,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n}),y=react.useMemo(()=>c?.positions??[],[c]);return {positions:react.useMemo(()=>i?[...y].sort((v,b)=>Xl(v,b,i,a)):y,[y,i,a]),isLoading:u,error:d,sortKey:i,sortDir:a,onSort:p,closePosition:f}}var ep={start:"justify-start",center:"justify-center",end:"justify-end"},fe={minHeight:28,maxHeight:28},Mt={minHeight:36,maxHeight:36},Ze={backgroundColor:"rgba(255, 255, 255, 0.06)"};function ie(e){return e===void 0||!Number.isFinite(e)?"--":utils.formatPriceInUsd(e)}function Ke(e){return Number.isFinite(e)?utils.formatAmountInUsd(e):"--"}function Lt(e){return Number.isFinite(e)?utils.formatAmountInUsd(e,{showPlusGtThanZero:true}):"--"}function li(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function et(e,t){return t||(Number.isFinite(e)?utils.formatAmount(e):"--")}function Ft(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 M({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":"",p=r!==void 0&&i!==void 0,c=ep[o],u=jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-500",children:[t,l]});return p?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:u}):jsxRuntime.jsx("div",{style:e,className:ui.cn("flex flex-row items-center",c),children:u})}var Y={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%"}},qt={minWidth:1e3};function rs({positions:e,sortKey:t,sortDir:r,onSort:s,onMarketClose:n,onLimitClose:i,isClosing:o,className:a}){let{t:l}=i18n.useTranslation(),p=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(M,{style:Y.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.asset")}),jsxRuntime.jsx(M,{style:Y.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.position")}),jsxRuntime.jsx(M,{style:Y.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.positionValue")}),jsxRuntime.jsx(M,{style:Y.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.entryPrice")}),jsxRuntime.jsx(M,{style:Y.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:l("perpetuals.positions.col.markPrice")}),jsxRuntime.jsx(M,{style:Y.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(M,{style:Y.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(M,{style:Y.tpsl,align:"center",children:l("perpetuals.positions.col.tpsl")}),jsxRuntime.jsx(M,{style:Y.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:{...qt,...fe},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:qt,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:{...qt,...fe},className:"flex flex-1 flex-col",children:p}),jsxRuntime.jsx("div",{style:qt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((c,u)=>jsxRuntime.jsx(rp,{position:c,striped:u%2===1,isClosing:o,onMarketClose:n,onLimitClose:i},c.symbol))})]})})}function rp({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"),p=a?"text-bullish":"text-bearish",u=e.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t?Ze:void 0,children:jsxRuntime.jsxs("div",{style:Mt,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsxs("div",{style:Y.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:Y.position,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",p),children:l}),jsxRuntime.jsxs("span",{className:"text-xs font-normal text-default-700",children:[et(e.quantity,e.quantityRaw)," ",o]})]}),jsxRuntime.jsx("div",{style:Y.value,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ke(e.notionalValue)})}),jsxRuntime.jsx("div",{style:Y.entry,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.entryPrice)})}),jsxRuntime.jsx("div",{style:Y.mark,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:Y.liq,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.liquidationPrice)})}),jsxRuntime.jsxs("div",{style:Y.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ke(e.margin)}),jsxRuntime.jsxs("span",{className:ui.cn("text-xs font-medium",u),children:["(",Lt(e.unrealizedPnl)," /"," ",li(e.unrealizedPnlPercent),")"]})]}),jsxRuntime.jsxs("div",{style:{...Y.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?ie(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?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsxs("div",{style:Y.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 ss(){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 sp(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open positions"})}function np({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n,className:i}){let{positions:o,isLoading:a,sortKey:l,sortDir:p,onSort:c,closePosition:u}=ts({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,onPlaceOrder:n});return a?jsxRuntime.jsx("div",{className:i,children:jsxRuntime.jsx(ss,{})}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(rs,{positions:o,sortKey:l,sortDir:p,onSort:c,onMarketClose:u.openMarketClose,onLimitClose:u.openLimitClose,isClosing:u.isClosing,className:i}),jsxRuntime.jsx(Jr,{isOpen:u.isModalOpen,position:u.selectedPosition,closeType:u.closeType,isSubmitting:u.isClosing,onClose:u.closeModal,onConfirm:u.handleConfirm})]})}function di(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 lp(e,t,r,s){let n=di(e,r),i=di(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 ns({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}){let[o,a]=react.useState("time"),[l,p]=react.useState("desc"),c=react.useCallback(w=>{a(D=>D===w?(p(B=>B==="asc"?"desc":"asc"),D):(p("asc"),w));},[]),{data:u,isLoading:d,error:f}=sr({userAddress:e,symbol:t},{enabled:!!e}),y=react.useRef(new Set),[,m]=react.useState(0),v=react.useCallback(()=>m(w=>w+1),[]),b=react.useCallback(w=>{y.current.add(w),v();},[v]),P=react.useCallback(w=>{y.current.delete(w),v();},[v]),[C,A]=react.useState(false),{mutateAsync:h,isPending:z}=lr({onSuccess:()=>{r?.();},onError:w=>{s?.(w);}}),L=react.useCallback(async w=>{if(n)try{let D=await n(w);return r?.(),D}catch(D){throw s?.(D instanceof Error?D:new Error(String(D))),D}if(i)try{let[D]=await i([w]);if(!D)throw new Error("cancelOrders returned no result");return r?.(),D}catch(D){throw s?.(D instanceof Error?D:new Error(String(D))),D}return h(w)},[n,i,h,r,s]),I=react.useMemo(()=>u?.orders??[],[u]),x=react.useMemo(()=>o?[...I].sort((w,D)=>lp(w,D,o,l)):I,[I,o,l]),G=react.useCallback(async w=>{if(!e)throw new Error("User address is required");b(w.orderId);try{await L({orderId:w.orderId,symbol:w.symbol,userAddress:e});}finally{P(w.orderId);}},[e,L,b,P]),X=react.useCallback(async()=>{if(!e)throw new Error("User address is required");if(I.length!==0){A(true);try{let w=I.map(D=>({orderId:D.orderId,symbol:D.symbol,userAddress:e}));if(i){try{await i(w);for(let D=0;D<w.length;D++)r?.();}catch(D){s?.(D instanceof Error?D:new Error(String(D)));}return}await Promise.allSettled(w.map(D=>L(D)));}finally{A(false);}}},[e,I,i,L,r,s]),W=y.current.size>0||C||z;return {orders:x,isLoading:d,error:f,sortKey:o,sortDir:l,onSort:c,handleCancelOrder:G,handleCancelAll:X,isCanceling:W,cancelingOrderIds:y.current,isCancelingAll:C}}var F={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}},Bt={minWidth:1100};function up(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 is({orders:e,sortKey:t,sortDir:r,onSort:s,onCancelOrder:n,onCancelAll:i,cancelingOrderIds:o,isCancelingAll:a,className:l}){let{t:p}=i18n.useTranslation(),c=p("perpetuals.openOrders.market"),u=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(M,{style:F.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.time")}),jsxRuntime.jsx(M,{style:F.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.size")}),jsxRuntime.jsx(M,{style:F.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.asset")}),jsxRuntime.jsx(M,{style:F.direction,sortKey:"direction",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.direction")}),jsxRuntime.jsx(M,{style:F.type,sortKey:"type",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.type")}),jsxRuntime.jsx(M,{style:F.leverage,sortKey:"leverage",activeSortKey:t,sortDir:r,onSort:s,children:jsxRuntime.jsx(ui.StyledTooltip,{content:p("perpetuals.openOrders.tooltip.leverage"),placement:"top",delay:200,closeDelay:0,children:jsxRuntime.jsx("span",{className:"border-b border-dashed border-default-500/40",children:p("perpetuals.openOrders.col.leverage")})})}),jsxRuntime.jsx(M,{style:F.orderValue,sortKey:"orderValue",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.orderValue")}),jsxRuntime.jsx(M,{style:F.executePrice,sortKey:"executePrice",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.executePrice")}),jsxRuntime.jsx(M,{style:F.currentPrice,sortKey:"currentPrice",activeSortKey:t,sortDir:r,onSort:s,children:p("perpetuals.openOrders.col.currentPrice")}),jsxRuntime.jsx(M,{style:F.triggerCondition,children:p("perpetuals.openOrders.col.triggerCondition")}),jsxRuntime.jsx(M,{style:F.tpsl,align:"center",children:p("perpetuals.openOrders.col.tpsl")}),jsxRuntime.jsx("div",{style:F.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"}):p("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:{...Bt,...fe},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:Bt,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:p("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:{...Bt,...fe},className:"flex flex-1 flex-col",children:u}),jsxRuntime.jsx("div",{style:Bt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((d,f)=>jsxRuntime.jsx(cp,{order:d,striped:f%2===1,isThisRowCanceling:o.has(d.orderId),isBatchCanceling:a,marketLabel:c,onCancel:n},d.orderId))})]})})}function cp({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",p=o(l?"perpetuals.openOrders.long":"perpetuals.openOrders.short"),c=l?"text-bullish":"text-bearish",u=up(e,n),d=e.isTrigger?n:Ke(e.price*e.quantity),f=e.isTrigger?n:ie(e.price);return jsxRuntime.jsx("div",{style:t?Ze:void 0,children:jsxRuntime.jsxs("div",{style:Mt,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxRuntime.jsx("div",{style:F.time,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:Ft(e.timestamp)})}),jsxRuntime.jsx("div",{style:F.size,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:et(e.quantity)})}),jsxRuntime.jsx("div",{style:F.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:F.direction,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:ui.cn("text-xs font-medium",c),children:p})}),jsxRuntime.jsx("div",{style:F.type,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:u})}),jsxRuntime.jsx("div",{style:F.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:F.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:F.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:F.currentPrice,className:"flex flex-row items-center justify-start",children:jsxRuntime.jsx("span",{className:"text-xs font-normal text-default-700",children:ie(e.markPrice)})}),jsxRuntime.jsx("div",{style:F.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:{...F.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?ie(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?ie(e.stopLossPrice):"--"})]}),jsxRuntime.jsx("div",{style:F.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 dp(){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 mp(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open orders"})}function Sp({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i,className:o}){let{t:a}=i18n.useTranslation(),{orders:l,sortKey:p,sortDir:c,onSort:u,handleCancelOrder:d,handleCancelAll:f,cancelingOrderIds:y,isCancelingAll:m}=ns({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,cancelOrder:n,cancelOrders:i}),[v,b]=react.useState(false),P=react.useCallback(()=>{l.length!==0&&b(true);},[l.length]),C=react.useCallback(()=>{m||b(false);},[m]),A=react.useCallback(async()=>{try{await f();}finally{b(false);}},[f]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(is,{className:o,orders:l,sortKey:p,sortDir:c,onSort:u,onCancelOrder:d,onCancelAll:P,cancelingOrderIds:y,isCancelingAll:m}),jsxRuntime.jsx(ui.StyledModal,{isOpen:v,onOpenChange:h=>{m||h||C();},size:"md",hideCloseButton:true,backdrop:"blur",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:C,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:()=>{A();},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 bi(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 Cp(e,t,r,s){let n=bi(e,r),i=bi(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 ls({userAddress:e,symbol:t}){let[r,s]=react.useState("time"),[n,i]=react.useState("desc"),o=react.useCallback(d=>{s(f=>f===d?(i(y=>y==="asc"?"desc":"asc"),f):(i("desc"),d));},[]),{data:a,isLoading:l,error:p}=nr({userAddress:e,symbol:t},{enabled:!!e,staleTime:5e3}),c=react.useMemo(()=>a?.trades??[],[a]);return {trades:react.useMemo(()=>[...c].sort((d,f)=>Cp(d,f,r,n)),[c,r,n]),isLoading:l,error:p,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%"}},us={minWidth:1100},Ep=48,hi={minHeight:36,maxHeight:36,padding:"0 16px"};function Rp(e){return e?!!(/^Open\s+Long\b/i.test(e)||/^Close\s+Short\b/i.test(e)):false}function cs({trades:e,sortKey:t,sortDir:r,onSort:s,className:n}){let{t:i}=i18n.useTranslation(),o=jsxRuntime.jsxs("div",{style:fe,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsxRuntime.jsx(M,{style:ne.time,sortKey:"time",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.time")}),jsxRuntime.jsx(M,{style:ne.size,sortKey:"size",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.size")}),jsxRuntime.jsx(M,{style:ne.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.asset")}),jsxRuntime.jsx(M,{style:ne.description,sortKey:"description",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.description")}),jsxRuntime.jsx(M,{style:ne.price,sortKey:"price",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.price")}),jsxRuntime.jsx(M,{style:ne.tradeValue,sortKey:"tradeValue",activeSortKey:t,sortDir:r,onSort:s,children:i("perpetuals.tradeHistory.col.tradeValue")}),jsxRuntime.jsx(M,{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:{...us,...fe},className:"flex flex-none flex-col",children:o}),e.length===0?jsxRuntime.jsx("div",{style:us,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(Ap,{trades:e})]})})}function Ap({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:us,className:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:r>0&&jsxRuntime.jsx(reactWindow.List,{style:{height:r},rowComponent:Np,rowCount:e.length,rowHeight:Ep,rowProps:s,overscanCount:4})})}function Np({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=Rp(s.dir),p=s.dir??"",c=l?"text-bullish":"text-bearish",u=a>=0?"text-bullish":"text-bearish";return jsxRuntime.jsx("div",{style:t,children:jsxRuntime.jsxs("div",{style:n?{...hi,...Ze}: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:Ft(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:et(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:p})}),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: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-default-700",children:Ke(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",u),children:Lt(a)})})]})})}function Up(){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 Ip(){return jsxRuntime.jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No trades"})}function Mp({userAddress:e,symbol:t,className:r}){let{trades:s,sortKey:n,sortDir:i,onSort:o}=ls({userAddress:e,symbol:t});return jsxRuntime.jsx(cs,{className:r,trades:s,sortKey:n,sortDir:i,onSort:o})}var Fp=1000000000n,qp=8,Hp=10n**BigInt(8);function yt(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return xi(r,Fp,t)}function Kt(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return xi(r,Hp,t)}var _p=Kt;function ds(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 xi(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 p=l.toString().padStart(r,"0");return p=p.replace(/0+$/,""),p?`${s?"-":""}${i.toString()}.${p}`:`${s?"-":""}${i.toString()}`}function gt(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function ms(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function fs({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:a}){let{t:l}=i18n.useTranslation(),p=t?Date.parse(t.expiresAt):0,[c,u]=react.useState(()=>p?gt(p):0);return react.useEffect(()=>{if(!e||!p)return;u(gt(p));let d=setInterval(()=>{let f=gt(p);u(f),f===0&&(o?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,p,o]),jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:d=>!d&&i(),hideCloseButton:true,backdrop:"blur",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(jp,{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 jp({breakdown:e}){let{t}=i18n.useTranslation();return jsxRuntime.jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.send"),value:`${yt(e.grossLamports)} SOL`}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.receive"),value:`${Kt(e.expectedOutputUSDC)} USDC`,highlight:true}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.platformFee"),value:`${yt(e.platformFeeLamports,6)} SOL`,muted:true}),jsxRuntime.jsx(zt,{label:t("perpDeposit.confirm.relayFee"),value:`${yt(e.relayDepositLamports,6)} SOL`,muted:true})]})}function zt({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 ys({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:l,className:p}){let{t:c}=i18n.useTranslation();return jsxRuntime.jsxs("div",{className:ui.cn("flex flex-col gap-4",p),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 Oi="#C7FF2E";function bs({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:l}=i18n.useTranslation(),p=iu(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"),u=t==="failed"&&!!i;return jsxRuntime.jsx(ui.StyledModal,{isOpen:e,onOpenChange:d=>!d&&o(),size:"md",hideCloseButton:true,backdrop:"blur",classNames:{base:"!bg-[#18181b] !rounded-[14px] !border !border-[rgba(39,39,42,1)] !shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5)] max-w-[420px]",body:"!p-0"},children:jsxRuntime.jsx(ui.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(su,{variant:p}),jsxRuntime.jsx("p",{className:ui.cn("text-sm leading-relaxed max-w-[320px]",ou(p)),children:c})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxRuntime.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsxRuntime.jsx(Ci,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsxRuntime.jsx(Ci,{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",u?"justify-between":"justify-end"),children:[u&&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",u?"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 Ci({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:[ms(r,6,4),jsxRuntime.jsx(uu,{})]})]})}function su({variant:e}){return e==="progress"?jsxRuntime.jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsxRuntime.jsx(nu,{})}):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(au,{className:"w-8 h-8",style:{color:Oi}})}):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(lu,{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(pu,{className:"w-8 h-8 text-rose-400"})})}function nu(){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:Oi,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,5 +41,5 @@
|
|
|
41
41
|
@keyframes lfi-perp-deposit-spin {
|
|
42
42
|
to { transform: rotate(360deg); }
|
|
43
43
|
}
|
|
44
|
-
`})]})}function $p(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function Vp(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 Gp(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 jp(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 Yp(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 Xp(){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 su({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:p,buildHyperliquidExplorerUrl:c,onSettled:u,onError:d,className:f}){let{t:y}=i18n.useTranslation(),[m,v]=react.useState(""),[b,P]=react.useState(n??""),C=react.useMemo(()=>{if(m&&(!/^\d+(\.\d+)?$/.test(m.trim())||Number(m)<=0))return y("perpDeposit.error.amountInvalid")},[m,y]),A=react.useMemo(()=>{if(b)return l?l(b):void 0},[b,l]),h=react.useMemo(()=>C?"":ds(m),[m,C]),z=792703809,F=react.useMemo(()=>!h||h==="0"||A||!b?null:{originChainId:z,userAddress:e,hyperliquidRecipient:b,grossAmount:h,source:r},[h,b,A,r,e]),M=yr(F,{enabled:!!F}),{state:x,execute:G,reset:X,dispatch:W}=gr(i),w=x.phase==="submitted"||x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"?x.intentId:void 0,D=br(w,{enabled:!!w&&x.phase!=="succeeded"&&x.phase!=="refunded"&&x.phase!=="failed"});react.useEffect(()=>{D.data&&W({type:"STATUS_UPDATE",status:D.data});},[D.data,W]),react.useEffect(()=>{x.phase==="succeeded"?u?.(x.intentId):x.phase==="failed"&&d?.(x.intentId,x.error.message);},[x,u,d]);let B=react.useCallback(()=>{M.data&&(W({type:"QUOTE_REQUEST"}),W({type:"QUOTE_RECEIVED",quote:M.data}));},[W,M.data]),$=react.useCallback(async()=>{if(x.phase==="ready_to_sign")try{await G({quote:x.quote,userAddress:e,hyperliquidRecipient:b,userId:t,source:r,campaign:s});}catch{}},[x,G,e,b,t,r,s]),he=react.useCallback(()=>{W({type:"QUOTE_EXPIRED"});},[W]),ee=react.useCallback(async()=>{W({type:"RESET"}),await M.refetch();},[W,M]),pe=x.phase==="ready_to_sign"||x.phase==="signing"||x.phase==="broadcasting"||x.phase==="expired",ve=x.phase==="submitted"||x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"&&!!x.intentId,J=x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"?x.status:void 0,Ue=!M.data||M.isFetching||!!C||!!A||!F;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:y("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:y("perpDeposit.description")})]}),jsxRuntime.jsx(ys,{amount:m,onAmountChange:v,recipient:b,onRecipientChange:P,balanceSol:o,onMax:a,amountError:C,recipientError:A,disabled:x.phase!=="idle"&&x.phase!=="expired"&&x.phase!=="failed"}),jsxRuntime.jsx(ui.Button,{color:"primary",isDisabled:Ue,isLoading:M.isFetching,onPress:B,children:M.isFetching?y("perpDeposit.gettingQuote"):y("perpDeposit.confirmQuote")}),M.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:y("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(fs,{isOpen:pe,quote:x.phase==="ready_to_sign"||x.phase==="signing"||x.phase==="broadcasting"||x.phase==="expired"?x.quote:void 0,isExecuting:x.phase==="signing"||x.phase==="broadcasting",isExpired:x.phase==="expired",onConfirm:$,onCancel:X,onExpire:he}),jsxRuntime.jsx(bs,{isOpen:ve,phase:x.phase,status:J,solanaExplorerUrl:J?.solanaTxHash&&p?p(J.solanaTxHash):void 0,hyperliquidExplorerUrl:J?.hyperliquidTxHash&&c?c(J.hyperliquidTxHash):void 0,onRetry:x.phase==="failed"?ee:void 0,onClose:X,errorMessage:x.phase==="failed"?x.error.message:void 0})]})}function vs({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=i18n.useTranslation(),a=e.phase,l=a==="executing",p=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:[p&&jsxRuntime.jsx(pu,{}),c&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!p&&!c&&e.steps.map((u,d)=>jsxRuntime.jsx(lu,{rec:u,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${u.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||p,children:e.steps.some(u=>u.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function lu({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),i=du(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(uu,{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(cu(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 pu(){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 uu({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 cu(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 du(e,t){return t()}function mu({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:l,runNext:p,runStep:c,reload:u}=wt({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),d=react.useCallback(()=>{p();},[p]),f=react.useCallback(m=>{c(m);},[c]),y=react.useCallback(()=>{u();},[u]);return jsxRuntime.jsx(vs,{state:l,onContinue:d,onRetryStep:f,onReload:y,onDismiss:o,className:a})}exports.ClosePositionModal=Jr;exports.CoinInfoNotFoundUI=hr;exports.CoinInfoSkeletonsUI=vr;exports.CoinInfoUI=Or;exports.CoinInfoWidget=Jo;exports.DEFAULT_ORDER_BOOK_PRECISION_OPTIONS=In;exports.DepositConfirmUI=fs;exports.DepositFlowWidget=su;exports.DepositFormUI=ys;exports.DepositStatusUI=bs;exports.HL_USDC_DECIMALS=Tp;exports.HyperliquidApiError=Ce;exports.HyperliquidInitUI=vs;exports.HyperliquidInitWidget=mu;exports.HyperliquidPerpetualsClient=jt;exports.LiberFiApiError=ue;exports.LiberFiHttpTransport=Ie;exports.LiberFiPerpDepositClient=Xt;exports.LiberFiPerpetualsClient=Yt;exports.OpenOrdersEmpty=ep;exports.OpenOrdersSkeleton=Zl;exports.OpenOrdersUI=is;exports.OpenOrdersWidget=ap;exports.OrderBookUI=Nr;exports.OrderBookWidget=Aa;exports.PerpetualsContext=Oe;exports.PerpetualsProvider=Ji;exports.PlaceOrderFormUI=Vr;exports.PlaceOrderFormWidget=Rl;exports.PositionsEmpty=zl;exports.PositionsSkeleton=ss;exports.PositionsUI=rs;exports.PositionsWidget=Wl;exports.SearchCoinsUI=wr;exports.SearchCoinsWidget=na;exports.TERMINAL_DEPOSIT_STATUSES=nt;exports.TradeHistoryEmpty=vp;exports.TradeHistorySkeleton=Sp;exports.TradeHistoryUI=cs;exports.TradeHistoryWidget=Pp;exports.TradesUI=qr;exports.TradesWidget=ul;exports.accountStateQueryKey=Ye;exports.activeAssetLeverageQueryKey=Pt;exports.aggregationFromStep=On;exports.assetMetaQueryKey=Js;exports.cancelOrder=tn;exports.classifyStep=Ct;exports.coinsQueryKey=As;exports.createOrder=en;exports.currentDepositBreakdown=Gi;exports.currentDepositStatus=Vi;exports.fetchActiveAssetLeverage=Ys;exports.fetchAssetMeta=Zs;exports.fetchCoins=Ns;exports.fetchKlines=Bs;exports.fetchMarket=Fs;exports.fetchMarkets=Hs;exports.fetchOrderBook=Ks;exports.fetchOrders=Vs;exports.fetchPerpDepositQuote=nn;exports.fetchPerpDepositStatus=pn;exports.fetchPositions=$s;exports.fetchRecentTrades=Ws;exports.fetchTrades=js;exports.fetchUniverse=Te;exports.hlUsdcRawToUsdc=Kt;exports.initialDepositState=xt;exports.initialSetupState=lt;exports.isDepositPolling=$i;exports.isDepositTerminal=Wi;exports.isTerminalDepositLifecycle=ji;exports.klinesQueryKey=_s;exports.lamportsToSol=yt;exports.marketQueryKey=Is;exports.marketsQueryKey=qs;exports.microUsdcToUsdc=wp;exports.nextRunnableStep=Tt;exports.orderBookQueryKey=Qs;exports.ordersQueryKey=je;exports.perpDepositQuoteQueryKey=sn;exports.perpDepositStatusQueryKey=ln;exports.positionsQueryKey=Ge;exports.recentTradesQueryKey=zs;exports.reduceDepositState=Jt;exports.reduceSetupState=Ot;exports.secondsUntil=gt;exports.shortAddress=ms;exports.solToLamports=ds;exports.supportsUniverseSnapshot=De;exports.tradesQueryKey=Gs;exports.universeQueryKey=ye;exports.useAccountStateQuery=mr;exports.useAccountStateSubscription=ko;exports.useActiveAssetLeverageQuery=ir;exports.useAssetMetaQuery=at;exports.useCancelOrderMutation=lr;exports.useCandlesSubscription=vo;exports.useClosePosition=es;exports.useCoinInfo=Cr;exports.useCoinsQuery=Zt;exports.useCreateOrderMutation=ar;exports.useHyperliquidSetup=wt;exports.useHyperliquidUserBootstrap=Ao;exports.useKlinesQuery=io;exports.useMarketDataSubscription=Fe;exports.useMarketQuery=it;exports.useMarketsQuery=er;exports.useOpenOrdersScript=ns;exports.useOrderBookQuery=tr;exports.useOrderBookScript=Er;exports.useOrdersQuery=sr;exports.usePerpDepositClient=No;exports.usePerpDepositClientMaybe=Le;exports.usePerpDepositExecute=gr;exports.usePerpDepositQuote=yr;exports.usePerpDepositStatus=br;exports.usePerpetualsClient=R;exports.usePlaceOrderFormScript=_r;exports.usePositionsQuery=ot;exports.usePositionsScript=ts;exports.useRecentTradesQuery=rr;exports.useSearchCoinsScript=Dr;exports.useTradeHistoryScript=ls;exports.useTradesQuery=nr;exports.useTradesScript=Ir;exports.useUniverseQuery=so;exports.useUserDataSubscription=Oo;//# sourceMappingURL=index.js.map
|
|
44
|
+
`})]})}function iu(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function ou(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 au(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 lu(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 pu(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 uu(){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 gu({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:p,buildHyperliquidExplorerUrl:c,onSettled:u,onError:d,className:f}){let{t:y}=i18n.useTranslation(),[m,v]=react.useState(""),[b,P]=react.useState(n??""),C=react.useMemo(()=>{if(m&&(!/^\d+(\.\d+)?$/.test(m.trim())||Number(m)<=0))return y("perpDeposit.error.amountInvalid")},[m,y]),A=react.useMemo(()=>{if(b)return l?l(b):void 0},[b,l]),h=react.useMemo(()=>C?"":ds(m),[m,C]),z=792703809,L=react.useMemo(()=>!h||h==="0"||A||!b?null:{originChainId:z,userAddress:e,hyperliquidRecipient:b,grossAmount:h,source:r},[h,b,A,r,e]),I=yr(L,{enabled:!!L}),{state:x,execute:G,reset:X,dispatch:W}=gr(i),w=x.phase==="submitted"||x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"?x.intentId:void 0,D=br(w,{enabled:!!w&&x.phase!=="succeeded"&&x.phase!=="refunded"&&x.phase!=="failed"});react.useEffect(()=>{D.data&&W({type:"STATUS_UPDATE",status:D.data});},[D.data,W]),react.useEffect(()=>{x.phase==="succeeded"?u?.(x.intentId):x.phase==="failed"&&d?.(x.intentId,x.error.message);},[x,u,d]);let B=react.useCallback(()=>{I.data&&(W({type:"QUOTE_REQUEST"}),W({type:"QUOTE_RECEIVED",quote:I.data}));},[W,I.data]),$=react.useCallback(async()=>{if(x.phase==="ready_to_sign")try{await G({quote:x.quote,userAddress:e,hyperliquidRecipient:b,userId:t,source:r,campaign:s});}catch{}},[x,G,e,b,t,r,s]),he=react.useCallback(()=>{W({type:"QUOTE_EXPIRED"});},[W]),ee=react.useCallback(async()=>{W({type:"RESET"}),await I.refetch();},[W,I]),pe=x.phase==="ready_to_sign"||x.phase==="signing"||x.phase==="broadcasting"||x.phase==="expired",ve=x.phase==="submitted"||x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"&&!!x.intentId,J=x.phase==="tracking"||x.phase==="succeeded"||x.phase==="refunded"||x.phase==="failed"?x.status:void 0,Ue=!I.data||I.isFetching||!!C||!!A||!L;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:y("perpDeposit.title")}),jsxRuntime.jsx("p",{className:"text-default-500 text-sm",children:y("perpDeposit.description")})]}),jsxRuntime.jsx(ys,{amount:m,onAmountChange:v,recipient:b,onRecipientChange:P,balanceSol:o,onMax:a,amountError:C,recipientError:A,disabled:x.phase!=="idle"&&x.phase!=="expired"&&x.phase!=="failed"}),jsxRuntime.jsx(ui.Button,{color:"primary",isDisabled:Ue,isLoading:I.isFetching,onPress:B,children:I.isFetching?y("perpDeposit.gettingQuote"):y("perpDeposit.confirmQuote")}),I.error&&jsxRuntime.jsx("div",{className:"text-danger text-xs",children:y("perpDeposit.error.quoteFailed")})]}),jsxRuntime.jsx(fs,{isOpen:pe,quote:x.phase==="ready_to_sign"||x.phase==="signing"||x.phase==="broadcasting"||x.phase==="expired"?x.quote:void 0,isExecuting:x.phase==="signing"||x.phase==="broadcasting",isExpired:x.phase==="expired",onConfirm:$,onCancel:X,onExpire:he}),jsxRuntime.jsx(bs,{isOpen:ve,phase:x.phase,status:J,solanaExplorerUrl:J?.solanaTxHash&&p?p(J.solanaTxHash):void 0,hyperliquidExplorerUrl:J?.hyperliquidTxHash&&c?c(J.hyperliquidTxHash):void 0,onRetry:x.phase==="failed"?ee:void 0,onClose:X,errorMessage:x.phase==="failed"?x.error.message:void 0})]})}function vs({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=i18n.useTranslation(),a=e.phase,l=a==="executing",p=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:[p&&jsxRuntime.jsx(Pu,{}),c&&jsxRuntime.jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!p&&!c&&e.steps.map((u,d)=>jsxRuntime.jsx(vu,{rec:u,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${u.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||p,children:e.steps.some(u=>u.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function vu({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=i18n.useTranslation(),i=Tu(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(Cu,{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(Ou(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 Pu(){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 Cu({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 Ou(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 Tu(e,t){return t()}function Du({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:l,runNext:p,runStep:c,reload:u}=wt({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),d=react.useCallback(()=>{p();},[p]),f=react.useCallback(m=>{c(m);},[c]),y=react.useCallback(()=>{u();},[u]);return jsxRuntime.jsx(vs,{state:l,onContinue:d,onRetryStep:f,onReload:y,onDismiss:o,className:a})}exports.ClosePositionModal=Jr;exports.CoinInfoNotFoundUI=hr;exports.CoinInfoSkeletonsUI=vr;exports.CoinInfoUI=Or;exports.CoinInfoWidget=ta;exports.DEFAULT_ORDER_BOOK_PRECISION_OPTIONS=Mn;exports.DepositConfirmUI=fs;exports.DepositFlowWidget=gu;exports.DepositFormUI=ys;exports.DepositStatusUI=bs;exports.HL_USDC_DECIMALS=qp;exports.HyperliquidApiError=Ce;exports.HyperliquidInitUI=vs;exports.HyperliquidInitWidget=Du;exports.HyperliquidPerpetualsClient=jt;exports.LiberFiApiError=ue;exports.LiberFiHttpTransport=Me;exports.LiberFiPerpDepositClient=Xt;exports.LiberFiPerpetualsClient=Yt;exports.OpenOrdersEmpty=mp;exports.OpenOrdersSkeleton=dp;exports.OpenOrdersUI=is;exports.OpenOrdersWidget=Sp;exports.OrderBookUI=Nr;exports.OrderBookWidget=qa;exports.PerpetualsContext=Oe;exports.PerpetualsProvider=Zi;exports.PlaceOrderFormUI=Vr;exports.PlaceOrderFormWidget=Bl;exports.PositionsEmpty=sp;exports.PositionsSkeleton=ss;exports.PositionsUI=rs;exports.PositionsWidget=np;exports.SearchCoinsUI=wr;exports.SearchCoinsWidget=pa;exports.TERMINAL_DEPOSIT_STATUSES=nt;exports.TradeHistoryEmpty=Ip;exports.TradeHistorySkeleton=Up;exports.TradeHistoryUI=cs;exports.TradeHistoryWidget=Mp;exports.TradesUI=qr;exports.TradesWidget=xl;exports.accountStateQueryKey=Ye;exports.activeAssetLeverageQueryKey=Pt;exports.aggregationFromStep=On;exports.assetMetaQueryKey=Js;exports.cancelOrder=tn;exports.classifyStep=Ct;exports.coinsQueryKey=As;exports.createOrder=en;exports.currentDepositBreakdown=ji;exports.currentDepositStatus=Gi;exports.fetchActiveAssetLeverage=Ys;exports.fetchAssetMeta=Zs;exports.fetchCoins=Ns;exports.fetchKlines=Bs;exports.fetchMarket=Ls;exports.fetchMarkets=Hs;exports.fetchOrderBook=Ks;exports.fetchOrders=Vs;exports.fetchPerpDepositQuote=nn;exports.fetchPerpDepositStatus=pn;exports.fetchPositions=$s;exports.fetchRecentTrades=Ws;exports.fetchTrades=js;exports.fetchUniverse=Te;exports.hlUsdcRawToUsdc=Kt;exports.initialDepositState=xt;exports.initialSetupState=lt;exports.isDepositPolling=Vi;exports.isDepositTerminal=$i;exports.isTerminalDepositLifecycle=Yi;exports.klinesQueryKey=_s;exports.lamportsToSol=yt;exports.marketQueryKey=Ms;exports.marketsQueryKey=qs;exports.microUsdcToUsdc=_p;exports.nextRunnableStep=Tt;exports.orderBookQueryKey=Qs;exports.ordersQueryKey=je;exports.perpDepositQuoteQueryKey=sn;exports.perpDepositStatusQueryKey=ln;exports.positionsQueryKey=Ge;exports.recentTradesQueryKey=zs;exports.reduceDepositState=Jt;exports.reduceSetupState=Ot;exports.secondsUntil=gt;exports.shortAddress=ms;exports.solToLamports=ds;exports.supportsUniverseSnapshot=De;exports.tradesQueryKey=Gs;exports.universeQueryKey=ye;exports.useAccountStateQuery=mr;exports.useAccountStateSubscription=Eo;exports.useActiveAssetLeverageQuery=ir;exports.useAssetMetaQuery=at;exports.useCancelOrderMutation=lr;exports.useCandlesSubscription=Po;exports.useClosePosition=es;exports.useCoinInfo=Cr;exports.useCoinsQuery=Zt;exports.useCreateOrderMutation=ar;exports.useHyperliquidSetup=wt;exports.useHyperliquidUserBootstrap=No;exports.useKlinesQuery=oo;exports.useMarketDataSubscription=Le;exports.useMarketQuery=it;exports.useMarketsQuery=er;exports.useOpenOrdersScript=ns;exports.useOrderBookQuery=tr;exports.useOrderBookScript=Er;exports.useOrdersQuery=sr;exports.usePerpDepositClient=Uo;exports.usePerpDepositClientMaybe=Fe;exports.usePerpDepositExecute=gr;exports.usePerpDepositQuote=yr;exports.usePerpDepositStatus=br;exports.usePerpetualsClient=R;exports.usePlaceOrderFormScript=_r;exports.usePositionsQuery=ot;exports.usePositionsScript=ts;exports.useRecentTradesQuery=rr;exports.useSearchCoinsScript=Dr;exports.useTradeHistoryScript=ls;exports.useTradesQuery=nr;exports.useTradesScript=Mr;exports.useUniverseQuery=no;exports.useUserDataSubscription=To;//# sourceMappingURL=index.js.map
|
|
45
45
|
//# sourceMappingURL=index.js.map
|