@myx-trade/sdk 1.0.20-beta.9 → 1.0.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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {ha,P,h,g,fa,ga,R as R$1,T,ja,V as V$1,f,X as X$1,Y as Y$1,ta,Z as Z$1,pa,d,oa,n,_,W,$ as $$1,S,m,j as j$1,i,ia,k as k$1,U,c,ba,aa,l as l$1,b,e}from'./chunk-HLJ4EUAC.mjs';export{na as COMMON_LP_AMOUNT_DECIMALS,ma as COMMON_PRICE_DECIMALS,a as ChainId,D as CloseTypeEnum,A as DirectionEnum,o as ErrorCode,C as ExecTypeEnum,F as ForwarderGetStatus,r as HttpKlineIntervalEnum,ha as Logger,u as MarketCapType,p as MarketPoolState,s as MarketType,P as MxSDK,x as OperationEnum,q as OracleType,B as OrderStatusEnum,w as OrderTypeEnum,v as SearchSecondTypeEnum,t as SearchTypeEnum,E as TradeFlowAccountTypeEnum,y as TradeFlowTypeEnum,z as TriggerTypeEnum,ra as approve,xa as base,qa as bigintAmountSlipperCalculator,pa as bigintTradingGasPriceWithRatio,oa as bigintTradingGasToRatioCalculator,va as formatUnits,la as getAllowanceApproved,ka as getBalanceOf,M as getBaseDetail,H as getBaseUrlByEnv,N as getMarketDetail,O as getMarketList,I as getOraclePrice,J as getPoolDetail,G as getPoolList,K as getPoolOpenOrders,ta as getPriceData,sa as getPricesData,f as getPublicClient,da as getSdkLogSink,L as getTickerData,ua as getTokenInfo,i as getWalletClient,Q as getWalletProvider,za as market,wa as parseUnits,Aa as pool,ya as quote,ga as sdkError,ea as sdkLog,fa as sdkWarn,g as setConfigManagerForViem,ca as setSdkLogSink}from'./chunk-HLJ4EUAC.mjs';import lt from'mitt';import {MD5,Hex}from'crypto-es';import pt from'reconnecting-websocket';import {maxUint256,zeroAddress,encodeFunctionData,isAddress,decodeEventLog,createWalletClient,custom,hexToBytes,toHex}from'viem';import Ae from'dayjs';import {merge}from'lodash-es';var $=(o,e)=>MD5(o,{outputLength:32}).toString(Hex);var V=o=>{switch(o.request){case "signin":return $(o.request)}return $(JSON.stringify(o))},N=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return $(JSON.stringify({topic:e,params:t}))}},_e=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",dt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Be=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:N({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[i,r]=t.split("_");return {...o,type:N({topic:"candle",params:{globalId:parseInt(i),resolution:r}}),globalId:parseInt(i),resolution:r}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=lt();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:i,...r}=t;this.config={...Ge,...r},this.logger=new ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let i={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new pt(this.config.url,this.config.protocols,i),this.setupEventListeners(e,t);}catch(i){t(i);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async i=>{this.eventBus.emit("open",i),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=i=>{this.handleMessage(i);},this.ws.onclose=i=>{this.eventBus.emit("close",i),this.stopHeartbeatTimer();},this.ws.onerror=i=>{this.eventBus.emit("error",i),t(i);},this.ws.addEventListener("reconnecting",i=>{this.eventBus.emit("reconnecting",{detail:i.detail||0}),this.isFirstConnection=false;}),this.ws.addEventListener("maxreconnectattempts",()=>{this.eventBus.emit("maxreconnectattempts",void 0);}));}pong(e){this.send({request:"pong",args:e});}request(e){return new Promise((t,i)=>{let r=V(e);this.waitingRequests.has(r)?(this.waitingRequests.get(r)?.onSuccess.add(t),this.waitingRequests.get(r)?.onError.add(i)):this.waitingRequests.set(r,{onSuccess:new Set([t]),onError:new Set([i])}),this.send(e);})}subscribe(e,t){let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(!n.has(g))if(n.add(g),this.subscriptions.has(g))this.subscriptions.get(g).callbacks.add(t);else {let s={id:g,topic:a.topic,callbacks:new Set([t])};this.subscriptions.set(g,s),r.push(g),this.logger.debug(`create new subscription: ${g}`);}}),r.length>0&&this.send({request:"subv2",args:r});}unsubscribe(e,t){if(!e)return;let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(n.has(g))return;n.add(g);let s=this.subscriptions.get(g);s&&(s.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${g}`),s.callbacks.size===0&&(this.subscriptions.delete(g),r.push(g),this.logger.debug(`subscription ${g} has no callbacks, will unsubscribe`)));}),r.length>0&&this.send({request:"unsubv2",args:r});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(_e(t)){this.handleAckMessage(t);return}this.handleSubscriptionMessage(t);}catch(t){this.logger.error(`Failed to parse WebSocket message: ${t}`);}}handleAckMessage(e){let t;switch(e.type){case "signin":t=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let i=this.waitingRequests.get(t),r=e.data.code===9200;r?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),i?.onError.size&&!r&&i.onError.forEach(n=>{n(new l("REQUEST_FAILED","Request failed"));}),i?.onSuccess.size&&r&&i.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=Be(e),i=t.type,r=this.subscriptions.get(i);r&&r.callbacks.forEach(n=>{try{n(t);}catch(a){this.logger.error(`Callback Error (${i}): ${a}`);}});}resubscribeAll(){if(this.subscriptions.size===0)return;this.logger.debug("resubscribe all...");let e=Array.from(this.subscriptions.values()).map(t=>t.id);e.length>0&&(this.send({request:"subv2",args:e}),this.logger.debug(`resubscribe ${e.length} topics`));}timeoutHeartbeat(){this.stopHeartbeatTimer(),Date.now()-this.lastMessageTime>(this.config.noMessageTimeout||Ge.noMessageTimeout)&&(this.logger.debug("no message timeout"),this.subscriptions.size>0?this.reconnect():this.ws?.close()),this.heartbeatIntervalId=setTimeout(()=>{this.timeoutHeartbeat();},this.config.heartbeatInterval);}stopHeartbeatTimer(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null);}};var We=[56,59144,42161],Ue=[59141,421614,97],$e=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var z=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let i=H.MainNet;e.getConfig().isBetaMode?i=H.BetaNet:e.getConfig().isTestnet&&(i=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:i,...this.configManager.getConfig()?.socketConfig,onBeforeReSubscribe:()=>{if(this.clientAuth)return this.auth(true).then(()=>{this.logger.debug("reconnect auth success");})}});}get isConnected(){return this.wsClient.isConnected()}connect(){this.wsClient.connect();}disconnect(){this.wsClient.disconnect();}reconnect(){this.wsClient.reconnect();}subscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.subscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}unsubscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}subscribeKline(e,t,i){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}unsubscribeKline(e,t,i){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function ut(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function mt(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function me(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let i=typeof t=="string"?t:{raw:t};return await o.signMessage({message:i})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let i=t.to;if(!i)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:i,data:t.data,value:t.value!=null?BigInt(t.value):void 0,gas:t.gasLimit!=null?BigInt(t.gasLimit):void 0,gasPrice:t.gasPrice!=null?BigInt(t.gasPrice):void 0,maxFeePerGas:t.maxFeePerGas!=null?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas!=null?BigInt(t.maxPriorityFeePerGas):void 0})}},...typeof e.signTypedData=="function"?{async signTypedData(t){return await e.signTypedData(t)}}:{}}}function Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:i=>o.signMessage(i),async sendTransaction(i){let r={...i};i.value!=null&&(r.value=BigInt(i.value)),i.gasLimit!=null&&(r.gasLimit=BigInt(i.gasLimit)),i.gasPrice!=null&&(r.gasPrice=BigInt(i.gasPrice)),i.maxFeePerGas!=null&&(r.maxFeePerGas=BigInt(i.maxFeePerGas)),i.maxPriorityFeePerGas!=null&&(r.maxPriorityFeePerGas=BigInt(i.maxPriorityFeePerGas));try{let a=(await o.sendTransaction(r)).hash;if(!a)throw new Error("sendTransaction: no hash in response");return {hash:a}}catch(n){let a=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||a.includes("BigInt")||a.includes("bigint")){let g={...i};i.value!=null&&(g.value=`0x${BigInt(i.value).toString(16)}`),i.gasLimit!=null&&(g.gasLimit=`0x${BigInt(i.gasLimit).toString(16)}`),i.gasPrice!=null&&(g.gasPrice=`0x${BigInt(i.gasPrice).toString(16)}`),i.maxFeePerGas!=null&&(g.maxFeePerGas=`0x${BigInt(i.maxFeePerGas).toString(16)}`),i.maxPriorityFeePerGas!=null&&(g.maxPriorityFeePerGas=`0x${BigInt(i.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(g)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw n}},signTransaction:typeof e.signTransaction=="function"?i=>t.signTransaction(i):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(i){return t.signTypedData(i.domain,i.types,i.message)}}:typeof t._signTypedData=="function"?{async signTypedData(i){return t._signTypedData(i.domain,i.types,i.message)}}:{}}}function K(o){return ut(o)?me(o):mt(o)?Ve(o):o}function qe(o){let e$1=e(o),t=[...e$1.privateJsonRPCUrl?[e$1.privateJsonRPCUrl]:[],...Array.isArray(e$1.publicJsonRPCUrl)?[...e$1.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var fe={};function bt(o){if(!fe[o]){let e$1=e(o);fe[o]={id:o,name:e$1.label||`Chain ${o}`,nativeCurrency:e$1.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),i=bt(e),r=await o.getAddress();return createWalletClient({account:r,chain:i,transport:custom({request:async a=>{if(a.method==="eth_accounts")return [r];if(a.method==="eth_sendTransaction"){let c=a.params?.[0]??{},{hash:d}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return d}if(a.method==="eth_signTypedData_v4"||a.method==="eth_signTypedData"){if(!o.signTypedData){let h=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(h.error)throw new Error(h.error.message);return h.result}let c=a.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let d=JSON.parse(c),{EIP712Domain:p,...u}=d.types;return await o.signTypedData({domain:d.domain,types:u,primaryType:d.primaryType,message:d.message})}let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(s.error)throw new Error(s.error.message);return s.result}})})}var j=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let i=(await this.config.walletClient.getAddresses())[0];if(i)return i}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?K(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:i,chainId:r}=e;if(t){if(!Ue.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of TESTNET_CHAIN_IDS`)}else if(i){if(!$e.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,i)=>{this._getAccessTokenQueue.push({resolve:t,reject:i,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let i=3600;if(t.expireAt){let r=Math.floor(Date.now()/1e3);i=t.expireAt-r,i<=0&&(fa("Received expired token, using default expiry"),i=3600);}return this.setAccessToken(t.accessToken,i),t.accessToken}else return fa("\u274C Received empty accessToken"),null}catch(t){return ga("\u274C Failed to refresh accessToken:",t),null}}setAccessToken(e,t=3600){this.accessToken=e,this.accessTokenExpiry=Date.now()+t*1e3;}getCurrentAccessToken(){return this.accessToken}isAccessTokenValid(){return !!this.accessToken}clearAccessToken(){this.accessToken=void 0,this.accessTokenExpiry=void 0;}getConfig(){return this.config}};var Q=class{constructor(e,t,i){this.configManager=e,this.utils=t,this.api=i;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){return (await this.api.getKlineData({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getKlineLatestBar({interval:e,...t}){this.configManager.getConfig();return (await this.api.getKlineLatestBar({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getTickerList(e){return (await this.api.getTickerData(e)).data}async searchMarketAuth(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:i})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:i})).data}async addFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:i})).data}async removeFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:i})).data}async getBaseDetail(e){return (await this.api.getBaseDetail(e)).data}async getMarketDetail(e){return (await this.api.getMarketDetail(e)).data}async getPoolSymbolAll(){return (await this.api.getPoolSymbolAll()).data}async getPoolFundingFeeInfo({poolId:e,chainId:t,marketPrice:i}){let r=await Z$1(t);try{return {code:0,data:await r.read.getPoolInfo([e,i])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async listPositions(e,t){let i=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:i??"",address:e,positionId:t})).data}}catch(r){return this.logger.error("Error fetching positions:",r),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:i,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:i,quoteToken:r,chainId:n,address:a}){this.configManager.getConfig();try{let s=await this.utils.getOraclePrice(e,n);if(!s)throw new Error("Failed to get price data");let c$1={poolId:e,oracleType:s.oracleType,publishTime:s.publishTime,oracleUpdateData:s?.vaa??"0"},d=!1;Number(i)>0&&(d=await this.utils.needsApproval(a,n,r,i,R$1(n).TRADING_ROUTER));let p=BigInt(0),u=BigInt(i)>0?BigInt(i):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:a}),h=m.code===0?m.data??0n:0n,w=BigInt(0);h<u&&(w=u-h,p=w);let I={token:r,amount:p.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let Ce=await U(n);if(d){let S=await this.utils.approveAuthorization({chainId:n,quoteAddress:r,amount:maxUint256.toString(),spenderAddress:R$1(n).TRADING_ROUTER});if(S.code!==0)throw new Error(S.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[c$1],I,t,i],{value:BigInt(s?.value??"1"),gas:BigInt(1e7)*c[n]/100n});return await f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(s){return {code:-1,message:s.message}}}};var wt={IOC:0},R=wt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},lr={NONE:0,GTE:1,LTE:2},k={INCREASE:0,DECREASE:1},pr={LONG:0,SHORT:1},ur={IOC:0},mr={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async createIncreaseOrder(e,t){try{let i=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()},c$1={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},d=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,R$1(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(d){let w=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(e.chainId).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let p=await U(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c$1,positionId:e.positionId});let w=await p.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...s},c$1]);u=await p.write.placeOrderWithPosition([e.positionId.toString(),{...s},c$1],{gasLimit:w*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c$1,depositData:s});let I=await p.estimateGas.placeOrderWithSalt(["1",{...s},c$1]);u=await p.write.placeOrderWithSalt(["1",{...s},c$1],{gasLimit:I*c[e.chainId]/100n});}let m=await f(e.chainId).waitForTransactionReceipt({hash:u});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:u,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(i){return this.logger.error("Error placing order:",i),{code:-1,message:i?.message}}}async closeAllPositions(e,t){try{let i={token:"0x0000000000000000000000000000000000000000",amount:"0"},r=t.map(d=>d.positionId.toString()),n=t.map(d=>({user:d.address,poolId:d.poolId,orderType:d.orderType,triggerType:d.triggerType,operation:k.DECREASE,direction:d.direction,collateralAmount:d.collateralAmount,size:d.size,price:d.price,timeInForce:R,postOnly:d.postOnly,slippagePct:d.slippagePct,leverage:d.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",i,r,n),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await U(e),g=await a.estimateGas.placeOrdersWithPosition([i,r,n]),s=await a.write.placeOrdersWithPosition([i,r,n],{gasLimit:g*c[e]/100n}),c$1=await f(e).waitForTransactionReceipt({hash:s});return {code:0,message:"close all positions success",transactionHash:s,blockNumber:c$1?.blockNumber,gasUsed:c$1?.gasUsed?.toString(),status:c$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c$1}}catch(i){return {code:-1,message:i?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},i=BigInt(e.collateralAmount),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c$1=await U(e.chainId),d;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,s,{data:t}]);let m=await c$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),s,t]);d=await c$1.write.placeOrderWithPosition([e.positionId.toString(),s,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,s,{data:t}]);let h=await c$1.estimateGas.placeOrderWithSalt(["1",s,t]);d=await c$1.write.placeOrderWithSalt(["1",s,t],{gasLimit:h*c[e.chainId]/100n});}let p=await f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let s=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},d;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],s]);d=await t.write.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],s],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",s);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],s]);d=await t.write.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],s],{gasLimit:h*c[e.chainId]/100n});}let p=await f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}let i={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",i);let s=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,i]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),r,i],{gasLimit:s*c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",i);let s=1,c$1=await t.estimateGas.placeOrderWithSalt([s.toString(),r,i]);n=await t.write.placeOrderWithSalt([s.toString(),r,i],{gasLimit:c$1*c[e.chainId]/100n});}let a=await f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:a?.blockNumber,gasUsed:a?.gasUsed?.toString(),status:a?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:a}}}catch(i){return {code:-1,message:i?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel all orders success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrder([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel order success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"Orders canceled success"}}catch(i){return this.logger.error("Error canceling orders:",i),{code:-1,message:i?.message}}}async updateOrderTpSl(e,t,i,r,n,a){let g=await this.utils.getNetworkFee(n,i),s={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:a?e.tpSize:"0",tpPrice:a?e.tpPrice:"0",slSize:a?e.slSize:"0",slPrice:a?e.slPrice:"0"}},c$1={token:t,amount:g.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await U(i);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(r,i,e.executionFeeToken,g.toString(),R$1(i).TRADING_ROUTER)){let w=await this.utils.approveAuthorization({chainId:i,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(i).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let u=await d.estimateGas.updateOrder([c$1,s]),m=await d.write.updateOrder([c$1,s],{gasLimit:u*c[i]/100n}),h=await f(i).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(p){return this.logger.error("Error updating order:",p),{code:-1,message:"Failed to update order"}}}async getOrders(e){let t=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getOrders(t??"",e)).data}}catch(i){return this.logger.error("Error fetching orders:",i),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:i,...e,address:t})).data}}};var he={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,i,r){try{if(!i||typeof i=="string"&&!i.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=r??R$1(t).Account,g=await T(t,i).read.allowance([e,n]);return {code:0,data:String(g)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await ja(n)}}async needsApproval(e,t,i,r,n){try{let g=(await this.getApproveQuoteAmount(e,t,i,n)).data,s=BigInt(g),c=BigInt(r);return s<c}catch(a){return this.logger.error("Error checking approval needs:",a),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:i,spenderAddress:r}){try{let n=await V$1(e,t),a=i??maxUint256,g=r??R$1(e).Account,s=await this.getGasPriceByRatio(),c=await n.write.approve([g,a],{gasPrice:s});return await f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,i,r){let a=this.configManager.getConfig().brokerAddress;try{let g=X$1(i,a),s=r??await this.configManager.getSignerAddress(i),c=await g.read.getUserFeeRate([s,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(g){return this.logger.error("Error getting user trading fee rate:",g),{code:-1,message:g?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await Y$1(t,0)).read.getExecutionFee([e])).toString()}catch(i){return this.logger.error("Error getting network fee:",i),"0"}}async getOraclePrice(e,t){try{let i=await ta(t,e);if(!i)throw new Error("Failed to get price data");return i}catch(i){throw this.logger.error("Error getting oracle price:",i),i}}async buildUpdatePriceParams(e,t){let i=await this.getOraclePrice(e,t);if(!i)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:i.vaa,publishTime:i.publishTime,oracleType:i.oracleType,value:i.value,price:i.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let i=await ja(e);return i?i.error:JSON.stringify(e)}catch(i){return i?.message??i?.toString()??t}}async checkSeamlessGas(e,t,i){let n=await(await Y$1(t,0)).read.getForwardFeeByToken([i]),g=await T(t,i).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(g)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:i}){try{return {code:0,data:await(await Z$1(e,0)).read.getPoolInfo([t,i])}}catch(r){return this.logger.error("Error getting pool info:",r),{code:-1,message:r?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let i=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);i&&i[1]&&(t=i[1]);}if(t){let i=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(i){let r=Object.keys(he).find(n=>n.toLowerCase()===i);if(r)return he[r]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await pa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,i=d[t];return oa(e,i?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,i,r){this.configManager=e,this.logger=t,this.utils=i,this.client=r;}async withRetry(e,t=3,i=300){let r;for(let n=0;n<t;n++)try{return await e()}catch(a){r=a,n<t-1&&await new Promise(g=>setTimeout(g,i));}throw r}async getTradeFlow(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:i,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:i}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=T(e,i),n=await this.configManager.getSignerAddress(e);return {code:0,data:await r.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,i,r,n){try{let g=await(await _(n)).write.updateAndWithdraw([e,t,i,r]);return {code:0,data:await f(n).waitForTransactionReceipt({hash:g})}}catch(a){return {code:-1,message:a.message}}}async deposit({amount:e,tokenAddress:t,chainId:i}){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"",n=R$1(i);try{if(await this.utils.needsApproval(r,i,t,e,n.Account)){let d=await this.utils.approveAuthorization({chainId:i,quoteAddress:t,amount:maxUint256.toString(),spenderAddress:n.Account});if(d.code!==0)throw new Error(d.message)}let s=await(await _(i)).write.deposit([r,t,e]);return {code:0,data:await f(i).waitForTransactionReceipt({hash:s})}}catch(a){return {code:-1,message:a.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:i}){try{let r=await this.getAccountInfo(t,i,e);if(r.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,i),a=r.data,g=BigInt(a?.quoteProfit??0),s=BigInt(a?.freeMargin??0),c=BigInt(a?.lockedMargin??0),d=n?.code===0?n.data:null,p=d?.status===1?BigInt(d?.lockedMargin??0):0n;return {code:0,data:s+g-c-p}}catch(r){return {code:-1,message:r.message}}}async getAccountInfo(e,t,i){let r=await Z$1(e);try{return {code:0,data:await r.read.getAccountInfo([i,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let i=this.configManager.getConfig(),r=X$1(e,i.brokerAddress),a=await f(e).getBlock({blockTag:"latest"}),g=Number(a?.timestamp??BigInt(Ae().unix()))+300;try{let s=await r.read.userFeeData([t]),c;try{c=await this.withRetry(()=>r.read.userNonces([t]));}catch{c=0n;}return {code:0,data:{nonce:c.toString(),deadline:g,...s}}}catch(s){return {code:-1,message:s.message}}}async getAccountVipInfoByBackend(e,t,i,r){let n=await this.configManager.getAccessToken()??"";try{let a=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:i,nonce:r});if(a.code!==9200)throw new l("REQUEST_FAILED",a.msg??"Failed to get account vip info");return {code:0,data:a.data}}catch(a){return {code:-1,message:a.message}}}async setUserFeeData(e,t,i,r,n){let a=this.configManager.getConfig();if(i<Ae().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let g=await W(t,a.brokerAddress),s={user:e,nonce:r.nonce,deadline:i,feeData:{tier:r.tier,referrer:r.referrer||zeroAddress,totalReferralRebatePct:r.totalReferralRebatePct,referrerRebatePct:r.referrerRebatePct,expiry:r.expiry},signature:n},c=await g.read.userNonces([e]);if(parseInt(c.toString())+1!==parseInt(r.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let d=await g.write.setUserFeeData([s]);return {code:0,data:await f(t).waitForTransactionReceipt({hash:d})}}catch(g){return {code:-1,message:g.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(i=>Qe(e,i)).join("&")}function Pt(o){let e=o||{};return Object.keys(e).filter(i=>typeof e[i]<"u").map(i=>Array.isArray(e[i])?Tt(e,i):Ct(e,i)).join("&")}function be(o){let e=Pt(o);return e?`?${e}`:""}var ie=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",i=await this.configManager.getSignerAddress(e.chainId);if(!i)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:i}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.get(this.buildRequestPath(e),t,merge(n$1,r))}async post(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.post(this.buildRequestPath(e),t,merge(n$1,r))}async put(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.put(this.buildRequestPath(e),t,merge(n$1,r))}async delete(e,{auth:t=false,...i}={}){let r=t?await this.buildAuthParams():{};return n.delete(this.buildRequestPath(e),merge(r,i))}};var re=class extends ie{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await n.get(`${this.getHost()}/v2/agent/forwarder/get${be(e)}`)}async getPoolList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return n.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return n.get(`${this.getHost()}/openapi/gateway/quote/price/oracles`,{chainId:e,poolIds:t.join(",")});throw new Error("Invalid pool id")}async getPoolDetail(e,t){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${be({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...i}){return await n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,i){return await n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,i){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${i}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:i,limit:r,interval:n$1}){return n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:i,limit:r,interval:n$1})}async getKlineLatestBar(e){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async removeFavorite({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:i,deadline:r,nonce:n$1}){return n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:i,deadline:r,nonce:n$1},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getAppealList(e){return this.get("/openapi/gateway/scan/dispute/list",e,{auth:true})}async getAppealDetail(e){return this.get("/openapi/gateway/scan/dispute/details",e,{auth:true})}async uploadAppealEvidence(e){return this.get("/openapi/gateway/scan/dispute/upload/evidence",e,{auth:true})}async getAppealReconsiderationList(e){return this.get("/openapi/gateway/scan/dispute/appeal/list",e,{auth:true})}async getAppealReconsiderationDetail(e){return this.get("/openapi/gateway/scan/dispute/appeal/details",e,{auth:true})}async getAppealReimbursementList(e){return this.get("/openapi/gateway/scan/reimbursement/list",e,{auth:true})}async getAppealNodeVoteList(e){return this.get("/openapi/gateway/scan/node/vote-list",e)}async getAppealNodeVoteDetails(e){return this.get("/openapi/gateway/scan/node/vote-details",e)}async getIsVoteNode(e){return this.get("/openapi/gateway/scan/node/vote-node-check",e)}async postVoteSignature(e){return this.get("/openapi/gateway/scan/node/vote",e,{auth:true})}async getPedingVoteCount(){return this.get("/openapi/gateway/scan/node/pending-vote-total",{},{auth:true})}async getMyAppealCount(){return this.get("/openapi/gateway/scan/processing-total",{},{auth:true})}async getWarmholeSign(e){return this.get("/openapi/gateway/scan/get-warmhole-sign",e,{auth:true})}async getDisputeTotalCount(){return this.get("/openapi/gateway/scan/dispute/dispute-total",{},{auth:true})}async getAppealTotalCount(){return this.get("/openapi/gateway/scan/dispute/appeal-total",{},{auth:true})}async getReimbursementTotalCount(){return this.get("/openapi/gateway/scan/dispute/reimbursement-total",{},{auth:true})}async getCurrentEpoch({address:e,accessToken:t,broker:i}){return n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:i},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:r}){return n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:i,myx_openapi_access_token:r}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,kt="0x55d398326f99059ff775485246999027b3197955";function vt(o){let e=hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),i=toHex(e.slice(32,64));return {v:e[64],r:t,s:i}}async function Mt(o,e,t,i,r,n,a,g){let s=T(e,t),c=await Je(s),[d]=await o.getAddresses();if(!d)throw new l("INVALID_SIGNER","No account for signPermit");let p={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:i,spender:r,value:n,nonce:a,deadline:g},m=await o.signTypedData({account:d,domain:{...c,chainId:c.chainId},types:p,primaryType:"Permit",message:u});return vt(m)}var ne=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async onCheckRelayer(e,t,i,r,n){let g=await(await $$1(i)).read.isUserRelayerEnabled([e,t]),c=await(await Y$1(i)).read.getForwardFeeByToken([r]),d=BigInt(c)*BigInt(Xe);n=n??d.toString();let p=await this.utils.needsApproval(e,i,r,n,R$1(i).TRADING_ROUTER);return g&&!p}async getContractAbiAndAddressByFunctionName(e,t){let i=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],r=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return i.includes(e)?{abi:S,address:R$1(t).TRADING_ROUTER}:n.includes(e)?{abi:m,address:R$1(t).Account}:r.includes(e)?{abi:j$1,address:this.configManager.getConfig().brokerAddress}:{abi:S,address:R$1(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,i$1){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await i(t),n=R$1(t),[a]=await r.getAddresses();if(!a)throw new l("INVALID_SIGNER","No account");let g=T(t,i$1);try{let s=await g.read.nonces([a]),c=await Mt(r,t,i$1,a,n.TRADING_ROUTER,maxUint256,s,e);return [{token:i$1,owner:a,spender:n.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch(s){if(ia(s))throw s;let c=s instanceof Error?s.message:String(s);throw new l("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${c}`)}}async getForwardEip712Domain(e){let i=await(await $$1(e)).read.eip712Domain();return {name:i[1],version:i[2],chainId:i[3],verifyingContract:i[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:i,forwardFeeToken:r,functionName:n,orderParams:a,value:g="0",gas:s="800000"}){let c=await(await $$1(e)).read.nonces([t]),d=Ae().add(60,"minute").unix(),p=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),h=encodeFunctionData({abi:u,functionName:n,args:a}),w=await i({domain:p,functionHash:h,to:m,nonce:c.toString(),deadline:d}),I=await this.api.forwarderTxApi({from:t,to:m,value:g??"0",gas:s,nonce:c.toString(),data:h,deadline:d,signature:w,forwardFeeToken:r},e);if(I.data?.txHash){for(let S=0;S<5;S++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};S<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Te){this.logger.error("Poll transaction from chain error:",Te),S<4&&await new Promise(ce=>setTimeout(ce,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async forwarderTx({from:e,to:t,value:i$1,gas:r,deadline:n,data:a,nonce:g,forwardFeeToken:s},c){let d=await this.getForwardEip712Domain(c),p=await i(c),[u]=await p.getAddresses();if(!u)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await p.signTypedData({account:u,domain:d,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(i$1??"0"),gas:BigInt(r),nonce:BigInt(g),deadline:BigInt(n),data:a}});return await this.api.forwarderTxApi({from:e,to:t,value:i$1,gas:r,nonce:g,data:a,deadline:n,signature:m,forwardFeeToken:s},c)}async approveBalance(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await V$1(e,t),n=R$1(e);return await r.write?.approve([n.TRADING_ROUTER,i])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:i,address:n,tokenAddress:r})).data,w=await(await Y$1(i)).read.getForwardFeeByToken([r]),I=BigInt(w)*BigInt(Xe);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r});let a=Ae().add(60,"minute").unix(),g=[];if(e)try{r===kt?(await this.approveBalance(i,r,maxUint256.toString()))?.hash&&(g=[]):g=await this.getUSDPermitParams(a,i,r);}catch(u){if(ia(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};this.logger.warn("Failed to get USD permit params, proceeding without permit:",u),g=[];}let s=await $$1(i,1),c=await(await $$1(i)).read.nonces([n]),d=encodeFunctionData({abi:k$1,functionName:"permitAndApproveForwarder",args:[t,e,g]}),p;try{p=await this.forwarderTx({from:n,to:s.address,value:"0",gas:"800000",nonce:c.toString(),data:d,deadline:a,forwardFeeToken:r},i);}catch(u){if(ia(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};throw u}if(p.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:p.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(w){this.logger.error("Poll transaction from chain error:",w),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getApproveBalance({chainId:e,forwardFeeToken:t,address:i}){try{let r=R$1(e).TRADING_ROUTER,a=await T(e,t).read.allowance([i,r]);return {code:0,data:String(a)}}catch(r){return {code:-1,message:r?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await $$1(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:i,functionName:r,data:n,seamlessAddress:a}){if(!e||!isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!a||!isAddress(a))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!i||!isAddress(i))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,i))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let s=await $$1(t),c,{abi:d,address:p}=await this.getContractAbiAndAddressByFunctionName(r,t);try{c=encodeFunctionData({abi:d,functionName:r,args:n});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(r)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await s.read.nonces([a]);return {from:a,to:p,value:"0",gas:"800000",deadline:Ae().add(60,"minute").unix(),data:c,nonce:u.toString(),forwardFeeToken:i}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return R$1(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return X$1(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let i=t==="DisputeFiled"?"caseId":"appealCaseId";for(let r of e.logs)try{let n=decodeEventLog({abi:l$1,data:r.data,topics:r.topics});if(n.eventName===t&&n.args&&i in n.args)return n.args[i]}catch{continue}return null}async submitAppeal(e,t,i){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(r,this.config.chainId,t,i,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let a=await this.getDisputeCourtContract(),g=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),s=BigInt(g[0].value.toString()||"1"),c=await a.estimateGas.fileDispute([g,e,t],{value:s}),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.fileDispute([g,e,t],{value:s,gasLimit:d,gasPrice:p}),m=await f(this.config.chainId).waitForTransactionReceipt({hash:u}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:i,deadline:r,v:n,r:a,s:g}){let s=await this.getDisputeCourtContract(),c=await s.estimateGas.vote([e,t,i?1:0,r,n,a,g]),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await s.write.vote([e,t,i?1:0,r,n,a,g],{gasLimit:d,gasPrice:p});return await f(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),i=await t.estimateGas.claimBond([e]),r=await this.client.utils.getGasLimitByRatio(i),n=await this.client.utils.getGasPriceByRatio(),a=await t.write.claimBond([e],{gasLimit:r,gasPrice:n});return f(this.config.chainId).waitForTransactionReceipt({hash:a})}async claimReimbursement(e,t,i,r){let n=await this.getReimbursementContract(),a=await n.estimateGas.claimReimbursement([e,t,i,r]),g=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),c=await n.write.claimReimbursement([e,t,i,r],{gasLimit:g,gasPrice:s});return f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,i){let r=await this.getDisputeCourtContract(),n=await this.client.utils.getGasPriceByRatio(),a=await this.client.utils.getGasLimitByRatio(await r.estimateGas.fileDisputeFromStaker([e,t,i])),g=await r.write.fileDisputeFromStaker([e,t,i],{gasLimit:a,gasPrice:n}),s=await f(this.config.chainId).waitForTransactionReceipt({hash:g}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,i){let r=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",a=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,i,a)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:a});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let s=await r.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),p=await r.write.appeal([e],{gasLimit:c,gasPrice:d}),u=await f(this.config.chainId).waitForTransactionReceipt({hash:p}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:u,appealCaseId:m,caseId:e}}async getAppealList(e){return this.client.api.getAppealList(e)}async getAppealDetail(e){return this.client.api.getAppealDetail(e)}async uploadAppealEvidence(e){return this.client.api.uploadAppealEvidence(e)}async getAppealReconsiderationList(e){return this.client.api.getAppealReconsiderationList(e)}async getAppealReconsiderationDetail(e){return this.client.api.getAppealReconsiderationDetail(e)}async getAppealReimbursementList(e){return this.client.api.getAppealReimbursementList(e)}async getAppealNodeVoteList(e){return this.client.api.getAppealNodeVoteList(e)}async getAppealNodeVoteDetail(e){return this.client.api.getAppealNodeVoteDetails(e)}async getIsVoteNode(e){return this.client.api.getIsVoteNode(e)}async postVoteSignature(e){return this.client.api.postVoteSignature(e)}async getPedingVoteCount(){return this.client.api.getPedingVoteCount()}async getMyAppealCount(){return this.client.api.getMyAppealCount()}async getWarmholeSign(e){return this.client.api.getWarmholeSign(e)}async getDisputeTotalCount(){return this.client.api.getDisputeTotalCount()}async getAppealTotalCount(){return this.client.api.getAppealTotalCount()}async getReimbursementTotalCount(){return this.client.api.getReimbursementTotalCount()}async getAppealStatus(e,t,i){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:await this.configManager.getAccessToken()??""})}};var se=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),i=await W(this.config.chainId,t.brokerAddress),r=await i.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(r),a=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimRebate([e],{gasPrice:a,gasLimit:n});return f(this.config.chainId).waitForTransactionReceipt({hash:g})}};var Dt=(s=>(s[s.UnderReview=1]="UnderReview",s[s.InitialVote=2]="InitialVote",s[s.PublicNotice=3]="PublicNotice",s[s.UnderReconsideration=4]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=6]="Failed",s[s.PlatformRuling=7]="PlatformRuling",s[s.PlatformRevoked=8]="PlatformRevoked",s))(Dt||{}),Ot=(d=>(d[d.InitialVoting=1]="InitialVoting",d[d.PublicNotice=2]="PublicNotice",d[d.UnderReconsideration=3]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=4]="Failed",d[d.PlatformRuling=6]="PlatformRuling",d[d.PlatformRevoked=7]="PlatformRevoked",d[d.ReconsiderationVoting=8]="ReconsiderationVoting",d[d.AppealRevert=9]="AppealRevert",d[d.NotAppealFailed=10]="NotAppealFailed",d))(Ot||{}),Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.PublicNotice=2]="PublicNotice",r[r.UnderReconsideration=3]="UnderReconsideration",r[r.Completed=4]="Completed",r))(Ft||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Lt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Lt||{}),_t=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(_t||{}),Bt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Bt||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),Wt=(i=>(i[i.NoVote=0]="NoVote",i[i.Supported=1]="Supported",i[i.Rejected=2]="Rejected",i))(Wt||{}),Ut=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Ut||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var xe=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new ha({logLevel:e.logLevel});let t=P.getInstance();h()?.hasSigner()||(t.setConfigManager(this.configManager),g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new re(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new Q(this.configManager,this.utils,this.api),this.position=new J(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new se(this);}auth(e){this.configManager.auth(e),P.getInstance().setConfigManager(this.configManager),g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Xn="1.0.20-beta.9";
2
- export{Gt as AppealCaseTypeEnum,_t as AppealClaimStatusEnum,Wt as AppealNodeStateEnum,Bt as AppealNodeVotedStateEnum,Ot as AppealReconsiderationType,Ft as AppealStage,$t as AppealStatus,Dt as AppealType,pr as Direction,Ut as IsVoteNodeEnum,xe as MyxClient,Nt as NodeTypeEnum,k as OperationType,mr as OrderStatus,Y as OrderType,Xn as SDK_VERSION,ur as TimeInForce,lr as TriggerType,Lt as VoteTypeEnum,me as fromViemWalletClient,K as normalizeSigner};
1
+ import {ha,P,h,g,fa,ga,R as R$1,T,ja,V as V$1,f,X as X$1,Y as Y$1,ta,Z as Z$1,pa,d,oa,n,_,W,$ as $$1,S,m,j as j$1,i,ia,k as k$1,U,c,ba,aa,l as l$1,b,e}from'./chunk-2EKPGZHK.mjs';export{na as COMMON_LP_AMOUNT_DECIMALS,ma as COMMON_PRICE_DECIMALS,a as ChainId,D as CloseTypeEnum,A as DirectionEnum,o as ErrorCode,C as ExecTypeEnum,F as ForwarderGetStatus,r as HttpKlineIntervalEnum,ha as Logger,u as MarketCapType,p as MarketPoolState,s as MarketType,P as MxSDK,x as OperationEnum,q as OracleType,B as OrderStatusEnum,w as OrderTypeEnum,v as SearchSecondTypeEnum,t as SearchTypeEnum,E as TradeFlowAccountTypeEnum,y as TradeFlowTypeEnum,z as TriggerTypeEnum,ra as approve,xa as base,qa as bigintAmountSlipperCalculator,pa as bigintTradingGasPriceWithRatio,oa as bigintTradingGasToRatioCalculator,va as formatUnits,la as getAllowanceApproved,ka as getBalanceOf,M as getBaseDetail,H as getBaseUrlByEnv,N as getMarketDetail,O as getMarketList,I as getOraclePrice,J as getPoolDetail,G as getPoolList,K as getPoolOpenOrders,ta as getPriceData,sa as getPricesData,f as getPublicClient,da as getSdkLogSink,L as getTickerData,ua as getTokenInfo,i as getWalletClient,Q as getWalletProvider,za as market,wa as parseUnits,Aa as pool,ya as quote,ga as sdkError,ea as sdkLog,fa as sdkWarn,g as setConfigManagerForViem,ca as setSdkLogSink}from'./chunk-2EKPGZHK.mjs';import lt from'mitt';import {MD5,Hex}from'crypto-es';import pt from'reconnecting-websocket';import {maxUint256,zeroAddress,encodeFunctionData,isAddress,decodeEventLog,createWalletClient,custom,hexToBytes,toHex}from'viem';import Ae from'dayjs';import {merge}from'lodash-es';var $=(o,e)=>MD5(o,{outputLength:32}).toString(Hex);var V=o=>{switch(o.request){case "signin":return $(o.request)}return $(JSON.stringify(o))},N=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return $(JSON.stringify({topic:e,params:t}))}},Be=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",dt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},_e=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:N({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[i,r]=t.split("_");return {...o,type:N({topic:"candle",params:{globalId:parseInt(i),resolution:r}}),globalId:parseInt(i),resolution:r}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=lt();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:i,...r}=t;this.config={...Ge,...r},this.logger=new ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let i={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new pt(this.config.url,this.config.protocols,i),this.setupEventListeners(e,t);}catch(i){t(i);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async i=>{this.eventBus.emit("open",i),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=i=>{this.handleMessage(i);},this.ws.onclose=i=>{this.eventBus.emit("close",i),this.stopHeartbeatTimer();},this.ws.onerror=i=>{this.eventBus.emit("error",i),t(i);},this.ws.addEventListener("reconnecting",i=>{this.eventBus.emit("reconnecting",{detail:i.detail||0}),this.isFirstConnection=false;}),this.ws.addEventListener("maxreconnectattempts",()=>{this.eventBus.emit("maxreconnectattempts",void 0);}));}pong(e){this.send({request:"pong",args:e});}request(e){return new Promise((t,i)=>{let r=V(e);this.waitingRequests.has(r)?(this.waitingRequests.get(r)?.onSuccess.add(t),this.waitingRequests.get(r)?.onError.add(i)):this.waitingRequests.set(r,{onSuccess:new Set([t]),onError:new Set([i])}),this.send(e);})}subscribe(e,t){let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(!n.has(g))if(n.add(g),this.subscriptions.has(g))this.subscriptions.get(g).callbacks.add(t);else {let s={id:g,topic:a.topic,callbacks:new Set([t])};this.subscriptions.set(g,s),r.push(g),this.logger.debug(`create new subscription: ${g}`);}}),r.length>0&&this.send({request:"subv2",args:r});}unsubscribe(e,t){if(!e)return;let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(n.has(g))return;n.add(g);let s=this.subscriptions.get(g);s&&(s.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${g}`),s.callbacks.size===0&&(this.subscriptions.delete(g),r.push(g),this.logger.debug(`subscription ${g} has no callbacks, will unsubscribe`)));}),r.length>0&&this.send({request:"unsubv2",args:r});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(Be(t)){this.handleAckMessage(t);return}this.handleSubscriptionMessage(t);}catch(t){this.logger.error(`Failed to parse WebSocket message: ${t}`);}}handleAckMessage(e){let t;switch(e.type){case "signin":t=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let i=this.waitingRequests.get(t),r=e.data.code===9200;r?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),i?.onError.size&&!r&&i.onError.forEach(n=>{n(new l("REQUEST_FAILED","Request failed"));}),i?.onSuccess.size&&r&&i.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=_e(e),i=t.type,r=this.subscriptions.get(i);r&&r.callbacks.forEach(n=>{try{n(t);}catch(a){this.logger.error(`Callback Error (${i}): ${a}`);}});}resubscribeAll(){if(this.subscriptions.size===0)return;this.logger.debug("resubscribe all...");let e=Array.from(this.subscriptions.values()).map(t=>t.id);e.length>0&&(this.send({request:"subv2",args:e}),this.logger.debug(`resubscribe ${e.length} topics`));}timeoutHeartbeat(){this.stopHeartbeatTimer(),Date.now()-this.lastMessageTime>(this.config.noMessageTimeout||Ge.noMessageTimeout)&&(this.logger.debug("no message timeout"),this.subscriptions.size>0?this.reconnect():this.ws?.close()),this.heartbeatIntervalId=setTimeout(()=>{this.timeoutHeartbeat();},this.config.heartbeatInterval);}stopHeartbeatTimer(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null);}};var We=[56,59144,42161],Ue=[59141,421614,97],$e=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var z=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let i=H.MainNet;e.getConfig().isBetaMode?i=H.BetaNet:e.getConfig().isTestnet&&(i=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:i,...this.configManager.getConfig()?.socketConfig,onBeforeReSubscribe:()=>{if(this.clientAuth)return this.auth(true).then(()=>{this.logger.debug("reconnect auth success");})}});}get isConnected(){return this.wsClient.isConnected()}connect(){this.wsClient.connect();}disconnect(){this.wsClient.disconnect();}reconnect(){this.wsClient.reconnect();}subscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.subscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}unsubscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}subscribeKline(e,t,i){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}unsubscribeKline(e,t,i){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function ut(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function mt(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function me(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let i=typeof t=="string"?t:{raw:t};return await o.signMessage({message:i})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let i=t.to;if(!i)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:i,data:t.data,value:t.value!=null?BigInt(t.value):void 0,gas:t.gasLimit!=null?BigInt(t.gasLimit):void 0,gasPrice:t.gasPrice!=null?BigInt(t.gasPrice):void 0,maxFeePerGas:t.maxFeePerGas!=null?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas!=null?BigInt(t.maxPriorityFeePerGas):void 0})}},...typeof e.signTypedData=="function"?{async signTypedData(t){return await e.signTypedData(t)}}:{}}}function Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:i=>o.signMessage(i),async sendTransaction(i){let r={...i};i.value!=null&&(r.value=BigInt(i.value)),i.gasLimit!=null&&(r.gasLimit=BigInt(i.gasLimit)),i.gasPrice!=null&&(r.gasPrice=BigInt(i.gasPrice)),i.maxFeePerGas!=null&&(r.maxFeePerGas=BigInt(i.maxFeePerGas)),i.maxPriorityFeePerGas!=null&&(r.maxPriorityFeePerGas=BigInt(i.maxPriorityFeePerGas));try{let a=(await o.sendTransaction(r)).hash;if(!a)throw new Error("sendTransaction: no hash in response");return {hash:a}}catch(n){let a=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||a.includes("BigInt")||a.includes("bigint")){let g={...i};i.value!=null&&(g.value=`0x${BigInt(i.value).toString(16)}`),i.gasLimit!=null&&(g.gasLimit=`0x${BigInt(i.gasLimit).toString(16)}`),i.gasPrice!=null&&(g.gasPrice=`0x${BigInt(i.gasPrice).toString(16)}`),i.maxFeePerGas!=null&&(g.maxFeePerGas=`0x${BigInt(i.maxFeePerGas).toString(16)}`),i.maxPriorityFeePerGas!=null&&(g.maxPriorityFeePerGas=`0x${BigInt(i.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(g)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw n}},signTransaction:typeof e.signTransaction=="function"?i=>t.signTransaction(i):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(i){return t.signTypedData(i.domain,i.types,i.message)}}:typeof t._signTypedData=="function"?{async signTypedData(i){return t._signTypedData(i.domain,i.types,i.message)}}:{}}}function K(o){return ut(o)?me(o):mt(o)?Ve(o):o}function qe(o){let e$1=e(o),t=[...e$1.privateJsonRPCUrl?[e$1.privateJsonRPCUrl]:[],...Array.isArray(e$1.publicJsonRPCUrl)?[...e$1.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var fe={};function bt(o){if(!fe[o]){let e$1=e(o);fe[o]={id:o,name:e$1.label||`Chain ${o}`,nativeCurrency:e$1.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),i=bt(e),r=await o.getAddress();return createWalletClient({account:r,chain:i,transport:custom({request:async a=>{if(a.method==="eth_accounts")return [r];if(a.method==="eth_sendTransaction"){let c=a.params?.[0]??{},{hash:d}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return d}if(a.method==="eth_signTypedData_v4"||a.method==="eth_signTypedData"){if(!o.signTypedData){let h=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(h.error)throw new Error(h.error.message);return h.result}let c=a.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let d=JSON.parse(c),{EIP712Domain:p,...u}=d.types;return await o.signTypedData({domain:d.domain,types:u,primaryType:d.primaryType,message:d.message})}let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(s.error)throw new Error(s.error.message);return s.result}})})}var j=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let i=(await this.config.walletClient.getAddresses())[0];if(i)return i}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?K(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:i,chainId:r}=e;if(t){if(!Ue.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of TESTNET_CHAIN_IDS`)}else if(i){if(!$e.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,i)=>{this._getAccessTokenQueue.push({resolve:t,reject:i,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let i=3600;if(t.expireAt){let r=Math.floor(Date.now()/1e3);i=t.expireAt-r,i<=0&&(fa("Received expired token, using default expiry"),i=3600);}return this.setAccessToken(t.accessToken,i),t.accessToken}else return fa("\u274C Received empty accessToken"),null}catch(t){return ga("\u274C Failed to refresh accessToken:",t),null}}setAccessToken(e,t=3600){this.accessToken=e,this.accessTokenExpiry=Date.now()+t*1e3;}getCurrentAccessToken(){return this.accessToken}isAccessTokenValid(){return !!this.accessToken}clearAccessToken(){this.accessToken=void 0,this.accessTokenExpiry=void 0;}getConfig(){return this.config}};var Q=class{constructor(e,t,i){this.configManager=e,this.utils=t,this.api=i;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){return (await this.api.getKlineData({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getKlineLatestBar({interval:e,...t}){this.configManager.getConfig();return (await this.api.getKlineLatestBar({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getTickerList(e){return (await this.api.getTickerData(e)).data}async searchMarketAuth(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:i})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:i})).data}async addFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:i})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:i})).data}async getBaseDetail(e){return (await this.api.getBaseDetail(e)).data}async getMarketDetail(e){return (await this.api.getMarketDetail(e)).data}async getPoolSymbolAll(){return (await this.api.getPoolSymbolAll()).data}async getPoolFundingFeeInfo({poolId:e,chainId:t,marketPrice:i}){let r=await Z$1(t);try{return {code:0,data:await r.read.getPoolInfo([e,i])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async listPositions(e,t){let i=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:i??"",address:e,positionId:t})).data}}catch(r){return this.logger.error("Error fetching positions:",r),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:i,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:i,quoteToken:r,chainId:n,address:a}){this.configManager.getConfig();try{let s=await this.utils.getOraclePrice(e,n);if(!s)throw new Error("Failed to get price data");let c$1={poolId:e,oracleType:s.oracleType,publishTime:s.publishTime,oracleUpdateData:s?.vaa??"0"},d=!1;Number(i)>0&&(d=await this.utils.needsApproval(a,n,r,i,R$1(n).TRADING_ROUTER));let p=BigInt(0),u=BigInt(i)>0?BigInt(i):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:a}),h=m.code===0?m.data??0n:0n,w=BigInt(0);h<u&&(w=u-h,p=w);let I={token:r,amount:p.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let Ce=await U(n);if(d){let S=await this.utils.approveAuthorization({chainId:n,quoteAddress:r,amount:maxUint256.toString(),spenderAddress:R$1(n).TRADING_ROUTER});if(S.code!==0)throw new Error(S.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[c$1],I,t,i],{value:BigInt(s?.value??"1"),gas:BigInt(1e7)*c[n]/100n});return await f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(s){return {code:-1,message:s.message}}}};var wt={IOC:0},R=wt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},lr={NONE:0,GTE:1,LTE:2},k={INCREASE:0,DECREASE:1},pr={LONG:0,SHORT:1},ur={IOC:0},mr={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async createIncreaseOrder(e,t){try{let i=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()},c$1={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},d=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,R$1(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(d){let w=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(e.chainId).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let p=await U(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c$1,positionId:e.positionId});let w=await p.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...s},c$1]);u=await p.write.placeOrderWithPosition([e.positionId.toString(),{...s},c$1],{gasLimit:w*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c$1,depositData:s});let I=await p.estimateGas.placeOrderWithSalt(["1",{...s},c$1]);u=await p.write.placeOrderWithSalt(["1",{...s},c$1],{gasLimit:I*c[e.chainId]/100n});}let m=await f(e.chainId).waitForTransactionReceipt({hash:u});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:u,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(i){return this.logger.error("Error placing order:",i),{code:-1,message:i?.message}}}async closeAllPositions(e,t){try{let i={token:"0x0000000000000000000000000000000000000000",amount:"0"},r=t.map(d=>d.positionId.toString()),n=t.map(d=>({user:d.address,poolId:d.poolId,orderType:d.orderType,triggerType:d.triggerType,operation:k.DECREASE,direction:d.direction,collateralAmount:d.collateralAmount,size:d.size,price:d.price,timeInForce:R,postOnly:d.postOnly,slippagePct:d.slippagePct,leverage:d.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",i,r,n),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await U(e),g=await a.estimateGas.placeOrdersWithPosition([i,r,n]),s=await a.write.placeOrdersWithPosition([i,r,n],{gasLimit:g*c[e]/100n}),c$1=await f(e).waitForTransactionReceipt({hash:s});return {code:0,message:"close all positions success",transactionHash:s,blockNumber:c$1?.blockNumber,gasUsed:c$1?.gasUsed?.toString(),status:c$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c$1}}catch(i){return {code:-1,message:i?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},i=BigInt(e.collateralAmount),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c$1=await U(e.chainId),d;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,s,{data:t}]);let m=await c$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),s,t]);d=await c$1.write.placeOrderWithPosition([e.positionId.toString(),s,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,s,{data:t}]);let h=await c$1.estimateGas.placeOrderWithSalt(["1",s,t]);d=await c$1.write.placeOrderWithSalt(["1",s,t],{gasLimit:h*c[e.chainId]/100n});}let p=await f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let s=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},d;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],s]);d=await t.write.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],s],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",s);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],s]);d=await t.write.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],s],{gasLimit:h*c[e.chainId]/100n});}let p=await f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}let i={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",i);let s=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,i]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),r,i],{gasLimit:s*c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",i);let s=1,c$1=await t.estimateGas.placeOrderWithSalt([s.toString(),r,i]);n=await t.write.placeOrderWithSalt([s.toString(),r,i],{gasLimit:c$1*c[e.chainId]/100n});}let a=await f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:a?.blockNumber,gasUsed:a?.gasUsed?.toString(),status:a?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:a}}}catch(i){return {code:-1,message:i?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel all orders success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrder([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel order success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await U(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"Orders canceled success"}}catch(i){return this.logger.error("Error canceling orders:",i),{code:-1,message:i?.message}}}async updateOrderTpSl(e,t,i,r,n,a){let g=await this.utils.getNetworkFee(n,i),s={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:a?e.tpSize:"0",tpPrice:a?e.tpPrice:"0",slSize:a?e.slSize:"0",slPrice:a?e.slPrice:"0"}},c$1={token:t,amount:g.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await U(i);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(r,i,e.executionFeeToken,g.toString(),R$1(i).TRADING_ROUTER)){let w=await this.utils.approveAuthorization({chainId:i,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(i).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let u=await d.estimateGas.updateOrder([c$1,s]),m=await d.write.updateOrder([c$1,s],{gasLimit:u*c[i]/100n}),h=await f(i).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(p){return this.logger.error("Error updating order:",p),{code:-1,message:"Failed to update order"}}}async getOrders(e){let t=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getOrders(t??"",e)).data}}catch(i){return this.logger.error("Error fetching orders:",i),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:i,...e,address:t})).data}}};var he={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,i,r){try{if(!i||typeof i=="string"&&!i.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=r??R$1(t).Account,g=await T(t,i).read.allowance([e,n]);return {code:0,data:String(g)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await ja(n)}}async needsApproval(e,t,i,r,n){try{let g=(await this.getApproveQuoteAmount(e,t,i,n)).data,s=BigInt(g),c=BigInt(r);return s<c}catch(a){return this.logger.error("Error checking approval needs:",a),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:i,spenderAddress:r}){try{let n=await V$1(e,t),a=i??maxUint256,g=r??R$1(e).Account,s=await this.getGasPriceByRatio(),c=await n.write.approve([g,a],{gasPrice:s});return await f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,i,r){let a=this.configManager.getConfig().brokerAddress;try{let g=X$1(i,a),s=r??await this.configManager.getSignerAddress(i),c=await g.read.getUserFeeRate([s,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(g){return this.logger.error("Error getting user trading fee rate:",g),{code:-1,message:g?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await Y$1(t,0)).read.getExecutionFee([e])).toString()}catch(i){return this.logger.error("Error getting network fee:",i),"0"}}async getOraclePrice(e,t){try{let i=await ta(t,e);if(!i)throw new Error("Failed to get price data");return i}catch(i){throw this.logger.error("Error getting oracle price:",i),i}}async buildUpdatePriceParams(e,t){let i=await this.getOraclePrice(e,t);if(!i)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:i.vaa,publishTime:i.publishTime,oracleType:i.oracleType,value:i.value,price:i.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let i=await ja(e);return i?i.error:JSON.stringify(e)}catch(i){return i?.message??i?.toString()??t}}async checkSeamlessGas(e,t,i){let n=await(await Y$1(t,0)).read.getForwardFeeByToken([i]),g=await T(t,i).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(g)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:i}){try{return {code:0,data:await(await Z$1(e,0)).read.getPoolInfo([t,i])}}catch(r){return this.logger.error("Error getting pool info:",r),{code:-1,message:r?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let i=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);i&&i[1]&&(t=i[1]);}if(t){let i=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(i){let r=Object.keys(he).find(n=>n.toLowerCase()===i);if(r)return he[r]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await pa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,i=d[t];return oa(e,i?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,i,r){this.configManager=e,this.logger=t,this.utils=i,this.client=r;}async withRetry(e,t=3,i=300){let r;for(let n=0;n<t;n++)try{return await e()}catch(a){r=a,n<t-1&&await new Promise(g=>setTimeout(g,i));}throw r}async getTradeFlow(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:i,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:i}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=T(e,i),n=await this.configManager.getSignerAddress(e);return {code:0,data:await r.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,i,r,n){try{let g=await(await _(n)).write.updateAndWithdraw([e,t,i,r]);return {code:0,data:await f(n).waitForTransactionReceipt({hash:g})}}catch(a){return {code:-1,message:a.message}}}async deposit({amount:e,tokenAddress:t,chainId:i}){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"",n=R$1(i);try{if(await this.utils.needsApproval(r,i,t,e,n.Account)){let d=await this.utils.approveAuthorization({chainId:i,quoteAddress:t,amount:maxUint256.toString(),spenderAddress:n.Account});if(d.code!==0)throw new Error(d.message)}let s=await(await _(i)).write.deposit([r,t,e]);return {code:0,data:await f(i).waitForTransactionReceipt({hash:s})}}catch(a){return {code:-1,message:a.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:i}){try{let r=await this.getAccountInfo(t,i,e);if(r.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,i),a=r.data,g=BigInt(a?.quoteProfit??0),s=BigInt(a?.freeMargin??0),c=BigInt(a?.lockedMargin??0),d=n?.code===0?n.data:null,p=d?.status===1?BigInt(d?.lockedMargin??0):0n;return {code:0,data:s+g-c-p}}catch(r){return {code:-1,message:r.message}}}async getAccountInfo(e,t,i){let r=await Z$1(e);try{return {code:0,data:await r.read.getAccountInfo([i,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let i=this.configManager.getConfig(),r=X$1(e,i.brokerAddress),a=await f(e).getBlock({blockTag:"latest"}),g=Number(a?.timestamp??BigInt(Ae().unix()))+300;try{let s=await r.read.userFeeData([t]),c;try{c=await this.withRetry(()=>r.read.userNonces([t]));}catch{c=0n;}return {code:0,data:{nonce:c.toString(),deadline:g,...s}}}catch(s){return {code:-1,message:s.message}}}async getAccountVipInfoByBackend(e,t,i,r){let n=await this.configManager.getAccessToken()??"";try{let a=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:i,nonce:r});if(a.code!==9200)throw new l("REQUEST_FAILED",a.msg??"Failed to get account vip info");return {code:0,data:a.data}}catch(a){return {code:-1,message:a.message}}}async setUserFeeData(e,t,i,r,n){let a=this.configManager.getConfig();if(i<Ae().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let g=await W(t,a.brokerAddress),s={user:e,nonce:r.nonce,deadline:i,feeData:{tier:r.tier,referrer:r.referrer||zeroAddress,totalReferralRebatePct:r.totalReferralRebatePct,referrerRebatePct:r.referrerRebatePct,expiry:r.expiry},signature:n},c=await g.read.userNonces([e]);if(parseInt(c.toString())+1!==parseInt(r.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let d=await g.write.setUserFeeData([s]);return {code:0,data:await f(t).waitForTransactionReceipt({hash:d})}}catch(g){return {code:-1,message:g.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(i=>Qe(e,i)).join("&")}function Pt(o){let e=o||{};return Object.keys(e).filter(i=>typeof e[i]<"u").map(i=>Array.isArray(e[i])?Tt(e,i):Ct(e,i)).join("&")}function be(o){let e=Pt(o);return e?`?${e}`:""}var ie=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",i=await this.configManager.getSignerAddress(e.chainId);if(!i)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:i}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.get(this.buildRequestPath(e),t,merge(n$1,r))}async post(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.post(this.buildRequestPath(e),t,merge(n$1,r))}async put(e,t,{auth:i=false,...r}={}){let n$1=i?await this.buildAuthParams():{};return n.put(this.buildRequestPath(e),t,merge(n$1,r))}async delete(e,{auth:t=false,...i}={}){let r=t?await this.buildAuthParams():{};return n.delete(this.buildRequestPath(e),merge(r,i))}};var re=class extends ie{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await n.get(`${this.getHost()}/v2/agent/forwarder/get${be(e)}`)}async getPoolList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return n.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return n.get(`${this.getHost()}/openapi/gateway/quote/price/oracles`,{chainId:e,poolIds:t.join(",")});throw new Error("Invalid pool id")}async getPoolDetail(e,t){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${be({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...i}){return await n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,i){return await n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,i){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${i}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:i,limit:r,interval:n$1}){return n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:i,limit:r,interval:n$1})}async getKlineLatestBar(e){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async addFavoritesBatch(e){return this.post("/openapi/gateway/scan/market/add-favorites-batch",e,{auth:true})}async removeFavorite({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...i}){return n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:i,deadline:r,nonce:n$1}){return n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:i,deadline:r,nonce:n$1},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getAppealList(e){return this.get("/openapi/gateway/scan/dispute/list",e,{auth:true})}async getAppealDetail(e){return this.get("/openapi/gateway/scan/dispute/details",e,{auth:true})}async uploadAppealEvidence(e){return this.get("/openapi/gateway/scan/dispute/upload/evidence",e,{auth:true})}async getAppealReconsiderationList(e){return this.get("/openapi/gateway/scan/dispute/appeal/list",e,{auth:true})}async getAppealReconsiderationDetail(e){return this.get("/openapi/gateway/scan/dispute/appeal/details",e,{auth:true})}async getAppealReimbursementList(e){return this.get("/openapi/gateway/scan/reimbursement/list",e,{auth:true})}async getAppealNodeVoteList(e){return this.get("/openapi/gateway/scan/node/vote-list",e)}async getAppealNodeVoteDetails(e){return this.get("/openapi/gateway/scan/node/vote-details",e)}async getIsVoteNode(e){return this.get("/openapi/gateway/scan/node/vote-node-check",e)}async postVoteSignature(e){return this.get("/openapi/gateway/scan/node/vote",e,{auth:true})}async getPedingVoteCount(){return this.get("/openapi/gateway/scan/node/pending-vote-total",{},{auth:true})}async getMyAppealCount(){return this.get("/openapi/gateway/scan/processing-total",{},{auth:true})}async getWarmholeSign(e){return this.get("/openapi/gateway/scan/get-warmhole-sign",e,{auth:true})}async getDisputeTotalCount(){return this.get("/openapi/gateway/scan/dispute/dispute-total",{},{auth:true})}async getAppealTotalCount(){return this.get("/openapi/gateway/scan/dispute/appeal-total",{},{auth:true})}async getReimbursementTotalCount(){return this.get("/openapi/gateway/scan/dispute/reimbursement-total",{},{auth:true})}async getCurrentEpoch({address:e,accessToken:t,broker:i}){return n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:i},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:r}){return n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:i,myx_openapi_access_token:r}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,kt="0x55d398326f99059ff775485246999027b3197955";function vt(o){let e=hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),i=toHex(e.slice(32,64));return {v:e[64],r:t,s:i}}async function Mt(o,e,t,i,r,n,a,g){let s=T(e,t),c=await Je(s),[d]=await o.getAddresses();if(!d)throw new l("INVALID_SIGNER","No account for signPermit");let p={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:i,spender:r,value:n,nonce:a,deadline:g},m=await o.signTypedData({account:d,domain:{...c,chainId:c.chainId},types:p,primaryType:"Permit",message:u});return vt(m)}var ne=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async onCheckRelayer(e,t,i,r,n){let g=await(await $$1(i)).read.isUserRelayerEnabled([e,t]),c=await(await Y$1(i)).read.getForwardFeeByToken([r]),d=BigInt(c)*BigInt(Xe);n=n??d.toString();let p=await this.utils.needsApproval(e,i,r,n,R$1(i).TRADING_ROUTER);return g&&!p}async getContractAbiAndAddressByFunctionName(e,t){let i=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],r=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return i.includes(e)?{abi:S,address:R$1(t).TRADING_ROUTER}:n.includes(e)?{abi:m,address:R$1(t).Account}:r.includes(e)?{abi:j$1,address:this.configManager.getConfig().brokerAddress}:{abi:S,address:R$1(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,i$1){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await i(t),n=R$1(t),[a]=await r.getAddresses();if(!a)throw new l("INVALID_SIGNER","No account");let g=T(t,i$1);try{let s=await g.read.nonces([a]),c=await Mt(r,t,i$1,a,n.TRADING_ROUTER,maxUint256,s,e);return [{token:i$1,owner:a,spender:n.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch(s){if(ia(s))throw s;let c=s instanceof Error?s.message:String(s);throw new l("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${c}`)}}async getForwardEip712Domain(e){let i=await(await $$1(e)).read.eip712Domain();return {name:i[1],version:i[2],chainId:i[3],verifyingContract:i[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:i,forwardFeeToken:r,functionName:n,orderParams:a,value:g="0",gas:s="800000"}){let c=await(await $$1(e)).read.nonces([t]),d=Ae().add(60,"minute").unix(),p=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),h=encodeFunctionData({abi:u,functionName:n,args:a}),w=await i({domain:p,functionHash:h,to:m,nonce:c.toString(),deadline:d}),I=await this.api.forwarderTxApi({from:t,to:m,value:g??"0",gas:s,nonce:c.toString(),data:h,deadline:d,signature:w,forwardFeeToken:r},e);if(I.data?.txHash){for(let S=0;S<5;S++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};S<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Te){this.logger.error("Poll transaction from chain error:",Te),S<4&&await new Promise(ce=>setTimeout(ce,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async forwarderTx({from:e,to:t,value:i$1,gas:r,deadline:n,data:a,nonce:g,forwardFeeToken:s},c){let d=await this.getForwardEip712Domain(c),p=await i(c),[u]=await p.getAddresses();if(!u)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await p.signTypedData({account:u,domain:d,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(i$1??"0"),gas:BigInt(r),nonce:BigInt(g),deadline:BigInt(n),data:a}});return await this.api.forwarderTxApi({from:e,to:t,value:i$1,gas:r,nonce:g,data:a,deadline:n,signature:m,forwardFeeToken:s},c)}async approveBalance(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await V$1(e,t),n=R$1(e);return await r.write?.approve([n.TRADING_ROUTER,i])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:i,address:n,tokenAddress:r})).data,w=await(await Y$1(i)).read.getForwardFeeByToken([r]),I=BigInt(w)*BigInt(Xe);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r});let a=Ae().add(60,"minute").unix(),g=[];if(e)try{r===kt?(await this.approveBalance(i,r,maxUint256.toString()))?.hash&&(g=[]):g=await this.getUSDPermitParams(a,i,r);}catch(u){if(ia(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};this.logger.warn("Failed to get USD permit params, proceeding without permit:",u),g=[];}let s=await $$1(i,1),c=await(await $$1(i)).read.nonces([n]),d=encodeFunctionData({abi:k$1,functionName:"permitAndApproveForwarder",args:[t,e,g]}),p;try{p=await this.forwarderTx({from:n,to:s.address,value:"0",gas:"800000",nonce:c.toString(),data:d,deadline:a,forwardFeeToken:r},i);}catch(u){if(ia(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};throw u}if(p.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:p.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(w){this.logger.error("Poll transaction from chain error:",w),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getApproveBalance({chainId:e,forwardFeeToken:t,address:i}){try{let r=R$1(e).TRADING_ROUTER,a=await T(e,t).read.allowance([i,r]);return {code:0,data:String(a)}}catch(r){return {code:-1,message:r?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await $$1(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:i,functionName:r,data:n,seamlessAddress:a}){if(!e||!isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!a||!isAddress(a))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!i||!isAddress(i))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,i))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let s=await $$1(t),c,{abi:d,address:p}=await this.getContractAbiAndAddressByFunctionName(r,t);try{c=encodeFunctionData({abi:d,functionName:r,args:n});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(r)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await s.read.nonces([a]);return {from:a,to:p,value:"0",gas:"800000",deadline:Ae().add(60,"minute").unix(),data:c,nonce:u.toString(),forwardFeeToken:i}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return R$1(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return X$1(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let i=t==="DisputeFiled"?"caseId":"appealCaseId";for(let r of e.logs)try{let n=decodeEventLog({abi:l$1,data:r.data,topics:r.topics});if(n.eventName===t&&n.args&&i in n.args)return n.args[i]}catch{continue}return null}async submitAppeal(e,t,i){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(r,this.config.chainId,t,i,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let a=await this.getDisputeCourtContract(),g=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),s=BigInt(g[0].value.toString()||"1"),c=await a.estimateGas.fileDispute([g,e,t],{value:s}),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.fileDispute([g,e,t],{value:s,gasLimit:d,gasPrice:p}),m=await f(this.config.chainId).waitForTransactionReceipt({hash:u}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:i,deadline:r,v:n,r:a,s:g}){let s=await this.getDisputeCourtContract(),c=await s.estimateGas.vote([e,t,i?1:0,r,n,a,g]),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await s.write.vote([e,t,i?1:0,r,n,a,g],{gasLimit:d,gasPrice:p});return await f(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),i=await t.estimateGas.claimBond([e]),r=await this.client.utils.getGasLimitByRatio(i),n=await this.client.utils.getGasPriceByRatio(),a=await t.write.claimBond([e],{gasLimit:r,gasPrice:n});return f(this.config.chainId).waitForTransactionReceipt({hash:a})}async claimReimbursement(e,t,i,r){let n=await this.getReimbursementContract(),a=await n.estimateGas.claimReimbursement([e,t,i,r]),g=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),c=await n.write.claimReimbursement([e,t,i,r],{gasLimit:g,gasPrice:s});return f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,i){let r=await this.getDisputeCourtContract(),n=await this.client.utils.getGasPriceByRatio(),a=await this.client.utils.getGasLimitByRatio(await r.estimateGas.fileDisputeFromStaker([e,t,i])),g=await r.write.fileDisputeFromStaker([e,t,i],{gasLimit:a,gasPrice:n}),s=await f(this.config.chainId).waitForTransactionReceipt({hash:g}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,i){let r=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",a=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,i,a)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:a});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let s=await r.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),p=await r.write.appeal([e],{gasLimit:c,gasPrice:d}),u=await f(this.config.chainId).waitForTransactionReceipt({hash:p}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:u,appealCaseId:m,caseId:e}}async getAppealList(e){return this.client.api.getAppealList(e)}async getAppealDetail(e){return this.client.api.getAppealDetail(e)}async uploadAppealEvidence(e){return this.client.api.uploadAppealEvidence(e)}async getAppealReconsiderationList(e){return this.client.api.getAppealReconsiderationList(e)}async getAppealReconsiderationDetail(e){return this.client.api.getAppealReconsiderationDetail(e)}async getAppealReimbursementList(e){return this.client.api.getAppealReimbursementList(e)}async getAppealNodeVoteList(e){return this.client.api.getAppealNodeVoteList(e)}async getAppealNodeVoteDetail(e){return this.client.api.getAppealNodeVoteDetails(e)}async getIsVoteNode(e){return this.client.api.getIsVoteNode(e)}async postVoteSignature(e){return this.client.api.postVoteSignature(e)}async getPedingVoteCount(){return this.client.api.getPedingVoteCount()}async getMyAppealCount(){return this.client.api.getMyAppealCount()}async getWarmholeSign(e){return this.client.api.getWarmholeSign(e)}async getDisputeTotalCount(){return this.client.api.getDisputeTotalCount()}async getAppealTotalCount(){return this.client.api.getAppealTotalCount()}async getReimbursementTotalCount(){return this.client.api.getReimbursementTotalCount()}async getAppealStatus(e,t,i){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:await this.configManager.getAccessToken()??""})}};var se=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),i=await W(this.config.chainId,t.brokerAddress),r=await i.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(r),a=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimRebate([e],{gasPrice:a,gasLimit:n});return f(this.config.chainId).waitForTransactionReceipt({hash:g})}};var Dt=(s=>(s[s.UnderReview=1]="UnderReview",s[s.InitialVote=2]="InitialVote",s[s.PublicNotice=3]="PublicNotice",s[s.UnderReconsideration=4]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=6]="Failed",s[s.PlatformRuling=7]="PlatformRuling",s[s.PlatformRevoked=8]="PlatformRevoked",s))(Dt||{}),Ot=(d=>(d[d.InitialVoting=1]="InitialVoting",d[d.PublicNotice=2]="PublicNotice",d[d.UnderReconsideration=3]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=4]="Failed",d[d.PlatformRuling=6]="PlatformRuling",d[d.PlatformRevoked=7]="PlatformRevoked",d[d.ReconsiderationVoting=8]="ReconsiderationVoting",d[d.AppealRevert=9]="AppealRevert",d[d.NotAppealFailed=10]="NotAppealFailed",d))(Ot||{}),Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.PublicNotice=2]="PublicNotice",r[r.UnderReconsideration=3]="UnderReconsideration",r[r.Completed=4]="Completed",r))(Ft||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Lt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Lt||{}),Bt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Bt||{}),_t=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(_t||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),Wt=(i=>(i[i.NoVote=0]="NoVote",i[i.Supported=1]="Supported",i[i.Rejected=2]="Rejected",i))(Wt||{}),Ut=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Ut||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var xe=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new ha({logLevel:e.logLevel});let t=P.getInstance();h()?.hasSigner()||(t.setConfigManager(this.configManager),g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new re(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new Q(this.configManager,this.utils,this.api),this.position=new J(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new se(this);}auth(e){this.configManager.auth(e),P.getInstance().setConfigManager(this.configManager),g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Xn="1.0.21";
2
+ export{Gt as AppealCaseTypeEnum,Bt as AppealClaimStatusEnum,Wt as AppealNodeStateEnum,_t as AppealNodeVotedStateEnum,Ot as AppealReconsiderationType,Ft as AppealStage,$t as AppealStatus,Dt as AppealType,pr as Direction,Ut as IsVoteNodeEnum,xe as MyxClient,Nt as NodeTypeEnum,k as OperationType,mr as OrderStatus,Y as OrderType,Xn as SDK_VERSION,ur as TimeInForce,lr as TriggerType,Lt as VoteTypeEnum,me as fromViemWalletClient,K as normalizeSigner};
package/dist/lp.d.mts CHANGED
@@ -1,2 +1,2 @@
1
1
  import 'viem';
2
- export { u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, w as CreatePoolRequest, x as TpSLParams, y as TpSl, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-C2d3GtOj.mjs';
2
+ export { u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, w as CreatePoolRequest, x as TpSLParams, y as TpSl, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-CbPRefJT.mjs';
package/dist/lp.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import 'viem';
2
- export { u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, w as CreatePoolRequest, x as TpSLParams, y as TpSl, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-C2d3GtOj.js';
2
+ export { u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, w as CreatePoolRequest, x as TpSLParams, y as TpSl, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-CbPRefJT.js';
package/dist/lp.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkSY4XAFN4_js=require('./chunk-SY4XAFN4.js');Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkSY4XAFN4_js.na}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ma}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkSY4XAFN4_js.xa}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ta}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkSY4XAFN4_js.sa}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkSY4XAFN4_js.za}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkSY4XAFN4_js.Aa}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ya}});
1
+ 'use strict';var chunkUIM35W7V_js=require('./chunk-UIM35W7V.js');Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkUIM35W7V_js.na}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkUIM35W7V_js.ma}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkUIM35W7V_js.xa}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkUIM35W7V_js.ta}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkUIM35W7V_js.sa}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkUIM35W7V_js.za}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkUIM35W7V_js.Aa}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkUIM35W7V_js.ya}});
package/dist/lp.mjs CHANGED
@@ -1 +1 @@
1
- export{na as COMMON_LP_AMOUNT_DECIMALS,ma as COMMON_PRICE_DECIMALS,xa as base,ta as getPriceData,sa as getPricesData,za as market,Aa as pool,ya as quote}from'./chunk-HLJ4EUAC.mjs';
1
+ export{na as COMMON_LP_AMOUNT_DECIMALS,ma as COMMON_PRICE_DECIMALS,xa as base,ta as getPriceData,sa as getPricesData,za as market,Aa as pool,ya as quote}from'./chunk-2EKPGZHK.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myx-trade/sdk",
3
- "version": "1.0.20-beta.9",
3
+ "version": "1.0.21",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"