@liberfi.io/ui-perpetuals 0.2.20 → 0.2.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {createContext,memo,useMemo,useContext,useState,useRef,useCallback,useEffect,useReducer}from'react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useQuery,useMutation,useQueryClient}from'@tanstack/react-query';import {SearchIcon,StyledTooltip,RHForm,RHNumberInput,Spinner,cn,Button,Modal,ModalContent,ModalHeader,ModalBody,ModalFooter,Input,StyledModal,XCloseIcon,Card,CardBody,CardHeader,CardFooter,Slider}from'@liberfi.io/ui';import {List}from'react-window';import {useResizeObserver,useTickAge}from'@liberfi.io/hooks';import {useForm}from'react-hook-form';import {useAuthCallback}from'@liberfi.io/wallet-connector';import {useTranslation}from'@liberfi.io/i18n';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.20");var qn="0.2.20";function _n(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 ke=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,u=l>0?(o-l)/l*100:0;return {symbol:n,price:o,change24h:u,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=_n(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 Qr={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"}},Bn=60*1e3,St=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;assetMetaCache=null;assetMetaPending=null;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||Qr[this.environment].api,this._wsEndpoint=t.wsEndpoint||Qr[this.environment].ws,this.timeout=t.timeout||3e4;}async request(t,r){let s=`${this.apiEndpoint}${t}`;try{let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout),o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(i),!o.ok)throw new le(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new le(`Request timeout after ${this.timeout}ms`,408,""):n instanceof le?n:new le(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){let[t]=await this.request("/info",{type:"metaAndAssetCtxs"});return t.universe.map(r=>`${r.name}-USDC`)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let[r,s]=await this.request("/info",{type:"metaAndAssetCtxs"}),n=r.universe.map((i,o)=>{let a=s[o],l=`${i.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),p=a.prevDayPx?parseFloat(a.prevDayPx):u,c=p>0?(u-p)/p*100:0;return {symbol:l,price:u,change24h:c,volume24h:parseFloat(a.dayNtlVlm||"0"),fundingRate:parseFloat(a.funding||"0"),openInterest:parseFloat(a.openInterest||"0"),markPrice:parseFloat(a.markPx||"0"),indexPrice:parseFloat(a.oraclePx||a.midPx||"0")}});if(t&&t.length>0){let i=new Set(t);return n.filter(o=>i.has(o.symbol))}return n}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),i=typeof s=="number"?{limit:s}:s,o=this.parseInterval(r),a=i.limit,l,u;i.from!==void 0&&i.to!==void 0?(l=i.from,u=i.to):i.to!==void 0&&a?(u=i.to,l=u-o*a):i.from!==void 0&&a?(l=i.from,u=l+o*a):(u=Date.now(),l=u-o*(a??100));let c=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:u}})).map(d=>({symbol:t,open:parseFloat(d.o),high:parseFloat(d.h),low:parseFloat(d.l),close:parseFloat(d.c),volume:parseFloat(d.v),timestamp:d.t,closeTimestamp:d.T}));return a&&c.length>a&&(c=c.slice(c.length-a)),c}async getOrderBook(t,r=10,s){let i={type:"l2Book",coin:this.symbolToCoin(t)};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa));let o=await this.request("/info",i),[a,l]=o.levels;return {symbol:t,bids:a.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),asks:l.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),timestamp:o.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(i=>({symbol:t,side:i.side==="B"?"buy":"sell",price:parseFloat(i.px),quantity:parseFloat(i.sz),timestamp:i.time,tradeId:i.tid}))}async placeOrder(t){throw new Error("placeOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async cancelOrder(t){throw new Error("cancelOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async getPositions(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let[r,s,n]=await Promise.all([this.request("/info",{type:"clearinghouseState",user:t.userAddress}),this.request("/info",{type:"frontendOpenOrders",user:t.userAddress}),this.request("/info",{type:"metaAndAssetCtxs"})]),i=zr(r,t.symbol),o=Wr(n);return i.positions=$r(i.positions,s,o),i.totalUnrealizedPnl=i.positions.reduce((a,l)=>a+l.unrealizedPnl,0),i}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 le&&(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<Bn)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=await this.request("/info",{type:"openOrders",user:t.userAddress}),s=r.map(Kr),n=t.symbol?s.filter(i=>i.symbol===t.symbol):s;return {orders:n,totalCount:n.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"userFills",user:t.userAddress}),s=r.map(n=>{let i=`${n.coin}-USDC`,o=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:i,side:o?"long":"short",price:parseFloat(n.px),quantity:parseFloat(n.sz),fee:parseFloat(n.fee||"0"),feeCurrency:n.feeToken||"USDC",isMaker:n.side==="M",timestamp:n.time}});return t.symbol&&(s=s.filter(n=>n.symbol===t.symbol)),t.startTime&&(s=s.filter(n=>n.timestamp>=t.startTime)),t.endTime&&(s=s.filter(n=>n.timestamp<=t.endTime)),t.limit&&(s=s.slice(0,t.limit)),{trades:s,totalCount:s.length,raw:r}}async connectWebSocket(){this.wsRefCount+=1,this.wsManager||(this.wsManager=new ke(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(Qn(s));})}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}};function zr(e,t){let r=e.assetPositions.map(o=>{let a=o.position,l=`${a.coin}-USDC`,u=parseFloat(a.szi);if(u===0)return null;let p=parseFloat(a.entryPx),c=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:u>0?"long":"short",quantity:Math.abs(u),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:p,markPrice:p,unrealizedPnl:c,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 Kr(e){let t=`${e.coin}-USDC`,r=parseFloat(e.origSz),s=parseFloat(e.sz),n=r-s,i=e.side===true||e.side==="B",o=typeof e.orderType=="string"?e.orderType:"Limit",l=/^market$/i.test(o)?"market":"limit",u=e.isTrigger===true,p;u&&(/take\s*profit/i.test(o)?p="tp":/stop/i.test(o)&&(p="sl"));let c=typeof e.triggerPx=="string"&&e.triggerPx.length>0?parseFloat(e.triggerPx):void 0,d=typeof e.triggerCondition=="string"&&e.triggerCondition!=="N/A"?e.triggerCondition:void 0;return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:t,side:i?"long":"short",orderType:l,price:parseFloat(e.limitPx),quantity:r,filledQuantity:n,remainingQuantity:s,status:n>0&&s>0?"partially_filled":"pending",timestamp:e.timestamp,updateTimestamp:e.timestamp,reduceOnly:e.reduceOnly===true,isTrigger:u||void 0,triggerPx:c,triggerType:p,triggerCondition:d}}function Hn(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 Qn(e){let t=e.clearinghouseState,r=t?zr(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=s.map(Kr),i=Hn(e.spotState?.balances),o=e.meta&&e.assetCtxs?Wr([e.meta,e.assetCtxs]):null,a=$r(r.positions,s,o),l=a.reduce((u,p)=>u+p.unrealizedPnl,0);return {positions:a,openOrders:n,spotBalances:i,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:l,serverTime:e.serverTime,raw:e}}function Wr(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 zn(e,t){let r=e.symbol.split("-")[0],s=e.side==="long"?"A":"B",n=s==="B",i,o;for(let a of t){if(a.coin!==r||a.reduceOnly!==true||a.isTrigger!==true||!(a.side===s||a.side===n))continue;let u=typeof a.orderType=="string"?a.orderType:"",p=/take\s*profit/i.test(u),c=/stop/i.test(u);p?(!i||a.timestamp>i.timestamp)&&(i=a):c&&(!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 $r(e,t,r){return e.map(s=>{let n={...s},{tp:i,sl:o}=zn(s,t);n.takeProfitPrice=i,n.stopLossPrice=o;let a=s.symbol.split("-")[0],l=r?.get(a);if(l&&Number.isFinite(l)&&l>0){n.markPrice=l;let u=s.side==="long"?1:-1,p=(l-s.entryPrice)*s.quantity*u;n.unrealizedPnl=p,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=p/s.margin*100);}return n})}var le=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var j=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Kn=3e4,ge=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??Kn,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 Wn(a);throw new j(`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 j)throw a;if(a instanceof Error&&a.name==="AbortError")throw new j(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new j(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(o);}}};async function Wn(e){try{return await e.text()}catch{return ""}}var $n="wss://api.hyperliquid.xyz/ws",Pt=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 ge({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??$n,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 j&&r.statusCode===404)return null;throw r}}async getMarkets(t){return this.transport.request("GET",{path:"/v1/markets",query:t&&t.length>0?{symbols:t.join(",")}:void 0})}async getKlines(t,r,s=100){let n=typeof s=="number"?{limit:s}:s,i={interval:r};return n.limit!==void 0&&(i.limit=String(n.limit)),n.from!==void 0&&(i.start=String(n.from)),n.to!==void 0&&(i.end=String(n.to)),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:i})}async getOrderBook(t,r=10,s){let n={maxLevel:String(r)};return s?.nSigFigs!==void 0&&(n.nSigFigs=String(s.nSigFigs),s.nSigFigs===5&&s.mantissa&&s.mantissa!==1&&(n.mantissa=String(s.mantissa))),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/orderbook`,query:n})}async getRecentTrades(t,r=50){return this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/trades`,query:{limit:String(r)}})}async getPositions(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getPositions requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/positions`,query:{symbol:t.symbol}});return {positions:r.positions,totalEquity:r.account?.totalEquity,availableBalance:r.account?.availableBalance,totalUnrealizedPnl:r.account?.totalUnrealizedPnl,raw:r}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getOpenOrders requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/orders`,query:{symbol:t.symbol}});return {orders:r,totalCount:r.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getTrades requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/fills`,query:{symbol:t.symbol,limit:t.limit!==void 0?String(t.limit):void 0,startTime:t.startTime!==void 0?String(t.startTime):void 0,endTime:t.endTime!==void 0?String(t.endTime):void 0}}),s=r.map(n=>({tradeId:n.tradeId,orderId:n.orderId,symbol:n.symbol,side:n.side,price:n.price,quantity:n.quantity,fee:n.fee,feeCurrency:n.feeCurrency,isMaker:n.isMaker,timestamp:n.timestamp}));return {trades:s,totalCount:s.length,raw:r}}async 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 ke(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 vt=class{transport;constructor(t){this.transport="transport"in t?t.transport:new ge(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 Me=new Set(["settled","refunded","failed"]);var Je={phase:"idle"};function Ct(e,t){switch(t.type){case "RESET":return Je;case "QUOTE_REQUEST":return e.phase==="idle"||e.phase==="ready_to_sign"||e.phase==="expired"||e.phase==="failed"?{phase:"quoting"}:e;case "QUOTE_RECEIVED":return e.phase==="quoting"?{phase:"ready_to_sign",quote:t.quote,expiresAtMs:Date.parse(t.quote.expiresAt)}:e;case "QUOTE_FAILED":return e.phase==="quoting"?{phase:"failed",error:t.error}:e;case "QUOTE_EXPIRED":return e.phase==="ready_to_sign"?{phase:"expired",quote:e.quote}:e;case "SIGN_START":return e.phase==="ready_to_sign"?{phase:"signing",quote:e.quote}:e;case "SIGN_FAILED":return e.phase==="signing"?{phase:"failed",error:t.error}:e;case "BROADCAST_START":return e.phase==="signing"?{phase:"broadcasting",quote:e.quote}:e;case "BROADCAST_FAILED":return e.phase==="broadcasting"||e.phase==="signing"?{phase:"failed",error:t.error}:e;case "SUBMIT_OK":return e.phase==="broadcasting"?{phase:"submitted",quote:e.quote,intentId:t.intentId,solanaTxHash:t.solanaTxHash}:e;case "SUBMIT_FAILED":return e.phase==="broadcasting"?{phase:"failed",error:t.error}:e;case "STATUS_UPDATE":{if(e.phase!=="submitted"&&e.phase!=="tracking")return e;let r=(e.phase==="submitted",e.intentId);return Gn(t.status,r)}}}function Gn(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 Vn(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function jn(e){return e.phase==="submitted"||e.phase==="tracking"}function Yn(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Xn(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 Jn(e){return e!==void 0&&Me.has(e)}var ue=createContext({});function ti({client:e,depositClient:t,children:r}){let s=useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsx(ue.Provider,{value:s,children:r})}function k(){let e=useContext(ue);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Gr(){return ["perps","coins"]}async function Vr(e){return await e.getSupportedCoins()}function Tt(e={}){let{client:t}=k();return useQuery({queryKey:Gr(),queryFn:async()=>Vr(t),staleTime:300*1e3,...e})}var jr=6e4;function Yr(e){return ["perps","market",e.symbol]}async function Xr(e,{symbol:t}){return await e.getMarket(t)}function Le(e,t={}){let{client:r}=k();return useQuery({queryKey:Yr(e),queryFn:async()=>Xr(r,e),staleTime:jr/2,refetchInterval:jr,...t})}var Jr=6e4;function Zr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function es(e,{symbols:t}={}){return await e.getMarkets(t)}function Dt(e={},t={}){let{client:r}=k();return useQuery({queryKey:Zr(e),queryFn:async()=>es(r,e),staleTime:Jr/2,refetchInterval:Jr,...t})}function ts(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function rs(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function li(e,t={}){let{client:r}=k();return useQuery({queryKey:ts(e),queryFn:async()=>rs(r,e),staleTime:30*1e3,...t})}function ss(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 ns(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function kt(e,t={}){let{client:r}=k();return useQuery({queryKey:ss(e),queryFn:async()=>ns(r,e),staleTime:5*1e3,...t})}function is(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function os(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function Ot(e,t={}){let{client:r}=k();return useQuery({queryKey:is(e),queryFn:async()=>os(r,e),staleTime:5*1e3,...t})}function Ze(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function as(e,t){return await e.getPositions(t)}function qe(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:Ze(n),queryFn:async()=>as(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function et(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function ls(e,t){return await e.getOpenOrders(t)}function wt(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:et(n),queryFn:async()=>ls(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function us(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function ps(e,t){return await e.getTrades(t)}function Rt(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:us(n),queryFn:async()=>ps(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function cs(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function ds(e,t){return await e.getActiveAssetLeverage(t)}function Et(e,t={}){let{client:r}=k(),{enabled:s=true,userAddress:n,symbol:i}=e;return useQuery({queryKey:cs({userAddress:n,symbol:i}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return ds(r,{userAddress:n,symbol:i})},enabled:s&&!!n&&!!i,staleTime:30*1e3,...t})}function ms(e){return ["perps","assetMeta",e.symbol??""]}async function fs(e,t){return await e.getAssetMeta(t)}function At(e,t={}){let{client:r}=k(),{enabled:s=true,symbol:n}=e;return useQuery({queryKey:ms({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return fs(r,{symbol:n})},enabled:s&&!!n,staleTime:60*1e3,...t})}async function gs(e,t){return await e.placeOrder(t)}function _e(e={}){let{client:t}=k();return useMutation({mutationFn:async r=>gs(t,r),...e})}async function ys(e,t){return await e.cancelOrder(t)}function Nt(e={}){let{client:t}=k();return useMutation({mutationFn:async r=>ys(t,r),...e})}function ye(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=k(),[a,l]=useState(null),[u,p]=useState(false),[c,d]=useState(null),f=useRef(null),m=useRef(null),y=useRef(i);y.current=i;let D=useCallback(x=>{let C=y.current;if(!C||C<=0){l(x);return}f.current=x,m.current===null&&(m.current=setTimeout(()=>{if(m.current=null,f.current!==null){let E=f.current;f.current=null,l(E);}},C));},[]),h=n?.nSigFigs!==void 0?`n${n.nSigFigs}${n.nSigFigs===5&&n.mantissa&&n.mantissa!==1?`m${n.mantissa}`:""}`:"";return useEffect(()=>{if(!s)return;let x=null,C=true;return (async()=>{try{if(await o.connectWebSocket(),!C)return;p(!0),d(null),x=o.subscribeMarketData(t,r,D,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(w){C&&(d(w instanceof Error?w:new Error("Connection failed")),p(false));}})(),()=>{if(C=false,x)try{o.unsubscribe(x);}catch(w){console.error("Failed to unsubscribe:",w);}o.disconnectWebSocket(),m.current!==null&&(clearTimeout(m.current),m.current=null),f.current=null,p(false),l(null);}},[o,t,r,s,D,h]),{data:a,isConnected:u,error:c}}function vi(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=k(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null),c=useCallback(d=>{o(d);},[]);return useEffect(()=>{if(!s)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),p(null),d=n.subscribeCandles(t,r,c);}catch(y){f&&(p(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:a,error:u}}function Lt(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=k(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null),c=useCallback(d=>{o(d);},[]);return useEffect(()=>{if(!s||!r)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),p(null),d=n.subscribeUserData(t,r,c);}catch(y){f&&(p(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:a,error:u}}function tt(e){return ["perps","accountState",e.userAddress??""]}function qt(e,t={}){let{enabled:r=true,...s}=e;return useQuery({queryKey:tt(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function wi(e){let{userAddress:t,enabled:r=true}=e,{client:s}=k(),n=useQueryClient(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null);return useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let c=null,d=true,f=y=>{if(!d)return;o(y),n.setQueryData(tt({userAddress:t}),y);let D={positions:y.positions,totalEquity:y.totalEquity,availableBalance:y.availableBalance,totalUnrealizedPnl:y.totalUnrealizedPnl,raw:y.raw};n.setQueryData(Ze({userAddress:t}),D);let h={orders:y.openOrders,totalCount:y.openOrders.length,raw:y.raw};n.setQueryData(et({userAddress:t}),h);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),p(null),c=s.subscribeAccountState(t,f);}catch(y){if(!d)return;l(false),p(y instanceof Error?y:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,c)try{s.unsubscribe(c);}catch(y){console.error("[useAccountStateSubscription] unsubscribe failed:",y);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:i,isConnected:a,error:u}}function Ri(){let e=useContext(ue);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 be(){return useContext(ue)?.depositClient}function hs(e){return ["perps","deposit","quote",e]}async function xs(e,t){return e.quote(t)}function Bt(e,t={}){let r=be(),s=(t.enabled??!!Ai(e))&&!!r;return useQuery({queryKey:hs(e??null),queryFn:async()=>xs(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Ai(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function Ht(e){let t=be(),[r,s]=useReducer(Ct,Je),n=useCallback(()=>{s({type:"RESET"});},[]),i=useCallback(async o=>{let{quote:a}=o;s({type:"SIGN_START"});let l;try{if(l=await e(a.serializedTxBase64,{isVersioned:a.isVersioned,sizeBytes:a.sizeBytes}),!l)throw new Error("wallet returned an empty tx hash")}catch(p){let c=Ps(p,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:c}),p}s({type:"BROADCAST_START"});let u={userSolanaAddress:o.userSolanaAddress,hyperliquidRecipient:o.hyperliquidRecipient,solanaTxHash:l,breakdown:a.breakdown,userId:o.userId,source:o.source,campaign:o.campaign,quoteIssuedAt:a.issuedAt};if(!t)throw s({type:"SUBMIT_FAILED",error:{code:"DEPOSIT_CLIENT_NOT_CONFIGURED",message:"Deposit client is not configured.",recoverable:false}}),new Error("Deposit client is not configured.");try{let p=await t.submit(u);return s({type:"SUBMIT_OK",intentId:p.intentId,solanaTxHash:l}),p.intentId}catch(p){let c=Ps(p,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:c}),p}},[t,e]);return {state:r,execute:i,reset:n,dispatch:s}}function Ps(e,t){if(e instanceof j){let r=Ii(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 Ii(e){if(e)try{return JSON.parse(e)}catch{return}}function vs(e){return ["perps","deposit","status",e??null]}async function Cs(e,t){return e.status(t)}function Qt(e,t={}){let r=be(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return useQuery({queryKey:vs(e??void 0),queryFn:async()=>Cs(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&Me.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var Be={phase:"idle",steps:[]};function rt(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Ui(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 st(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?Mi(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 Be}}function nt(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 Ui(e,t){return e.toLowerCase()===t.toLowerCase()}function Mi(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 ot(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,l]=useReducer(st,Be),u=useRef(t),p=useRef(s),c=useRef(i),d=useRef(o);u.current=t,p.current=s,c.current=i,d.current=o;let f=useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let x=await u.current.getAccountState(r),C=p.current.map(E=>({step:E,status:rt(E,x)}));l({type:"LOAD_SUCCESS",accountState:x,steps:C});}catch(x){let C=Ds(x);l({type:"LOAD_ERROR",error:C.message}),d.current?.(C,{});}}},[r]);useEffect(()=>{n&&r&&f();},[n,r,f]);let m=useCallback(async x=>{let C=a.steps[x];if(C){l({type:"RUN_STEP",index:x});try{let E=await qi(u.current,C.step);l({type:"STEP_SUCCESS",index:x,txHash:E.txHash,accountState:E.state});}catch(E){let w=Ds(E);l({type:"STEP_ERROR",index:x,error:w.message}),d.current?.(w,{stepId:C.step.id});}}},[a.steps]),y=useCallback(async()=>{let x=nt(a);x!=null&&await m(x);},[a,m]),D=useCallback(()=>l({type:"RESET"}),[]),h=useRef(false);return useEffect(()=>{a.phase==="done"&&!h.current?(h.current=true,c.current?.(a)):a.phase!=="done"&&(h.current=false);},[a]),{state:a,reload:f,runNext:y,runStep:m,reset:D}}function qi(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 Ds(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function zt(){return jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}var Os="liberfi-perp-shimmer",_i=`
|
|
1
|
+
import {createContext,memo,useMemo,useContext,useState,useRef,useCallback,useEffect,useReducer}from'react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useQuery,useMutation,useQueryClient}from'@tanstack/react-query';import {SearchIcon,StyledTooltip,RHForm,RHNumberInput,Spinner,cn,Button,Modal,ModalContent,ModalHeader,ModalBody,ModalFooter,Input,StyledModal,XCloseIcon,Card,CardBody,CardHeader,CardFooter,Slider}from'@liberfi.io/ui';import {List}from'react-window';import {useResizeObserver,useTickAge}from'@liberfi.io/hooks';import {useForm}from'react-hook-form';import {useAuthCallback}from'@liberfi.io/wallet-connector';import {useTranslation}from'@liberfi.io/i18n';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-perpetuals"]="0.2.21");var qn="0.2.21";function _n(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 ke=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,u=l>0?(o-l)/l*100:0;return {symbol:n,price:o,change24h:u,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=_n(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 Qr={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"}},Bn=60*1e3,St=class{apiEndpoint;_wsEndpoint;timeout;environment;wsManager=null;wsRefCount=0;assetMetaCache=null;assetMetaPending=null;constructor(t={}){this.environment=t.environment||"testnet",this.apiEndpoint=t.apiEndpoint||Qr[this.environment].api,this._wsEndpoint=t.wsEndpoint||Qr[this.environment].ws,this.timeout=t.timeout||3e4;}async request(t,r){let s=`${this.apiEndpoint}${t}`;try{let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout),o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal});if(clearTimeout(i),!o.ok)throw new le(`HTTP ${o.status}: ${o.statusText}`,o.status,await o.text());return await o.json()}catch(n){throw n.name==="AbortError"?new le(`Request timeout after ${this.timeout}ms`,408,""):n instanceof le?n:new le(`Network error: ${n.message}`,0,"")}}symbolToCoin(t){return t.split("-")[0]}parseInterval(t){return {"1m":6e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"4h":144e5,"1d":864e5,"1w":6048e5}[t]}async getSupportedCoins(){let[t]=await this.request("/info",{type:"metaAndAssetCtxs"});return t.universe.map(r=>`${r.name}-USDC`)}async getMarket(t){let r=await this.getMarkets([t]);return r.length>0?r[0]:null}async getMarkets(t){let[r,s]=await this.request("/info",{type:"metaAndAssetCtxs"}),n=r.universe.map((i,o)=>{let a=s[o],l=`${i.name}-USDC`,u=parseFloat(a.midPx||a.markPx||"0"),p=a.prevDayPx?parseFloat(a.prevDayPx):u,c=p>0?(u-p)/p*100:0;return {symbol:l,price:u,change24h:c,volume24h:parseFloat(a.dayNtlVlm||"0"),fundingRate:parseFloat(a.funding||"0"),openInterest:parseFloat(a.openInterest||"0"),markPrice:parseFloat(a.markPx||"0"),indexPrice:parseFloat(a.oraclePx||a.midPx||"0")}});if(t&&t.length>0){let i=new Set(t);return n.filter(o=>i.has(o.symbol))}return n}async getKlines(t,r,s=100){let n=this.symbolToCoin(t),i=typeof s=="number"?{limit:s}:s,o=this.parseInterval(r),a=i.limit,l,u;i.from!==void 0&&i.to!==void 0?(l=i.from,u=i.to):i.to!==void 0&&a?(u=i.to,l=u-o*a):i.from!==void 0&&a?(l=i.from,u=l+o*a):(u=Date.now(),l=u-o*(a??100));let c=(await this.request("/info",{type:"candleSnapshot",req:{coin:n,interval:r,startTime:l,endTime:u}})).map(d=>({symbol:t,open:parseFloat(d.o),high:parseFloat(d.h),low:parseFloat(d.l),close:parseFloat(d.c),volume:parseFloat(d.v),timestamp:d.t,closeTimestamp:d.T}));return a&&c.length>a&&(c=c.slice(c.length-a)),c}async getOrderBook(t,r=10,s){let i={type:"l2Book",coin:this.symbolToCoin(t)};s?.nSigFigs!==void 0&&(i.nSigFigs=s.nSigFigs,s.nSigFigs===5&&s.mantissa!==void 0&&s.mantissa!==1&&(i.mantissa=s.mantissa));let o=await this.request("/info",i),[a,l]=o.levels;return {symbol:t,bids:a.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),asks:l.slice(0,r).map(u=>({price:parseFloat(u.px),quantity:parseFloat(u.sz),count:u.n})),timestamp:o.time}}async getRecentTrades(t,r=50){let s=this.symbolToCoin(t);return (await this.request("/info",{type:"recentTrades",coin:s})).slice(0,r).map(i=>({symbol:t,side:i.side==="B"?"buy":"sell",price:parseFloat(i.px),quantity:parseFloat(i.sz),timestamp:i.time,tradeId:i.tid}))}async placeOrder(t){throw new Error("placeOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async cancelOrder(t){throw new Error("cancelOrder() requires wallet private key configuration for EIP-712 signature. Please configure authentication before calling this method. See: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint")}async getPositions(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let[r,s,n]=await Promise.all([this.request("/info",{type:"clearinghouseState",user:t.userAddress}),this.request("/info",{type:"frontendOpenOrders",user:t.userAddress}),this.request("/info",{type:"metaAndAssetCtxs"})]),i=zr(r,t.symbol),o=Wr(n);return i.positions=$r(i.positions,s,o),i.totalUnrealizedPnl=i.positions.reduce((a,l)=>a+l.unrealizedPnl,0),i}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 le&&(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<Bn)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=await this.request("/info",{type:"openOrders",user:t.userAddress}),s=r.map(Kr),n=t.symbol?s.filter(i=>i.symbol===t.symbol):s;return {orders:n,totalCount:n.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("Hyperliquid requires userAddress parameter. Example: { userAddress: '0x...' }");let r=await this.request("/info",{type:"userFills",user:t.userAddress}),s=r.map(n=>{let i=`${n.coin}-USDC`,o=n.dir.includes("Long");return {tradeId:n.tid.toString(),orderId:n.oid.toString(),symbol:i,side:o?"long":"short",price:parseFloat(n.px),quantity:parseFloat(n.sz),fee:parseFloat(n.fee||"0"),feeCurrency:n.feeToken||"USDC",isMaker:n.side==="M",timestamp:n.time}});return t.symbol&&(s=s.filter(n=>n.symbol===t.symbol)),t.startTime&&(s=s.filter(n=>n.timestamp>=t.startTime)),t.endTime&&(s=s.filter(n=>n.timestamp<=t.endTime)),t.limit&&(s=s.slice(0,t.limit)),{trades:s,totalCount:s.length,raw:r}}async connectWebSocket(){this.wsRefCount+=1,this.wsManager||(this.wsManager=new ke(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(Qn(s));})}unsubscribe(t){this.wsManager&&this.wsManager.unsubscribe(t);}};function zr(e,t){let r=e.assetPositions.map(o=>{let a=o.position,l=`${a.coin}-USDC`,u=parseFloat(a.szi);if(u===0)return null;let p=parseFloat(a.entryPx),c=parseFloat(a.unrealizedPnl),d=parseFloat(a.positionValue);return {symbol:l,side:u>0?"long":"short",quantity:Math.abs(u),quantityRaw:a.szi.startsWith("-")?a.szi.slice(1):a.szi,entryPrice:p,markPrice:p,unrealizedPnl:c,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 Kr(e){let t=`${e.coin}-USDC`,r=parseFloat(e.origSz),s=parseFloat(e.sz),n=r-s,i=e.side===true||e.side==="B",o=typeof e.orderType=="string"?e.orderType:"Limit",l=/^market$/i.test(o)?"market":"limit",u=e.isTrigger===true,p;u&&(/take\s*profit/i.test(o)?p="tp":/stop/i.test(o)&&(p="sl"));let c=typeof e.triggerPx=="string"&&e.triggerPx.length>0?parseFloat(e.triggerPx):void 0,d=typeof e.triggerCondition=="string"&&e.triggerCondition!=="N/A"?e.triggerCondition:void 0;return {orderId:e.oid.toString(),clientOrderId:e.cloid??void 0,symbol:t,side:i?"long":"short",orderType:l,price:parseFloat(e.limitPx),quantity:r,filledQuantity:n,remainingQuantity:s,status:n>0&&s>0?"partially_filled":"pending",timestamp:e.timestamp,updateTimestamp:e.timestamp,reduceOnly:e.reduceOnly===true,isTrigger:u||void 0,triggerPx:c,triggerType:p,triggerCondition:d}}function Hn(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 Qn(e){let t=e.clearinghouseState,r=t?zr(t):{positions:[],totalEquity:0,availableBalance:0},s=e.openOrders??[],n=s.map(Kr),i=Hn(e.spotState?.balances),o=e.meta&&e.assetCtxs?Wr([e.meta,e.assetCtxs]):null,a=$r(r.positions,s,o),l=a.reduce((u,p)=>u+p.unrealizedPnl,0);return {positions:a,openOrders:n,spotBalances:i,totalEquity:r.totalEquity??0,availableBalance:r.availableBalance??0,totalUnrealizedPnl:l,serverTime:e.serverTime,raw:e}}function Wr(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 zn(e,t){let r=e.symbol.split("-")[0],s=e.side==="long"?"A":"B",n=s==="B",i,o;for(let a of t){if(a.coin!==r||a.reduceOnly!==true||a.isTrigger!==true||!(a.side===s||a.side===n))continue;let u=typeof a.orderType=="string"?a.orderType:"",p=/take\s*profit/i.test(u),c=/stop/i.test(u);p?(!i||a.timestamp>i.timestamp)&&(i=a):c&&(!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 $r(e,t,r){return e.map(s=>{let n={...s},{tp:i,sl:o}=zn(s,t);n.takeProfitPrice=i,n.stopLossPrice=o;let a=s.symbol.split("-")[0],l=r?.get(a);if(l&&Number.isFinite(l)&&l>0){n.markPrice=l;let u=s.side==="long"?1:-1,p=(l-s.entryPrice)*s.quantity*u;n.unrealizedPnl=p,n.notionalValue=l*s.quantity,s.margin>0&&(n.unrealizedPnlPercent=p/s.margin*100);}return n})}var le=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="HyperliquidApiError";}};var j=class extends Error{constructor(r,s,n){super(r);this.statusCode=s;this.responseBody=n;this.name="LiberFiApiError";}},Kn=3e4,ge=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??Kn,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 Wn(a);throw new j(`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 j)throw a;if(a instanceof Error&&a.name==="AbortError")throw new j(`Request timeout after ${i}ms: ${t} ${s}`,408,"");let l=a instanceof Error?a.message:String(a);throw new j(`Network error: ${t} ${s}: ${l}`,0,"")}finally{clearTimeout(o);}}};async function Wn(e){try{return await e.text()}catch{return ""}}var $n="wss://api.hyperliquid.xyz/ws",Pt=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 ge({baseUrl:t.baseUrl,timeout:t.timeout,headers:t.headers,defaultQuery:t.provider?{provider:t.provider}:void 0});}this.wsEndpoint=t.wsEndpoint??$n,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 j&&r.statusCode===404)return null;throw r}}async getMarkets(t){return this.transport.request("GET",{path:"/v1/markets",query:t&&t.length>0?{symbols:t.join(",")}:void 0})}async getKlines(t,r,s=100){let n=typeof s=="number"?{limit:s}:s,i={interval:r};return n.limit!==void 0&&(i.limit=String(n.limit)),n.from!==void 0&&(i.start=String(n.from)),n.to!==void 0&&(i.end=String(n.to)),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/klines`,query:i})}async getOrderBook(t,r=10,s){let n={maxLevel:String(r)};return s?.nSigFigs!==void 0&&(n.nSigFigs=String(s.nSigFigs),s.nSigFigs===5&&s.mantissa&&s.mantissa!==1&&(n.mantissa=String(s.mantissa))),this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/orderbook`,query:n})}async getRecentTrades(t,r=50){return this.transport.request("GET",{path:`/v1/markets/${encodeURIComponent(t)}/trades`,query:{limit:String(r)}})}async getPositions(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getPositions requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/positions`,query:{symbol:t.symbol}});return {positions:r.positions,totalEquity:r.account?.totalEquity,availableBalance:r.account?.availableBalance,totalUnrealizedPnl:r.account?.totalUnrealizedPnl,raw:r}}async getOpenOrders(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getOpenOrders requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/orders`,query:{symbol:t.symbol}});return {orders:r,totalCount:r.length,raw:r}}async getTrades(t={}){if(!t.userAddress)throw new Error("LiberFiPerpetualsClient.getTrades requires `userAddress`.");let r=await this.transport.request("GET",{path:`/v1/users/${encodeURIComponent(t.userAddress)}/fills`,query:{symbol:t.symbol,limit:t.limit!==void 0?String(t.limit):void 0,startTime:t.startTime!==void 0?String(t.startTime):void 0,endTime:t.endTime!==void 0?String(t.endTime):void 0}}),s=r.map(n=>({tradeId:n.tradeId,orderId:n.orderId,symbol:n.symbol,side:n.side,price:n.price,quantity:n.quantity,fee:n.fee,feeCurrency:n.feeCurrency,isMaker:n.isMaker,timestamp:n.timestamp}));return {trades:s,totalCount:s.length,raw:r}}async 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 ke(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 vt=class{transport;constructor(t){this.transport="transport"in t?t.transport:new ge(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 Me=new Set(["settled","refunded","failed"]);var Xe={phase:"idle"};function Ct(e,t){switch(t.type){case "RESET":return Xe;case "QUOTE_REQUEST":return e.phase==="idle"||e.phase==="ready_to_sign"||e.phase==="expired"||e.phase==="failed"?{phase:"quoting"}:e;case "QUOTE_RECEIVED":return e.phase==="quoting"?{phase:"ready_to_sign",quote:t.quote,expiresAtMs:Date.parse(t.quote.expiresAt)}:e;case "QUOTE_FAILED":return e.phase==="quoting"?{phase:"failed",error:t.error}:e;case "QUOTE_EXPIRED":return e.phase==="ready_to_sign"?{phase:"expired",quote:e.quote}:e;case "SIGN_START":return e.phase==="ready_to_sign"?{phase:"signing",quote:e.quote}:e;case "SIGN_FAILED":return e.phase==="signing"?{phase:"failed",error:t.error}:e;case "BROADCAST_START":return e.phase==="signing"?{phase:"broadcasting",quote:e.quote}:e;case "BROADCAST_FAILED":return e.phase==="broadcasting"||e.phase==="signing"?{phase:"failed",error:t.error}:e;case "SUBMIT_OK":return e.phase==="broadcasting"?{phase:"submitted",quote:e.quote,intentId:t.intentId,solanaTxHash:t.solanaTxHash}:e;case "SUBMIT_FAILED":return e.phase==="broadcasting"?{phase:"failed",error:t.error}:e;case "STATUS_UPDATE":{if(e.phase!=="submitted"&&e.phase!=="tracking")return e;let r=(e.phase==="submitted",e.intentId);return Gn(t.status,r)}}}function Gn(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 Vn(e){return e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"}function jn(e){return e.phase==="submitted"||e.phase==="tracking"}function Yn(e){if(e.phase==="tracking"||e.phase==="succeeded"||e.phase==="refunded"||e.phase==="failed"&&e.status)return e.status.status}function Jn(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 Xn(e){return e!==void 0&&Me.has(e)}var ue=createContext({});function ti({client:e,depositClient:t,children:r}){let s=useMemo(()=>({client:e,depositClient:t}),[e,t]);return jsx(ue.Provider,{value:s,children:r})}function k(){let e=useContext(ue);if(!e||!e.client)throw new Error("usePerpetualsClient must be used within a PerpetualsProvider");return e}function Gr(){return ["perps","coins"]}async function Vr(e){return await e.getSupportedCoins()}function Tt(e={}){let{client:t}=k();return useQuery({queryKey:Gr(),queryFn:async()=>Vr(t),staleTime:300*1e3,...e})}var jr=6e4;function Yr(e){return ["perps","market",e.symbol]}async function Jr(e,{symbol:t}){return await e.getMarket(t)}function Le(e,t={}){let{client:r}=k();return useQuery({queryKey:Yr(e),queryFn:async()=>Jr(r,e),staleTime:jr/2,refetchInterval:jr,...t})}var Xr=6e4;function Zr(e={}){return ["perps","markets",JSON.stringify((e.symbols??[]).sort())]}async function es(e,{symbols:t}={}){return await e.getMarkets(t)}function Dt(e={},t={}){let{client:r}=k();return useQuery({queryKey:Zr(e),queryFn:async()=>es(r,e),staleTime:Xr/2,refetchInterval:Xr,...t})}function ts(e){return ["perps","klines",e.symbol,e.interval,String(e.limit??100)]}async function rs(e,{symbol:t,interval:r,limit:s}){return await e.getKlines(t,r,s)}function li(e,t={}){let{client:r}=k();return useQuery({queryKey:ts(e),queryFn:async()=>rs(r,e),staleTime:30*1e3,...t})}function ss(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 ns(e,{symbol:t,maxLevel:r,aggregation:s}){return await e.getOrderBook(t,r,s)}function kt(e,t={}){let{client:r}=k();return useQuery({queryKey:ss(e),queryFn:async()=>ns(r,e),staleTime:5*1e3,...t})}function is(e){return ["perps","recentTrades",e.symbol,String(e.limit??50)]}async function os(e,{symbol:t,limit:r}){return await e.getRecentTrades(t,r)}function Ot(e,t={}){let{client:r}=k();return useQuery({queryKey:is(e),queryFn:async()=>os(r,e),staleTime:5*1e3,...t})}function Ze(e){return ["perps","positions",e.userAddress??"",e.symbol??""]}async function as(e,t){return await e.getPositions(t)}function qe(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:Ze(n),queryFn:async()=>as(r,n),enabled:s&&!!n.userAddress,staleTime:10*1e3,...t})}function et(e){return ["perps","orders",e.userAddress??"",e.symbol??""]}async function ls(e,t){return await e.getOpenOrders(t)}function wt(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:et(n),queryFn:async()=>ls(r,n),enabled:s&&!!n.userAddress,staleTime:5*1e3,...t})}function us(e){return ["perps","trades",e.userAddress??"",e.symbol??"",String(e.limit??50),String(e.startTime??""),String(e.endTime??"")]}async function ps(e,t){return await e.getTrades(t)}function Rt(e,t={}){let{client:r}=k(),{enabled:s=true,...n}=e;return useQuery({queryKey:us(n),queryFn:async()=>ps(r,n),enabled:s&&!!n.userAddress,staleTime:30*1e3,...t})}function cs(e){return ["perps","activeAssetLeverage",e.userAddress??"",e.symbol??""]}async function ds(e,t){return await e.getActiveAssetLeverage(t)}function Et(e,t={}){let{client:r}=k(),{enabled:s=true,userAddress:n,symbol:i}=e;return useQuery({queryKey:cs({userAddress:n,symbol:i}),queryFn:async()=>{if(!n)throw new Error("useActiveAssetLeverageQuery: userAddress is required");return ds(r,{userAddress:n,symbol:i})},enabled:s&&!!n&&!!i,staleTime:30*1e3,...t})}function ms(e){return ["perps","assetMeta",e.symbol??""]}async function fs(e,t){return await e.getAssetMeta(t)}function At(e,t={}){let{client:r}=k(),{enabled:s=true,symbol:n}=e;return useQuery({queryKey:ms({symbol:n}),queryFn:async()=>{if(!n)throw new Error("useAssetMetaQuery: symbol is required");return fs(r,{symbol:n})},enabled:s&&!!n,staleTime:60*1e3,...t})}async function gs(e,t){return await e.placeOrder(t)}function _e(e={}){let{client:t}=k();return useMutation({mutationFn:async r=>gs(t,r),...e})}async function ys(e,t){return await e.cancelOrder(t)}function Nt(e={}){let{client:t}=k();return useMutation({mutationFn:async r=>ys(t,r),...e})}function ye(e){let{type:t,symbol:r,enabled:s=true,aggregation:n,throttleMs:i}=e,{client:o}=k(),[a,l]=useState(null),[u,p]=useState(false),[c,d]=useState(null),f=useRef(null),m=useRef(null),y=useRef(i);y.current=i;let D=useCallback(x=>{let C=y.current;if(!C||C<=0){l(x);return}f.current=x,m.current===null&&(m.current=setTimeout(()=>{if(m.current=null,f.current!==null){let E=f.current;f.current=null,l(E);}},C));},[]),h=n?.nSigFigs!==void 0?`n${n.nSigFigs}${n.nSigFigs===5&&n.mantissa&&n.mantissa!==1?`m${n.mantissa}`:""}`:"";return useEffect(()=>{if(!s)return;let x=null,C=true;return (async()=>{try{if(await o.connectWebSocket(),!C)return;p(!0),d(null),x=o.subscribeMarketData(t,r,D,t==="orderBook"&&n?{aggregation:n}:void 0);}catch(w){C&&(d(w instanceof Error?w:new Error("Connection failed")),p(false));}})(),()=>{if(C=false,x)try{o.unsubscribe(x);}catch(w){console.error("Failed to unsubscribe:",w);}o.disconnectWebSocket(),m.current!==null&&(clearTimeout(m.current),m.current=null),f.current=null,p(false),l(null);}},[o,t,r,s,D,h]),{data:a,isConnected:u,error:c}}function vi(e){let{symbol:t,interval:r,enabled:s=true}=e,{client:n}=k(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null),c=useCallback(d=>{o(d);},[]);return useEffect(()=>{if(!s)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),p(null),d=n.subscribeCandles(t,r,c);}catch(y){f&&(p(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:a,error:u}}function Lt(e){let{type:t,userAddress:r,enabled:s=true}=e,{client:n}=k(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null),c=useCallback(d=>{o(d);},[]);return useEffect(()=>{if(!s||!r)return;let d=null,f=true;return (async()=>{try{if(await n.connectWebSocket(),!f)return;l(!0),p(null),d=n.subscribeUserData(t,r,c);}catch(y){f&&(p(y instanceof Error?y:new Error("Connection failed")),l(false));}})(),()=>{if(f=false,d)try{n.unsubscribe(d);}catch(y){console.error("Failed to unsubscribe:",y);}n.disconnectWebSocket(),l(false),o(null);}},[n,t,r,s,c]),{data:i,isConnected:a,error:u}}function tt(e){return ["perps","accountState",e.userAddress??""]}function qt(e,t={}){let{enabled:r=true,...s}=e;return useQuery({queryKey:tt(s),queryFn:()=>null,enabled:r&&!!s.userAddress,staleTime:1/0,refetchOnWindowFocus:false,refetchOnReconnect:false,...t})}function wi(e){let{userAddress:t,enabled:r=true}=e,{client:s}=k(),n=useQueryClient(),[i,o]=useState(null),[a,l]=useState(false),[u,p]=useState(null);return useEffect(()=>{if(!r||!t||typeof s.subscribeAccountState!="function")return;let c=null,d=true,f=y=>{if(!d)return;o(y),n.setQueryData(tt({userAddress:t}),y);let D={positions:y.positions,totalEquity:y.totalEquity,availableBalance:y.availableBalance,totalUnrealizedPnl:y.totalUnrealizedPnl,raw:y.raw};n.setQueryData(Ze({userAddress:t}),D);let h={orders:y.openOrders,totalCount:y.openOrders.length,raw:y.raw};n.setQueryData(et({userAddress:t}),h);};return (async()=>{try{if(await s.connectWebSocket(),!d)return;l(!0),p(null),c=s.subscribeAccountState(t,f);}catch(y){if(!d)return;l(false),p(y instanceof Error?y:new Error("WebSocket connect failed"));}})(),()=>{if(d=false,c)try{s.unsubscribe(c);}catch(y){console.error("[useAccountStateSubscription] unsubscribe failed:",y);}s.disconnectWebSocket(),l(false);}},[s,n,t,r]),{data:i,isConnected:a,error:u}}function Ri(){let e=useContext(ue);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 be(){return useContext(ue)?.depositClient}function hs(e){return ["perps","deposit","quote",e]}async function xs(e,t){return e.quote(t)}function Bt(e,t={}){let r=be(),s=(t.enabled??!!Ai(e))&&!!r;return useQuery({queryKey:hs(e??null),queryFn:async()=>xs(r,e),enabled:s,staleTime:0,gcTime:3e4,refetchOnWindowFocus:false,...t})}function Ai(e){return !!(e&&e.userSolanaAddress&&e.hyperliquidRecipient&&e.grossLamports&&e.source)}function Ht(e){let t=be(),[r,s]=useReducer(Ct,Xe),n=useCallback(()=>{s({type:"RESET"});},[]),i=useCallback(async o=>{let{quote:a}=o;s({type:"SIGN_START"});let l;try{if(l=await e(a.serializedTxBase64,{isVersioned:a.isVersioned,sizeBytes:a.sizeBytes}),!l)throw new Error("wallet returned an empty tx hash")}catch(p){let c=Ps(p,"WALLET_SIGN_OR_BROADCAST_FAILED");throw s({type:"SIGN_FAILED",error:c}),p}s({type:"BROADCAST_START"});let u={userSolanaAddress:o.userSolanaAddress,hyperliquidRecipient:o.hyperliquidRecipient,solanaTxHash:l,breakdown:a.breakdown,userId:o.userId,source:o.source,campaign:o.campaign,quoteIssuedAt:a.issuedAt};if(!t)throw s({type:"SUBMIT_FAILED",error:{code:"DEPOSIT_CLIENT_NOT_CONFIGURED",message:"Deposit client is not configured.",recoverable:false}}),new Error("Deposit client is not configured.");try{let p=await t.submit(u);return s({type:"SUBMIT_OK",intentId:p.intentId,solanaTxHash:l}),p.intentId}catch(p){let c=Ps(p,"DEPOSIT_SUBMIT_FAILED");throw s({type:"SUBMIT_FAILED",error:c}),p}},[t,e]);return {state:r,execute:i,reset:n,dispatch:s}}function Ps(e,t){if(e instanceof j){let r=Ii(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 Ii(e){if(e)try{return JSON.parse(e)}catch{return}}function vs(e){return ["perps","deposit","status",e??null]}async function Cs(e,t){return e.status(t)}function Qt(e,t={}){let r=be(),s=(t.enabled??!!e)&&!!r,n=t.pollIntervalMs??3e3;return useQuery({queryKey:vs(e??void 0),queryFn:async()=>Cs(r,e),enabled:s,refetchInterval:i=>{let o=i.state.data;return o&&Me.has(o.status)?false:n},refetchOnWindowFocus:false,staleTime:0,...t})}var Be={phase:"idle",steps:[]};function rt(e,t){switch(e.id){case "approveBuilderFee":{let r=t.builderApproval;return r&&Ui(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 st(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?Mi(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 Be}}function nt(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 Ui(e,t){return e.toLowerCase()===t.toLowerCase()}function Mi(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 ot(e){let{adapter:t,userAddress:r,steps:s,autoLoad:n=true,onComplete:i,onError:o}=e,[a,l]=useReducer(st,Be),u=useRef(t),p=useRef(s),c=useRef(i),d=useRef(o);u.current=t,p.current=s,c.current=i,d.current=o;let f=useCallback(async()=>{if(r){l({type:"START_LOADING"});try{let x=await u.current.getAccountState(r),C=p.current.map(E=>({step:E,status:rt(E,x)}));l({type:"LOAD_SUCCESS",accountState:x,steps:C});}catch(x){let C=Ds(x);l({type:"LOAD_ERROR",error:C.message}),d.current?.(C,{});}}},[r]);useEffect(()=>{n&&r&&f();},[n,r,f]);let m=useCallback(async x=>{let C=a.steps[x];if(C){l({type:"RUN_STEP",index:x});try{let E=await qi(u.current,C.step);l({type:"STEP_SUCCESS",index:x,txHash:E.txHash,accountState:E.state});}catch(E){let w=Ds(E);l({type:"STEP_ERROR",index:x,error:w.message}),d.current?.(w,{stepId:C.step.id});}}},[a.steps]),y=useCallback(async()=>{let x=nt(a);x!=null&&await m(x);},[a,m]),D=useCallback(()=>l({type:"RESET"}),[]),h=useRef(false);return useEffect(()=>{a.phase==="done"&&!h.current?(h.current=true,c.current?.(a)):a.phase!=="done"&&(h.current=false);},[a]),{state:a,reload:f,runNext:y,runStep:m,reset:D}}function qi(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 Ds(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error")}function zt(){return jsx("div",{className:"flex items-center justify-center px-4 py-3 bg-neutral-900 border-b border-neutral-800",children:jsx("span",{className:"text-neutral-400 text-sm",children:"Market data not available"})})}var Os="liberfi-perp-shimmer",_i=`
|
|
2
2
|
@keyframes ${Os}{0%{background-position:200% 0}100%{background-position:-200% 0}}
|
|
3
|
-
`;function pe(){return jsx("style",{children:_i})}var Kt={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:`${Os} 1.8s ease-in-out infinite`,borderRadius:6};function Y(e){return {...Kt,animationDelay:`${e}ms`}}function $t(){return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsx("div",{style:xe(0,84,23)}),jsx("div",{style:xe(60,52,16)})]}),jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsx(Wt,{labelWidth:72,valueWidth:64,delay:120}),jsx(Wt,{labelWidth:72,valueWidth:48,delay:180}),jsx(Wt,{labelWidth:84,valueWidth:56,delay:240}),jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsx("div",{style:xe(300,132,16)}),jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsx("div",{style:xe(330,64,17)}),jsx("div",{style:xe(360,64,17)})]})]})]})]})]})}function Wt({labelWidth:e,valueWidth:t,delay:r}){return jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsx("div",{style:xe(r,e,16)}),jsx("div",{style:xe(r+30,t,17)})]})}function xe(e,t,r){return {...Y(e),width:t,height:r}}function Vt(e){let[t,r]=useState(),[s,n]=useState(0),{data:i,isPending:o}=Le({symbol:e}),{data:a,isConnected:l}=ye({type:"ticker",symbol:e,enabled:!!i});return useEffect(()=>{i&&r(i);},[i]),useEffect(()=>{if(!a)return;let u=Qi(a,e);u&&r(p=>zi(p??i??void 0,u,e));},[a,i,e]),useEffect(()=>{let u=()=>{let c=Date.now(),d=3600*1e3,f=c%d,m=d-f;return Math.floor(m/1e3)};n(u());let p=setInterval(()=>{n(u());},1e3);return ()=>clearInterval(p)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function Qi(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 Oe(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function zi(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:Oe(t.price,e?.price??0),change24h:Oe(t.change24h,e?.change24h??0),volume24h:Oe(t.volume24h,e?.volume24h??0),fundingRate:Oe(t.fundingRate,e?.fundingRate??0),openInterest:Oe(t.openInterest,e?.openInterest??0),markPrice:Oe(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 Ki(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 Rs(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 Es(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 jt({marketData:e,fundingCountdown:t}){let{symbol:r,price:s,change24h:n,indexPrice:i,volume24h:o,openInterest:a,fundingRate:l}=e,u=typeof n=="number"&&Number.isFinite(n)?n:0,p=typeof l=="number"&&Number.isFinite(l)?l:0,c=u>=0,d=u.toFixed(2);return jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Es(s)}),jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:c?"#C7FF2E":"#F76816"},children:[c?"+":"",d,"%"]})]}),jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:i?Es(i):"-"})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Rs(o,0)})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Rs(a*(e.markPrice||s))})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:p>=0?"#C7FF2E":"#F76816"},children:[(p*100).toFixed(5),"%"]}),jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Ki(t)})]})]})]})]})}function Wi({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Vt(e);return r?jsx($t,{}):t?jsx(jt,{marketData:t,fundingCountdown:s}):jsx(zt,{})}function Xt({onSelectCoin:e}={}){let[t,r]=useState(""),[s,n]=useState([]),{data:i,isPending:o}=Tt(),{data:a,isPending:l}=Dt({symbols:i},{enabled:!!i&&i.length>0});useEffect(()=>{a&&n(a);},[a]);let u=useMemo(()=>{if(!t.trim())return s;let c=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(c))},[s,t]);return {coins:s,isLoading:o||l,searchQuery:t,setSearchQuery:r,filteredCoins:u,handleSelectCoin:c=>{e?.(c);}}}function Ns(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 ji(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Jt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsx("div",{style:{padding:"16px 16px 12px"},children:jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsx(SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsx("input",{type:"text",placeholder:"Search coins...",value:t,onChange:i=>r(i.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxs("div",{className:"flex-1 overflow-auto",children:[jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):e.length===0?jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:t?"No coins found":"No coins available"})}):e.map(i=>{let o=i.change24h>=0,a=i.change24h.toFixed(2),l=(i.fundingRate*100).toFixed(4),u=i.fundingRate>=0,p=i.symbol.split("-")[0];return jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(i.symbol),onMouseEnter:c=>{c.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent";},children:[jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsx("img",{src:`https://app.hyperliquid.xyz/coins/${p}.svg`,alt:p,className:"rounded-full",style:{width:20,height:20},onError:c=>{let d=c.target;d.style.display="none";}}),jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:p})]}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:ji(i.price)}),jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:o?"#C7FF2E":"#F76816",textAlign:"right"},children:[o?"+":"",a,"%"]}),jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:u?"#C7FF2E":"#F76816",textAlign:"right"},children:[l,"%"]}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ns(i.volume24h)}),jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ns(i.openInterest*i.price)})]},i.symbol)})]})]})}function Yi({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Xt({onSelectCoin:e});return jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsx(Jt,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function qs(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 Ms(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 Ls(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]=useState(null),[i,o]=useState(r);useEffect(()=>{o(r);},[r]);let{data:a,isPending:l}=kt({symbol:e,maxLevel:t}),u=useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,m=s?.asks[0]?.price??a?.asks[0]?.price,y=f&&m?(f+m)/2:m??f??0;return y>0?Math.floor(Math.log10(y)):null},[s,a]),p=useMemo(()=>{if(u===null)return;let f=Math.pow(10,u);return qs(f,i)},[i,u]),{data:c}=ye({type:"orderBook",symbol:e,enabled:!!a,aggregation:p,throttleMs:100});return useEffect(()=>{c?n(c):a&&n(a);},[c,a]),{...useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=Ms(s.bids,i,"bid"),m=Ms(s.asks,i,"ask"),y=f.sort((I,g)=>g.price-I.price).slice(0,t),D=m.sort((I,g)=>I.price-g.price).slice(0,t),h=Ls(y),x=Ls(D),C=h[0]?.price||0,w=(x[0]?.price||0)-C,N=C>0?w/C*100:0;return {bids:h,asks:x,spread:w,spreadPercentage:N}},[s,i,t]),isLoading:l,precision:i,setPrecision:o}}var Bs={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Zi={backgroundColor:"#000000",fontSize:11},eo={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},tr={flex:"1 1 0%"},to={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ro={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},so={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},no={color:"#F76816",fontWeight:400},io={color:"#C7FF2E",fontWeight:400},Hs={flex:"1 1 0%",color:"#ffffff"},oo={flex:"1 1 0%"},ao={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},lo={gap:12,fontSize:12,color:"#ffffff"},uo={color:"#ffffff"},po={color:"#ffffff",fontWeight:500},co={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},mo={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)"},Ws={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},fo={...Ws,color:"#C7FF2E"};function go(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 Qs(e){return Math.round(e).toLocaleString("en-US")}function zs(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var Ks=memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",l=useMemo(()=>a?{...ro,width:`${n}%`}:{...so,width:`${n}%`},[a,n]),u=useMemo(()=>o?()=>o(t):void 0,[o,t]);return jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:to,onClick:u,children:[jsx("div",{className:"absolute left-0 top-0",style:l}),jsx("div",{className:"relative z-10 flex items-center",style:oo,children:jsx("span",{style:a?no:io,children:go(t)})}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Hs,children:Qs(r)}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Hs,children:Qs(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 yo({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let[n,i]=useState(false),o=useRef(null);useEffect(()=>{if(!n)return;let l=u=>{o.current?.contains(u.target)||i(false);};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[n]);let a=useMemo(()=>({color:"#6b6b6b",transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[n]);return jsx("div",{className:"flex items-center justify-center",style:ao,children:jsxs("div",{className:"flex items-center",style:lo,children:[jsx("span",{style:uo,children:"Spread:"}),jsxs("div",{ref:o,className:"relative",children:[jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-white/80 transition-colors",style:co,onClick:()=>i(l=>!l),"aria-haspopup":"listbox","aria-expanded":n,children:[jsx("span",{children:zs(t)}),jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:a,children:jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:mo,children:r.map(l=>{let u=l===t;return jsx("button",{type:"button",role:"option","aria-selected":u,className:"cursor-pointer transition-colors",style:u?fo:Ws,onMouseEnter:p=>{p.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(l),i(false);},children:zs(l)},l)})})]}),jsxs("span",{style:po,children:[e.toFixed(3),"%"]})]})})}function sr({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let a=useRef(null),l=useRef(null),u=useRef(true),p=useRef(true),c=useMemo(()=>[...t].reverse(),[t]);useEffect(()=>{let m=a.current;if(!m||!u.current)return;let y=m.scrollHeight;m.scrollTop!==y&&(m.scrollTop=y);},[c]),useEffect(()=>{let m=l.current;!m||!p.current||m.scrollTop!==0&&(m.scrollTop=0);},[e]);let d=useCallback(()=>{let m=a.current;if(!m)return;let y=m.scrollHeight-m.scrollTop-m.clientHeight;u.current=y<=24;},[]),f=useCallback(()=>{let m=l.current;m&&(p.current=m.scrollTop<=24);},[]);return jsxs("div",{className:"flex flex-col h-full min-h-0",style:Zi,children:[jsxs("div",{className:"flex items-center flex-none",style:eo,children:[jsx("div",{className:"flex items-center",style:tr,children:"Price"}),jsx("div",{className:"flex items-center justify-end",style:tr,children:"Amount (USD)"}),jsx("div",{className:"flex items-center justify-end",style:tr,children:"Total (USD)"})]}),jsx("div",{ref:a,onScroll:d,className:"flex-1 min-h-0 overflow-y-auto",style:Bs,children:c.map((m,y)=>jsx(Ks,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"ask",onPriceClick:o},`ask-${m.price}-${y}`))}),jsx("div",{className:"flex-none",children:jsx(yo,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:Bs,children:e.map((m,y)=>jsx(Ks,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:o},`bid-${m.price}-${y}`))})]})}var Gs=[1,2,5,10,100,1e3],bo={backgroundColor:"#000000",fontSize:11},ho={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},we={flex:"1 1 0%"},xo={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},So={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function $s({delay:e}){return jsxs("div",{className:"flex items-center",style:xo,children:[jsx("div",{style:we,children:jsx("div",{style:{...Y(e),height:11,width:56}})}),jsx("div",{className:"flex justify-end",style:we,children:jsx("div",{style:{...Y(e+30),height:11,width:64}})}),jsx("div",{className:"flex justify-end",style:we,children:jsx("div",{style:{...Y(e+60),height:11,width:64}})})]})}function Po(){let e=Array.from({length:8},(r,s)=>s),t=Array.from({length:8},(r,s)=>s);return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex flex-col h-full min-h-0",style:bo,children:[jsxs("div",{className:"flex items-center flex-none",style:ho,children:[jsx("div",{className:"flex items-center",style:we,children:"Price"}),jsx("div",{className:"flex items-center justify-end",style:we,children:"Amount (USD)"}),jsx("div",{className:"flex items-center justify-end",style:we,children:"Total (USD)"})]}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsx($s,{delay:r*40},`ask-${r}`))}),jsx("div",{className:"flex-none flex items-center justify-center",style:So,children:jsx("div",{style:{...Y(0),width:96,height:12}})}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsx($s,{delay:200+r*40},`bid-${r}`))})]})]})}function vo(){return jsx("div",{className:"flex items-center justify-center h-full",children:jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function Co({symbol:e,maxLevel:t=40,precisionOptions:r=Gs,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:l,spreadPercentage:u,isLoading:p,precision:c,setPrecision:d}=er({symbol:e,maxLevel:t,precision:o});return p?jsx(Po,{}):a.length===0&&l.length===0?jsx(vo,{}):jsx("div",{className:i,children:jsx(sr,{bids:a,asks:l,spreadPercentage:u,precision:c,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var ko=200;function or({symbol:e,limit:t=50}){let[r,s]=useState([]),{data:n,isPending:i}=Ot({symbol:e,limit:t}),{data:o}=ye({type:"trades",symbol:e,enabled:!!n});useEffect(()=>{n&&s(n.filter(Vs));},[n]);let a=useRef([]),l=useRef(null),u=useRef(t);return u.current=t,useEffect(()=>{if(!o)return;let p=Oo(o);p.length!==0&&(a.current.push(...p),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let c=a.current;a.current=[],c.length!==0&&s(d=>{let f=c.filter(m=>!d.some(y=>y.timestamp===m.timestamp&&y.price===m.price&&y.quantity===m.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,u.current)});},ko)));},[o]),useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function Oo(e){return (Array.isArray(e)?e:[e]).filter(Vs)}function Vs(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 ut=22,js=28,Ys=100,Xs=120,No={backgroundColor:"#000000",fontSize:11},Io={height:js,minHeight:js,padding:"0 16px",color:"#6b6b6b",fontSize:11},Fo={flex:"1 1 0%",maxWidth:Ys},Uo={flex:"1 1 0%",marginLeft:20},Mo={flex:"1 1 0%",maxWidth:Xs,textAlign:"right"},Lo={height:ut,minHeight:ut,maxHeight:ut,padding:"0 16px"},qo={flex:"1 1 0%",maxWidth:Ys},_o={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Bo={flex:"1 1 0%",maxWidth:Xs,textAlign:"right",color:"#777A8C"},Ho={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},Qo={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function zo(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 Ko(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"-"}function Wo(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 $o(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Go({index:e,style:t,trades:r,onTradeClick:s}){let n=r[e],i=n?.timestamp??Date.now(),o=useTickAge(i),a=useMemo(()=>!n||!Number.isFinite(n.price)||!Number.isFinite(n.quantity)?0:n.price*n.quantity,[n]),l=useMemo(()=>({...n?.side==="buy"?Ho:Qo,width:`${$o(a)}%`}),[n,a]);if(!n)return null;let u=n.side==="buy";return jsx("div",{style:t,children:jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Lo,onClick:s?()=>s(n):void 0,children:[jsx("div",{style:l}),jsx("div",{className:"relative z-10 flex items-center",style:qo,children:jsx("span",{className:u?"text-bullish":"text-bearish",children:zo(n.price)})}),jsx("div",{className:"relative z-10 flex items-center",style:_o,children:Ko(a)}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Bo,children:Wo(o)})]})})}function ur({trades:e,onTradeClick:t}){let r=useRef(null),{height:s=0}=useResizeObserver({ref:r}),n=useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxs("div",{className:"flex flex-col h-full",style:No,children:[jsxs("div",{className:"flex items-center flex-none",style:Io,children:[jsx("div",{style:Fo,children:"Price"}),jsx("div",{style:Uo,children:"Size (USD)"}),jsx("div",{style:Mo,children:"Age"})]}),jsx("div",{ref:r,className:"flex-1 min-h-0",children:s>0&&jsx(List,{style:{height:s},rowComponent:Go,rowCount:e.length,rowHeight:ut,rowProps:n,overscanCount:4})})]})}var Vo={backgroundColor:"#000000",fontSize:11},jo={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},Js={flex:"1 1 0%",maxWidth:100},Zs={flex:"1 1 0%",marginLeft:20},en={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Yo={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Xo({delay:e}){return jsxs("div",{className:"flex items-center",style:Yo,children:[jsx("div",{style:Js,children:jsx("div",{style:{...Y(e),height:11,width:56}})}),jsx("div",{style:Zs,children:jsx("div",{style:{...Y(e+30),height:11,width:64}})}),jsx("div",{className:"flex justify-end",style:en,children:jsx("div",{style:{...Y(e+60),height:11,width:28}})})]})}function Jo(){let e=Array.from({length:12},(t,r)=>r);return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex flex-col h-full",style:Vo,children:[jsxs("div",{className:"flex items-center flex-none",style:jo,children:[jsx("div",{style:Js,children:"Price"}),jsx("div",{style:Zs,children:"Size (USD)"}),jsx("div",{style:en,children:"Age"})]}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsx(Xo,{delay:t*35},`trade-${t}`))})]})]})}function Zo(){return jsx("div",{className:"flex items-center justify-center h-full",children:jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function ea({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=or({symbol:e,limit:t});return i?jsx(Jo,{}):n.length===0?jsx(Zo,{}):jsx("div",{className:s,children:jsx(ur,{trades:n,onTradeClick:r})})}function tn(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function rn(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:tn(s,n)*(e-t)/t*r*100}function ze(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let i=tn(s,n),o=e/r/100;return t*(1+i*o)}function sn(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 nn(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var oa=20;function cr({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:o}){let[a,l]=useState("long"),[u,p]=useState("market"),c=useForm({defaultValues:{amount:void 0,leverage:oa,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=Le({symbol:e}),{data:f}=At({symbol:e}),m=f?.szDecimals,y=f?.maxLeverage??r,{mutateAsync:D,isPending:h}=_e({onSuccess:()=>{c.reset(),s?.();},onError:v=>{n?.(v);}}),x=useMutation({mutationFn:async v=>{if(!o)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await o(v)},onSuccess:()=>{c.reset(),s?.();},onError:v=>{n?.(v);}}),C=h||x.isPending,E=c.watch(),{amount:w,leverage:N,price:I}=E,g=useMemo(()=>u==="limit"&&I?I:d?.price||0,[u,I,d?.price]),z=useMemo(()=>!w||w<=0||!N?0:w*N,[w,N]),H=useMemo(()=>z?z*5e-4:0,[z]),L=useMemo(()=>z?z+H:0,[z,H]),ee=useMemo(()=>{if(!w||!g||!N||N===1||!f?.maxLeverage)return;let v=1/(2*f.maxLeverage),re=(1/N-v)/(a==="long"?1-v:1+v);return a==="long"?g*(1-re):g*(1+re)},[w,g,N,a,f?.maxLeverage]),{data:V}=qe({userAddress:t,symbol:e}),Ie=V?.totalEquity??0,ne=V?.availableBalance??0,Te=useMemo(()=>{let v=V?.positions?.[0];if(!v)return;let re=v.symbol.includes("-")?v.symbol.split("-")[0]:v.symbol;return {side:v.side,quantity:v.quantity,quantityRaw:v.quantityRaw,margin:v.margin,base:re}},[V?.positions]),{data:K}=qt({userAddress:t,enabled:!!t}),Fe=useMemo(()=>K?.openOrders?.length?K.openOrders.some(v=>v.symbol===e):false,[K?.openOrders,e]),{data:Ue}=Et({userAddress:t,symbol:e}),S=Ue?.value,te=!t||S!==void 0,De=useRef(null);useEffect(()=>{De.current!==e&&S&&S>0&&(c.setValue("leverage",S),De.current=e);},[e,S,c]),useEffect(()=>{De.current=null;},[e]),useEffect(()=>{if(!(typeof w!="number"||Number.isNaN(w))){if(w<0){c.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}ne>0&&w>ne&&c.setValue("amount",ne,{shouldValidate:false,shouldDirty:true});}},[w,ne,c]);let xt=useCallback(async v=>{if(!t)throw new Error("User address is required");if(!v.amount||v.amount<=0)throw new Error("Amount is required");let re=u==="limit"?v.price:void 0,Ye=v.takeProfitPrice,Xe=v.stopLossPrice;if(!Ye&&v.takeProfitPercent&&v.takeProfitPercent>0&&g&&(Ye=ze(v.takeProfitPercent,g,v.leverage,a,"tp")),!Xe&&v.stopLossPercent&&v.stopLossPercent>0&&g&&(Xe=ze(v.stopLossPercent,g,v.leverage,a,"sl")),o){if(!g||g<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(m===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Ln=v.amount*v.leverage/g;await x.mutateAsync({symbol:e,side:a,orderType:u,amount:v.amount,price:re,leverage:v.leverage,takeProfitPrice:Ye,stopLossPrice:Xe,userAddress:t,size:Ln,refPrice:g,szDecimals:m});return}await D({symbol:e,side:a,orderType:u,amount:v.amount,price:re,leverage:v.leverage,takeProfitPrice:Ye,stopLossPrice:Xe,userAddress:t});},[e,a,u,g,m,t,o,x,D]);return {form:c,side:a,orderType:u,setSide:l,setOrderType:p,handleSubmit:xt,isSubmitting:C,currentPrice:g,estimatedFee:H,estimatedTotal:L,liquidationPrice:ee,availableMargin:ne,accountValue:Ie,currentPosition:Te,maxLeverage:y,currentLeverage:S,isLeverageReady:te,hasOpenOrdersForSymbol:Fe,szDecimals:m,onUpdateLeverage:i}}var W="#C7FF2E",fa=W,mn="#F76816",ln=mn;function dr(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 ga="https://app.hyperliquid.xyz/coins",ya=10;function fn(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var ba={...Kt,display:"inline-block",width:28,height:14,borderRadius:4};function un(e,t=2){return e.toFixed(t)}function ha(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 de=1;function xa(e){let t=Math.max(de,Math.floor(e)),r=n=>{let i=Math.round(n);return i<=10?Math.max(de,i):Math.round(i/5)*5},s=new Set([de,t]);for(let n of [.25,.5,.75]){let i=r(t*n);i>de&&i<t&&s.add(i);}return Array.from(s).sort((n,i)=>n-i).map(n=>({value:n,label:`${n}x`}))}function Sa({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:i,onConfirm:o,onUpdate:a,onClose:l}){let u=Math.max(de,Math.floor(r)),[p,c]=useState(Math.max(de,Math.min(t,u))),[d,f]=useState(false);useEffect(()=>{e&&(c(Math.max(de,Math.min(t,u))),f(false));},[e,t,u]);let m=useMemo(()=>xa(u),[u]),y=useCallback(async()=>{if(!d){if(!a){o(p),l();return}f(true);try{await a(p),o(p),l();}catch{f(false);}}},[d,a,p,o,l]),D=useAuthCallback(y);return jsx(StyledModal,{isOpen:e,onOpenChange:h=>{d||h||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:jsx(ModalContent,{children:jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-2",children:[jsx("h3",{className:"text-base font-semibold text-white m-0",children:"Adjust Leverage"}),jsx("button",{type:"button",onClick:l,disabled:d,"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:jsx(XCloseIcon,{width:16,height:16})})]}),jsxs("div",{className:"px-5 pb-5 pt-2 flex flex-col gap-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[n?jsxs("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ln},children:["You may not update leverage for ",s," while a position is open."]}):jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:"Adjust your leverage to manage your exposure. Higher leverage increases both potential profits and risks."}),i&&jsxs("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ln},children:["Open order(s) for ",s," will be affected by leverage change."]})]}),jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[jsx("style",{children:`
|
|
3
|
+
`;function pe(){return jsx("style",{children:_i})}var Kt={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:`${Os} 1.8s ease-in-out infinite`,borderRadius:6};function Y(e){return {...Kt,animationDelay:`${e}ms`}}function $t(){return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsx("div",{style:xe(0,84,23)}),jsx("div",{style:xe(60,52,16)})]}),jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsx(Wt,{labelWidth:72,valueWidth:64,delay:120}),jsx(Wt,{labelWidth:72,valueWidth:48,delay:180}),jsx(Wt,{labelWidth:84,valueWidth:56,delay:240}),jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsx("div",{style:xe(300,132,16)}),jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsx("div",{style:xe(330,64,17)}),jsx("div",{style:xe(360,64,17)})]})]})]})]})]})}function Wt({labelWidth:e,valueWidth:t,delay:r}){return jsxs("div",{className:"flex flex-col",style:{gap:4},children:[jsx("div",{style:xe(r,e,16)}),jsx("div",{style:xe(r+30,t,17)})]})}function xe(e,t,r){return {...Y(e),width:t,height:r}}function Vt(e){let[t,r]=useState(),[s,n]=useState(0),{data:i,isPending:o}=Le({symbol:e}),{data:a,isConnected:l}=ye({type:"ticker",symbol:e,enabled:!!i});return useEffect(()=>{i&&r(i);},[i]),useEffect(()=>{if(!a)return;let u=Qi(a,e);u&&r(p=>zi(p??i??void 0,u,e));},[a,i,e]),useEffect(()=>{let u=()=>{let c=Date.now(),d=3600*1e3,f=c%d,m=d-f;return Math.floor(m/1e3)};n(u());let p=setInterval(()=>{n(u());},1e3);return ()=>clearInterval(p)},[]),{marketData:t,isLoading:o,fundingCountdown:s}}function Qi(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 Oe(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function zi(e,t,r){return {symbol:t.symbol??e?.symbol??r,price:Oe(t.price,e?.price??0),change24h:Oe(t.change24h,e?.change24h??0),volume24h:Oe(t.volume24h,e?.volume24h??0),fundingRate:Oe(t.fundingRate,e?.fundingRate??0),openInterest:Oe(t.openInterest,e?.openInterest??0),markPrice:Oe(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 Ki(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 Rs(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 Es(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 jt({marketData:e,fundingCountdown:t}){let{symbol:r,price:s,change24h:n,indexPrice:i,volume24h:o,openInterest:a,fundingRate:l}=e,u=typeof n=="number"&&Number.isFinite(n)?n:0,p=typeof l=="number"&&Number.isFinite(l)?l:0,c=u>=0,d=u.toFixed(2);return jsxs("div",{className:"flex items-center px-4",style:{minHeight:64,maxHeight:64,gap:24},children:[jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[jsx("span",{style:{fontSize:18,fontWeight:500,lineHeight:"23px",letterSpacing:"-0.36px",color:"#ffffff"},children:Es(s)}),jsxs("span",{style:{fontSize:12,fontWeight:400,lineHeight:"16px",color:c?"#C7FF2E":"#F76816"},children:[c?"+":"",d,"%"]})]}),jsxs("div",{className:"flex items-center",style:{gap:24},children:[jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Oracle Price"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:i?Es(i):"-"})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"24h Volume"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Rs(o,0)})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Open Interest"}),jsx("span",{style:{fontSize:13,fontWeight:400,lineHeight:"17px",color:"#ffffff"},children:Rs(a*(e.markPrice||s))})]}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{style:{fontSize:12,color:"#b5b5b5",lineHeight:"16px",letterSpacing:"-0.12px"},children:"Funding / Countdown"}),jsxs("div",{className:"flex items-center",style:{gap:8},children:[jsxs("span",{style:{fontSize:13,lineHeight:"17px",color:p>=0?"#C7FF2E":"#F76816"},children:[(p*100).toFixed(5),"%"]}),jsx("span",{style:{fontSize:13,lineHeight:"17px",color:"#ffffff"},children:Ki(t)})]})]})]})]})}function Wi({symbol:e}){let{marketData:t,isLoading:r,fundingCountdown:s}=Vt(e);return r?jsx($t,{}):t?jsx(jt,{marketData:t,fundingCountdown:s}):jsx(zt,{})}function Jt({onSelectCoin:e}={}){let[t,r]=useState(""),[s,n]=useState([]),{data:i,isPending:o}=Tt(),{data:a,isPending:l}=Dt({symbols:i},{enabled:!!i&&i.length>0});useEffect(()=>{a&&n(a);},[a]);let u=useMemo(()=>{if(!t.trim())return s;let c=t.toLowerCase().trim();return s.filter(d=>d.symbol.toLowerCase().includes(c))},[s,t]);return {coins:s,isLoading:o||l,searchQuery:t,setSearchQuery:r,filteredCoins:u,handleSelectCoin:c=>{e?.(c);}}}function Ns(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 ji(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Xt({coins:e,searchQuery:t,onSearchChange:r,onSelectCoin:s,isLoading:n}){return jsxs("div",{className:"flex flex-col",style:{backgroundColor:"#1A1A1A",flex:"1 1 0",minHeight:0},children:[jsx("div",{style:{padding:"16px 16px 12px"},children:jsxs("div",{className:"flex items-center",style:{height:32,border:"1px solid #2a2a2a",borderRadius:4,padding:"0 6px 0 12px",gap:8},children:[jsx(SearchIcon,{className:"flex-shrink-0",style:{width:14,height:14,color:"#6b6b6b"}}),jsx("input",{type:"text",placeholder:"Search coins...",value:t,onChange:i=>r(i.target.value),className:"flex-1 bg-transparent outline-none",style:{fontSize:12,color:"#ffffff",border:"none"}})]})}),jsxs("div",{className:"flex-1 overflow-auto",children:[jsxs("div",{className:"flex items-center",style:{height:28,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)",position:"sticky",top:0,backgroundColor:"#1A1A1A",zIndex:1},children:[jsx("span",{style:{flex:"0 0 140px",fontSize:12,color:"#6b6b6b"},children:"Token"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Last Price"}),jsx("span",{style:{flex:"0 0 120px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Change"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"8h Funding"}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"24h Volume"}),jsx("span",{style:{flex:"1",fontSize:12,color:"#6b6b6b",textAlign:"right"},children:"Open Interest"})]}),n?jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:"Loading..."})}):e.length===0?jsx("div",{className:"flex items-center justify-center",style:{height:100},children:jsx("span",{style:{fontSize:12,color:"#6b6b6b"},children:t?"No coins found":"No coins available"})}):e.map(i=>{let o=i.change24h>=0,a=i.change24h.toFixed(2),l=(i.fundingRate*100).toFixed(4),u=i.fundingRate>=0,p=i.symbol.split("-")[0];return jsxs("div",{className:"flex items-center cursor-pointer transition-colors",style:{height:36,padding:"0 16px",borderBottom:"1px solid rgba(42,42,42,0.5)"},onClick:()=>s(i.symbol),onMouseEnter:c=>{c.currentTarget.style.backgroundColor="rgba(255,255,255,0.03)";},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent";},children:[jsxs("div",{className:"flex items-center",style:{flex:"0 0 140px",gap:8},children:[jsx("img",{src:`https://app.hyperliquid.xyz/coins/${p}.svg`,alt:p,className:"rounded-full",style:{width:20,height:20},onError:c=>{let d=c.target;d.style.display="none";}}),jsx("span",{style:{fontSize:12,fontWeight:500,color:"#ffffff"},children:p})]}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#ffffff",textAlign:"right"},children:ji(i.price)}),jsxs("span",{style:{flex:"0 0 120px",fontSize:12,fontWeight:500,color:o?"#C7FF2E":"#F76816",textAlign:"right"},children:[o?"+":"",a,"%"]}),jsxs("span",{style:{flex:"0 0 100px",fontSize:12,color:u?"#C7FF2E":"#F76816",textAlign:"right"},children:[l,"%"]}),jsx("span",{style:{flex:"0 0 100px",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ns(i.volume24h)}),jsx("span",{style:{flex:"1",fontSize:12,color:"#b5b5b5",textAlign:"right"},children:Ns(i.openInterest*i.price)})]},i.symbol)})]})]})}function Yi({onSelectCoin:e,className:t}){let{filteredCoins:r,isLoading:s,searchQuery:n,setSearchQuery:i,handleSelectCoin:o}=Jt({onSelectCoin:e});return jsx("div",{className:t,style:{display:"flex",flexDirection:"column",flex:"1 1 0",minHeight:0,overflow:"hidden"},children:jsx(Xt,{coins:r,searchQuery:n,onSearchChange:i,onSelectCoin:o,isLoading:s})})}function qs(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 Ms(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 Ls(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]=useState(null),[i,o]=useState(r);useEffect(()=>{o(r);},[r]);let{data:a,isPending:l}=kt({symbol:e,maxLevel:t}),u=useMemo(()=>{let f=s?.bids[0]?.price??a?.bids[0]?.price,m=s?.asks[0]?.price??a?.asks[0]?.price,y=f&&m?(f+m)/2:m??f??0;return y>0?Math.floor(Math.log10(y)):null},[s,a]),p=useMemo(()=>{if(u===null)return;let f=Math.pow(10,u);return qs(f,i)},[i,u]),{data:c}=ye({type:"orderBook",symbol:e,enabled:!!a,aggregation:p,throttleMs:100});return useEffect(()=>{c?n(c):a&&n(a);},[c,a]),{...useMemo(()=>{if(!s)return {bids:[],asks:[],spread:0,spreadPercentage:0};let f=Ms(s.bids,i,"bid"),m=Ms(s.asks,i,"ask"),y=f.sort((I,g)=>g.price-I.price).slice(0,t),D=m.sort((I,g)=>I.price-g.price).slice(0,t),h=Ls(y),x=Ls(D),C=h[0]?.price||0,w=(x[0]?.price||0)-C,N=C>0?w/C*100:0;return {bids:h,asks:x,spread:w,spreadPercentage:N}},[s,i,t]),isLoading:l,precision:i,setPrecision:o}}var Bs={scrollbarWidth:"thin",scrollbarColor:"rgba(63,63,70,0.6) transparent"},Zi={backgroundColor:"#000000",fontSize:11},eo={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},tr={flex:"1 1 0%"},to={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16,fontSize:11},ro={height:20,background:"linear-gradient(to right, rgba(247,104,22,0), #F76816)",opacity:.15},so={height:20,background:"linear-gradient(to right, rgba(199,255,46,0), #C7FF2E)",opacity:.15},no={color:"#F76816",fontWeight:400},io={color:"#C7FF2E",fontWeight:400},Hs={flex:"1 1 0%",color:"#ffffff"},oo={flex:"1 1 0%"},ao={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"},lo={gap:12,fontSize:12,color:"#ffffff"},uo={color:"#ffffff"},po={color:"#ffffff",fontWeight:500},co={color:"#ffffff",fontWeight:400,background:"none",border:"none",padding:0,gap:4},mo={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)"},Ws={padding:"4px 10px",fontSize:12,color:"#ffffff",background:"transparent",border:"none",borderRadius:4,textAlign:"left"},fo={...Ws,color:"#C7FF2E"};function go(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 Qs(e){return Math.round(e).toLocaleString("en-US")}function zs(e){return e>=1?e.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0}):e.toString()}var Ks=memo(function({price:t,quantity:r,total:s,percentage:n,side:i,onPriceClick:o}){let a=i==="ask",l=useMemo(()=>a?{...ro,width:`${n}%`}:{...so,width:`${n}%`},[a,n]),u=useMemo(()=>o?()=>o(t):void 0,[o,t]);return jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:to,onClick:u,children:[jsx("div",{className:"absolute left-0 top-0",style:l}),jsx("div",{className:"relative z-10 flex items-center",style:oo,children:jsx("span",{style:a?no:io,children:go(t)})}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Hs,children:Qs(r)}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Hs,children:Qs(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 yo({spreadPercentage:e,precision:t,precisionOptions:r,onPrecisionChange:s}){let[n,i]=useState(false),o=useRef(null);useEffect(()=>{if(!n)return;let l=u=>{o.current?.contains(u.target)||i(false);};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[n]);let a=useMemo(()=>({color:"#6b6b6b",transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"}),[n]);return jsx("div",{className:"flex items-center justify-center",style:ao,children:jsxs("div",{className:"flex items-center",style:lo,children:[jsx("span",{style:uo,children:"Spread:"}),jsxs("div",{ref:o,className:"relative",children:[jsxs("button",{type:"button",className:"flex items-center cursor-pointer hover:text-white/80 transition-colors",style:co,onClick:()=>i(l=>!l),"aria-haspopup":"listbox","aria-expanded":n,children:[jsx("span",{children:zs(t)}),jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",style:a,children:jsx("path",{d:"M1 2.5L4 5.5L7 2.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&jsx("div",{role:"listbox",className:"absolute left-1/2 -translate-x-1/2 z-20 flex flex-col",style:mo,children:r.map(l=>{let u=l===t;return jsx("button",{type:"button",role:"option","aria-selected":u,className:"cursor-pointer transition-colors",style:u?fo:Ws,onMouseEnter:p=>{p.currentTarget.style.backgroundColor="rgba(255,255,255,0.06)";},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent";},onClick:()=>{s(l),i(false);},children:zs(l)},l)})})]}),jsxs("span",{style:po,children:[e.toFixed(3),"%"]})]})})}function sr({bids:e,asks:t,spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i,onPriceClick:o}){let a=useRef(null),l=useRef(null),u=useRef(true),p=useRef(true),c=useMemo(()=>[...t].reverse(),[t]);useEffect(()=>{let m=a.current;if(!m||!u.current)return;let y=m.scrollHeight;m.scrollTop!==y&&(m.scrollTop=y);},[c]),useEffect(()=>{let m=l.current;!m||!p.current||m.scrollTop!==0&&(m.scrollTop=0);},[e]);let d=useCallback(()=>{let m=a.current;if(!m)return;let y=m.scrollHeight-m.scrollTop-m.clientHeight;u.current=y<=24;},[]),f=useCallback(()=>{let m=l.current;m&&(p.current=m.scrollTop<=24);},[]);return jsxs("div",{className:"flex flex-col h-full min-h-0",style:Zi,children:[jsxs("div",{className:"flex items-center flex-none",style:eo,children:[jsx("div",{className:"flex items-center",style:tr,children:"Price"}),jsx("div",{className:"flex items-center justify-end",style:tr,children:"Amount (USD)"}),jsx("div",{className:"flex items-center justify-end",style:tr,children:"Total (USD)"})]}),jsx("div",{ref:a,onScroll:d,className:"flex-1 min-h-0 overflow-y-auto",style:Bs,children:c.map((m,y)=>jsx(Ks,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"ask",onPriceClick:o},`ask-${m.price}-${y}`))}),jsx("div",{className:"flex-none",children:jsx(yo,{spreadPercentage:r,precision:s,precisionOptions:n,onPrecisionChange:i})}),jsx("div",{ref:l,onScroll:f,className:"flex-1 min-h-0 overflow-y-auto",style:Bs,children:e.map((m,y)=>jsx(Ks,{price:m.price,quantity:m.quantity,total:m.total,percentage:m.percentage,side:"bid",onPriceClick:o},`bid-${m.price}-${y}`))})]})}var Gs=[1,2,5,10,100,1e3],bo={backgroundColor:"#000000",fontSize:11},ho={height:28,minHeight:28,padding:"0 16px",gap:16,color:"#6b6b6b",fontSize:11},we={flex:"1 1 0%"},xo={height:22,minHeight:22,maxHeight:22,padding:"0 16px",gap:16},So={height:24,minHeight:24,padding:"0 16px",backgroundColor:"rgba(26,26,26,0.5)"};function $s({delay:e}){return jsxs("div",{className:"flex items-center",style:xo,children:[jsx("div",{style:we,children:jsx("div",{style:{...Y(e),height:11,width:56}})}),jsx("div",{className:"flex justify-end",style:we,children:jsx("div",{style:{...Y(e+30),height:11,width:64}})}),jsx("div",{className:"flex justify-end",style:we,children:jsx("div",{style:{...Y(e+60),height:11,width:64}})})]})}function Po(){let e=Array.from({length:8},(r,s)=>s),t=Array.from({length:8},(r,s)=>s);return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex flex-col h-full min-h-0",style:bo,children:[jsxs("div",{className:"flex items-center flex-none",style:ho,children:[jsx("div",{className:"flex items-center",style:we,children:"Price"}),jsx("div",{className:"flex items-center justify-end",style:we,children:"Amount (USD)"}),jsx("div",{className:"flex items-center justify-end",style:we,children:"Total (USD)"})]}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(r=>jsx($s,{delay:r*40},`ask-${r}`))}),jsx("div",{className:"flex-none flex items-center justify-center",style:So,children:jsx("div",{style:{...Y(0),width:96,height:12}})}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.map(r=>jsx($s,{delay:200+r*40},`bid-${r}`))})]})]})}function vo(){return jsx("div",{className:"flex items-center justify-center h-full",children:jsx("span",{className:"text-neutral-400 text-sm",children:"No order book data available"})})}function Co({symbol:e,maxLevel:t=40,precisionOptions:r=Gs,defaultPrecision:s,onPriceClick:n,className:i}){let o=s??r[0]??1,{bids:a,asks:l,spreadPercentage:u,isLoading:p,precision:c,setPrecision:d}=er({symbol:e,maxLevel:t,precision:o});return p?jsx(Po,{}):a.length===0&&l.length===0?jsx(vo,{}):jsx("div",{className:i,children:jsx(sr,{bids:a,asks:l,spreadPercentage:u,precision:c,precisionOptions:r,onPrecisionChange:d,onPriceClick:n})})}var ko=200;function or({symbol:e,limit:t=50}){let[r,s]=useState([]),{data:n,isPending:i}=Ot({symbol:e,limit:t}),{data:o}=ye({type:"trades",symbol:e,enabled:!!n});useEffect(()=>{n&&s(n.filter(Vs));},[n]);let a=useRef([]),l=useRef(null),u=useRef(t);return u.current=t,useEffect(()=>{if(!o)return;let p=Oo(o);p.length!==0&&(a.current.push(...p),l.current===null&&(l.current=setTimeout(()=>{l.current=null;let c=a.current;a.current=[],c.length!==0&&s(d=>{let f=c.filter(m=>!d.some(y=>y.timestamp===m.timestamp&&y.price===m.price&&y.quantity===m.quantity));return f.length===0?d:[...f.reverse(),...d].slice(0,u.current)});},ko)));},[o]),useEffect(()=>()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),a.current=[];},[e]),{trades:r,isLoading:i}}function Oo(e){return (Array.isArray(e)?e:[e]).filter(Vs)}function Vs(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 ut=22,js=28,Ys=100,Js=120,No={backgroundColor:"#000000",fontSize:11},Io={height:js,minHeight:js,padding:"0 16px",color:"#6b6b6b",fontSize:11},Fo={flex:"1 1 0%",maxWidth:Ys},Uo={flex:"1 1 0%",marginLeft:20},Mo={flex:"1 1 0%",maxWidth:Js,textAlign:"right"},Lo={height:ut,minHeight:ut,maxHeight:ut,padding:"0 16px"},qo={flex:"1 1 0%",maxWidth:Ys},_o={flex:"1 1 0%",marginLeft:20,color:"#FCFCFC"},Bo={flex:"1 1 0%",maxWidth:Js,textAlign:"right",color:"#777A8C"},Ho={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bullish))",opacity:.15,pointerEvents:"none"},Qo={position:"absolute",left:0,top:0,height:20,background:"linear-gradient(to right, transparent, var(--color-bearish))",opacity:.15,pointerEvents:"none"};function zo(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 Ko(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"-"}function Wo(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 $o(e){return !Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(100,15*Math.log10(e)-5))}function Go({index:e,style:t,trades:r,onTradeClick:s}){let n=r[e],i=n?.timestamp??Date.now(),o=useTickAge(i),a=useMemo(()=>!n||!Number.isFinite(n.price)||!Number.isFinite(n.quantity)?0:n.price*n.quantity,[n]),l=useMemo(()=>({...n?.side==="buy"?Ho:Qo,width:`${$o(a)}%`}),[n,a]);if(!n)return null;let u=n.side==="buy";return jsx("div",{style:t,children:jsxs("div",{className:"relative flex items-center cursor-pointer hover:bg-white/5 transition-colors",style:Lo,onClick:s?()=>s(n):void 0,children:[jsx("div",{style:l}),jsx("div",{className:"relative z-10 flex items-center",style:qo,children:jsx("span",{className:u?"text-bullish":"text-bearish",children:zo(n.price)})}),jsx("div",{className:"relative z-10 flex items-center",style:_o,children:Ko(a)}),jsx("div",{className:"relative z-10 flex items-center justify-end",style:Bo,children:Wo(o)})]})})}function ur({trades:e,onTradeClick:t}){let r=useRef(null),{height:s=0}=useResizeObserver({ref:r}),n=useMemo(()=>({trades:e,onTradeClick:t}),[e,t]);return jsxs("div",{className:"flex flex-col h-full",style:No,children:[jsxs("div",{className:"flex items-center flex-none",style:Io,children:[jsx("div",{style:Fo,children:"Price"}),jsx("div",{style:Uo,children:"Size (USD)"}),jsx("div",{style:Mo,children:"Age"})]}),jsx("div",{ref:r,className:"flex-1 min-h-0",children:s>0&&jsx(List,{style:{height:s},rowComponent:Go,rowCount:e.length,rowHeight:ut,rowProps:n,overscanCount:4})})]})}var Vo={backgroundColor:"#000000",fontSize:11},jo={height:28,minHeight:28,padding:"0 16px",color:"#6b6b6b",fontSize:11},Xs={flex:"1 1 0%",maxWidth:100},Zs={flex:"1 1 0%",marginLeft:20},en={flex:"1 1 0%",maxWidth:120,textAlign:"right"},Yo={height:22,minHeight:22,maxHeight:22,padding:"0 16px"};function Jo({delay:e}){return jsxs("div",{className:"flex items-center",style:Yo,children:[jsx("div",{style:Xs,children:jsx("div",{style:{...Y(e),height:11,width:56}})}),jsx("div",{style:Zs,children:jsx("div",{style:{...Y(e+30),height:11,width:64}})}),jsx("div",{className:"flex justify-end",style:en,children:jsx("div",{style:{...Y(e+60),height:11,width:28}})})]})}function Xo(){let e=Array.from({length:12},(t,r)=>r);return jsxs(Fragment,{children:[jsx(pe,{}),jsxs("div",{className:"flex flex-col h-full",style:Vo,children:[jsxs("div",{className:"flex items-center flex-none",style:jo,children:[jsx("div",{style:Xs,children:"Price"}),jsx("div",{style:Zs,children:"Size (USD)"}),jsx("div",{style:en,children:"Age"})]}),jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.map(t=>jsx(Jo,{delay:t*35},`trade-${t}`))})]})]})}function Zo(){return jsx("div",{className:"flex items-center justify-center h-full",children:jsx("span",{className:"text-neutral-400 text-sm",children:"No recent trades"})})}function ea({symbol:e,limit:t=100,onTradeClick:r,className:s}){let{trades:n,isLoading:i}=or({symbol:e,limit:t});return i?jsx(Xo,{}):n.length===0?jsx(Zo,{}):jsx("div",{className:s,children:jsx(ur,{trades:n,onTradeClick:r})})}function tn(e,t){return e==="long"&&t==="tp"||e==="short"&&t==="sl"?1:-1}function rn(e,t,r,s,n){return !Number.isFinite(e)||!t||t<=0||!r||r<=0?void 0:tn(s,n)*(e-t)/t*r*100}function ze(e,t,r,s,n){if(!Number.isFinite(e)||!t||t<=0||!r||r<=0)return;let i=tn(s,n),o=e/r/100;return t*(1+i*o)}function sn(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 nn(e){return Number.isFinite(e)?Math.round(e*100)/100:e}var oa=20;function cr({symbol:e,userAddress:t,maxLeverage:r=150,onSuccess:s,onError:n,onUpdateLeverage:i,onPlaceOrder:o}){let[a,l]=useState("long"),[u,p]=useState("market"),c=useForm({defaultValues:{amount:void 0,leverage:oa,takeProfitPrice:void 0,takeProfitPercent:void 0,stopLossPrice:void 0,stopLossPercent:void 0}}),{data:d}=Le({symbol:e}),{data:f}=At({symbol:e}),m=f?.szDecimals,y=f?.maxLeverage??r,{mutateAsync:D,isPending:h}=_e({onSuccess:()=>{c.reset(),s?.();},onError:v=>{n?.(v);}}),x=useMutation({mutationFn:async v=>{if(!o)throw new Error("onPlaceOrder is not configured; cannot submit via host path");return await o(v)},onSuccess:()=>{c.reset(),s?.();},onError:v=>{n?.(v);}}),C=h||x.isPending,E=c.watch(),{amount:w,leverage:N,price:I}=E,g=useMemo(()=>u==="limit"&&I?I:d?.price||0,[u,I,d?.price]),z=useMemo(()=>!w||w<=0||!N?0:w*N,[w,N]),H=useMemo(()=>z?z*5e-4:0,[z]),L=useMemo(()=>z?z+H:0,[z,H]),ee=useMemo(()=>{if(!w||!g||!N||N===1||!f?.maxLeverage)return;let v=1/(2*f.maxLeverage),re=(1/N-v)/(a==="long"?1-v:1+v);return a==="long"?g*(1-re):g*(1+re)},[w,g,N,a,f?.maxLeverage]),{data:V}=qe({userAddress:t,symbol:e}),Ie=V?.totalEquity??0,ne=V?.availableBalance??0,Te=useMemo(()=>{let v=V?.positions?.[0];if(!v)return;let re=v.symbol.includes("-")?v.symbol.split("-")[0]:v.symbol;return {side:v.side,quantity:v.quantity,quantityRaw:v.quantityRaw,margin:v.margin,base:re}},[V?.positions]),{data:K}=qt({userAddress:t,enabled:!!t}),Fe=useMemo(()=>K?.openOrders?.length?K.openOrders.some(v=>v.symbol===e):false,[K?.openOrders,e]),{data:Ue}=Et({userAddress:t,symbol:e}),S=Ue?.value,te=!t||S!==void 0,De=useRef(null);useEffect(()=>{De.current!==e&&S&&S>0&&(c.setValue("leverage",S),De.current=e);},[e,S,c]),useEffect(()=>{De.current=null;},[e]),useEffect(()=>{if(!(typeof w!="number"||Number.isNaN(w))){if(w<0){c.setValue("amount",void 0,{shouldValidate:false,shouldDirty:false});return}ne>0&&w>ne&&c.setValue("amount",ne,{shouldValidate:false,shouldDirty:true});}},[w,ne,c]);let xt=useCallback(async v=>{if(!t)throw new Error("User address is required");if(!v.amount||v.amount<=0)throw new Error("Amount is required");let re=u==="limit"?v.price:void 0,Ye=v.takeProfitPrice,Je=v.stopLossPrice;if(!Ye&&v.takeProfitPercent&&v.takeProfitPercent>0&&g&&(Ye=ze(v.takeProfitPercent,g,v.leverage,a,"tp")),!Je&&v.stopLossPercent&&v.stopLossPercent>0&&g&&(Je=ze(v.stopLossPercent,g,v.leverage,a,"sl")),o){if(!g||g<=0)throw new Error("Mark price is unavailable; please retry once the market loads");if(m===void 0)throw new Error("Asset metadata is loading; please retry in a moment");let Ln=v.amount*v.leverage/g;await x.mutateAsync({symbol:e,side:a,orderType:u,amount:v.amount,price:re,leverage:v.leverage,takeProfitPrice:Ye,stopLossPrice:Je,userAddress:t,size:Ln,refPrice:g,szDecimals:m});return}await D({symbol:e,side:a,orderType:u,amount:v.amount,price:re,leverage:v.leverage,takeProfitPrice:Ye,stopLossPrice:Je,userAddress:t});},[e,a,u,g,m,t,o,x,D]);return {form:c,side:a,orderType:u,setSide:l,setOrderType:p,handleSubmit:xt,isSubmitting:C,currentPrice:g,estimatedFee:H,estimatedTotal:L,liquidationPrice:ee,availableMargin:ne,accountValue:Ie,currentPosition:Te,maxLeverage:y,currentLeverage:S,isLeverageReady:te,hasOpenOrdersForSymbol:Fe,szDecimals:m,onUpdateLeverage:i}}var W="#C7FF2E",fa=W,mn="#F76816",ln=mn;function dr(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 ga="https://app.hyperliquid.xyz/coins",ya=10;function fn(e){let t=e.replace(/[^\d.]/g,""),r=t.split(".");return r.length>1?`${r[0]}.${r.slice(1).join("")}`:t}var ba={...Kt,display:"inline-block",width:28,height:14,borderRadius:4};function un(e,t=2){return e.toFixed(t)}function ha(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 de=1;function xa(e){let t=Math.max(de,Math.floor(e)),r=n=>{let i=Math.round(n);return i<=10?Math.max(de,i):Math.round(i/5)*5},s=new Set([de,t]);for(let n of [.25,.5,.75]){let i=r(t*n);i>de&&i<t&&s.add(i);}return Array.from(s).sort((n,i)=>n-i).map(n=>({value:n,label:`${n}x`}))}function Sa({isOpen:e,initialLeverage:t,maxLeverage:r,coinName:s,hasOpenPosition:n,hasOpenOrders:i,onConfirm:o,onUpdate:a,onClose:l}){let u=Math.max(de,Math.floor(r)),[p,c]=useState(Math.max(de,Math.min(t,u))),[d,f]=useState(false);useEffect(()=>{e&&(c(Math.max(de,Math.min(t,u))),f(false));},[e,t,u]);let m=useMemo(()=>xa(u),[u]),y=useCallback(async()=>{if(!d){if(!a){o(p),l();return}f(true);try{await a(p),o(p),l();}catch{f(false);}}},[d,a,p,o,l]),D=useAuthCallback(y);return jsx(StyledModal,{isOpen:e,onOpenChange:h=>{d||h||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:jsx(ModalContent,{children:jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-2",children:[jsx("h3",{className:"text-base font-semibold text-white m-0",children:"Adjust Leverage"}),jsx("button",{type:"button",onClick:l,disabled:d,"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:jsx(XCloseIcon,{width:16,height:16})})]}),jsxs("div",{className:"px-5 pb-5 pt-2 flex flex-col gap-4",children:[jsxs("div",{className:"flex flex-col gap-1",children:[n?jsxs("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ln},children:["You may not update leverage for ",s," while a position is open."]}):jsx("p",{className:"text-[13px] text-zinc-400 leading-[18px] m-0",children:"Adjust your leverage to manage your exposure. Higher leverage increases both potential profits and risks."}),i&&jsxs("p",{className:"text-[13px] leading-[18px] m-0",style:{color:ln},children:["Open order(s) for ",s," will be affected by leverage change."]})]}),jsxs("div",{className:"perp-leverage-slider",style:{padding:"8px 6px 4px"},children:[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: ${W} !important; }
|
|
6
6
|
.perp-leverage-slider [data-slot="thumb"] { background-color: ${W} !important; }
|
|
@@ -22,7 +22,7 @@ import {createContext,memo,useMemo,useContext,useState,useRef,useCallback,useEff
|
|
|
22
22
|
.perp-slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: ${W}; 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
|
-
`}),jsx("input",{type:"range",value:Math.round(V),onChange:S=>Ie(Number(S.target.value)),min:0,max:100,step:1,disabled:c<=0,className:"perp-slider",style:{"--pct":`${Math.round(V)}%`}}),jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsx("span",{children:"0%"}),jsx("span",{children:"25%"}),jsx("span",{children:"50%"}),jsx("span",{children:"75%"}),jsx("span",{children:"100%"})]})]}),jsxs("div",{className:"flex items-center justify-between",style:{marginTop:16},children:[jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsx("div",{onClick:()=>I(S=>!S),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:N?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:N&&jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsx("span",{children:"Est. Liq. Price: "}),jsx("span",{style:{color:"#b5b5b5"},children:p?ha(p):"--"})]})]}),N&&jsxs("div",{className:"flex",style:{gap:8},children:[jsxs("div",{className:"flex-1",children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsx(ct,{methods:e,field:"takeProfitPrice",placeholder:"Enter TP price",refPrice:l,leverage:g,side:t})]}),jsxs("div",{style:{width:70},children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsx(ct,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:g,side:t})]})]}),N&&jsxs("div",{className:"flex",style:{gap:8},children:[jsxs("div",{className:"flex-1",children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsx(ct,{methods:e,field:"stopLossPrice",placeholder:"Enter SL price",refPrice:l,leverage:g,side:t})]}),jsxs("div",{style:{width:70},children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsx(ct,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:g,side:t})]})]}),(()=>{let S=K.kind==="submit",te=S?"submit":"button",xt=S?t==="long"?fa:mn:K.kind==="deposit"?W:"rgba(63,63,70,0.6)",v=K.kind==="invalid"?"#71717a":"#000000",re=S&&o;return jsxs("button",{type:te,disabled:K.disabled,onClick:S?void 0:Fe,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:v,backgroundColor:xt,borderRadius:9999,border:"none",cursor:K.disabled?"not-allowed":"pointer",opacity:K.disabled?.9:1},children:[re&&jsx(Spinner,{size:"sm",color:"current"}),re?"Placing order...":K.label]})})(),jsxs("div",{style:{fontSize:12,display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[jsxs("div",{className:"flex justify-between items-center",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxs("button",{type:"button",onClick:x,disabled:!x,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:dr(W,26),color:W,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:x?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:S=>{x&&(S.currentTarget.style.backgroundColor=dr(W,51));},onMouseLeave:S=>{x&&(S.currentTarget.style.backgroundColor=dr(W,26));},children:[un(c)," USDC"]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[un(d)," USDC"]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?`${f.side==="long"?"Long":"Short"} ${f.quantityRaw??String(f.quantity)} ${f.base} (${f.margin.toFixed(2)} USDC)`:"--"})]})]})]})})]}),jsx("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column"},children:jsxs("div",{className:"flex items-center justify-end",style:{gap:6},children:[jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:S=>{let te=S.target;te.style.display="none";}})]})}),jsx(Sa,{isOpen:E,initialLeverage:g,maxLeverage:m,coinName:f?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!f,hasOpenOrders:D,onConfirm:S=>e.setValue("leverage",S),onUpdate:C,onClose:()=>w(false)})]})}function va({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,onPlaceOrder:a,className:l}){let{form:u,side:p,orderType:c,setSide:d,setOrderType:f,handleSubmit:m,isSubmitting:y,currentPrice:D,estimatedFee:h,estimatedTotal:x,liquidationPrice:C,availableMargin:E,accountValue:w,currentPosition:N,maxLeverage:I,isLeverageReady:g,hasOpenOrdersForSymbol:z,szDecimals:H,onUpdateLeverage:L}=cr({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:a});return jsx("div",{className:l,children:jsx(fr,{methods:u,side:p,orderType:c,onSideChange:d,onOrderTypeChange:f,onSubmit:m,isSubmitting:y,symbol:e,currentPrice:D,estimatedFee:h,estimatedTotal:x,liquidationPrice:C,availableMargin:E,accountValue:w,currentPosition:N,maxLeverage:I,isLeverageReady:g,hasOpenOrdersForSymbol:z,szDecimals:H,onAddFunds:i,onUpdateLeverage:L})})}function xn(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.unrealizedPnlPercent}}function Ca(e,t,r,s){let n=xn(e,r),i=xn(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 gr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s}){let[n,i]=useState("marginPnl"),[o,a]=useState("desc"),l=useCallback(h=>{i(x=>x===h?(a(C=>C==="asc"?"desc":"asc"),x):(a("asc"),h));},[]),{data:u,isLoading:p,error:c}=qe({userAddress:e,symbol:t},{enabled:!!e}),{mutateAsync:d,isPending:f}=_e({onSuccess:()=>{r?.();},onError:h=>{s?.(h);}}),m=useMemo(()=>u?.positions??[],[u]),y=useMemo(()=>n?[...m].sort((h,x)=>Ca(h,x,n,o)):m,[m,n,o]),D=useCallback(async h=>{if(!e)throw new Error("User address is required");let x=h.side==="long"?"short":"long";await d({symbol:h.symbol,side:x,orderType:"market",amount:Math.abs(h.quantity),leverage:h.leverage,userAddress:e});},[e,d]);return {positions:y,isLoading:p,error:c,sortKey:n,sortDir:o,onSort:l,handleClosePosition:D,isClosing:f}}function We(e){if(e===void 0||!Number.isFinite(e))return "--";let t=Math.abs(e),r;return t>=1e3?r=0:t>=1?r=2:t>=.01?r=4:r=6,"$"+e.toLocaleString("en-US",{minimumFractionDigits:r,maximumFractionDigits:r})}function Pn(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function Ta(e){return Number.isFinite(e)?(e>=0?"+":"-")+"$"+Math.abs(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function Da(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function ka(e,t){return t||(Number.isFinite(e)?e.toFixed(5).replace(/\.?0+$/,""):"--")}var B={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%"}},dt={minWidth:1e3},yr={minHeight:28,maxHeight:28},Oa={minHeight:36,maxHeight:36};function oe({style:e,children:t,sortKey:r,activeSortKey:s,sortDir:n,onSort:i,alignEnd:o}){let l=r!==void 0&&r===s?n==="asc"?" \u2191":" \u2193":"",u=r!==void 0&&i!==void 0,p=jsxs("span",{className:"text-xs font-normal text-default-500",children:[t,l]});return u?jsx("button",{type:"button",onClick:()=>i?.(r),style:e,className:cn("flex flex-row items-center cursor-pointer hover:text-foreground",o?"justify-end":"justify-start"),children:p}):jsx("div",{style:e,className:cn("flex flex-row items-center",o?"justify-end":"justify-start"),children:p})}function br({positions:e,sortKey:t,sortDir:r,onSort:s,onClosePosition:n,isClosing:i,className:o}){let{t:a}=useTranslation(),l=jsxs("div",{style:yr,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsx(oe,{style:B.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.asset")}),jsx(oe,{style:B.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.position")}),jsx(oe,{style:B.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.positionValue")}),jsx(oe,{style:B.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.entryPrice")}),jsx(oe,{style:B.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.markPrice")}),jsx(oe,{style:B.liq,sortKey:"liq",activeSortKey:t,sortDir:r,onSort:s,children:jsx(StyledTooltip,{content:a("perpetuals.positions.tooltip.liqPrice"),placement:"top",delay:200,closeDelay:0,children:jsxs("span",{className:"border-b border-dashed border-default-500/40",children:[jsx("span",{className:"hidden sm:inline",children:a("perpetuals.positions.col.liqPrice")}),jsx("span",{className:"inline sm:hidden",children:a("perpetuals.positions.col.liqPriceShort")})]})})}),jsx(oe,{style:B.marginPnl,sortKey:"marginPnl",activeSortKey:t,sortDir:r,onSort:s,children:jsx(StyledTooltip,{content:a("perpetuals.positions.tooltip.marginPnl"),placement:"top",delay:200,closeDelay:0,children:jsx("span",{className:"border-b border-dashed border-default-500/40",children:a("perpetuals.positions.col.marginPnl")})})}),jsx(oe,{style:B.tpsl,children:a("perpetuals.positions.col.tpsl")}),jsx(oe,{style:B.close,alignEnd:true,children:a("perpetuals.positions.col.close")})]});return e.length===0?jsx("div",{className:cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",o),children:jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsx("div",{style:{...dt,...yr},className:"flex flex-1 flex-col",children:l}),jsx("div",{style:dt,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:a("perpetuals.positions.empty")})]})}):jsx("div",{className:cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",o),children:jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsx("div",{style:{...dt,...yr},className:"flex flex-1 flex-col",children:l}),jsx("div",{style:dt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((u,p)=>jsx(wa,{position:u,striped:p%2===1,isClosing:i,onClose:n},u.symbol))})]})})}function wa({position:e,striped:t,isClosing:r,onClose:s}){let{t:n}=useTranslation(),i=e.symbol.split("-")[0],o=e.side==="long",a=n(o?"perpetuals.positions.long":"perpetuals.positions.short"),l=o?"text-bullish":"text-bearish",p=e.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsx("div",{className:cn(t?"bg-default-100/30":"bg-transparent"),children:jsxs("div",{style:Oa,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxs("div",{style:B.asset,className:"flex flex-row items-center justify-start gap-1.5",children:[jsx("img",{alt:i,src:`https://app.hyperliquid.xyz/coins/${i}.svg`,className:"rounded-full",style:{width:16,height:16},onError:c=>{c.currentTarget.style.display="none";}}),jsx("span",{className:"text-xs font-medium text-foreground",children:i})]}),jsxs("div",{style:B.position,className:"flex flex-row items-center justify-start gap-1",children:[jsx("span",{className:cn("text-xs font-medium",l),children:a}),jsxs("span",{className:"text-xs font-normal text-default-700",children:[ka(e.quantity,e.quantityRaw)," ",i]})]}),jsx("div",{style:B.value,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:Pn(e.notionalValue)})}),jsx("div",{style:B.entry,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.entryPrice)})}),jsx("div",{style:B.mark,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.markPrice)})}),jsx("div",{style:B.liq,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.liquidationPrice)})}),jsxs("div",{style:B.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsx("span",{className:"text-xs font-normal text-default-700",children:Pn(e.margin)}),jsxs("span",{className:cn("text-xs font-medium",p),children:["(",Ta(e.unrealizedPnl)," /"," ",Da(e.unrealizedPnlPercent),")"]})]}),jsxs("div",{style:{...B.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsx("span",{className:"pr-1 text-right text-xs font-normal text-default-700",children:e.takeProfitPrice!==void 0?We(e.takeProfitPrice):"--"}),jsx("span",{className:"text-xs font-normal text-default-500",children:"/"}),jsx("span",{className:"pl-1 text-left text-xs font-normal text-default-700",children:e.stopLossPrice!==void 0?We(e.stopLossPrice):"--"})]}),jsx("div",{style:B.close,className:"flex flex-row items-center justify-end gap-2",children:jsx("button",{type:"button",onClick:()=>s(e),disabled:r,className: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:n("perpetuals.positions.close.market")})})]})})}function hr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Ra(){return jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open positions"})}function Ea({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:i,isLoading:o,sortKey:a,sortDir:l,onSort:u,handleClosePosition:p,isClosing:c}=gr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s});return o?jsx("div",{className:n,children:jsx(hr,{})}):jsx(br,{positions:i,sortKey:a,sortDir:l,onSort:u,onClosePosition:p,isClosing:c,className:n})}function Sr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s}){let[n,i]=useState([]),{data:o,isLoading:a,error:l}=wt({userAddress:e,symbol:t},{enabled:!!e}),{data:u}=Lt({type:"orders",userAddress:e||"",enabled:!!e}),{mutateAsync:p,isPending:c}=Nt({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});useEffect(()=>{o?.orders&&i(o.orders);},[o]),useEffect(()=>{u&&i(f=>{let m=f.findIndex(y=>y.orderId===u.orderId);if(u.status==="cancelled"||u.status==="filled"||u.status==="rejected")return m!==-1?f.filter((y,D)=>D!==m):f;if(m!==-1){let y=[...f];return y[m]=u,y}return [u,...f]});},[u]);let d=useCallback(async f=>{if(!e)throw new Error("User address is required");await p({orderId:f.orderId,symbol:f.symbol,userAddress:e});},[e,p]);return {orders:n,isLoading:a,error:l,handleCancelOrder:d,isCanceling:c}}function Dn(e,t=2){return e.toFixed(t)}function Fa(e){return Dn(e,4)}function Pr(e){return Dn(e,4)}function Ua(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function vr({orders:e,onCancelOrder:t,isCanceling:r}){return e.length===0?jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsx("thead",{children:jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsx("tbody",{children:e.map(s=>jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("td",{className:"py-1.5 px-3",children:jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxs("span",{className:cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${Fa(s.price)}`}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.quantity)}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.filledQuantity)}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.remainingQuantity)}),jsx("td",{className:"py-1.5 px-3 text-right",children:jsx("span",{className:cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Ua(s.timestamp)}),jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsx(Button,{size:"sm",onClick:()=>t(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function Cr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Tr(){return jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function Ma({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:i,isLoading:o,handleCancelOrder:a,isCanceling:l}=Sr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s});return o?jsx("div",{className:n,children:jsx(Cr,{})}):i.length===0?jsx("div",{className:n,children:jsx(Tr,{})}):jsx("div",{className:n,children:jsx(vr,{orders:i,onCancelOrder:a,isCanceling:l})})}function La(e){let t=Date.now(),r=t;switch(e){case "today":let s=new Date;return s.setHours(0,0,0,0),{startTime:s.getTime(),endTime:r};case "7d":return {startTime:t-10080*60*1e3,endTime:r};case "30d":return {startTime:t-720*60*60*1e3,endTime:r};default:return {}}}function kr({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50}){let[n,i]=useState(r),[o,a]=useState(1),[l,u]=useState([]),{startTime:p,endTime:c}=La(n),{data:d,isLoading:f,error:m}=Rt({userAddress:e,symbol:t,startTime:p,endTime:c,limit:1e3},{enabled:!!e});useEffect(()=>{d?.trades&&(u(d.trades),a(1));},[d]),useEffect(()=>{a(1);},[n]);let y=Math.ceil(l.length/s),D=(o-1)*s,h=D+s;return {trades:l.slice(D,h),isLoading:f,error:m,timeRange:n,setTimeRange:i,currentPage:o,totalPages:y,goToNextPage:()=>{o<y&&a(o+1);},goToPreviousPage:()=>{o>1&&a(o-1);},goToPage:N=>{N>=1&&N<=y&&a(N);}}}function Or(e,t=2){return e.toFixed(t)}function qa(e){return Or(e,4)}function _a(e){return Or(e,4)}function Ba(e){let t=new Date(e),r=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${i}:${o}`}var Ha=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function wr({trades:e,timeRange:t,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:i,onPreviousPage:o,onGoToPage:a}){return jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsx("div",{className:"flex gap-2",children:Ha.map(l=>{let u=t===l.value;return jsx("button",{type:"button",className:cn("rounded px-3 transition-colors",!u&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:u?"#1c1c1c":"transparent",color:u?"#ffffff":"#b5b5b5"},onClick:()=>r(l.value),children:l.label},l.value)})}),e.length===0?jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxs(Fragment,{children:[jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsx("thead",{children:jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsx("tbody",{children:e.map(l=>jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:l.symbol.split("-")[0]}),jsx("td",{className:"py-1.5 px-3",children:jsx("span",{className:cn("px-2 py-0.5 rounded text-[11px]",l.side==="long"?"bg-bullish/20 text-bullish":"bg-bearish/20 text-bearish"),children:l.side.toUpperCase()})}),jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",qa(l.price)]}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:_a(l.quantity)}),jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[Or(l.fee,4)," ",l.feeCurrency]}),jsx("td",{className:"py-1.5 px-3 text-center",children:jsx("span",{className:cn("px-2 py-0.5 rounded text-[11px]",l.isMaker?"bg-blue-600/20 text-blue-500":"bg-purple-600/20 text-purple-500"),children:l.isMaker?"Maker":"Taker"})}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Ba(l.timestamp)})]},l.tradeId))})]})}),n>1&&jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxs("div",{className:"flex gap-2",children:[jsx(Button,{size:"sm",onClick:o,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(l,u)=>{let p;return n<=5||s<=3?p=u+1:s>=n-2?p=n-4+u:p=s-2+u,jsx("button",{type:"button",className:cn("w-8 h-8 text-sm rounded transition-colors",s===p?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>a(p),children:p},p)})}),jsx(Button,{size:"sm",onClick:i,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function Rr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Er(){return jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function za({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:i,isLoading:o,timeRange:a,setTimeRange:l,currentPage:u,totalPages:p,goToNextPage:c,goToPreviousPage:d,goToPage:f}=kr({userAddress:e,symbol:t,initialTimeRange:r,pageSize:s});return o?jsx("div",{className:n,children:jsx(Rr,{})}):i.length===0?jsx("div",{className:n,children:jsx(Er,{})}):jsx("div",{className:n,children:jsx(wr,{trades:i,timeRange:a,onTimeRangeChange:l,currentPage:u,totalPages:p,onNextPage:c,onPreviousPage:d,onGoToPage:f})})}var Ka=1000000000n,Wa=8,$a=10n**BigInt(8);function $e(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return wn(r,Ka,t)}function ft(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return wn(r,$a,t)}var Ga=ft;function Ar(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 wn(e,t,r){let s=e<0n,n=s?-e:e,i=n/t,o=n%t;if(r<=0)return o*2n>=t&&(i+=1n),`${s?"-":""}${i.toString()}`;let a=10n**BigInt(r),l=(o*a+t/2n)/t;l>=a&&(i+=1n,l=0n);let u=l.toString().padStart(r,"0");return u=u.replace(/0+$/,""),u?`${s?"-":""}${i.toString()}.${u}`:`${s?"-":""}${i.toString()}`}function Ge(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function Nr(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function Ir({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:a}){let{t:l}=useTranslation(),u=t?Date.parse(t.expiresAt):0,[p,c]=useState(()=>u?Ge(u):0);return useEffect(()=>{if(!e||!u)return;c(Ge(u));let d=setInterval(()=>{let f=Ge(u);c(f),f===0&&(o?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,u,o]),jsx(Modal,{isOpen:e,onOpenChange:d=>!d&&i(),hideCloseButton:true,backdrop:"blur",children:jsxs(ModalContent,{className:"bg-content2 rounded-lg",children:[jsx(ModalHeader,{children:l("perpDeposit.confirm.title")}),jsxs(ModalBody,{children:[t?jsx(rl,{breakdown:t.breakdown}):jsx("div",{className:"flex h-32 items-center justify-center",children:jsx(Spinner,{})}),t&&!s&&jsx("div",{className:"text-default-500 mt-4 text-xs",children:l("perpDeposit.confirm.expiresIn",{seconds:p})}),s&&jsx("div",{className:"text-warning-500 mt-4 text-xs",children:l("perpDeposit.confirm.expired")}),a&&jsx("div",{className:"text-danger mt-4 text-xs",children:a})]}),jsxs(ModalFooter,{className:"flex justify-between gap-2",children:[jsx(Button,{variant:"flat",color:"default",onPress:i,isDisabled:r,children:l("perpDeposit.confirm.cancel")}),jsx(Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:l("perpDeposit.confirm.cta")})]})]})})}function rl({breakdown:e}){let{t}=useTranslation();return jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsx(gt,{label:t("perpDeposit.confirm.send"),value:`${$e(e.grossLamports)} SOL`}),jsx(gt,{label:t("perpDeposit.confirm.receive"),value:`${ft(e.expectedOutputUSDC)} USDC`,highlight:true}),jsx(gt,{label:t("perpDeposit.confirm.platformFee"),value:`${$e(e.platformFeeLamports,6)} SOL`,muted:true}),jsx(gt,{label:t("perpDeposit.confirm.relayFee"),value:`${$e(e.relayDepositLamports,6)} SOL`,muted:true})]})}function gt({label:e,value:t,highlight:r,muted:s}){return jsxs("div",{className:"flex items-center justify-between",children:[jsx("dt",{className:"text-default-500",children:e}),jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-default-500 text-xs":"text-foreground",children:t})]})}function Fr({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:l,className:u}){let{t:p}=useTranslation();return jsxs("div",{className:cn("flex flex-col gap-4",u),children:[jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[jsx("label",{htmlFor:"perp-deposit-amount",className:"text-sm font-medium text-foreground",children:p("perpDeposit.amount")}),n&&jsx("span",{className:"text-xs text-default-500",children:p("perpDeposit.amount.balance",{balance:n})})]}),jsx("div",{className:"relative",children:jsx(Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:p("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:i,isInvalid:!!o,errorMessage:o,endContent:jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{className:"text-default-500 text-sm",children:p("perpDeposit.amount.unit")}),n&&l&&jsx(Button,{size:"sm",variant:"flat",color:"primary",onPress:l,isDisabled:i,children:p("perpDeposit.amount.max")})]})})})]}),jsxs("div",{children:[jsx("label",{htmlFor:"perp-deposit-recipient",className:"text-sm font-medium text-foreground mb-1.5 block",children:p("perpDeposit.recipient")}),jsx(Input,{id:"perp-deposit-recipient",type:"text",placeholder:p("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:i,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}var In="#C7FF2E";function Mr({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:l}=useTranslation(),u=dl(t),p=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"),c=t==="failed"&&!!i;return jsx(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:jsx(ModalContent,{children:jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-start justify-between px-5 pt-5 pb-2",children:[jsx("div",{className:"flex items-center gap-2.5",children:jsx("h3",{className:"text-base font-semibold text-white",children:l("perpDeposit.status.title")})}),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:jsx(XCloseIcon,{width:16,height:16})})]}),jsxs("div",{className:"px-5 pb-3 pt-2",children:[jsxs("div",{className:"rounded-[12px] bg-[#0a0a0b] border border-[#27272a] px-4 py-6 flex flex-col items-center text-center gap-4",children:[jsx(pl,{variant:u}),jsx("p",{className:cn("text-sm leading-relaxed max-w-[320px]",ml(u)),children:p})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsx(Nn,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsx(Nn,{href:n,label:l("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxs("div",{className:cn("px-5 pb-5 pt-2 flex gap-2",c?"justify-between":"justify-end"),children:[c&&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")}),jsx("button",{type:"button",onClick:o,className:cn("cursor-pointer h-10 rounded-[10px] font-medium transition-colors flex items-center justify-center",c?"flex-1 bg-[rgba(39,39,42,1)] hover:bg-[rgba(63,63,70,1)] text-white":"px-6 bg-[rgba(39,39,42,1)] hover:bg-[rgba(63,63,70,1)] text-white"),children:l("perpDeposit.status.close")})]})]})})})}function Nn({href:e,label:t,hash:r}){return jsxs("a",{href:e,target:"_blank",rel:"noreferrer",className:"group flex items-center justify-between gap-2 px-3 py-2 rounded-[10px] bg-[#0a0a0b] border border-[#27272a] hover:border-[rgba(199,255,46,0.4)] transition-colors",children:[jsx("span",{className:"text-xs text-zinc-400 group-hover:text-white transition-colors",children:t}),jsxs("span",{className:"flex items-center gap-1.5 text-xs tabular-nums text-zinc-300 group-hover:text-[#C7FF2E] transition-colors",children:[Nr(r,6,4),jsx(bl,{})]})]})}function pl({variant:e}){return e==="progress"?jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsx(cl,{})}):e==="success"?jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(199,255,46,0.12)]",children:jsx(fl,{className:"w-8 h-8",style:{color:In}})}):e==="warning"?jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(245,158,11,0.12)]",children:jsx(gl,{className:"w-8 h-8 text-amber-400"})}):jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(239,68,68,0.12)]",children:jsx(yl,{className:"w-8 h-8 text-rose-400"})})}function cl(){return jsxs(Fragment,{children:[jsxs("svg",{className:"lfi-perp-deposit-spinner",viewBox:"0 0 50 50",width:48,height:48,"aria-hidden":"true",children:[jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"4"}),jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:In,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsx("style",{children:`
|
|
25
|
+
`}),jsx("input",{type:"range",value:Math.round(V),onChange:S=>Ie(Number(S.target.value)),min:0,max:100,step:1,disabled:c<=0,className:"perp-slider",style:{"--pct":`${Math.round(V)}%`}}),jsxs("div",{className:"flex justify-between",style:{fontSize:10,color:"#b5b5b5",marginTop:4},children:[jsx("span",{children:"0%"}),jsx("span",{children:"25%"}),jsx("span",{children:"50%"}),jsx("span",{children:"75%"}),jsx("span",{children:"100%"})]})]}),jsxs("div",{className:"flex items-center justify-between",style:{marginTop:16},children:[jsxs("div",{className:"flex items-center",style:{gap:6},children:[jsx("div",{onClick:()=>I(S=>!S),style:{width:16,height:16,borderRadius:4,border:"1px solid #2a2a2a",backgroundColor:N?"#C7FF2E":"transparent",flexShrink:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:N&&jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#000000",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsx("span",{style:{fontSize:12,fontWeight:500,color:"#b5b5b5"},children:"TP/SL"})]}),jsxs("div",{style:{fontSize:12,color:"#6b6b6b"},children:[jsx("span",{children:"Est. Liq. Price: "}),jsx("span",{style:{color:"#b5b5b5"},children:p?ha(p):"--"})]})]}),N&&jsxs("div",{className:"flex",style:{gap:8},children:[jsxs("div",{className:"flex-1",children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP Price"}),jsx(ct,{methods:e,field:"takeProfitPrice",placeholder:"Enter TP price",refPrice:l,leverage:g,side:t})]}),jsxs("div",{style:{width:70},children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"TP %"}),jsx(ct,{methods:e,field:"takeProfitPercent",placeholder:"0.0",refPrice:l,leverage:g,side:t})]})]}),N&&jsxs("div",{className:"flex",style:{gap:8},children:[jsxs("div",{className:"flex-1",children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL Price"}),jsx(ct,{methods:e,field:"stopLossPrice",placeholder:"Enter SL price",refPrice:l,leverage:g,side:t})]}),jsxs("div",{style:{width:70},children:[jsx("span",{style:{fontSize:12,color:"#6b6b6b",marginBottom:2,display:"block"},children:"SL %"}),jsx(ct,{methods:e,field:"stopLossPercent",placeholder:"0.0",refPrice:l,leverage:g,side:t})]})]}),(()=>{let S=K.kind==="submit",te=S?"submit":"button",xt=S?t==="long"?fa:mn:K.kind==="deposit"?W:"rgba(63,63,70,0.6)",v=K.kind==="invalid"?"#71717a":"#000000",re=S&&o;return jsxs("button",{type:te,disabled:K.disabled,onClick:S?void 0:Fe,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:v,backgroundColor:xt,borderRadius:9999,border:"none",cursor:K.disabled?"not-allowed":"pointer",opacity:K.disabled?.9:1},children:[re&&jsx(Spinner,{size:"sm",color:"current"}),re?"Placing order...":K.label]})})(),jsxs("div",{style:{fontSize:12,display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[jsxs("div",{className:"flex justify-between items-center",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Available Margin"}),jsxs("button",{type:"button",onClick:x,disabled:!x,style:{height:24,padding:"0 8px",borderRadius:4,border:"none",backgroundColor:dr(W,26),color:W,fontSize:12,fontWeight:500,lineHeight:"16px",cursor:x?"pointer":"default",transition:"background-color 150ms ease-in-out"},onMouseEnter:S=>{x&&(S.currentTarget.style.backgroundColor=dr(W,51));},onMouseLeave:S=>{x&&(S.currentTarget.style.backgroundColor=dr(W,26));},children:[un(c)," USDC"]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Perps Account Value"}),jsxs("span",{style:{color:"#b5b5b5",fontSize:12},children:[un(d)," USDC"]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{style:{color:"#6b6b6b"},children:"Current Position"}),jsx("span",{style:{color:"#b5b5b5",fontSize:12},children:f?`${f.side==="long"?"Long":"Short"} ${f.quantityRaw??String(f.quantity)} ${f.base} (${f.margin.toFixed(2)} USDC)`:"--"})]})]})]})})]}),jsx("div",{style:{padding:"10px 16px",fontSize:12,display:"flex",flexDirection:"column"},children:jsxs("div",{className:"flex items-center justify-end",style:{gap:6},children:[jsx("span",{style:{fontSize:11,color:"#6b6b6b"},children:"powered by"}),jsx("img",{src:"https://axiom-assets.sfo3.cdn.digitaloceanspaces.com/images/hyperliquid-logo.svg",alt:"Hyperliquid",className:"h-3 opacity-60",onError:S=>{let te=S.target;te.style.display="none";}})]})}),jsx(Sa,{isOpen:E,initialLeverage:g,maxLeverage:m,coinName:f?.base??(a.includes("-")?a.split("-")[0]:a),hasOpenPosition:!!f,hasOpenOrders:D,onConfirm:S=>e.setValue("leverage",S),onUpdate:C,onClose:()=>w(false)})]})}function va({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onAddFunds:i,onUpdateLeverage:o,onPlaceOrder:a,className:l}){let{form:u,side:p,orderType:c,setSide:d,setOrderType:f,handleSubmit:m,isSubmitting:y,currentPrice:D,estimatedFee:h,estimatedTotal:x,liquidationPrice:C,availableMargin:E,accountValue:w,currentPosition:N,maxLeverage:I,isLeverageReady:g,hasOpenOrdersForSymbol:z,szDecimals:H,onUpdateLeverage:L}=cr({symbol:e,userAddress:t,maxLeverage:r,onSuccess:s,onError:n,onUpdateLeverage:o,onPlaceOrder:a});return jsx("div",{className:l,children:jsx(fr,{methods:u,side:p,orderType:c,onSideChange:d,onOrderTypeChange:f,onSubmit:m,isSubmitting:y,symbol:e,currentPrice:D,estimatedFee:h,estimatedTotal:x,liquidationPrice:C,availableMargin:E,accountValue:w,currentPosition:N,maxLeverage:I,isLeverageReady:g,hasOpenOrdersForSymbol:z,szDecimals:H,onAddFunds:i,onUpdateLeverage:L})})}function xn(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 Ca(e,t,r,s){let n=xn(e,r),i=xn(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 gr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s}){let[n,i]=useState("marginPnl"),[o,a]=useState("desc"),l=useCallback(h=>{i(x=>x===h?(a(C=>C==="asc"?"desc":"asc"),x):(a("asc"),h));},[]),{data:u,isLoading:p,error:c}=qe({userAddress:e,symbol:t},{enabled:!!e}),{mutateAsync:d,isPending:f}=_e({onSuccess:()=>{r?.();},onError:h=>{s?.(h);}}),m=useMemo(()=>u?.positions??[],[u]),y=useMemo(()=>n?[...m].sort((h,x)=>Ca(h,x,n,o)):m,[m,n,o]),D=useCallback(async h=>{if(!e)throw new Error("User address is required");let x=h.side==="long"?"short":"long";await d({symbol:h.symbol,side:x,orderType:"market",amount:Math.abs(h.quantity),leverage:h.leverage,userAddress:e});},[e,d]);return {positions:y,isLoading:p,error:c,sortKey:n,sortDir:o,onSort:l,handleClosePosition:D,isClosing:f}}function We(e){if(e===void 0||!Number.isFinite(e))return "--";let t=Math.abs(e),r;return t>=1e3?r=0:t>=1?r=2:t>=.01?r=4:r=6,"$"+e.toLocaleString("en-US",{minimumFractionDigits:r,maximumFractionDigits:r})}function Pn(e){return Number.isFinite(e)?"$"+e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function Ta(e){return Number.isFinite(e)?(e>=0?"+":"-")+"$"+Math.abs(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"--"}function Da(e){return Number.isFinite(e)?Math.abs(e).toFixed(2)+"%":"--"}function ka(e,t){return t||(Number.isFinite(e)?e.toFixed(5).replace(/\.?0+$/,""):"--")}var B={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%"}},dt={minWidth:1e3},yr={minHeight:28,maxHeight:28},Oa={minHeight:36,maxHeight:36},wa={start:"justify-start",center:"justify-center",end:"justify-end"};function oe({style:e,children:t,sortKey:r,activeSortKey:s,sortDir:n,onSort:i,align:o="start"}){let l=r!==void 0&&r===s?n==="asc"?" \u2191":" \u2193":"",u=r!==void 0&&i!==void 0,p=wa[o],c=jsxs("span",{className:"text-xs font-normal text-default-500",children:[t,l]});return u?jsx("button",{type:"button",onClick:()=>i?.(r),style:e,className:cn("flex flex-row items-center cursor-pointer hover:text-foreground",p),children:c}):jsx("div",{style:e,className:cn("flex flex-row items-center",p),children:c})}function br({positions:e,sortKey:t,sortDir:r,onSort:s,onClosePosition:n,isClosing:i,className:o}){let{t:a}=useTranslation(),l=jsxs("div",{style:yr,className:"flex flex-1 flex-row items-center justify-start border-default-200 px-4 sm:border-b",children:[jsx(oe,{style:B.asset,sortKey:"asset",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.asset")}),jsx(oe,{style:B.position,sortKey:"position",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.position")}),jsx(oe,{style:B.value,sortKey:"value",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.positionValue")}),jsx(oe,{style:B.entry,sortKey:"entry",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.entryPrice")}),jsx(oe,{style:B.mark,sortKey:"mark",activeSortKey:t,sortDir:r,onSort:s,children:a("perpetuals.positions.col.markPrice")}),jsx(oe,{style:B.liq,sortKey:"liq",activeSortKey:t,sortDir:r,onSort:s,children:jsx(StyledTooltip,{content:a("perpetuals.positions.tooltip.liqPrice"),placement:"top",delay:200,closeDelay:0,children:jsxs("span",{className:"border-b border-dashed border-default-500/40",children:[jsx("span",{className:"hidden sm:inline",children:a("perpetuals.positions.col.liqPrice")}),jsx("span",{className:"inline sm:hidden",children:a("perpetuals.positions.col.liqPriceShort")})]})})}),jsx(oe,{style:B.marginPnl,sortKey:"marginPnl",activeSortKey:t,sortDir:r,onSort:s,children:jsx(StyledTooltip,{content:a("perpetuals.positions.tooltip.marginPnl"),placement:"top",delay:200,closeDelay:0,children:jsx("span",{className:"border-b border-dashed border-default-500/40",children:a("perpetuals.positions.col.marginPnl")})})}),jsx(oe,{style:B.tpsl,align:"center",children:a("perpetuals.positions.col.tpsl")}),jsx(oe,{style:B.close,align:"end",children:a("perpetuals.positions.col.close")})]});return e.length===0?jsx("div",{className:cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",o),children:jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsx("div",{style:{...dt,...yr},className:"flex flex-1 flex-col",children:l}),jsx("div",{style:dt,className:"flex flex-1 flex-col items-center justify-center py-6 text-xs text-default-700",children:a("perpetuals.positions.empty")})]})}):jsx("div",{className:cn("flex w-full min-w-0 flex-col overflow-hidden bg-transparent",o),children:jsxs("div",{className:"flex flex-1 flex-col overflow-x-auto",children:[jsx("div",{style:{...dt,...yr},className:"flex flex-1 flex-col",children:l}),jsx("div",{style:dt,className:"flex flex-1 flex-col overflow-y-auto",children:e.map((u,p)=>jsx(Ra,{position:u,striped:p%2===1,isClosing:i,onClose:n},u.symbol))})]})})}function Ra({position:e,striped:t,isClosing:r,onClose:s}){let{t:n}=useTranslation(),i=e.symbol.split("-")[0],o=e.side==="long",a=n(o?"perpetuals.positions.long":"perpetuals.positions.short"),l=o?"text-bullish":"text-bearish",p=e.unrealizedPnl>=0?"text-bullish":"text-bearish";return jsx("div",{className:cn(t?"bg-default-100/30":"bg-transparent"),children:jsxs("div",{style:Oa,className:"flex flex-1 flex-row items-center justify-start px-4",children:[jsxs("div",{style:B.asset,className:"flex flex-row items-center justify-start gap-1.5",children:[jsx("img",{alt:i,src:`https://app.hyperliquid.xyz/coins/${i}.svg`,className:"rounded-full",style:{width:16,height:16},onError:c=>{c.currentTarget.style.display="none";}}),jsx("span",{className:"text-xs font-medium text-foreground",children:i})]}),jsxs("div",{style:B.position,className:"flex flex-row items-center justify-start gap-1",children:[jsx("span",{className:cn("text-xs font-medium",l),children:a}),jsxs("span",{className:"text-xs font-normal text-default-700",children:[ka(e.quantity,e.quantityRaw)," ",i]})]}),jsx("div",{style:B.value,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:Pn(e.notionalValue)})}),jsx("div",{style:B.entry,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.entryPrice)})}),jsx("div",{style:B.mark,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.markPrice)})}),jsx("div",{style:B.liq,className:"flex flex-row items-center justify-start",children:jsx("span",{className:"text-xs font-normal text-default-700",children:We(e.liquidationPrice)})}),jsxs("div",{style:B.marginPnl,className:"flex flex-row items-center justify-start gap-1",children:[jsx("span",{className:"text-xs font-normal text-default-700",children:Pn(e.margin)}),jsxs("span",{className:cn("text-xs font-medium",p),children:["(",Ta(e.unrealizedPnl)," /"," ",Da(e.unrealizedPnlPercent),")"]})]}),jsxs("div",{style:{...B.tpsl,display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center"},children:[jsx("span",{className:"pr-1 text-right text-xs font-normal text-default-700",children:e.takeProfitPrice!==void 0?We(e.takeProfitPrice):"--"}),jsx("span",{className:"text-xs font-normal text-default-500",children:"/"}),jsx("span",{className:"pl-1 text-left text-xs font-normal text-default-700",children:e.stopLossPrice!==void 0?We(e.stopLossPrice):"--"})]}),jsx("div",{style:B.close,className:"flex flex-row items-center justify-end gap-2",children:jsx("button",{type:"button",onClick:()=>s(e),disabled:r,className: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:n("perpetuals.positions.close.market")})})]})})}function hr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Ea(){return jsx("div",{className:"flex h-24 items-center justify-center text-[14px] text-default-700",children:"No open positions"})}function Aa({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s,className:n}){let{positions:i,isLoading:o,sortKey:a,sortDir:l,onSort:u,handleClosePosition:p,isClosing:c}=gr({userAddress:e,symbol:t,onCloseSuccess:r,onCloseError:s});return o?jsx("div",{className:n,children:jsx(hr,{})}):jsx(br,{positions:i,sortKey:a,sortDir:l,onSort:u,onClosePosition:p,isClosing:c,className:n})}function Sr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s}){let[n,i]=useState([]),{data:o,isLoading:a,error:l}=wt({userAddress:e,symbol:t},{enabled:!!e}),{data:u}=Lt({type:"orders",userAddress:e||"",enabled:!!e}),{mutateAsync:p,isPending:c}=Nt({onSuccess:()=>{r?.();},onError:f=>{s?.(f);}});useEffect(()=>{o?.orders&&i(o.orders);},[o]),useEffect(()=>{u&&i(f=>{let m=f.findIndex(y=>y.orderId===u.orderId);if(u.status==="cancelled"||u.status==="filled"||u.status==="rejected")return m!==-1?f.filter((y,D)=>D!==m):f;if(m!==-1){let y=[...f];return y[m]=u,y}return [u,...f]});},[u]);let d=useCallback(async f=>{if(!e)throw new Error("User address is required");await p({orderId:f.orderId,symbol:f.symbol,userAddress:e});},[e,p]);return {orders:n,isLoading:a,error:l,handleCancelOrder:d,isCanceling:c}}function Dn(e,t=2){return e.toFixed(t)}function Ua(e){return Dn(e,4)}function Pr(e){return Dn(e,4)}function Ma(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0");return `${r}:${s}:${n}`}function vr({orders:e,onCancelOrder:t,isCanceling:r}){return e.length===0?jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"}):jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsx("thead",{children:jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Type"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Amount"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Filled"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Remaining"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Status"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Action"})]})}),jsx("tbody",{children:e.map(s=>jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("td",{className:"py-1.5 px-3",children:jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"font-medium",style:{color:"#ffffff"},children:s.symbol.split("-")[0]}),jsxs("span",{className:cn(s.side==="long"?"text-bullish":"text-bearish"),children:[s.side.toUpperCase(),s.leverage?` ${s.leverage}x`:""]})]})}),jsx("td",{className:"py-1.5 px-3 capitalize",style:{color:"#ffffff"},children:s.orderType}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:s.orderType==="market"?jsx("span",{style:{color:"#b5b5b5"},children:"Market"}):`$${Ua(s.price)}`}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.quantity)}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.filledQuantity)}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Pr(s.remainingQuantity)}),jsx("td",{className:"py-1.5 px-3 text-right",children:jsx("span",{className:cn("px-2 py-0.5 rounded","text-[11px]",s.status==="pending"&&"bg-yellow-600/20 text-yellow-500",s.status==="partially_filled"&&"bg-blue-600/20 text-blue-500",s.status==="filled"&&"bg-green-600/20 text-green-500",s.status==="cancelled"&&"bg-neutral-600/20 text-neutral-400",s.status==="rejected"&&"bg-red-600/20 text-red-500"),children:s.status.replace("_"," ")})}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Ma(s.timestamp)}),jsx("td",{className:"py-1.5 px-3 text-right",children:s.status==="pending"||s.status==="partially_filled"?jsx(Button,{size:"sm",onClick:()=>t(s),isLoading:r,className:"bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1",children:"Cancel"}):jsx("span",{className:"text-[11px]",style:{color:"#6b6d7a"},children:"-"})})]},s.orderId))})]})})}function Cr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Tr(){return jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No open orders"})}function La({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s,className:n}){let{orders:i,isLoading:o,handleCancelOrder:a,isCanceling:l}=Sr({userAddress:e,symbol:t,onCancelSuccess:r,onCancelError:s});return o?jsx("div",{className:n,children:jsx(Cr,{})}):i.length===0?jsx("div",{className:n,children:jsx(Tr,{})}):jsx("div",{className:n,children:jsx(vr,{orders:i,onCancelOrder:a,isCanceling:l})})}function qa(e){let t=Date.now(),r=t;switch(e){case "today":let s=new Date;return s.setHours(0,0,0,0),{startTime:s.getTime(),endTime:r};case "7d":return {startTime:t-10080*60*1e3,endTime:r};case "30d":return {startTime:t-720*60*60*1e3,endTime:r};default:return {}}}function kr({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50}){let[n,i]=useState(r),[o,a]=useState(1),[l,u]=useState([]),{startTime:p,endTime:c}=qa(n),{data:d,isLoading:f,error:m}=Rt({userAddress:e,symbol:t,startTime:p,endTime:c,limit:1e3},{enabled:!!e});useEffect(()=>{d?.trades&&(u(d.trades),a(1));},[d]),useEffect(()=>{a(1);},[n]);let y=Math.ceil(l.length/s),D=(o-1)*s,h=D+s;return {trades:l.slice(D,h),isLoading:f,error:m,timeRange:n,setTimeRange:i,currentPage:o,totalPages:y,goToNextPage:()=>{o<y&&a(o+1);},goToPreviousPage:()=>{o>1&&a(o-1);},goToPage:N=>{N>=1&&N<=y&&a(N);}}}function Or(e,t=2){return e.toFixed(t)}function _a(e){return Or(e,4)}function Ba(e){return Or(e,4)}function Ha(e){let t=new Date(e),r=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return `${r}/${s} ${n}:${i}:${o}`}var Qa=[{label:"Today",value:"today"},{label:"7 Days",value:"7d"},{label:"30 Days",value:"30d"},{label:"All",value:"all"}];function wr({trades:e,timeRange:t,onTimeRangeChange:r,currentPage:s,totalPages:n,onNextPage:i,onPreviousPage:o,onGoToPage:a}){return jsxs("div",{className:"w-full flex flex-col gap-4",children:[jsx("div",{className:"flex gap-2",children:Qa.map(l=>{let u=t===l.value;return jsx("button",{type:"button",className:cn("rounded px-3 transition-colors",!u&&"hover:bg-[#1A1A1A]"),style:{height:24,fontSize:11,border:"1px solid #1c1c1c",backgroundColor:u?"#1c1c1c":"transparent",color:u?"#ffffff":"#b5b5b5"},onClick:()=>r(l.value),children:l.label},l.value)})}),e.length===0?jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"}):jsxs(Fragment,{children:[jsx("div",{className:"w-full overflow-x-auto bg-transparent",children:jsxs("table",{className:"w-full",style:{fontSize:11},children:[jsx("thead",{children:jsxs("tr",{style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Asset"}),jsx("th",{className:"text-left py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Side"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Price"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Quantity"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Fee"}),jsx("th",{className:"text-center py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Maker/Taker"}),jsx("th",{className:"text-right py-1.5 px-3 font-normal",style:{fontSize:11,color:"#b5b5b5"},children:"Time"})]})}),jsx("tbody",{children:e.map(l=>jsxs("tr",{className:"hover:bg-neutral-900/50",style:{borderBottom:"1px solid #1c1c1c"},children:[jsx("td",{className:"py-1.5 px-3 font-medium",style:{color:"#ffffff"},children:l.symbol.split("-")[0]}),jsx("td",{className:"py-1.5 px-3",children:jsx("span",{className:cn("px-2 py-0.5 rounded text-[11px]",l.side==="long"?"bg-bullish/20 text-bullish":"bg-bearish/20 text-bearish"),children:l.side.toUpperCase()})}),jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:["$",_a(l.price)]}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:Ba(l.quantity)}),jsxs("td",{className:"py-1.5 px-3 text-right",style:{color:"#ffffff"},children:[Or(l.fee,4)," ",l.feeCurrency]}),jsx("td",{className:"py-1.5 px-3 text-center",children:jsx("span",{className:cn("px-2 py-0.5 rounded text-[11px]",l.isMaker?"bg-blue-600/20 text-blue-500":"bg-purple-600/20 text-purple-500"),children:l.isMaker?"Maker":"Taker"})}),jsx("td",{className:"py-1.5 px-3 text-right",style:{color:"#b5b5b5"},children:Ha(l.timestamp)})]},l.tradeId))})]})}),n>1&&jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"text-sm text-neutral-400",children:["Page ",s," of ",n]}),jsxs("div",{className:"flex gap-2",children:[jsx(Button,{size:"sm",onClick:o,disabled:s===1,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),jsx("div",{className:"flex gap-1",children:Array.from({length:Math.min(5,n)},(l,u)=>{let p;return n<=5||s<=3?p=u+1:s>=n-2?p=n-4+u:p=s-2+u,jsx("button",{type:"button",className:cn("w-8 h-8 text-sm rounded transition-colors",s===p?"bg-neutral-700 text-white":"text-neutral-400 hover:bg-neutral-800 hover:text-white"),onClick:()=>a(p),children:p},p)})}),jsx(Button,{size:"sm",onClick:i,disabled:s===n,className:"bg-neutral-800 hover:bg-neutral-700 text-white disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})]})}function Rr(){return jsxs("div",{className:"w-full space-y-4 p-4",children:[jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"}),jsx("div",{className:"h-4 bg-neutral-800 rounded w-full animate-pulse"})]})}function Er(){return jsx("div",{className:"flex items-center justify-center h-24",style:{fontSize:11,color:"#b5b5b5"},children:"No trade history"})}function Ka({userAddress:e,symbol:t,initialTimeRange:r="7d",pageSize:s=50,className:n}){let{trades:i,isLoading:o,timeRange:a,setTimeRange:l,currentPage:u,totalPages:p,goToNextPage:c,goToPreviousPage:d,goToPage:f}=kr({userAddress:e,symbol:t,initialTimeRange:r,pageSize:s});return o?jsx("div",{className:n,children:jsx(Rr,{})}):i.length===0?jsx("div",{className:n,children:jsx(Er,{})}):jsx("div",{className:n,children:jsx(wr,{trades:i,timeRange:a,onTimeRangeChange:l,currentPage:u,totalPages:p,onNextPage:c,onPreviousPage:d,onGoToPage:f})})}var Wa=1000000000n,$a=8,Ga=10n**BigInt(8);function $e(e,t=4){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return wn(r,Wa,t)}function ft(e,t=2){if(!e)return "0";let r;try{r=BigInt(e);}catch{return "0"}return wn(r,Ga,t)}var Va=ft;function Ar(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 wn(e,t,r){let s=e<0n,n=s?-e:e,i=n/t,o=n%t;if(r<=0)return o*2n>=t&&(i+=1n),`${s?"-":""}${i.toString()}`;let a=10n**BigInt(r),l=(o*a+t/2n)/t;l>=a&&(i+=1n,l=0n);let u=l.toString().padStart(r,"0");return u=u.replace(/0+$/,""),u?`${s?"-":""}${i.toString()}.${u}`:`${s?"-":""}${i.toString()}`}function Ge(e,t=Date.now()){return Math.max(0,Math.floor((e-t)/1e3))}function Nr(e,t=6,r=4){return e?e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`:""}function Ir({isOpen:e,quote:t,isExecuting:r,isExpired:s,onConfirm:n,onCancel:i,onExpire:o,error:a}){let{t:l}=useTranslation(),u=t?Date.parse(t.expiresAt):0,[p,c]=useState(()=>u?Ge(u):0);return useEffect(()=>{if(!e||!u)return;c(Ge(u));let d=setInterval(()=>{let f=Ge(u);c(f),f===0&&(o?.(),clearInterval(d));},1e3);return ()=>clearInterval(d)},[e,u,o]),jsx(Modal,{isOpen:e,onOpenChange:d=>!d&&i(),hideCloseButton:true,backdrop:"blur",children:jsxs(ModalContent,{className:"bg-content2 rounded-lg",children:[jsx(ModalHeader,{children:l("perpDeposit.confirm.title")}),jsxs(ModalBody,{children:[t?jsx(sl,{breakdown:t.breakdown}):jsx("div",{className:"flex h-32 items-center justify-center",children:jsx(Spinner,{})}),t&&!s&&jsx("div",{className:"text-default-500 mt-4 text-xs",children:l("perpDeposit.confirm.expiresIn",{seconds:p})}),s&&jsx("div",{className:"text-warning-500 mt-4 text-xs",children:l("perpDeposit.confirm.expired")}),a&&jsx("div",{className:"text-danger mt-4 text-xs",children:a})]}),jsxs(ModalFooter,{className:"flex justify-between gap-2",children:[jsx(Button,{variant:"flat",color:"default",onPress:i,isDisabled:r,children:l("perpDeposit.confirm.cancel")}),jsx(Button,{color:"primary",onPress:n,isDisabled:!t||r||s,isLoading:r,children:l("perpDeposit.confirm.cta")})]})]})})}function sl({breakdown:e}){let{t}=useTranslation();return jsxs("dl",{className:"flex flex-col gap-2 text-sm",children:[jsx(gt,{label:t("perpDeposit.confirm.send"),value:`${$e(e.grossLamports)} SOL`}),jsx(gt,{label:t("perpDeposit.confirm.receive"),value:`${ft(e.expectedOutputUSDC)} USDC`,highlight:true}),jsx(gt,{label:t("perpDeposit.confirm.platformFee"),value:`${$e(e.platformFeeLamports,6)} SOL`,muted:true}),jsx(gt,{label:t("perpDeposit.confirm.relayFee"),value:`${$e(e.relayDepositLamports,6)} SOL`,muted:true})]})}function gt({label:e,value:t,highlight:r,muted:s}){return jsxs("div",{className:"flex items-center justify-between",children:[jsx("dt",{className:"text-default-500",children:e}),jsx("dd",{className:r?"text-foreground text-base font-semibold":s?"text-default-500 text-xs":"text-foreground",children:t})]})}function Fr({amount:e,onAmountChange:t,recipient:r,onRecipientChange:s,balanceSol:n,disabled:i,amountError:o,recipientError:a,onMax:l,className:u}){let{t:p}=useTranslation();return jsxs("div",{className:cn("flex flex-col gap-4",u),children:[jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[jsx("label",{htmlFor:"perp-deposit-amount",className:"text-sm font-medium text-foreground",children:p("perpDeposit.amount")}),n&&jsx("span",{className:"text-xs text-default-500",children:p("perpDeposit.amount.balance",{balance:n})})]}),jsx("div",{className:"relative",children:jsx(Input,{id:"perp-deposit-amount",type:"text",inputMode:"decimal",placeholder:p("perpDeposit.amount.placeholder"),value:e,onValueChange:t,isDisabled:i,isInvalid:!!o,errorMessage:o,endContent:jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{className:"text-default-500 text-sm",children:p("perpDeposit.amount.unit")}),n&&l&&jsx(Button,{size:"sm",variant:"flat",color:"primary",onPress:l,isDisabled:i,children:p("perpDeposit.amount.max")})]})})})]}),jsxs("div",{children:[jsx("label",{htmlFor:"perp-deposit-recipient",className:"text-sm font-medium text-foreground mb-1.5 block",children:p("perpDeposit.recipient")}),jsx(Input,{id:"perp-deposit-recipient",type:"text",placeholder:p("perpDeposit.recipient.placeholder"),value:r,onValueChange:s,isDisabled:i,isInvalid:!!a,errorMessage:a,autoComplete:"off",spellCheck:"false"})]})]})}var In="#C7FF2E";function Mr({isOpen:e,phase:t,status:r,solanaExplorerUrl:s,hyperliquidExplorerUrl:n,onRetry:i,onClose:o,errorMessage:a}){let{t:l}=useTranslation(),u=ml(t),p=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"),c=t==="failed"&&!!i;return jsx(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:jsx(ModalContent,{children:jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-start justify-between px-5 pt-5 pb-2",children:[jsx("div",{className:"flex items-center gap-2.5",children:jsx("h3",{className:"text-base font-semibold text-white",children:l("perpDeposit.status.title")})}),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:jsx(XCloseIcon,{width:16,height:16})})]}),jsxs("div",{className:"px-5 pb-3 pt-2",children:[jsxs("div",{className:"rounded-[12px] bg-[#0a0a0b] border border-[#27272a] px-4 py-6 flex flex-col items-center text-center gap-4",children:[jsx(cl,{variant:u}),jsx("p",{className:cn("text-sm leading-relaxed max-w-[320px]",fl(u)),children:p})]}),(r?.solanaTxHash||r?.hyperliquidTxHash)&&jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?.solanaTxHash&&s&&jsx(Nn,{href:s,label:l("perpDeposit.status.viewSolanaTx"),hash:r.solanaTxHash}),r?.hyperliquidTxHash&&n&&jsx(Nn,{href:n,label:l("perpDeposit.status.viewHyperliquidTx"),hash:r.hyperliquidTxHash})]})]}),jsxs("div",{className:cn("px-5 pb-5 pt-2 flex gap-2",c?"justify-between":"justify-end"),children:[c&&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")}),jsx("button",{type:"button",onClick:o,className:cn("cursor-pointer h-10 rounded-[10px] font-medium transition-colors flex items-center justify-center",c?"flex-1 bg-[rgba(39,39,42,1)] hover:bg-[rgba(63,63,70,1)] text-white":"px-6 bg-[rgba(39,39,42,1)] hover:bg-[rgba(63,63,70,1)] text-white"),children:l("perpDeposit.status.close")})]})]})})})}function Nn({href:e,label:t,hash:r}){return jsxs("a",{href:e,target:"_blank",rel:"noreferrer",className:"group flex items-center justify-between gap-2 px-3 py-2 rounded-[10px] bg-[#0a0a0b] border border-[#27272a] hover:border-[rgba(199,255,46,0.4)] transition-colors",children:[jsx("span",{className:"text-xs text-zinc-400 group-hover:text-white transition-colors",children:t}),jsxs("span",{className:"flex items-center gap-1.5 text-xs tabular-nums text-zinc-300 group-hover:text-[#C7FF2E] transition-colors",children:[Nr(r,6,4),jsx(hl,{})]})]})}function cl({variant:e}){return e==="progress"?jsx("div",{className:"relative w-14 h-14 flex items-center justify-center",children:jsx(dl,{})}):e==="success"?jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(199,255,46,0.12)]",children:jsx(gl,{className:"w-8 h-8",style:{color:In}})}):e==="warning"?jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(245,158,11,0.12)]",children:jsx(yl,{className:"w-8 h-8 text-amber-400"})}):jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center bg-[rgba(239,68,68,0.12)]",children:jsx(bl,{className:"w-8 h-8 text-rose-400"})})}function dl(){return jsxs(Fragment,{children:[jsxs("svg",{className:"lfi-perp-deposit-spinner",viewBox:"0 0 50 50",width:48,height:48,"aria-hidden":"true",children:[jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"4"}),jsx("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:In,strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"90 60"})]}),jsx("style",{children:`
|
|
26
26
|
.lfi-perp-deposit-spinner {
|
|
27
27
|
animation: lfi-perp-deposit-spin 0.9s linear infinite;
|
|
28
28
|
transform-origin: center;
|
|
@@ -30,5 +30,5 @@ import {createContext,memo,useMemo,useContext,useState,useRef,useCallback,useEff
|
|
|
30
30
|
@keyframes lfi-perp-deposit-spin {
|
|
31
31
|
to { transform: rotate(360deg); }
|
|
32
32
|
}
|
|
33
|
-
`})]})}function dl(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function ml(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 fl(e){return jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e.className,style:e.style,children:jsx("path",{d:"M20 6L9 17l-5-5"})})}function gl(e){return jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm0 4c.6 0 1 .4 1 1v6c0 .6-.4 1-1 1s-1-.4-1-1V7c0-.6.4-1 1-1zm0 12c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"})})}function yl(e){return jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e.className,children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("path",{d:"M15 9l-6 6M9 9l6 6"})]})}function bl(){return jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),jsx("polyline",{points:"15 3 21 3 21 9"}),jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}function Cl({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:u,buildHyperliquidExplorerUrl:p,onSettled:c,onError:d,className:f}){let{t:m}=useTranslation(),[y,D]=useState(""),[h,x]=useState(n??""),C=useMemo(()=>{if(y&&(!/^\d+(\.\d+)?$/.test(y.trim())||Number(y)<=0))return m("perpDeposit.error.amountInvalid")},[y,m]),E=useMemo(()=>{if(h)return l?l(h):void 0},[h,l]),w=useMemo(()=>C?"":Ar(y),[y,C]),N=useMemo(()=>!w||w==="0"||E||!h?null:{userSolanaAddress:e,hyperliquidRecipient:h,grossLamports:w,source:r},[w,h,E,r,e]),I=Bt(N,{enabled:!!N}),{state:g,execute:z,reset:H,dispatch:L}=Ht(i),ee=g.phase==="submitted"||g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"?g.intentId:void 0,V=Qt(ee,{enabled:!!ee&&g.phase!=="succeeded"&&g.phase!=="refunded"&&g.phase!=="failed"});useEffect(()=>{V.data&&L({type:"STATUS_UPDATE",status:V.data});},[V.data,L]),useEffect(()=>{g.phase==="succeeded"?c?.(g.intentId):g.phase==="failed"&&d?.(g.intentId,g.error.message);},[g,c,d]);let Ie=useCallback(()=>{I.data&&(L({type:"QUOTE_REQUEST"}),L({type:"QUOTE_RECEIVED",quote:I.data}));},[L,I.data]),ne=useCallback(async()=>{if(g.phase==="ready_to_sign")try{await z({quote:g.quote,userSolanaAddress:e,hyperliquidRecipient:h,userId:t,source:r,campaign:s});}catch{}},[g,z,e,h,t,r,s]),Te=useCallback(()=>{L({type:"QUOTE_EXPIRED"});},[L]),K=useCallback(async()=>{L({type:"RESET"}),await I.refetch();},[L,I]),Fe=g.phase==="ready_to_sign"||g.phase==="signing"||g.phase==="broadcasting"||g.phase==="expired",Ue=g.phase==="submitted"||g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"&&!!g.intentId,S=g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"?g.status:void 0,te=!I.data||I.isFetching||!!C||!!E||!N;return jsxs(Card,{className:f,children:[jsxs(CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxs("div",{children:[jsx("h3",{className:"text-lg font-semibold",children:m("perpDeposit.title")}),jsx("p",{className:"text-default-500 text-sm",children:m("perpDeposit.description")})]}),jsx(Fr,{amount:y,onAmountChange:D,recipient:h,onRecipientChange:x,balanceSol:o,onMax:a,amountError:C,recipientError:E,disabled:g.phase!=="idle"&&g.phase!=="expired"&&g.phase!=="failed"}),jsx(Button,{color:"primary",isDisabled:te,isLoading:I.isFetching,onPress:Ie,children:I.isFetching?m("perpDeposit.gettingQuote"):m("perpDeposit.confirmQuote")}),I.error&&jsx("div",{className:"text-danger text-xs",children:m("perpDeposit.error.quoteFailed")})]}),jsx(Ir,{isOpen:Fe,quote:g.phase==="ready_to_sign"||g.phase==="signing"||g.phase==="broadcasting"||g.phase==="expired"?g.quote:void 0,isExecuting:g.phase==="signing"||g.phase==="broadcasting",isExpired:g.phase==="expired",onConfirm:ne,onCancel:H,onExpire:Te}),jsx(Mr,{isOpen:Ue,phase:g.phase,status:S,solanaExplorerUrl:S?.solanaTxHash&&u?u(S.solanaTxHash):void 0,hyperliquidExplorerUrl:S?.hyperliquidTxHash&&p?p(S.hyperliquidTxHash):void 0,onRetry:g.phase==="failed"?K:void 0,onClose:H,errorMessage:g.phase==="failed"?g.error.message:void 0})]})}function Br({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=useTranslation(),a=e.phase,l=a==="executing",u=a==="loading",p=a==="error"&&e.steps.length===0;return jsxs(Card,{className:cn("w-full max-w-md",i),children:[jsxs(CardHeader,{className:"flex flex-col items-start gap-1",children:[jsx("h3",{className:"text-lg font-semibold",children:o("perpDeposit.setup.title")}),jsx("p",{className:"text-foreground-500 text-sm",children:o("perpDeposit.setup.description")})]}),jsxs(CardBody,{className:"gap-3",children:[u&&jsx(Rl,{}),p&&jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!u&&!p&&e.steps.map((c,d)=>jsx(wl,{rec:c,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${c.step.id}-${d}`)),a==="done"&&jsx("p",{className:"text-success text-sm",children:o("perpDeposit.setup.alreadyActive")})]}),jsxs(CardFooter,{className:"flex justify-between gap-2",children:[n&&jsx(Button,{variant:"light",onPress:n,isDisabled:l,children:o(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsx("div",{className:"flex-1"}),p&&s&&jsx(Button,{color:"primary",onPress:s,children:o("perpDeposit.setup.retry")}),!p&&a!=="done"&&jsx(Button,{color:"primary",onPress:t,isLoading:l,isDisabled:l||u,children:e.steps.some(c=>c.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function wl({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=useTranslation(),i=Nl(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 jsxs("div",{className: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:[jsxs("div",{className:"flex-1",children:[jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsx(El,{status:e.status,isCurrent:r}),jsx("span",{children:i})]}),jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:o}),e.status==="error"&&e.error&&jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsx("span",{className:cn(Al(e.status)),children:a}),e.status==="error"&&s&&jsx(Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function Rl(){let{t:e}=useTranslation();return jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsx(Spinner,{size:"sm"}),jsx("span",{children:e("perpDeposit.setup.loading")})]})}function El({status:e,isCurrent:t}){return e==="running"||t?jsx(Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Al(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 Nl(e,t){return t()}function Il({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:l,runNext:u,runStep:p,reload:c}=ot({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),d=useCallback(()=>{u();},[u]),f=useCallback(y=>{p(y);},[p]),m=useCallback(()=>{c();},[c]);return jsx(Br,{state:l,onContinue:d,onRetryStep:f,onReload:m,onDismiss:o,className:a})}export{zt as CoinInfoNotFoundUI,$t as CoinInfoSkeletonsUI,jt as CoinInfoUI,Wi as CoinInfoWidget,Gs as DEFAULT_ORDER_BOOK_PRECISION_OPTIONS,Ir as DepositConfirmUI,Cl as DepositFlowWidget,Fr as DepositFormUI,Mr as DepositStatusUI,Wa as HL_USDC_DECIMALS,le as HyperliquidApiError,Br as HyperliquidInitUI,Il as HyperliquidInitWidget,St as HyperliquidPerpetualsClient,j as LiberFiApiError,ge as LiberFiHttpTransport,vt as LiberFiPerpDepositClient,Pt as LiberFiPerpetualsClient,Tr as OpenOrdersEmpty,Cr as OpenOrdersSkeleton,vr as OpenOrdersUI,Ma as OpenOrdersWidget,sr as OrderBookUI,Co as OrderBookWidget,ue as PerpetualsContext,ti as PerpetualsProvider,fr as PlaceOrderFormUI,va as PlaceOrderFormWidget,Ra as PositionsEmpty,hr as PositionsSkeleton,br as PositionsUI,Ea as PositionsWidget,Jt as SearchCoinsUI,Yi as SearchCoinsWidget,Me as TERMINAL_DEPOSIT_STATUSES,Er as TradeHistoryEmpty,Rr as TradeHistorySkeleton,wr as TradeHistoryUI,za as TradeHistoryWidget,ur as TradesUI,ea as TradesWidget,tt as accountStateQueryKey,cs as activeAssetLeverageQueryKey,qs as aggregationFromStep,ms as assetMetaQueryKey,ys as cancelOrder,rt as classifyStep,Gr as coinsQueryKey,gs as createOrder,Xn as currentDepositBreakdown,Yn as currentDepositStatus,ds as fetchActiveAssetLeverage,fs as fetchAssetMeta,Vr as fetchCoins,rs as fetchKlines,Xr as fetchMarket,es as fetchMarkets,ns as fetchOrderBook,ls as fetchOrders,xs as fetchPerpDepositQuote,Cs as fetchPerpDepositStatus,as as fetchPositions,os as fetchRecentTrades,ps as fetchTrades,ft as hlUsdcRawToUsdc,Je as initialDepositState,Be as initialSetupState,jn as isDepositPolling,Vn as isDepositTerminal,Jn as isTerminalDepositLifecycle,ts as klinesQueryKey,$e as lamportsToSol,Yr as marketQueryKey,Zr as marketsQueryKey,Ga as microUsdcToUsdc,nt as nextRunnableStep,ss as orderBookQueryKey,et as ordersQueryKey,hs as perpDepositQuoteQueryKey,vs as perpDepositStatusQueryKey,Ze as positionsQueryKey,is as recentTradesQueryKey,Ct as reduceDepositState,st as reduceSetupState,Ge as secondsUntil,Nr as shortAddress,Ar as solToLamports,us as tradesQueryKey,qt as useAccountStateQuery,wi as useAccountStateSubscription,Et as useActiveAssetLeverageQuery,At as useAssetMetaQuery,Nt as useCancelOrderMutation,vi as useCandlesSubscription,Vt as useCoinInfo,Tt as useCoinsQuery,_e as useCreateOrderMutation,ot as useHyperliquidSetup,li as useKlinesQuery,ye as useMarketDataSubscription,Le as useMarketQuery,Dt as useMarketsQuery,Sr as useOpenOrdersScript,kt as useOrderBookQuery,er as useOrderBookScript,wt as useOrdersQuery,Ri as usePerpDepositClient,be as usePerpDepositClientMaybe,Ht as usePerpDepositExecute,Bt as usePerpDepositQuote,Qt as usePerpDepositStatus,k as usePerpetualsClient,cr as usePlaceOrderFormScript,qe as usePositionsQuery,gr as usePositionsScript,Ot as useRecentTradesQuery,Xt as useSearchCoinsScript,kr as useTradeHistoryScript,Rt as useTradesQuery,or as useTradesScript,Lt as useUserDataSubscription,qn as version};//# sourceMappingURL=index.mjs.map
|
|
33
|
+
`})]})}function ml(e){switch(e){case "succeeded":return "success";case "refunded":return "warning";case "failed":return "error";default:return "progress"}}function fl(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 gl(e){return jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e.className,style:e.style,children:jsx("path",{d:"M20 6L9 17l-5-5"})})}function yl(e){return jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",className:e.className,children:jsx("path",{d:"M12 2a10 10 0 100 20 10 10 0 000-20zm0 4c.6 0 1 .4 1 1v6c0 .6-.4 1-1 1s-1-.4-1-1V7c0-.6.4-1 1-1zm0 12c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"})})}function bl(e){return jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e.className,children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("path",{d:"M15 9l-6 6M9 9l6 6"})]})}function hl(){return jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),jsx("polyline",{points:"15 3 21 3 21 9"}),jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}function Tl({userSolanaAddress:e,userId:t,source:r,campaign:s,defaultRecipient:n,signAndBroadcast:i,balanceSol:o,onMaxClick:a,validateRecipient:l,buildSolanaExplorerUrl:u,buildHyperliquidExplorerUrl:p,onSettled:c,onError:d,className:f}){let{t:m}=useTranslation(),[y,D]=useState(""),[h,x]=useState(n??""),C=useMemo(()=>{if(y&&(!/^\d+(\.\d+)?$/.test(y.trim())||Number(y)<=0))return m("perpDeposit.error.amountInvalid")},[y,m]),E=useMemo(()=>{if(h)return l?l(h):void 0},[h,l]),w=useMemo(()=>C?"":Ar(y),[y,C]),N=useMemo(()=>!w||w==="0"||E||!h?null:{userSolanaAddress:e,hyperliquidRecipient:h,grossLamports:w,source:r},[w,h,E,r,e]),I=Bt(N,{enabled:!!N}),{state:g,execute:z,reset:H,dispatch:L}=Ht(i),ee=g.phase==="submitted"||g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"?g.intentId:void 0,V=Qt(ee,{enabled:!!ee&&g.phase!=="succeeded"&&g.phase!=="refunded"&&g.phase!=="failed"});useEffect(()=>{V.data&&L({type:"STATUS_UPDATE",status:V.data});},[V.data,L]),useEffect(()=>{g.phase==="succeeded"?c?.(g.intentId):g.phase==="failed"&&d?.(g.intentId,g.error.message);},[g,c,d]);let Ie=useCallback(()=>{I.data&&(L({type:"QUOTE_REQUEST"}),L({type:"QUOTE_RECEIVED",quote:I.data}));},[L,I.data]),ne=useCallback(async()=>{if(g.phase==="ready_to_sign")try{await z({quote:g.quote,userSolanaAddress:e,hyperliquidRecipient:h,userId:t,source:r,campaign:s});}catch{}},[g,z,e,h,t,r,s]),Te=useCallback(()=>{L({type:"QUOTE_EXPIRED"});},[L]),K=useCallback(async()=>{L({type:"RESET"}),await I.refetch();},[L,I]),Fe=g.phase==="ready_to_sign"||g.phase==="signing"||g.phase==="broadcasting"||g.phase==="expired",Ue=g.phase==="submitted"||g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"&&!!g.intentId,S=g.phase==="tracking"||g.phase==="succeeded"||g.phase==="refunded"||g.phase==="failed"?g.status:void 0,te=!I.data||I.isFetching||!!C||!!E||!N;return jsxs(Card,{className:f,children:[jsxs(CardBody,{className:"flex flex-col gap-4 p-6",children:[jsxs("div",{children:[jsx("h3",{className:"text-lg font-semibold",children:m("perpDeposit.title")}),jsx("p",{className:"text-default-500 text-sm",children:m("perpDeposit.description")})]}),jsx(Fr,{amount:y,onAmountChange:D,recipient:h,onRecipientChange:x,balanceSol:o,onMax:a,amountError:C,recipientError:E,disabled:g.phase!=="idle"&&g.phase!=="expired"&&g.phase!=="failed"}),jsx(Button,{color:"primary",isDisabled:te,isLoading:I.isFetching,onPress:Ie,children:I.isFetching?m("perpDeposit.gettingQuote"):m("perpDeposit.confirmQuote")}),I.error&&jsx("div",{className:"text-danger text-xs",children:m("perpDeposit.error.quoteFailed")})]}),jsx(Ir,{isOpen:Fe,quote:g.phase==="ready_to_sign"||g.phase==="signing"||g.phase==="broadcasting"||g.phase==="expired"?g.quote:void 0,isExecuting:g.phase==="signing"||g.phase==="broadcasting",isExpired:g.phase==="expired",onConfirm:ne,onCancel:H,onExpire:Te}),jsx(Mr,{isOpen:Ue,phase:g.phase,status:S,solanaExplorerUrl:S?.solanaTxHash&&u?u(S.solanaTxHash):void 0,hyperliquidExplorerUrl:S?.hyperliquidTxHash&&p?p(S.hyperliquidTxHash):void 0,onRetry:g.phase==="failed"?K:void 0,onClose:H,errorMessage:g.phase==="failed"?g.error.message:void 0})]})}function Br({state:e,onContinue:t,onRetryStep:r,onReload:s,onDismiss:n,className:i}){let{t:o}=useTranslation(),a=e.phase,l=a==="executing",u=a==="loading",p=a==="error"&&e.steps.length===0;return jsxs(Card,{className:cn("w-full max-w-md",i),children:[jsxs(CardHeader,{className:"flex flex-col items-start gap-1",children:[jsx("h3",{className:"text-lg font-semibold",children:o("perpDeposit.setup.title")}),jsx("p",{className:"text-foreground-500 text-sm",children:o("perpDeposit.setup.description")})]}),jsxs(CardBody,{className:"gap-3",children:[u&&jsx(El,{}),p&&jsx("p",{className:"text-danger text-sm",children:o("perpDeposit.setup.loadFailed",{message:e.error??""})}),!u&&!p&&e.steps.map((c,d)=>jsx(Rl,{rec:c,index:d,isCurrent:e.currentIndex===d,onRetry:r},`${c.step.id}-${d}`)),a==="done"&&jsx("p",{className:"text-success text-sm",children:o("perpDeposit.setup.alreadyActive")})]}),jsxs(CardFooter,{className:"flex justify-between gap-2",children:[n&&jsx(Button,{variant:"light",onPress:n,isDisabled:l,children:o(a==="done"?"perpDeposit.setup.dismiss":"perpDeposit.setup.skip")}),jsx("div",{className:"flex-1"}),p&&s&&jsx(Button,{color:"primary",onPress:s,children:o("perpDeposit.setup.retry")}),!p&&a!=="done"&&jsx(Button,{color:"primary",onPress:t,isLoading:l,isDisabled:l||u,children:e.steps.some(c=>c.status==="done")?o("perpDeposit.setup.continue"):o("perpDeposit.setup.cta")})]})]})}function Rl({rec:e,index:t,isCurrent:r,onRetry:s}){let{t:n}=useTranslation(),i=Il(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 jsxs("div",{className: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:[jsxs("div",{className:"flex-1",children:[jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[jsx(Al,{status:e.status,isCurrent:r}),jsx("span",{children:i})]}),jsx("p",{className:"text-foreground-500 mt-1 text-xs",children:o}),e.status==="error"&&e.error&&jsx("p",{className:"text-danger mt-1 text-xs",children:e.error})]}),jsxs("div",{className:"flex flex-col items-end gap-1 text-xs",children:[jsx("span",{className:cn(Nl(e.status)),children:a}),e.status==="error"&&s&&jsx(Button,{size:"sm",variant:"flat",color:"danger",onPress:()=>s(t),children:n("perpDeposit.setup.retry")})]})]})}function El(){let{t:e}=useTranslation();return jsxs("div",{className:"flex items-center gap-2 py-2 text-sm",children:[jsx(Spinner,{size:"sm"}),jsx("span",{children:e("perpDeposit.setup.loading")})]})}function Al({status:e,isCurrent:t}){return e==="running"||t?jsx(Spinner,{size:"sm"}):e==="done"||e==="skipped"?jsx("span",{"aria-hidden":true,className:"text-success",children:"\u2713"}):e==="error"?jsx("span",{"aria-hidden":true,className:"text-danger",children:"!"}):jsx("span",{"aria-hidden":true,className:"border-foreground-400 inline-block h-3 w-3 rounded-full border"})}function Nl(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 Il(e,t){return t()}function Fl({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i,onDismiss:o,className:a}){let{state:l,runNext:u,runStep:p,reload:c}=ot({adapter:e,userAddress:t,steps:r,autoLoad:s,onComplete:n,onError:i}),d=useCallback(()=>{u();},[u]),f=useCallback(y=>{p(y);},[p]),m=useCallback(()=>{c();},[c]);return jsx(Br,{state:l,onContinue:d,onRetryStep:f,onReload:m,onDismiss:o,className:a})}export{zt as CoinInfoNotFoundUI,$t as CoinInfoSkeletonsUI,jt as CoinInfoUI,Wi as CoinInfoWidget,Gs as DEFAULT_ORDER_BOOK_PRECISION_OPTIONS,Ir as DepositConfirmUI,Tl as DepositFlowWidget,Fr as DepositFormUI,Mr as DepositStatusUI,$a as HL_USDC_DECIMALS,le as HyperliquidApiError,Br as HyperliquidInitUI,Fl as HyperliquidInitWidget,St as HyperliquidPerpetualsClient,j as LiberFiApiError,ge as LiberFiHttpTransport,vt as LiberFiPerpDepositClient,Pt as LiberFiPerpetualsClient,Tr as OpenOrdersEmpty,Cr as OpenOrdersSkeleton,vr as OpenOrdersUI,La as OpenOrdersWidget,sr as OrderBookUI,Co as OrderBookWidget,ue as PerpetualsContext,ti as PerpetualsProvider,fr as PlaceOrderFormUI,va as PlaceOrderFormWidget,Ea as PositionsEmpty,hr as PositionsSkeleton,br as PositionsUI,Aa as PositionsWidget,Xt as SearchCoinsUI,Yi as SearchCoinsWidget,Me as TERMINAL_DEPOSIT_STATUSES,Er as TradeHistoryEmpty,Rr as TradeHistorySkeleton,wr as TradeHistoryUI,Ka as TradeHistoryWidget,ur as TradesUI,ea as TradesWidget,tt as accountStateQueryKey,cs as activeAssetLeverageQueryKey,qs as aggregationFromStep,ms as assetMetaQueryKey,ys as cancelOrder,rt as classifyStep,Gr as coinsQueryKey,gs as createOrder,Jn as currentDepositBreakdown,Yn as currentDepositStatus,ds as fetchActiveAssetLeverage,fs as fetchAssetMeta,Vr as fetchCoins,rs as fetchKlines,Jr as fetchMarket,es as fetchMarkets,ns as fetchOrderBook,ls as fetchOrders,xs as fetchPerpDepositQuote,Cs as fetchPerpDepositStatus,as as fetchPositions,os as fetchRecentTrades,ps as fetchTrades,ft as hlUsdcRawToUsdc,Xe as initialDepositState,Be as initialSetupState,jn as isDepositPolling,Vn as isDepositTerminal,Xn as isTerminalDepositLifecycle,ts as klinesQueryKey,$e as lamportsToSol,Yr as marketQueryKey,Zr as marketsQueryKey,Va as microUsdcToUsdc,nt as nextRunnableStep,ss as orderBookQueryKey,et as ordersQueryKey,hs as perpDepositQuoteQueryKey,vs as perpDepositStatusQueryKey,Ze as positionsQueryKey,is as recentTradesQueryKey,Ct as reduceDepositState,st as reduceSetupState,Ge as secondsUntil,Nr as shortAddress,Ar as solToLamports,us as tradesQueryKey,qt as useAccountStateQuery,wi as useAccountStateSubscription,Et as useActiveAssetLeverageQuery,At as useAssetMetaQuery,Nt as useCancelOrderMutation,vi as useCandlesSubscription,Vt as useCoinInfo,Tt as useCoinsQuery,_e as useCreateOrderMutation,ot as useHyperliquidSetup,li as useKlinesQuery,ye as useMarketDataSubscription,Le as useMarketQuery,Dt as useMarketsQuery,Sr as useOpenOrdersScript,kt as useOrderBookQuery,er as useOrderBookScript,wt as useOrdersQuery,Ri as usePerpDepositClient,be as usePerpDepositClientMaybe,Ht as usePerpDepositExecute,Bt as usePerpDepositQuote,Qt as usePerpDepositStatus,k as usePerpetualsClient,cr as usePlaceOrderFormScript,qe as usePositionsQuery,gr as usePositionsScript,Ot as useRecentTradesQuery,Jt as useSearchCoinsScript,kr as useTradeHistoryScript,Rt as useTradesQuery,or as useTradesScript,Lt as useUserDataSubscription,qn as version};//# sourceMappingURL=index.mjs.map
|
|
34
34
|
//# sourceMappingURL=index.mjs.map
|