UNPKG

hyperliquid

Version:
1 lines 81.5 kB
var _=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var N={PRODUCTION:"https://api.hyperliquid.xyz",TESTNET:"https://api.hyperliquid-testnet.xyz"},X={PRODUCTION:"wss://api.hyperliquid.xyz/ws",TESTNET:"wss://api.hyperliquid-testnet.xyz/ws"},d={ARBITRUM_MAINNET:"0xa4b1",ARBITRUM_TESTNET:"0x66eee"},M={INFO:"/info",EXCHANGE:"/exchange"},ie=(l=>(l.ALL_MIDS="allMids",l.META="meta",l.OPEN_ORDERS="openOrders",l.FRONTEND_OPEN_ORDERS="frontendOpenOrders",l.USER_FILLS="userFills",l.USER_FILLS_BY_TIME="userFillsByTime",l.USER_RATE_LIMIT="userRateLimit",l.ORDER_STATUS="orderStatus",l.L2_BOOK="l2Book",l.CANDLE_SNAPSHOT="candleSnapshot",l.PERPS_META_AND_ASSET_CTXS="metaAndAssetCtxs",l.PERPS_CLEARINGHOUSE_STATE="clearinghouseState",l.USER_FUNDING="userFunding",l.USER_NON_FUNDING_LEDGER_UPDATES="userNonFundingLedgerUpdates",l.FUNDING_HISTORY="fundingHistory",l.SPOT_META="spotMeta",l.SPOT_CLEARINGHOUSE_STATE="spotClearinghouseState",l.SPOT_META_AND_ASSET_CTXS="spotMetaAndAssetCtxs",l.PREDICTED_FUNDINGS="predictedFundings",l.SPOT_DEPLOY_STATE="spotDeployState",l.TOKEN_DETAILS="tokenDetails",l.MAX_BUILDER_FEE="maxBuilderFee",l.HISTORICAL_ORDERS="historicalOrders",l.USER_TWAP_SLICE_FILLS="userTwapSliceFills",l.SUB_ACCOUNTS="subAccounts",l.VAULT_DETAILS="vaultDetails",l.USER_VAULT_EQUITIES="userVaultEquities",l.USER_ROLE="userRole",l.DELEGATIONS="delegations",l.DELEGATOR_SUMMARY="delegatorSummary",l.PERPS_AT_OPEN_INTEREST_CAP="perpsAtOpenInterestCap",l.DELEGATOR_HISTORY="delegatorHistory",l.DELEGATOR_REWARDS="delegatorRewards",l.VALIDATOR_SUMMARIES="validatorSummaries",l.VAULT_SUMMARIES="vaultSummaries",l.BLOCK_DETAILS="blockDetails",l.TX_DETAILS="txDetails",l.USER_DETAILS="userDetails",l.USER_FEES="userFees",l.PORTFOLIO="portfolio",l.PRE_TRANSFER_CHECK="preTransferCheck",l.REFERRAL="referral",l.EXTRA_AGENTS="extraAgents",l.IS_VIP="isVip",l.LEGAL_CHECK="legalCheck",l.USER_TWAP_SLICE_FILLS_BY_TIME="userTwapSliceFillsByTime",l.TWAP_HISTORY="twapHistory",l.USER_TO_MULTI_SIG_SIGNERS="userToMultiSigSigners",l.BUILDER_FEE_APPROVAL="builderFeeApproval",l.USER_ORDER_HISTORY="userOrderHistory",l.PERP_DEX_LIMITS="perpDexLimits",l))(ie||{}),J=(p=>(p.ORDER="order",p.CANCEL="cancel",p.CANCEL_BY_CLOID="cancelByCloid",p.SCHEDULE_CANCEL="scheduleCancel",p.MODIFY="modify",p.BATCH_MODIFY="batchModify",p.UPDATE_LEVERAGE="updateLeverage",p.UPDATE_ISOLATED_MARGIN="updateIsolatedMargin",p.USD_SEND="usdSend",p.SPOT_SEND="spotSend",p.WITHDRAW="withdraw3",p.SPOT_USER="spotUser",p.VAULT_TRANSFER="vaultTransfer",p.CREATE_VAULT="createVault",p.VAULT_DISTRIBUTE="vaultDistribute",p.VAULT_MODIFY="vaultModify",p.SET_REFERRER="setReferrer",p.REGISTER_REFERRER="registerReferrer",p.USD_CLASS_TRANSFER="usdClassTransfer",p.TWAP_ORDER="twapOrder",p.TWAP_CANCEL="twapCancel",p.APPROVE_AGENT="approveAgent",p.APPROVE_BUILDER_FEE="approveBuilderFee",p.EVM_USER_MODIFY="evmUserModify",p.CLAIM_REWARDS="claimRewards",p.CREATE_SUB_ACCOUNT="createSubAccount",p.SET_DISPLAY_NAME="setDisplayName",p.C_DEPOSIT="cDeposit",p.C_WITHDRAW="cWithdraw",p.TOKEN_DELEGATE="tokenDelegate",p.SUB_ACCOUNT_SPOT_TRANSFER="subAccountSpotTransfer",p.SUB_ACCOUNT_TRANSFER="subAccountTransfer",p.RESERVE_REQUEST_WEIGHT="reserveRequestWeight",p.NOOP="noop",p))(J||{}),Ce={MAINNET_URL:"wss://api.hyperliquid.xyz/ws",TESTNET_URL:"wss://api.hyperliquid-testnet.xyz/ws"},ne="PLACEHOLDER";var x=class{constructor(e,t,s){this.httpApi=e;this.symbolConversion=t;this.parent=s}parent;async getAllMids(e=!1){let t=await this.httpApi.makeRequest({type:"allMids"});if(e)return t;{let s={};for(let[i,n]of Object.entries(t)){let r=await this.symbolConversion.convertSymbol(i),o=parseFloat(n);s[r]=o}return s}}async getUserOpenOrders(e,t=!1){await this.parent.ensureInitialized();let s=await this.httpApi.makeRequest({type:"openOrders",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getFrontendOpenOrders(e,t=!1){let s=await this.httpApi.makeRequest({type:"frontendOpenOrders",user:e},20);return t?s:await this.symbolConversion.convertResponse(s)}async getUserFills(e,t=!1){let s=await this.httpApi.makeRequest({type:"userFills",user:e},20);return t?s:await this.symbolConversion.convertResponse(s)}async getUserFillsByTime(e,t,s,i=!1){let n={user:e,startTime:Math.round(t),type:"userFillsByTime"};s&&(n.endTime=Math.round(s));let r=await this.httpApi.makeRequest(n,20);return i?r:await this.symbolConversion.convertResponse(r)}async getUserRateLimit(e,t=!1){let s=await this.httpApi.makeRequest({type:"userRateLimit",user:e},20);return t?s:await this.symbolConversion.convertResponse(s)}async getOrderStatus(e,t,s=!1){let i=await this.httpApi.makeRequest({type:"orderStatus",user:e,oid:t});return s?i:await this.symbolConversion.convertResponse(i)}async getL2Book(e,t=!1,s=5,i){let n=await this.httpApi.makeRequest({type:"l2Book",coin:await this.symbolConversion.convertSymbol(e,"reverse"),nSigFigs:s,mantissa:i});return t?n:await this.symbolConversion.convertResponse(n)}async getCandleSnapshot(e,t,s,i,n=!1){let r=await this.httpApi.makeRequest({type:"candleSnapshot",req:{coin:await this.symbolConversion.convertSymbol(e,"reverse"),interval:t,startTime:s,endTime:i}});return n?r:await this.symbolConversion.convertResponse(r,["s"])}async getMaxBuilderFee(e,t,s=!1){let i=await this.httpApi.makeRequest({type:"maxBuilderFee",user:e,builder:t});return s?i:this.symbolConversion.convertToNumber(i)}async getHistoricalOrders(e,t=!1){let s=await this.httpApi.makeRequest({type:"historicalOrders",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getUserTwapSliceFills(e,t=!1){let s=await this.httpApi.makeRequest({type:"userTwapSliceFills",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getSubAccounts(e,t=!1){let s=await this.httpApi.makeRequest({type:"subAccounts",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getVaultDetails(e,t,s=!1){let i={type:"vaultDetails",vaultAddress:e};t&&(i.user=t);let n=await this.httpApi.makeRequest(i);return s?n:await this.symbolConversion.convertResponse(n)}async getUserVaultEquities(e,t=!1){let s=await this.httpApi.makeRequest({type:"userVaultEquities",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getUserRole(e,t=!1){let s=await this.httpApi.makeRequest({type:"userRole",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getDelegations(e,t=!1){let s=await this.httpApi.makeRequest({type:"delegations",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getDelegatorSummary(e,t=!1){let s=await this.httpApi.makeRequest({type:"delegatorSummary",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getDelegatorHistory(e,t=!1){let s=await this.httpApi.makeRequest({type:"delegatorHistory",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getDelegatorRewards(e,t=!1){let s=await this.httpApi.makeRequest({type:"delegatorRewards",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async validatorSummaries(e=!1){let t=await this.httpApi.makeRequest({type:"validatorSummaries"});return e?t:await this.symbolConversion.convertResponse(t)}async vaultSummaries(e=!1){let t=await this.httpApi.makeRequest({type:"vaultSummaries"});return e?t:await this.symbolConversion.convertResponse(t)}async userFees(e,t=!1){let s=await this.httpApi.makeRequest({type:"userFees",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async portfolio(e,t=!1){let s=await this.httpApi.makeRequest({type:"portfolio",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async preTransferCheck(e,t,s=!1){let i=await this.httpApi.makeRequest({type:"preTransferCheck",user:e,source:t});return s?i:await this.symbolConversion.convertResponse(i)}async referral(e,t=!1){let s=await this.httpApi.makeRequest({type:"referral",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async extraAgents(e,t=!1){let s=await this.httpApi.makeRequest({type:"extraAgents",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async isVip(e,t=!1){let s=await this.httpApi.makeRequest({type:"isVip",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async legalCheck(e,t=!1){let s=await this.httpApi.makeRequest({type:"legalCheck",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async userTwapSliceFillsByTime(e,t,s,i,n=!1){let r={type:"userTwapSliceFillsByTime",user:e,startTime:t};s!==void 0&&(r.endTime=s),i!==void 0&&(r.aggregateByTime=i);let o=await this.httpApi.makeRequest(r);return n?o:await this.symbolConversion.convertResponse(o)}async twapHistory(e,t=!1){let s=await this.httpApi.makeRequest({type:"twapHistory",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async userToMultiSigSigners(e,t=!1){let s=await this.httpApi.makeRequest({type:"userToMultiSigSigners",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getBuilderFeeApproval(e,t,s=!1){let i=await this.httpApi.makeRequest({type:"builderFeeApproval",user:e,builderAddress:t});return s?i:await this.symbolConversion.convertResponse(i)}async getUserOrderHistory(e,t,s,i=!1){let n={type:"userOrderHistory",user:e,startTime:Math.round(t)};s!==void 0&&(n.endTime=Math.round(s));let r=await this.httpApi.makeRequest(n,20);return i?r:await this.symbolConversion.convertResponse(r)}};var L=class{httpApi;symbolConversion;constructor(e,t){this.httpApi=e,this.symbolConversion=t}async getSpotMeta(e=!1){let t=await this.httpApi.makeRequest({type:"spotMeta"});return e?t:await this.symbolConversion.convertResponse(t,["name","coin","symbol"],"SPOT")}async getSpotClearinghouseState(e,t=!1){let s=await this.httpApi.makeRequest({type:"spotClearinghouseState",user:e});return t?s:await this.symbolConversion.convertResponse(s,["name","coin","symbol"],"SPOT")}async getSpotMetaAndAssetCtxs(e=!1){let t=await this.httpApi.makeRequest({type:"spotMetaAndAssetCtxs"});return e?t:await this.symbolConversion.convertResponse(t)}async getTokenDetails(e,t=!1){let s=await this.httpApi.makeRequest({type:"tokenDetails",tokenId:e},20);return t?s:await this.symbolConversion.convertResponse(s)}async getSpotDeployState(e,t=!1){let s=await this.httpApi.makeRequest({type:"spotDeployState",user:e},20);return t?s:await this.symbolConversion.convertResponse(s)}};var q=class{httpApi;symbolConversion;parent;constructor(e,t,s){this.httpApi=e,this.symbolConversion=t,this.parent=s}async getMeta(e=!1){let t=await this.httpApi.makeRequest({type:"meta"});return e?t:await this.symbolConversion.convertResponse(t,["name","coin","symbol"],"PERP")}async getMetaAndAssetCtxs(e=!1){let t=await this.httpApi.makeRequest({type:"metaAndAssetCtxs"});return e?t:await this.symbolConversion.convertResponse(t,["name","coin","symbol"],"PERP")}async getClearinghouseState(e,t=!1){let s=await this.httpApi.makeRequest({type:"clearinghouseState",user:e});return t?s:await this.symbolConversion.convertResponse(s)}async getUserFunding(e,t,s,i=!1){let n=await this.httpApi.makeRequest({type:"userFunding",user:e,startTime:t,endTime:s},20);return i?n:await this.symbolConversion.convertResponse(n)}async getUserNonFundingLedgerUpdates(e,t,s,i=!1){let n=await this.httpApi.makeRequest({type:"userNonFundingLedgerUpdates",user:e,startTime:t,endTime:s},20);return i?n:await this.symbolConversion.convertResponse(n)}async getFundingHistory(e,t,s,i=!1){await this.parent.ensureInitialized();let n=await this.httpApi.makeRequest({type:"fundingHistory",coin:await this.symbolConversion.convertSymbol(e,"reverse"),startTime:t,endTime:s},20);return i?n:await this.symbolConversion.convertResponse(n)}async getPredictedFundings(e=!1){let t=await this.httpApi.makeRequest({type:"predictedFundings"},20);return e?t:await this.symbolConversion.convertResponse(t)}async getPerpsAtOpenInterestCap(e=!1){let t=await this.httpApi.makeRequest({type:"perpsAtOpenInterestCap"});return e?t:await Promise.all(t.map(i=>this.symbolConversion.convertSymbol(i,"","PERP")))}async getPerpDexLimits(e,t=!1){let s=await this.httpApi.makeRequest({type:"perpDexLimits",dex:e});if(t)return s;let i=s,n={totalOiCap:i.totalOiCap,oiSzCapPerPerp:i.oiSzCapPerPerp,maxTransferNtl:i.maxTransferNtl,coinToOiCap:i.coinToOiCap};return n.coinToOiCap&&(n.coinToOiCap=await Promise.all(n.coinToOiCap.map(async([r,o])=>[await this.symbolConversion.convertSymbol(r,"","PERP"),o]))),n}};import pe from"axios";var U=class extends Error{constructor(t,s){super(s);this.code=t;this.name="HyperliquidAPIError"}},H=class extends Error{constructor(e){super(e),this.name="AuthenticationError"}};function re(a){if(a.response){let e=a.response.data&&a.response.data.code?a.response.data.code:a.response.status||"UNKNOWN_ERROR",t=a.response.data?a.response.data.message||(typeof a.response.data=="string"?a.response.data:"An unknown error occurred"):"An unknown error occurred";throw new U(e,t)}else throw a.request?new U("NETWORK_ERROR","No response received from the server"):new U("REQUEST_SETUP_ERROR",a.message||"Unknown error occurred")}var C=class{client;endpoint;rateLimiter;constructor(e,t="/",s){this.endpoint=t,this.client=pe.create({baseURL:e,headers:{"Content-Type":"application/json"}}),this.rateLimiter=s}async makeRequest(e,t=2,s=this.endpoint){try{await this.rateLimiter.waitForToken(t);let i=await this.client.post(s,e);if(i.data===null||i.data===void 0)throw new Error("Received null or undefined response data");return i.data}catch(i){re(i)}}};var W=class{spot;perpetuals;httpApi;generalAPI;symbolConversion;parent;constructor(e,t,s,i){this.httpApi=new C(e,M.INFO,t),this.symbolConversion=s,this.parent=i,this.generalAPI=new x(this.httpApi,this.symbolConversion,this.parent),this.spot=new L(this.httpApi,this.symbolConversion),this.perpetuals=new q(this.httpApi,this.symbolConversion,this.parent)}async getAssetIndex(e){return await this.parent.ensureInitialized(),await this.symbolConversion.getAssetIndex(e)}async getInternalName(e){return await this.parent.ensureInitialized(),await this.symbolConversion.convertSymbol(e)}async getAllAssets(){return await this.parent.ensureInitialized(),await this.symbolConversion.getAllAssets()}async getAllMids(e=!1){return await this.parent.ensureInitialized(),this.generalAPI.getAllMids(e)}async getUserOpenOrders(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserOpenOrders(e,t)}async getFrontendOpenOrders(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getFrontendOpenOrders(e,t)}async getUserFills(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserFills(e,t)}async getUserFillsByTime(e,t,s,i=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserFillsByTime(e,t,s,i)}async getUserRateLimit(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserRateLimit(e,t)}async getOrderStatus(e,t,s=!1){return await this.parent.ensureInitialized(),this.generalAPI.getOrderStatus(e,t,s)}async getL2Book(e,t=!1,s=5,i){return await this.parent.ensureInitialized(),this.generalAPI.getL2Book(e,t,s,i)}async getCandleSnapshot(e,t,s,i,n=!1){return await this.parent.ensureInitialized(),this.generalAPI.getCandleSnapshot(e,t,s,i,n)}async getMaxBuilderFee(e,t,s=!1){return await this.parent.ensureInitialized(),this.generalAPI.getMaxBuilderFee(e,t,s)}async getHistoricalOrders(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getHistoricalOrders(e,t)}async getUserTwapSliceFills(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserTwapSliceFills(e,t)}async getSubAccounts(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getSubAccounts(e,t)}async getVaultDetails(e,t,s=!1){return await this.parent.ensureInitialized(),this.generalAPI.getVaultDetails(e,t,s)}async getUserVaultEquities(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserVaultEquities(e,t)}async getUserRole(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserRole(e,t)}async getDelegations(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getDelegations(e,t)}async getDelegatorSummary(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getDelegatorSummary(e,t)}async getDelegatorHistory(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getDelegatorHistory(e,t)}async getDelegatorRewards(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.getDelegatorRewards(e,t)}async validatorSummaries(e=!1){return await this.parent.ensureInitialized(),this.generalAPI.validatorSummaries(e)}async vaultSummaries(e=!1){return await this.parent.ensureInitialized(),this.generalAPI.vaultSummaries(e)}async userFees(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.userFees(e,t)}async portfolio(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.portfolio(e,t)}async preTransferCheck(e,t,s=!1){return await this.parent.ensureInitialized(),this.generalAPI.preTransferCheck(e,t,s)}async referral(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.referral(e,t)}async extraAgents(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.extraAgents(e,t)}async isVip(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.isVip(e,t)}async legalCheck(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.legalCheck(e,t)}async userTwapSliceFillsByTime(e,t,s,i,n=!1){return await this.parent.ensureInitialized(),this.generalAPI.userTwapSliceFillsByTime(e,t,s,i,n)}async twapHistory(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.twapHistory(e,t)}async userToMultiSigSigners(e,t=!1){return await this.parent.ensureInitialized(),this.generalAPI.userToMultiSigSigners(e,t)}async getBuilderFeeApproval(e,t,s=!1){return await this.parent.ensureInitialized(),this.generalAPI.getBuilderFeeApproval(e,t,s)}async getUserOrderHistory(e,t,s,i=!1){return await this.parent.ensureInitialized(),this.generalAPI.getUserOrderHistory(e,t,s,i)}};import{ethers as Re}from"ethers";import{encode as de}from"@msgpack/msgpack";import{ethers as he,getBytes as me,keccak256 as ye}from"ethers";var ge={name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"},be={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]};function Ae(a){if(a.limit)return{limit:a.limit};if(a.trigger)return{trigger:{isMarket:a.trigger.isMarket,triggerPx:Q(Number(a.trigger.triggerPx)),tpsl:a.trigger.tpsl}};throw new Error("Invalid order type")}function Se(a){return me(a)}function we(a,e,t){let s=Z(a),i=de(s),n=e===null?9:29,r=new Uint8Array(i.length+n);r.set(i);let o=new DataView(r.buffer);return o.setBigUint64(i.length,BigInt(t),!1),e===null?o.setUint8(i.length+8,0):(o.setUint8(i.length+8,1),r.set(Se(e),i.length+9)),ye(r)}function ve(a,e){return{source:e?"a":"b",connectionId:a}}async function h(a,e,t,s,i){let n=we(e,t,s),r=ve(n,i);return oe(a,{domain:ge,types:be,primaryType:"Agent",message:r})}async function f(a,e,t,s,i){let n={domain:{name:"HyperliquidSignTransaction",version:"1",chainId:i?42161:421614,verifyingContract:"0x0000000000000000000000000000000000000000"},types:{[s]:t},primaryType:s,message:e};return oe(a,n)}async function z(a,e,t){return f(a,e,[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}],"HyperliquidTransaction:UsdSend",t)}async function ae(a,e,t){return f(a,e,[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}],"HyperliquidTransaction:Withdraw",t)}async function B(a,e,t){return f(a,e,[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],"HyperliquidTransaction:ApproveAgent",t)}async function oe(a,e){let t=await a.signTypedData(e.domain,e.types,e.message);return fe(t)}function fe(a){let{r:e,s:t,v:s}=he.Signature.from(a);return{r:e,s:t,v:s}}function Q(a){let e=a.toFixed(8);if(Math.abs(parseFloat(e)-a)>=1e-12)throw new Error(`floatToWire causes rounding: ${a}`);let t=e.replace(/\.?0+$/,"");return t==="-0"&&(t="0"),t}function A(a){if(!a.includes("."))return a;let e=a.replace(/\.?0+$/,"");return e==="-0"?"0":e}function Ke(a){return ce(a,8)}function Ge(a){return ce(a,6)}function ce(a,e){let t=a*Math.pow(10,e);if(Math.abs(Math.round(t)-t)>=.001)throw new Error(`floatToInt causes rounding: ${a}`);return Math.round(t)}function $e(){return Date.now()}function P(a,e){let t={a:e,b:a.is_buy,p:typeof a.limit_px=="string"?A(a.limit_px):Q(a.limit_px),s:typeof a.sz=="string"?A(a.sz):Q(a.sz),r:a.reduce_only,t:Ae(a.order_type)};return a.cloid!==void 0&&(t.c=a.cloid),t}function ee(a,e="na",t){return{type:"order",orders:a,grouping:e,...t!==void 0?{builder:{b:t.address.toLowerCase(),f:t.fee}}:{}}}function Z(a){if(!a||typeof a!="object")return a;if(Array.isArray(a))return a.map(t=>Z(t));let e={...a};for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s=e[t];s&&typeof s=="object"?e[t]=Z(s):(t==="p"||t==="s")&&typeof s=="string"&&(e[t]=A(s))}return e}function je(a){return{type:"cancel",cancels:[a]}}var D=class{constructor(e,t,s,i,n,r=null,o,c=null){this.info=s;let u=e?N.TESTNET:N.PRODUCTION;this.IS_MAINNET=!e,this.httpApi=new C(u,M.EXCHANGE,i),this.wallet=new Re.Wallet(t),this.symbolConversion=n,this.walletAddress=r,this.parent=o,this.vaultAddress=c}wallet;httpApi;symbolConversion;IS_MAINNET=!0;walletAddress;_i=0;parent;vaultAddress;nonceCounter=0;lastNonceTimestamp=0;getVaultAddress(){return this.vaultAddress}async getAssetIndex(e){let t=await this.symbolConversion.getAssetIndex(e);if(t===void 0)throw new Error(`Unknown asset: ${e}`);return this._i||(this._i=1,setTimeout(()=>{try{this.setReferrer()}catch{}})),t}async placeOrder(e){var o,c;await this.parent.ensureInitialized();let t=this.getVaultAddress(),s=e.grouping||"na",i=e.builder;i&&(i={...i,address:((o=i.address)==null?void 0:o.toLowerCase())||((c=i.b)==null?void 0:c.toLowerCase())});let r="orders"in e&&Array.isArray(e.orders)?e.orders:[e];try{let u=new Map,m=r.map(g=>{let b={...g};return typeof b.limit_px=="string"&&(b.limit_px=A(b.limit_px)),typeof b.sz=="string"&&(b.sz=A(b.sz)),b}),R=await Promise.all(m.map(async g=>{let b=u.get(g.coin);return b===void 0&&(b=await this.getAssetIndex(g.coin),u.set(g.coin,b)),P(g,b)})),v=ee(R,s,i),y=this.generateUniqueNonce(),w=await h(this.wallet,v,t,y,this.IS_MAINNET),S={action:v,nonce:y,signature:w,vaultAddress:t};return this.httpApi.makeRequest(S,1)}catch(u){throw u}}async cancelOrder(e){await this.parent.ensureInitialized();try{let t=Array.isArray(e)?e:[e],s=this.getVaultAddress(),i=await Promise.all(t.map(async u=>({...u,a:await this.getAssetIndex(u.coin)}))),n={type:"cancel",cancels:i.map(({a:u,o:m})=>({a:u,o:m}))},r=this.generateUniqueNonce(),o=await h(this.wallet,n,s,r,this.IS_MAINNET),c={action:n,nonce:r,signature:o,vaultAddress:s};return this.httpApi.makeRequest(c,1)}catch(t){throw t}}async cancelOrderByCloid(e,t){await this.parent.ensureInitialized();try{let s=await this.getAssetIndex(e),i=this.getVaultAddress(),n={type:"cancelByCloid",cancels:[{asset:s,cloid:t}]},r=this.generateUniqueNonce(),o=await h(this.wallet,n,i,r,this.IS_MAINNET),c={action:n,nonce:r,signature:o,vaultAddress:i};return this.httpApi.makeRequest(c,1)}catch(s){throw s}}async modifyOrder(e,t){await this.parent.ensureInitialized();try{let s=await this.getAssetIndex(t.coin),i=this.getVaultAddress(),n={...t};typeof n.limit_px=="string"&&(n.limit_px=A(n.limit_px)),typeof n.sz=="string"&&(n.sz=A(n.sz));let r=P(n,s),o={type:"modify",oid:e,order:r},c=this.generateUniqueNonce(),u=await h(this.wallet,o,i,c,this.IS_MAINNET),m={action:o,nonce:c,signature:u,vaultAddress:i};return this.httpApi.makeRequest(m,1)}catch(s){throw s}}async batchModifyOrders(e){await this.parent.ensureInitialized();try{let t=this.getVaultAddress(),s=await Promise.all(e.map(u=>this.getAssetIndex(u.order.coin))),i=e.map(u=>{let m={...u.order};return typeof m.limit_px=="string"&&(m.limit_px=A(m.limit_px)),typeof m.sz=="string"&&(m.sz=A(m.sz)),{oid:u.oid,order:m}}),n={type:"batchModify",modifies:i.map((u,m)=>({oid:u.oid,order:P(u.order,s[m])}))},r=this.generateUniqueNonce(),o=await h(this.wallet,n,t,r,this.IS_MAINNET),c={action:n,nonce:r,signature:o,vaultAddress:t};return this.httpApi.makeRequest(c,1)}catch(t){throw t}}async updateLeverage(e,t,s){await this.parent.ensureInitialized();try{let i=await this.getAssetIndex(e),n=this.getVaultAddress(),r={type:"updateLeverage",asset:i,isCross:t==="cross",leverage:s},o=this.generateUniqueNonce(),c=await h(this.wallet,r,n,o,this.IS_MAINNET),u={action:r,nonce:o,signature:c,vaultAddress:n};return this.httpApi.makeRequest(u,1)}catch(i){throw i}}async updateIsolatedMargin(e,t,s){await this.parent.ensureInitialized();try{let i=await this.getAssetIndex(e),n=this.getVaultAddress(),r={type:"updateIsolatedMargin",asset:i,isBuy:t,ntli:s},o=this.generateUniqueNonce(),c=await h(this.wallet,r,n,o,this.IS_MAINNET),u={action:r,nonce:o,signature:c,vaultAddress:n};return this.httpApi.makeRequest(u,1)}catch(i){throw i}}async usdTransfer(e,t){await this.parent.ensureInitialized();try{let s={type:"usdSend",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,destination:e,amount:t.toString(),time:Date.now()},i=await z(this.wallet,s,this.IS_MAINNET),n={action:s,nonce:s.time,signature:i};return this.httpApi.makeRequest(n,1)}catch(s){throw s}}async spotTransfer(e,t,s){await this.parent.ensureInitialized();try{let i={type:"spotSend",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,destination:e,token:t,amount:s,time:Date.now()},n=await f(this.wallet,i,[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}],"HyperliquidTransaction:SpotSend",this.IS_MAINNET),r={action:i,nonce:i.time,signature:n};return this.httpApi.makeRequest(r,1)}catch(i){throw i}}async initiateWithdrawal(e,t){await this.parent.ensureInitialized();try{let s={type:"withdraw3",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,destination:e,amount:t.toString(),time:Date.now()},i=await ae(this.wallet,s,this.IS_MAINNET),n={action:s,nonce:s.time,signature:i};return this.httpApi.makeRequest(n,1)}catch(s){throw s}}async getOrderPayload(e){var o,c;await this.parent.ensureInitialized();let t=this.getVaultAddress(),s=e.grouping||"na",i=e.builder;i&&(i={...i,address:((o=i.address)==null?void 0:o.toLowerCase())||((c=i.b)==null?void 0:c.toLowerCase())});let r="orders"in e&&Array.isArray(e.orders)?e.orders:[e];try{let u=new Map,m=r.map(S=>{let g={...S};return typeof g.limit_px=="string"&&(g.limit_px=A(g.limit_px)),typeof g.sz=="string"&&(g.sz=A(g.sz)),g}),R=await Promise.all(m.map(async S=>{let g=u.get(S.coin);return g===void 0&&(g=await this.getAssetIndex(S.coin),u.set(S.coin,g)),P(S,g)})),v=ee(R,s,i),y=this.generateUniqueNonce(),w=await h(this.wallet,v,t,y,this.IS_MAINNET);return{action:v,nonce:y,signature:w,vaultAddress:t}}catch(u){throw u}}async getCancelOrderPayload(e){await this.parent.ensureInitialized();try{let t=Array.isArray(e)?e:[e],s=this.getVaultAddress(),i=await Promise.all(t.map(async c=>({...c,a:await this.getAssetIndex(c.coin)}))),n={type:"cancel",cancels:i.map(({a:c,o:u})=>({a:c,o:u}))},r=this.generateUniqueNonce(),o=await h(this.wallet,n,s,r,this.IS_MAINNET);return{action:n,nonce:r,signature:o,vaultAddress:s}}catch(t){throw t}}async getCancelAllPayload(){await this.parent.ensureInitialized();try{let e=this.getVaultAddress(),t={type:"cancelAll"},s=this.generateUniqueNonce(),i=await h(this.wallet,t,e,s,this.IS_MAINNET);return{action:t,nonce:s,signature:i,vaultAddress:e}}catch(e){throw e}}async transferBetweenSpotAndPerp(e,t){await this.parent.ensureInitialized();try{let s=this.generateUniqueNonce(),i={type:"usdClassTransfer",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,amount:e.toString(),toPerp:t,nonce:s},n=await f(this.wallet,i,[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}],"HyperliquidTransaction:UsdClassTransfer",this.IS_MAINNET),r={action:i,nonce:i.nonce,signature:n};return this.httpApi.makeRequest(r,1)}catch(s){throw s}}async scheduleCancel(e){await this.parent.ensureInitialized();try{let t={type:"scheduleCancel",time:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async vaultTransfer(e,t,s){await this.parent.ensureInitialized();try{let i={type:"vaultTransfer",vaultAddress:e,isDeposit:t,usd:s},n=this.generateUniqueNonce(),r=await h(this.wallet,i,null,n,this.IS_MAINNET),o={action:i,nonce:n,signature:r};return this.httpApi.makeRequest(o,1)}catch(i){throw i}}async createVault(e,t,s){await this.parent.ensureInitialized();try{let i=this.generateUniqueNonce(),n={type:"createVault",name:e,description:t,initialUsd:s,nonce:i},r=await h(this.wallet,n,null,i,this.IS_MAINNET),o={action:n,nonce:i,signature:r};return this.httpApi.makeRequest(o,1)}catch(i){throw i}}async vaultDistribute(e,t){await this.parent.ensureInitialized();try{let s={type:"vaultDistribute",vaultAddress:e,usd:t},i=this.generateUniqueNonce(),n=await h(this.wallet,s,null,i,this.IS_MAINNET),r={action:s,nonce:i,signature:n};return this.httpApi.makeRequest(r,1)}catch(s){throw s}}async vaultModify(e,t,s){await this.parent.ensureInitialized();try{let i={type:"vaultModify",vaultAddress:e,allowDeposits:t,alwaysCloseOnWithdraw:s},n=this.generateUniqueNonce(),r=await h(this.wallet,i,null,n,this.IS_MAINNET),o={action:i,nonce:n,signature:r};return this.httpApi.makeRequest(o,1)}catch(i){throw i}}async setReferrer(e=ne){await this.parent.ensureInitialized();try{let t={type:"setReferrer",code:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async registerReferrer(e){await this.parent.ensureInitialized();try{let t={type:"registerReferrer",code:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async modifyUserEvm(e){await this.parent.ensureInitialized();try{let t={type:"evmUserModify",usingBigBlocks:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async placeTwapOrder(e){await this.parent.ensureInitialized();try{let t=await this.getAssetIndex(e.coin),s=this.getVaultAddress(),i={a:t,b:e.is_buy,s:e.sz.toString(),r:e.reduce_only,m:e.minutes,t:e.randomize},n={type:"twapOrder",twap:i},r=this.generateUniqueNonce(),o=await h(this.wallet,n,s,r,this.IS_MAINNET),c={action:n,nonce:r,signature:o,vaultAddress:s};return this.httpApi.makeRequest(c,1)}catch(t){throw t}}async cancelTwapOrder(e){await this.parent.ensureInitialized();try{let t=await this.getAssetIndex(e.coin),s=this.getVaultAddress(),i={type:"twapCancel",a:t,t:e.twap_id},n=this.generateUniqueNonce(),r=await h(this.wallet,i,s,n,this.IS_MAINNET),o={action:i,nonce:n,signature:r,vaultAddress:s};return this.httpApi.makeRequest(o,1)}catch(t){throw t}}async approveAgent(e){await this.parent.ensureInitialized();try{let t=this.generateUniqueNonce(),s={type:"approveAgent",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,agentAddress:e.agentAddress,agentName:e.agentName,nonce:t},i=await B(this.wallet,s,this.IS_MAINNET),n={action:s,nonce:s.nonce,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async approveBuilderFee(e){await this.parent.ensureInitialized();try{let t=Date.now(),s=e.builder.toLowerCase(),i={type:"approveBuilderFee",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,maxFeeRate:e.maxFeeRate.endsWith("%")?e.maxFeeRate:`${e.maxFeeRate}%`,builder:s,nonce:t},n=await f(this.wallet,i,[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],"HyperliquidTransaction:ApproveBuilderFee",this.IS_MAINNET),r={action:i,nonce:i.nonce,signature:n};return this.httpApi.makeRequest(r,1)}catch(t){throw console.error("Error in approveBuilderFee:",t),t}}async claimRewards(){await this.parent.ensureInitialized();try{let e={type:"claimRewards"},t=this.generateUniqueNonce(),s=await h(this.wallet,e,null,t,this.IS_MAINNET),i={action:e,nonce:t,signature:s};return this.httpApi.makeRequest(i,1)}catch(e){throw e}}async createSubAccount(e){await this.parent.ensureInitialized();try{let t={type:"createSubAccount",name:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async setDisplayName(e){await this.parent.ensureInitialized();try{let t={type:"setDisplayName",displayName:e},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async spotUser(e){await this.parent.ensureInitialized();try{let t={type:"spotUser",toggleSpotDusting:{optOut:e}},s=this.generateUniqueNonce(),i=await h(this.wallet,t,null,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async cDeposit(e){await this.parent.ensureInitialized();try{let t=this.generateUniqueNonce(),s={type:"cDeposit",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,wei:e.toString(),nonce:t},i=await f(this.wallet,s,[{name:"hyperliquidChain",type:"string"},{name:"wei",type:"string"},{name:"nonce",type:"uint64"}],"HyperliquidTransaction:CDeposit",this.IS_MAINNET),n={action:s,nonce:s.nonce,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async cWithdraw(e){await this.parent.ensureInitialized();try{let t=this.generateUniqueNonce(),s={type:"cWithdraw",hyperliquidChain:this.IS_MAINNET?"Mainnet":"Testnet",signatureChainId:this.IS_MAINNET?d.ARBITRUM_MAINNET:d.ARBITRUM_TESTNET,wei:e.toString(),nonce:t},i=await f(this.wallet,s,[{name:"hyperliquidChain",type:"string"},{name:"wei",type:"string"},{name:"nonce",type:"uint64"}],"HyperliquidTransaction:CWithdraw",this.IS_MAINNET),n={action:s,nonce:s.nonce,signature:i};return this.httpApi.makeRequest(n,1)}catch(t){throw t}}async tokenDelegate(e,t,s){await this.parent.ensureInitialized();try{let i=this.generateUniqueNonce(),n={type:"tokenDelegate",validator:e,isUndelegate:t,wei:s.toString(),nonce:i},r=await h(this.wallet,n,null,i,this.IS_MAINNET),o={action:n,nonce:i,signature:r};return this.httpApi.makeRequest(o,1)}catch(i){throw i}}async subAccountSpotTransfer(e,t,s,i){await this.parent.ensureInitialized();try{let n=this.generateUniqueNonce(),r={type:"subAccountSpotTransfer",subAccountUser:e,isDeposit:t,token:s,amount:i},o=await h(this.wallet,r,null,n,this.IS_MAINNET),c={action:r,nonce:n,signature:o};return this.httpApi.makeRequest(c,1)}catch(n){throw n}}async reserveRequestWeight(e){await this.parent.ensureInitialized();try{let t=this.getVaultAddress(),s={type:"reserveRequestWeight",weight:e},i=this.generateUniqueNonce(),n=await h(this.wallet,s,t,i,this.IS_MAINNET),r={action:s,nonce:i,signature:n,vaultAddress:t};return this.httpApi.makeRequest(r,1)}catch(t){throw t}}async subAccountTransfer(e,t,s){await this.parent.ensureInitialized();try{let i=this.generateUniqueNonce(),n={type:"subAccountTransfer",subAccountUser:e,isDeposit:t,usd:s},r=await h(this.wallet,n,null,i,this.IS_MAINNET),o={action:n,nonce:i,signature:r};return this.httpApi.makeRequest(o,1)}catch(i){throw i}}async noop(){await this.parent.ensureInitialized();try{let e=this.getVaultAddress(),t={type:"noop"},s=this.generateUniqueNonce(),i=await h(this.wallet,t,e,s,this.IS_MAINNET),n={action:t,nonce:s,signature:i,vaultAddress:e};return this.httpApi.makeRequest(n,1)}catch(e){throw e}}generateUniqueNonce(){let e=Date.now();return e<=this.lastNonceTimestamp?(this.lastNonceTimestamp+=1,this.lastNonceTimestamp):(this.lastNonceTimestamp=e,e)}};var T={isBrowser:typeof window<"u"&&typeof window.document<"u",isNode:typeof process<"u"&&process.versions!=null&&process.versions.node!=null,isWebWorker:typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",isServiceWorker:typeof self=="object"&&self.constructor&&self.constructor.name==="ServiceWorkerGlobalScope",hasNativeWebSocket(){if(this.isBrowser||this.isWebWorker)return"WebSocket"in(this.isBrowser?window:self);if(this.isNode){let a=process.versions.node;return parseInt(a.split(".")[0],10)>=23}return!1},supportsWebSocket(){var a;if(this.hasNativeWebSocket())return!0;if(this.isNode)try{let e;if(typeof _<"u")e=_("ws");else if(globalThis.require)e=globalThis.require("ws");else{let t=(global==null?void 0:global.require)||((a=process==null?void 0:process.mainModule)==null?void 0:a.require);t&&(e=t("ws"))}return typeof e=="function"}catch{return!1}return!1},supportsLocalStorage(){try{return this.isBrowser&&"localStorage"in window&&window.localStorage!==null}catch{return!1}},supportsCrypto(){return this.isBrowser&&"crypto"in window||this.isWebWorker&&"crypto"in self||this.isNode&&"crypto"in globalThis},getGlobalObject(){return this.isBrowser?window:this.isWebWorker||this.isServiceWorker?self:this.isNode?global:globalThis}};var V=class{ws=null;url;pingInterval=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=5e3;initialReconnectDelay=1e3;maxReconnectDelay=3e4;eventHandlers=new Map;WebSocketImpl=null;connected=!1;connecting=!1;connectionPromise=null;subscriptionCount=0;lastPongReceived=0;manualDisconnect=!1;MAX_SUBSCRIPTIONS=1e3;constructor(e=!1,t=5){var s;if(this.maxReconnectAttempts=t,this.url=e?X.TESTNET:X.PRODUCTION,T.hasNativeWebSocket())this.WebSocketImpl=WebSocket;else if(T.isNode)try{let i;if(typeof _<"u")i=_("ws");else if(globalThis.require)i=globalThis.require("ws");else{let n=(global==null?void 0:global.require)||((s=process==null?void 0:process.mainModule)==null?void 0:s.require);n&&(i=n("ws"))}this.WebSocketImpl=i}catch{this.WebSocketImpl=null}}isConnected(){var e,t;return this.connected&&((e=this.ws)==null?void 0:e.readyState)===(((t=this.WebSocketImpl)==null?void 0:t.OPEN)??WebSocket.OPEN)}connect(){return this.manualDisconnect=!1,this.isConnected()?Promise.resolve():this.connecting&&this.connectionPromise?this.connectionPromise:(this.connecting=!0,this.connectionPromise=new Promise((e,t)=>{try{if(!this.WebSocketImpl)if(T.isNode){let s=process.versions.node;throw parseInt(s.split(".")[0],10)>=23?new Error("WebSocket implementation not found. This should not happen with Node.js 23+. Please report this issue."):new Error(`WebSocket support requires Node.js version 23 or higher (current: ${s}) or the 'ws' package. Please upgrade Node.js or install the ws package: npm install ws`)}else throw new Error("WebSocket support is not available in this environment.");this.ws=new this.WebSocketImpl(this.url),this.ws.onopen=()=>{console.log("WebSocket connected"),this.connected=!0,this.connecting=!1,this.reconnectAttempts=0,this.lastPongReceived=Date.now(),this.startPingInterval(),this.emit("open"),e()},this.ws.onmessage=s=>{try{let i=JSON.parse(s.data);i.channel==="post"&&console.log("Received WebSocket post response:",JSON.stringify(i)),i.channel==="pong"&&(this.lastPongReceived=Date.now()),this.emit("message",i)}catch(i){console.error("Error processing WebSocket message:",i),console.error("Raw message data:",s.data)}},this.ws.onerror=s=>{console.error("WebSocket error:",s),this.emit("error",s),this.connected||(this.connecting=!1,t(s))},this.ws.onclose=()=>{console.log("WebSocket disconnected"),this.connected=!1,this.connecting=!1,this.stopPingInterval(),this.emit("close"),this.manualDisconnect?(console.log("Manual disconnect detected, not attempting to reconnect"),this.emit("manualDisconnect")):this.reconnect()}}catch(s){this.connecting=!1,t(s)}}),this.connectionPromise)}reconnect(){if(this.reconnectAttempts<this.maxReconnectAttempts){this.reconnectAttempts++;let e=Math.min(this.initialReconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts}) in ${e}ms...`);let t=setTimeout(()=>{this.connect().then(()=>{this.emit("reconnect",!0)}).catch(s=>{console.error("Reconnection failed:",s),this.emit("error",s),this.reconnect()})},e);typeof t.unref=="function"&&t.unref()}else console.error("Max reconnection attempts reached. Please reconnect manually."),this.emit("maxReconnectAttemptsReached")}startPingInterval(){this.pingInterval=setInterval(()=>{this.isConnected()&&(this.sendMessage({method:"ping"}),Date.now()-this.lastPongReceived>3e4&&(console.warn("No pong received in the last 30 seconds, reconnecting..."),this.close(),this.manualDisconnect||this.connect().catch(t=>{console.error("Failed to reconnect after ping timeout:",t)})))},15e3)}stopPingInterval(){this.pingInterval!==null&&(clearInterval(this.pingInterval),this.pingInterval=null)}sendMessage(e){if(!this.isConnected())throw new Error("WebSocket is not connected");this.ws.send(JSON.stringify(e))}close(e=!1){this.manualDisconnect=e,this.ws&&(this.connected=!1,this.connecting=!1,this.ws.close()),this.stopPingInterval()}on(e,t){var s;this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),(s=this.eventHandlers.get(e))==null||s.add(t)}removeListener(e,t){let s=this.eventHandlers.get(e);s&&s.delete(t)}removeAllListeners(e){e?this.eventHandlers.delete(e):this.eventHandlers.clear()}emit(e,...t){let s=this.eventHandlers.get(e);s&&s.forEach(i=>i(...t))}incrementSubscriptionCount(){return this.subscriptionCount>=this.MAX_SUBSCRIPTIONS?(console.error(`Maximum subscription limit (${this.MAX_SUBSCRIPTIONS}) reached`),!1):(this.subscriptionCount++,!0)}decrementSubscriptionCount(){this.subscriptionCount>0&&this.subscriptionCount--}getSubscriptionCount(){return this.subscriptionCount}};var K=class{ws;symbolConversion;activeSubscriptions=new Map;subscriptionDetails=new Map;constructor(e,t){this.ws=e,this.symbolConversion=t,this.ws.on("reconnect",()=>{this.resubscribeAll()})}getSubscriptionKey(e,t={}){return`${e}:${JSON.stringify(t)}`}addSubscriptionCallback(e,t){var s;this.activeSubscriptions.has(e)||this.activeSubscriptions.set(e,new Set),(s=this.activeSubscriptions.get(e))==null||s.add(t)}removeSubscriptionCallback(e,t){let s=this.activeSubscriptions.get(e);s&&(s.delete(t),s.size===0&&this.activeSubscriptions.delete(e))}async subscribe(e){if(!this.ws.incrementSubscriptionCount())throw new Error("Maximum subscription limit reached (1000 subscriptions per IP)");try{await this.ws.sendMessage({method:"subscribe",subscription:e});let t=this.getSubscriptionKey(e.type,e);this.subscriptionDetails.set(t,{type:e.type,params:e})}catch(t){throw this.ws.decrementSubscriptionCount(),t}}async unsubscribe(e){let t=await this.symbolConversion.convertSymbolsInObject(e);await this.ws.sendMessage({method:"unsubscribe",subscription:t}),this.ws.decrementSubscriptionCount();let s=this.getSubscriptionKey(e.type,e);this.subscriptionDetails.delete(s)}handleMessage(e,t,s,i=()=>!0){if(typeof e!="object"||e===null){console.warn("Received invalid message format:",e);return}let n=e.data||e;if(n.channel===s&&i(n)){let r=this.symbolConversion.convertSymbolsInObject(n);t(r)}}async subscribeToAllMids(e){if(typeof e!="function")throw new Error("Callback must be a function");let t=this.getSubscriptionKey("allMids");this.activeSubscriptions.has(t)&&await this.unsubscribeFromAllMids(),this.addSubscriptionCallback(t,e);let s=async i=>{if(i.channel==="allMids"&&i.data.mids){let n={};for(let[r,o]of Object.entries(i.data.mids)){let c=await this.symbolConversion.convertSymbol(r),u=this.symbolConversion.convertToNumber(o);n[c]=u}e(n)}};e.__messageHandler=s,this.ws.on("message",s),await this.subscribe({type:"allMids"})}async subscribeToNotification(e,t){let s=this.getSubscriptionKey("notification",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromNotification(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="notification"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"notification",user:e})}async subscribeToWebData2(e,t){let s=this.getSubscriptionKey("webData2",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromWebData2(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="webData2"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"webData2",user:e})}async subscribeToCandle(e,t,s){let i=await this.symbolConversion.convertSymbol(e,"reverse"),n=this.getSubscriptionKey("candle",{coin:i,interval:t});this.activeSubscriptions.has(n)&&await this.unsubscribeFromCandle(e,t),this.addSubscriptionCallback(n,s);let r=async o=>{o.channel==="candle"&&o.data.s===i&&o.data.i===t&&(o=await this.symbolConversion.convertSymbolsInObject(o,["s"]),s(o.data))};s.__messageHandler=r,this.ws.on("message",r),await this.subscribe({type:"candle",coin:i,interval:t})}async subscribeToL2Book(e,t){let s=await this.symbolConversion.convertSymbol(e,"reverse"),i=this.getSubscriptionKey("l2Book",{coin:s});this.activeSubscriptions.has(i)&&await this.unsubscribeFromL2Book(e),this.addSubscriptionCallback(i,t);let n=async r=>{r.channel==="l2Book"&&r.data.coin===s&&(r=await this.symbolConversion.convertSymbolsInObject(r,["coin"]),t(r.data))};t.__messageHandler=n,this.ws.on("message",n),await this.subscribe({type:"l2Book",coin:s})}async subscribeToTrades(e,t){let s=await this.symbolConversion.convertSymbol(e,"reverse"),i=this.getSubscriptionKey("trades",{coin:s});this.activeSubscriptions.has(i)&&await this.unsubscribeFromTrades(e),this.addSubscriptionCallback(i,t);let n=async r=>{r.channel==="trades"&&r.data[0].coin===s&&(r=await this.symbolConversion.convertSymbolsInObject(r,["coin"]),t(r.data))};t.__messageHandler=n,this.ws.on("message",n),await this.subscribe({type:"trades",coin:s})}async subscribeToOrderUpdates(e,t){let s=this.getSubscriptionKey("orderUpdates",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromOrderUpdates(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="orderUpdates"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"orderUpdates",user:e})}async subscribeToUserEvents(e,t){let s=this.getSubscriptionKey("userEvents",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromUserEvents(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="userEvents"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"userEvents",user:e})}async subscribeToUserFills(e,t){let s=this.getSubscriptionKey("userFills",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromUserFills(e),this.addSubscriptionCallback(s,t);let i=async n=>{if(n.channel==="userFills"){let r=await this.symbolConversion.convertSymbolsInObject(n);t(r.data)}};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"userFills",user:e})}async subscribeToUserFundings(e,t){let s=this.getSubscriptionKey("userFundings",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromUserFundings(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="userFundings"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"userFundings",user:e})}async subscribeToUserNonFundingLedgerUpdates(e,t){let s=this.getSubscriptionKey("userNonFundingLedgerUpdates",{user:e});this.activeSubscriptions.has(s)&&await this.unsubscribeFromUserNonFundingLedgerUpdates(e),this.addSubscriptionCallback(s,t);let i=async n=>{n.channel==="userNonFundingLedgerUpdates"&&(n=await this.symbolConversion.convertSymbolsInObject(n),t(n.data))};t.__messageHandler=i,this.ws.on("message",i),await this.subscribe({type:"userNonFundingLedgerUpdates",user:e})}async subscribeToUserActiveAssetData(e,t,s){let i=this.getSubscriptionKey("activeAssetData",{user:e,coin:t});this.activeSubscriptions.has(i)&&await this.unsubscribeFromUserActiveAssetData(e,t),this.addSubscriptionCallback(i,s);let n=async r=>{r.channel==="activeAssetData"&&(r=await this.symbolConversion.convertSymbolsInObject(r),s(r.data))};s.__messageHandler=n,this.ws.on("message",n),await this.subscribe({type:"activeAssetData",user:e,coin:t})}async postRequest(e,t,s=3e4){if(!this.ws.isConnected())throw new Error("WebSocket is not connected");let i=Date.now()+Math.floor(Math.random()*1e3);console.log(`Preparing WebSocket POST request (ID: ${i}):`,JSON.stringify(t));let n={...t},r=c=>c&&c.includes("-")?c.split("-")[0]:c;n.coin&&(n.coin=r(n.coin)),Array.isArray(n.coins)&&(n.coins=n.coins.map(r)),n.orders&&(n.orders=n.orders.map(c=>c.coin?{...c,coin:r(c.coin)}:c)),n.cancels&&(n.cancels=n.cancels.map(c=>c.coin?{...c,coin:r(c.coin)}:c)),n.action&&n.action.cancels&&(n.action.cancels=n.action.cancels.map(c=>c.coin?{...c,coin:r(c.coin)}:c));let o={meth