@myx-trade/sdk 1.0.24-beta.21 → 1.0.24-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkDK433OVO_js=require('./chunk-DK433OVO.js'),kt=require('mitt'),cryptoEs=require('crypto-es'),St=require('reconnecting-websocket'),viem=require('viem'),Pe=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var kt__default=/*#__PURE__*/_interopDefault(kt);var St__default=/*#__PURE__*/_interopDefault(St);var Pe__default=/*#__PURE__*/_interopDefault(Pe);var Q=(c,e)=>cryptoEs.MD5(c,{outputLength:32}).toString(cryptoEs.Hex);var J=c=>{switch(c.request){case "signin":return Q(c.request)}return Q(JSON.stringify(c))},$=c=>{let{topic:e,params:t}=c;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 Q(JSON.stringify({topic:e,params:t}))}},qe=({type:c})=>c==="pong"||c==="signin"||c==="subv2"||c==="unsubv2"||c==="ping"||c==="pong",Ct=c=>{switch(c){case "order":case "position":case "ticker.*":return c;default:let[e]=c.split(".");return e}},Ke=c=>{switch(Ct(c.type)){case "ticker":{let[,t=""]=c.type.split(".");return {...c,type:$({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=c.type.split("."),[r,n]=t.split("_");return {...c,type:$({topic:"candle",params:{globalId:parseInt(r),resolution:n}}),globalId:parseInt(r),resolution:n}}}return c};var p=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 ze={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},Y=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=kt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:r,...n}=t;this.config={...ze,...n},this.logger=new chunkDK433OVO_js.ja({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 r={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 St__default.default(this.config.url,this.config.protocols,r),this.setupEventListeners(e,t);}catch(r){t(r);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async r=>{this.eventBus.emit("open",r),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=r=>{this.handleMessage(r);},this.ws.onclose=r=>{this.eventBus.emit("close",r),this.stopHeartbeatTimer();},this.ws.onerror=r=>{this.eventBus.emit("error",r),t(r);},this.ws.addEventListener("reconnecting",r=>{this.eventBus.emit("reconnecting",{detail:r.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,r)=>{let n=J(e);this.waitingRequests.has(n)?(this.waitingRequests.get(n)?.onSuccess.add(t),this.waitingRequests.get(n)?.onError.add(r)):this.waitingRequests.set(n,{onSuccess:new Set([t]),onError:new Set([r])}),this.send(e);})}subscribe(e,t){let r=Array.isArray(e)?e:[e],n=[],i=new Set;r.forEach(s=>{let o=$(s);if(!i.has(o))if(i.add(o),this.subscriptions.has(o))this.subscriptions.get(o).callbacks.add(t);else {let l={id:o,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(o,l),n.push(o),this.logger.debug(`create new subscription: ${o}`);}}),n.length>0&&this.send({request:"subv2",args:n});}unsubscribe(e,t){if(!e)return;let r=Array.isArray(e)?e:[e],n=[],i=new Set;r.forEach(s=>{let o=$(s);if(i.has(o))return;i.add(o);let l=this.subscriptions.get(o);l&&(l.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${o}`),l.callbacks.size===0&&(this.subscriptions.delete(o),n.push(o),this.logger.debug(`subscription ${o} has no callbacks, will unsubscribe`)));}),n.length>0&&this.send({request:"unsubv2",args:n});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new p("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(qe(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=J({request:e.type,args:""});break;default:t=J({request:e.type,args:e.data.data});break}let r=this.waitingRequests.get(t),n=e.data.code===9200;n?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),r?.onError.size&&!n&&r.onError.forEach(i=>{i(new p("REQUEST_FAILED","Request failed"));}),r?.onSuccess.size&&n&&r.onSuccess.forEach(i=>{i(e.data);});}handleSubscriptionMessage(e){let t=Ke(e),r=t.type,n=this.subscriptions.get(r);n&&n.callbacks.forEach(i=>{try{i(t);}catch(s){this.logger.error(`Callback Error (${r}): ${s}`);}});}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||ze.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 je=[56,59144,42161],Qe=[59141,421614,97],Je=[97,421614];var X={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 r=X.MainNet;e.getConfig().isBetaMode?r=X.BetaNet:e.getConfig().isTestnet&&(r=X.TestNet),this.wsClient=new Y({logLevel:this.configManager.getConfig()?.logLevel,url:r,...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 r=Array.isArray(e)?e:[e];this.wsClient.subscribe(r.map(n=>({topic:"ticker",params:{globalId:n}})),t);}unsubscribeTickers(e,t){let r=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(r.map(n=>({topic:"ticker",params:{globalId:n}})),t);}subscribeKline(e,t,r){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}unsubscribeKline(e,t,r){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new p("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 Pt(c){return typeof c.getAddresses=="function"&&typeof c.getAddress!="function"&&typeof c.signMessage=="function"&&typeof c.sendTransaction=="function"}function Rt(c){let e=c;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function Ae(c){let e=c;return {async getAddress(){let[t]=await c.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let r=typeof t=="string"?t:{raw:t};return await c.signMessage({message:r})},signTransaction:t=>c.signTransaction(t),async sendTransaction(t){let r=t.to;if(!r)throw new Error("sendTransaction: to is required");return {hash:await c.sendTransaction({to:r,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 Ye(c){let e=c,t=c;return {getAddress:()=>c.getAddress(),signMessage:r=>c.signMessage(r),async sendTransaction(r){let n={...r};r.value!=null&&(n.value=BigInt(r.value)),r.gasLimit!=null&&(n.gasLimit=BigInt(r.gasLimit)),r.gasPrice!=null&&(n.gasPrice=BigInt(r.gasPrice)),r.maxFeePerGas!=null&&(n.maxFeePerGas=BigInt(r.maxFeePerGas)),r.maxPriorityFeePerGas!=null&&(n.maxPriorityFeePerGas=BigInt(r.maxPriorityFeePerGas));try{let s=(await c.sendTransaction(n)).hash;if(!s)throw new Error("sendTransaction: no hash in response");return {hash:s}}catch(i){let s=typeof i=="object"&&i!==null?String(i.message):"";if(i instanceof TypeError||s.includes("BigInt")||s.includes("bigint")){let o={...r};r.value!=null&&(o.value=`0x${BigInt(r.value).toString(16)}`),r.gasLimit!=null&&(o.gasLimit=`0x${BigInt(r.gasLimit).toString(16)}`),r.gasPrice!=null&&(o.gasPrice=`0x${BigInt(r.gasPrice).toString(16)}`),r.maxFeePerGas!=null&&(o.maxFeePerGas=`0x${BigInt(r.maxFeePerGas).toString(16)}`),r.maxPriorityFeePerGas!=null&&(o.maxPriorityFeePerGas=`0x${BigInt(r.maxPriorityFeePerGas).toString(16)}`);let g=(await c.sendTransaction(o)).hash;if(!g)throw new Error("sendTransaction: no hash in response");return {hash:g}}throw i}},signTransaction:typeof e.signTransaction=="function"?r=>t.signTransaction(r):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(r){return t.signTypedData(r.domain,r.types,r.message)}}:typeof t._signTypedData=="function"?{async signTypedData(r){return t._signTypedData(r.domain,r.types,r.message)}}:{}}}function ee(c){return Pt(c)?Ae(c):Rt(c)?Ye(c):c}function Xe(c){let e=chunkDK433OVO_js.f(c),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${c} has no jsonRPCUrl configured`);return t[0]}var Ie={};function Mt(c){if(!Ie[c]){let e=chunkDK433OVO_js.f(c);Ie[c]={id:c,name:e.label||`Chain ${c}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[Xe(c)]}}};}return Ie[c]}async function Ze(c,e){let t=Xe(e),r=Mt(e),n=await c.getAddress();return viem.createWalletClient({account:n,chain:r,transport:viem.custom({request:async s=>{if(s.method==="eth_accounts")return [n];if(s.method==="eth_sendTransaction"){let g=s.params?.[0]??{},{hash:a}=await c.sendTransaction({to:g.to,data:g.data,value:g.value!=null?BigInt(g.value):void 0,gasLimit:g.gas!=null?BigInt(g.gas):void 0,gasPrice:g.gasPrice!=null?BigInt(g.gasPrice):void 0,maxFeePerGas:g.maxFeePerGas!=null?BigInt(g.maxFeePerGas):void 0,maxPriorityFeePerGas:g.maxPriorityFeePerGas!=null?BigInt(g.maxPriorityFeePerGas):void 0});return a}if(s.method==="eth_signTypedData_v4"||s.method==="eth_signTypedData"){if(!c.signTypedData){let f=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(f.error)throw new Error(f.error.message);return f.result}let g=s.params?.[1];if(typeof g!="string")throw new Error("Invalid eth_signTypedData_v4 params");let a=JSON.parse(g),{EIP712Domain:d,...u}=a.types;return await c.signTypedData({domain:a.domain,types:u,primaryType:a.primaryType,message:a.message})}let l=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(l.error)throw new Error(l.error.message);return l.result}})})}var te=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.getWalletClient?.()||this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let r=(await this.config.walletClient.getAddresses())[0];if(r)return r}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new p("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.getWalletClient){let n=0;for(;n<1e4;){let i=this.config.getWalletClient();if(i)return i;await new Promise(s=>setTimeout(s,200)),n+=200;}throw new p("INVALID_SIGNER","WalletClient not available after chain switch")}if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await Ze(this._normalizedSigner,e);throw new p("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?ee(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:r,chainId:n}=e;if(t){if(!Qe.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of TESTNET_CHAIN_IDS`)}else if(r){if(!Je.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!je.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,r)=>{this._getAccessTokenQueue.push({resolve:t,reject:r,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 chunkDK433OVO_js.ha("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let r=3600;if(t.expireAt){let n=Math.floor(Date.now()/1e3);r=t.expireAt-n,r<=0&&(chunkDK433OVO_js.ha("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return chunkDK433OVO_js.ha("\u274C Received empty accessToken"),null}catch(t){return chunkDK433OVO_js.ia("\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 re=class{constructor(e,t,r){this.configManager=e,this.utils=t,this.api=r;}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 r=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:r})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:r})).data}async addFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:r})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:r})).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:r}){let n=await chunkDK433OVO_js.$(t);try{return {code:0,data:await n.read.getPoolInfo([e,r])}}catch(i){return {code:-1,message:i.message}}}};var ne=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async listPositions(e,t){let r=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:r??"",address:e,positionId:t})).data}}catch(n){return this.logger.error("Error fetching positions:",n),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:r,...e,address:t})).data}}async getForwardEip712Domain(e){let r=await(await chunkDK433OVO_js.ba(e)).read.eip712Domain();return {name:r[1],version:r[2],chainId:r[3],verifyingContract:r[4]}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:r,quoteToken:n,chainId:i,address:s}){try{let o=!1;if(Number(r)>0&&(o=await this.utils.needsApproval(s,i,n,r,chunkDK433OVO_js.S(i).TRADING_ROUTER)),!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let l=BigInt(0),g=BigInt(r)>0?BigInt(r):0n,a=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:s}),d=a.code===0?a.data??0n:0n,u=BigInt(0);d<g&&(u=g-d,l=u);let m={token:n,amount:l.toString()};if(o){let xe=await this.utils.approveAuthorization({chainId:i,quoteAddress:n,amount:viem.maxUint256.toString(),spenderAddress:chunkDK433OVO_js.S(i).TRADING_ROUTER});if(xe.code!==0)throw new Error(xe.message)}let f=chunkDK433OVO_js.S(i).TRADING_ROUTER,{hexData:b,executionGasFee:A}=await chunkDK433OVO_js.xa.buildHexDataAndExecutionGasFee({abi:chunkDK433OVO_js.T,method:"adjustCollateral",args:[m,t,r],chainId:i}),{createAt:R,txId:x,signData:I,gasEscrow:B}=await chunkDK433OVO_js.xa.buildSignData({from:s,to:f,data:b,chainId:i}),D=await chunkDK433OVO_js.Y(i),ct=await D.estimateGas.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A}),{gasLimit:gt,gasPrice:lt}=await chunkDK433OVO_js.ta(i,ct),ve=await D.write.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A,gasLimit:gt,gasPrice:lt}),pt=await chunkDK433OVO_js.za.waitForTransactionReceipt(i,ve);return {code:0,data:{hash:ve,txId:x,receipt:pt}}}catch(o){return {code:-1,message:o.message}}}};var Dt={IOC:0},M=Dt.IOC;var ie={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},xn={NONE:0,GTE:1,LTE:2},E={INCREASE:0,DECREASE:1},Mn={LONG:0,SHORT:1},En={IOC:0},Dn={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var se=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async createIncreaseOrder(e,t){try{let r=BigInt(e.collateralAmount)+BigInt(t),n=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=n.code===0?n.data??0n:0n,s=BigInt(0),o=r-i;o>BigInt(0)&&(s=o);let l={token:e.executionFeeToken,amount:s.toString()},g={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:E.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:M,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},a=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkDK433OVO_js.S(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");if(a){let b=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkDK433OVO_js.S(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await chunkDK433OVO_js.V(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...g,positionId:e.positionId});let b=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...l},g]);u=await d.write.placeOrderWithPosition([e.positionId.toString(),{...l},g],{gasLimit:b*chunkDK433OVO_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:g,depositData:l});let A=await d.estimateGas.placeOrderWithSalt(["1",{...l},g]);u=await d.write.placeOrderWithSalt(["1",{...l},g],{gasLimit:A*chunkDK433OVO_js.c[e.chainId]/100n});}let m=await chunkDK433OVO_js.g(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(r){return this.logger.error("Error placing order:",r),{code:-1,message:r?.message}}}async closeAllPositions(e,t){try{let r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n=t.map(a=>a.positionId.toString()),i=t.map(a=>({user:a.address,poolId:a.poolId,orderType:a.orderType,triggerType:a.triggerType,operation:E.DECREASE,direction:a.direction,collateralAmount:a.collateralAmount,size:a.size,price:a.price,timeInForce:M,postOnly:a.postOnly,slippagePct:a.slippagePct,leverage:a.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",r,n,i),!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let s=await chunkDK433OVO_js.V(e),o=await s.estimateGas.placeOrdersWithPosition([r,n,i]),l=await s.write.placeOrdersWithPosition([r,n,i],{gasLimit:o*chunkDK433OVO_js.c[e]/100n}),g=await chunkDK433OVO_js.g(e).waitForTransactionReceipt({hash:l});return {code:0,message:"close all positions success",transactionHash:l,blockNumber:g?.blockNumber,gasUsed:g?.gasUsed?.toString(),status:g?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:g}}catch(r){return {code:-1,message:r?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:M,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},r=BigInt(e.collateralAmount),n=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=n.code===0?n.data??0n:0n,s=BigInt(0),o=r-i;o>BigInt(0)&&(s=o);let l={token:e.executionFeeToken,amount:s.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let g=await chunkDK433OVO_js.V(e.chainId),a;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,l,{data:t}]);let m=await g.estimateGas.placeOrderWithPosition([e.positionId.toString(),l,t]);a=await g.write.placeOrderWithPosition([e.positionId.toString(),l,t],{gasLimit:m*chunkDK433OVO_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,l,{data:t}]);let f=await g.estimateGas.placeOrderWithSalt(["1",l,t]);a=await g.write.placeOrderWithSalt(["1",l,t],{gasLimit:f*chunkDK433OVO_js.c[e.chainId]/100n});}let d=await chunkDK433OVO_js.g(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkDK433OVO_js.V(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let l=[{user:e.address,poolId:e.poolId,orderType:ie.STOP,triggerType:e.tpTriggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:M,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:ie.STOP,triggerType:e.slTriggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:M,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],g={token:"0x0000000000000000000000000000000000000000",amount:"0"},a;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([g,[e.positionId.toString(),e.positionId.toString()],l]);a=await t.write.placeOrdersWithPosition([g,[e.positionId.toString(),e.positionId.toString()],l],{gasLimit:m*chunkDK433OVO_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",l);let m=1,f=await t.estimateGas.placeOrdersWithSalt([g,[m.toString(),m.toString()],l]);a=await t.write.placeOrdersWithSalt([g,[m.toString(),m.toString()],l],{gasLimit:f*chunkDK433OVO_js.c[e.chainId]/100n});}let d=await chunkDK433OVO_js.g(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}let r={user:e.address,poolId:e.poolId,orderType:ie.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:E.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:M,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},n={token:"0x0000000000000000000000000000000000000000",amount:"0"},i;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",r);let l=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),n,r]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),n,r],{gasLimit:l*chunkDK433OVO_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",r);let l=1,g=await t.estimateGas.placeOrderWithSalt([l.toString(),n,r]);i=await t.write.placeOrderWithSalt([l.toString(),n,r],{gasLimit:g*chunkDK433OVO_js.c[e.chainId]/100n});}let s=await chunkDK433OVO_js.g(e.chainId).waitForTransactionReceipt({hash:i});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:i,blockNumber:s?.blockNumber,gasUsed:s?.gasUsed?.toString(),status:s?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:s}}}catch(r){return {code:-1,message:r?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkDK433OVO_js.V(t)).write.cancelOrders([e]);return await chunkDK433OVO_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"cancel all orders success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkDK433OVO_js.V(t)).write.cancelOrder([e]);return await chunkDK433OVO_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"cancel order success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkDK433OVO_js.V(t)).write.cancelOrders([e]);return await chunkDK433OVO_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"Orders canceled success"}}catch(r){return this.logger.error("Error canceling orders:",r),{code:-1,message:r?.message}}}async updateOrderTpSl(e,t,r,n,i,s){let o=await this.utils.getNetworkFee(i,r),l={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:s?e.tpSize:"0",tpPrice:s?e.tpPrice:"0",slSize:s?e.slSize:"0",slPrice:s?e.slPrice:"0"}},g={token:t,amount:o.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let a=await chunkDK433OVO_js.V(r);this.logger.info("updateOrderTpSl params",l);try{if(await this.utils.needsApproval(n,r,e.executionFeeToken,o.toString(),chunkDK433OVO_js.S(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkDK433OVO_js.S(r).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let u=await a.estimateGas.updateOrder([g,l]),m=await a.write.updateOrder([g,l],{gasLimit:u*chunkDK433OVO_js.c[r]/100n}),f=await chunkDK433OVO_js.g(r).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",f),{code:0,data:f,message:"update order success"}}catch(d){return this.logger.error("Error updating order:",d),{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(r){return this.logger.error("Error fetching orders:",r),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:r,...e,address:t})).data}}async cancelPriceOrder({chainId:e,txtId:t}){let r=o=>viem.isHex(o)?viem.padHex(o,{size:32}):viem.padHex(viem.toHex(o),{size:32}),i=await(await chunkDK433OVO_js.Y(e)).write?.cancel([r(t)]);return {code:0,data:await chunkDK433OVO_js.g(e).waitForTransactionReceipt({hash:i})}}catch(){return {code:-1,message:"Failed to cancel order"}}};var ae=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,r,n){try{if(!r||typeof r=="string"&&!r.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let i=n??chunkDK433OVO_js.S(t).Account,o=await chunkDK433OVO_js.U(t,r).read.allowance([e,i]);return {code:0,data:String(o)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await chunkDK433OVO_js.ma(i)}}async needsApproval(e,t,r,n,i){try{let o=(await this.getApproveQuoteAmount(e,t,r,i)).data,l=BigInt(o),g=BigInt(n);return l<g}catch(s){return this.logger.error("Error checking approval needs:",s),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:r,spenderAddress:n}){try{let i=await chunkDK433OVO_js.W(e,t),s=r??viem.maxUint256,o=n??chunkDK433OVO_js.S(e).Account,l=await this.getGasPriceByRatio(),g=await i.write.approve([o,s],{gasPrice:l});return await chunkDK433OVO_js.g(e).waitForTransactionReceipt({hash:g}),{code:0,message:"Approval success"}}catch(i){return this.logger.error("Approval error:",i),{code:-1,message:i?.message}}}async getUserTradingFeeRate(e,t,r,n){let s=this.configManager.getConfig().brokerAddress;try{let o=chunkDK433OVO_js.Z(r,s),l=n??await this.configManager.getSignerAddress(r),g=await o.read.getUserFeeRate([l,e,t]);return {code:0,data:{takerFeeRate:g[0].toString(),makerFeeRate:g[1].toString(),baseTakerFeeRate:g[2].toString(),baseMakerFeeRate:g[3].toString()}}}catch(o){return this.logger.error("Error getting user trading fee rate:",o),{code:-1,message:o?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkDK433OVO_js._(t,0)).read.getExecutionFee([e])).toString()}catch(r){return this.logger.error("Error getting network fee:",r),"0"}}async getOraclePrice(e,t){try{let r=await chunkDK433OVO_js.Ea(t,e);if(!r)throw new Error("Failed to get price data");return r}catch(r){throw this.logger.error("Error getting oracle price:",r),r}}async buildUpdatePriceParams(e,t){let r=await this.getOraclePrice(e,t);if(!r)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:r.vaa,publishTime:r.publishTime,oracleType:r.oracleType,value:r.value,price:r.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 p("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof p)return e.message;let r=await chunkDK433OVO_js.ma(e);return r?r.error:JSON.stringify(e)}catch(r){return r?.message??r?.toString()??t}}async checkSeamlessGas(e,t,r){let i=await(await chunkDK433OVO_js._(t,0)).read.getForwardFeeByToken([r]),o=await chunkDK433OVO_js.U(t,r).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(o)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:r}){try{return {code:0,data:await(await chunkDK433OVO_js.$(e,0)).read.getPoolInfo([t,r])}}catch(n){return this.logger.error("Error getting pool info:",n),{code:-1,message:n?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof p)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 r=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);r&&r[1]&&(t=r[1]);}if(t){let r=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(r){let n=Object.keys(chunkDK433OVO_js.ka).find(i=>i.toLowerCase()===r);if(n)return chunkDK433OVO_js.ka[n]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkDK433OVO_js.sa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,r=chunkDK433OVO_js.e[t];return chunkDK433OVO_js.ra(e,r?.gasLimitRatio??1.3)}async generateTxId(){return chunkDK433OVO_js.xa.generateTxId()}};var oe=class{constructor(e,t,r,n){this.configManager=e,this.logger=t,this.utils=r,this.client=n;}async withRetry(e,t=3,r=300){let n;for(let i=0;i<t;i++)try{return await e()}catch(s){n=s,i<t-1&&await new Promise(o=>setTimeout(o,r));}throw n}async getTradeFlow(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:r,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:r}){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=chunkDK433OVO_js.U(e,r),i=await this.configManager.getSignerAddress(e);return {code:0,data:await n.read.balanceOf([t||i])}}async updateAndWithdraw(e,t,r,n,i){try{let o=await(await chunkDK433OVO_js.aa(i)).write.updateAndWithdraw([e,t,r,n]);return {code:0,data:await chunkDK433OVO_js.g(i).waitForTransactionReceipt({hash:o})}}catch(s){return {code:-1,message:s.message}}}async deposit({amount:e,tokenAddress:t,chainId:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"",i=chunkDK433OVO_js.S(r);try{if(await this.utils.needsApproval(n,r,t,e,i.Account)){let a=await this.utils.approveAuthorization({chainId:r,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:i.Account});if(a.code!==0)throw new Error(a.message)}let l=await(await chunkDK433OVO_js.aa(r)).write.deposit([n,t,e]);return {code:0,data:await chunkDK433OVO_js.g(r).waitForTransactionReceipt({hash:l})}}catch(s){return {code:-1,message:s.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:r}){try{let n=await this.getAccountInfo(t,r,e);if(n.code!==0)throw new p("REQUEST_FAILED","Failed to get account info");let i=await this.client.appeal.getAppealStatus(e,t,r),s=n.data,o=BigInt(s?.quoteProfit??0),l=BigInt(s?.freeMargin??0),g=BigInt(s?.lockedMargin??0),a=i?.code===0?i.data:null,d=a?.status===1?BigInt(a?.lockedMargin??0):0n;return {code:0,data:l+o-g-d}}catch(n){return {code:-1,message:n.message}}}async getAccountInfo(e,t,r){let n=await chunkDK433OVO_js.$(e);try{return {code:0,data:await n.read.getAccountInfo([r,t])}}catch(i){return {code:-1,message:i.message}}}async getAccountVipInfo(e,t){let r=this.configManager.getConfig(),n=chunkDK433OVO_js.Z(e,r.brokerAddress),s=await chunkDK433OVO_js.g(e).getBlock({blockTag:"latest"}),o=Number(s?.timestamp??BigInt(Pe__default.default().unix()))+300;try{let l=await n.read.userFeeData([t]),g;try{g=await this.withRetry(()=>n.read.userNonces([t]));}catch{g=0n;}return {code:0,data:{nonce:g.toString(),deadline:o,...l}}}catch(l){return {code:-1,message:l.message}}}async getAccountVipInfoByBackend(e,t,r,n){let i=await this.configManager.getAccessToken()??"";try{let s=await this.client.api.getAccountVipInfo({address:e,accessToken:i,chainId:t,deadline:r,nonce:n});if(s.code!==9200)throw new p("REQUEST_FAILED",s.msg??"Failed to get account vip info");return {code:0,data:s.data}}catch(s){return {code:-1,message:s.message}}}async setUserFeeData(e,t,r,n,i){let s=this.configManager.getConfig();if(r<Pe__default.default().unix())throw new p("REQUEST_FAILED","Invalid deadline, please try again");try{let o=await chunkDK433OVO_js.X(t,s.brokerAddress),l={user:e,nonce:n.nonce,deadline:r,feeData:{tier:n.tier,referrer:n.referrer||viem.zeroAddress,totalReferralRebatePct:n.totalReferralRebatePct,referrerRebatePct:n.referrerRebatePct,expiry:n.expiry},signature:i},g=await o.read.userNonces([e]);if(parseInt(g.toString())+1!==parseInt(n.nonce.toString()))throw new p("REQUEST_FAILED","Invalid nonce, please try again");let a=await o.write.setUserFeeData([l]);return {code:0,data:await chunkDK433OVO_js.g(t).waitForTransactionReceipt({hash:a})}}catch(o){return {code:-1,message:o.message}}}};function it(c,e){return `${encodeURIComponent(c)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Bt(c,e){return it(e,c[e])}function Gt(c,e){return c[e].map(r=>it(e,r)).join("&")}function Wt(c){let e=c||{};return Object.keys(e).filter(r=>typeof e[r]<"u").map(r=>Array.isArray(e[r])?Gt(e,r):Bt(e,r)).join("&")}function Te(c){let e=Wt(c);return e?`?${e}`:""}var ge=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 p("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",r=await this.configManager.getSignerAddress(e.chainId);if(!r)throw new p("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:r}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkDK433OVO_js.o.get(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async post(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkDK433OVO_js.o.post(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async put(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkDK433OVO_js.o.put(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async delete(e,{auth:t=false,...r}={}){let n=t?await this.buildAuthParams():{};return chunkDK433OVO_js.o.delete(this.buildRequestPath(e),lodashEs.merge(n,r))}};var le=class extends ge{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkDK433OVO_js.o.get(`${this.getHost()}/v2/agent/forwarder/get${Te(e)}`)}async getPoolList(){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkDK433OVO_js.o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async adjustCollateralForwarderTxApi(e,t){return chunkDK433OVO_js.o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkDK433OVO_js.o.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 chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${Te({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...r}){return await chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/position/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,r){return await chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/order/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,r){return await chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${r}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:r,limit:n,interval:i}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:n,interval:i})}async getKlineLatestBar(e){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkDK433OVO_js.o.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getTransactionOnline({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/execution/list`,r,{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,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:n,nonce:i}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:r,deadline:n,nonce:i},{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:r}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:r},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getProfitLock(e){return this.get("/openapi/gateway/scan/market/profit-lock",e,{auth:true})}async getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:n}){return chunkDK433OVO_js.o.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:r,myx_openapi_access_token:n}})}};var st=async c=>{try{let e=await c.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 Ut={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"}]},ot=2,Vt="0x55d398326f99059ff775485246999027b3197955";function Ht(c){let e=viem.hexToBytes(c);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),r=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:r}}async function qt(c,e,t,r,n,i,s,o){let l=chunkDK433OVO_js.U(e,t),g=await st(l),[a]=await c.getAddresses();if(!a)throw new p("INVALID_SIGNER","No account for signPermit");let d={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:r,spender:n,value:i,nonce:s,deadline:o},m=await c.signTypedData({account:a,domain:{...g,chainId:g.chainId},types:d,primaryType:"Permit",message:u});return Ht(m)}var pe=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async onCheckRelayer(e,t,r,n,i){let o=await(await chunkDK433OVO_js.ba(r)).read.isUserRelayerEnabled([e,t]),g=await(await chunkDK433OVO_js._(r)).read.getForwardFeeByToken([n]),a=BigInt(g)*BigInt(ot);i=i??a.toString();let d=await this.utils.needsApproval(e,r,n,i,chunkDK433OVO_js.S(r).TRADING_ROUTER);return o&&!d}async getContractAbiAndAddressByFunctionName(e,t){let r=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],n=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return r.includes(e)?{abi:chunkDK433OVO_js.T,address:chunkDK433OVO_js.S(t).TRADING_ROUTER}:i.includes(e)?{abi:chunkDK433OVO_js.n,address:chunkDK433OVO_js.S(t).Account}:n.includes(e)?{abi:chunkDK433OVO_js.k,address:this.configManager.getConfig().brokerAddress}:{abi:chunkDK433OVO_js.T,address:chunkDK433OVO_js.S(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let n=await chunkDK433OVO_js.j(t),i=chunkDK433OVO_js.S(t),[s]=await n.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let o=chunkDK433OVO_js.U(t,r);try{let l=await o.read.nonces([s]),g=await qt(n,t,r,s,i.TRADING_ROUTER,viem.maxUint256,l,e);return [{token:r,owner:s,spender:i.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:g.v,r:g.r,s:g.s}]}catch(l){if(chunkDK433OVO_js.la(l))throw l;let g=l instanceof Error?l.message:String(l);throw new p("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${g}`)}}async getForwardEip712Domain(e){let r=await(await chunkDK433OVO_js.ba(e)).read.eip712Domain();return {name:r[1],version:r[2],chainId:r[3],verifyingContract:r[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:r,forwardFeeToken:n,functionName:i,orderParams:s,value:o="0",gas:l="800000"}){let g=await(await chunkDK433OVO_js.ba(e)).read.nonces([t]),a=Pe__default.default().add(60,"minute").unix(),d=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),f=viem.encodeFunctionData({abi:u,functionName:i,args:s}),b=await r({domain:d,functionHash:f,to:m,nonce:g.toString(),deadline:a}),A=await this.api.forwarderTxApi({from:t,to:m,value:o??"0",gas:l,nonce:g.toString(),data:f,deadline:a,signature:b,forwardFeeToken:n},e);if(A.data?.txHash){for(let I=0;I<5;I++)try{if((await this.api.fetchForwarderGetApi({requestId:A.data.requestId})).data?.status===9)return {code:0};I<4&&await new Promise(D=>setTimeout(D,1e3));}catch(B){this.logger.error("Poll transaction from chain error:",B),I<4&&await new Promise(D=>setTimeout(D,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:r,gas:n,deadline:i,data:s,nonce:o,forwardFeeToken:l},g){let a=await this.getForwardEip712Domain(g),d=await chunkDK433OVO_js.j(g),[u]=await d.getAddresses();if(!u)throw new p("INVALID_SIGNER","Missing signer for forwarderTx");let m=await d.signTypedData({account:u,domain:a,types:Ut,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(r??"0"),gas:BigInt(n),nonce:BigInt(o),deadline:BigInt(i),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:r,gas:n,nonce:o,data:s,deadline:i,signature:m,forwardFeeToken:l},g)}async approveBalance(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let n=await chunkDK433OVO_js.W(e,t),i=chunkDK433OVO_js.S(e);return await n.write?.approve([i.TRADING_ROUTER,r])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:n}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:r,address:i,tokenAddress:n})).data,b=await(await chunkDK433OVO_js._(r)).read.getForwardFeeByToken([n]),A=BigInt(b)*BigInt(ot);if(A>0&&A>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new p("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:i,approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:n});let s=Pe__default.default().add(60,"minute").unix(),o=[];if(e)try{n===Vt?(await this.approveBalance(r,n,viem.maxUint256.toString()))?.hash&&(o=[]):o=await this.getUSDPermitParams(s,r,n);}catch(u){if(chunkDK433OVO_js.la(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),o=[];}let l=await chunkDK433OVO_js.ba(r,1),g=await(await chunkDK433OVO_js.ba(r)).read.nonces([i]),a=viem.encodeFunctionData({abi:chunkDK433OVO_js.l,functionName:"permitAndApproveForwarder",args:[t,e,o]}),d;try{d=await this.forwarderTx({from:i,to:l.address,value:"0",gas:"800000",nonce:g.toString(),data:a,deadline:s,forwardFeeToken:n},r);}catch(u){if(chunkDK433OVO_js.la(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(d.data?.txHash){for(let f=0;f<5;f++)try{if((await this.api.fetchForwarderGetApi({requestId:d.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};f<4&&await new Promise(A=>setTimeout(A,1e3));}catch(b){this.logger.error("Poll transaction from chain error:",b),f<4&&await new Promise(A=>setTimeout(A,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:r}){try{let n=chunkDK433OVO_js.S(e).TRADING_ROUTER,s=await chunkDK433OVO_js.U(e,t).read.allowance([r,n]);return {code:0,data:String(s)}}catch(n){return {code:-1,message:n?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkDK433OVO_js.ba(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:r,functionName:n,data:i,seamlessAddress:s}){if(!e||!viem.isAddress(e))throw new p("PARAM_ERROR","address (master) is missing or invalid");if(!s||!viem.isAddress(s))throw new p("PARAM_ERROR","seamlessAddress is missing or invalid");if(!r||!viem.isAddress(r))throw new p("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(i))throw new p("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,r))throw new p("INSUFFICIENT_BALANCE","Insufficient relay fee");let l=await chunkDK433OVO_js.ba(t),g,{abi:a,address:d}=await this.getContractAbiAndAddressByFunctionName(n,t);try{g=viem.encodeFunctionData({abi:a,functionName:n,args:i});}catch(m){throw new p("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(n)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await l.read.nonces([s]);return {from:s,to:d,value:"0",gas:"800000",deadline:Pe__default.default().add(60,"minute").unix(),data:g,nonce:u.toString(),forwardFeeToken:r}}async adjustCollateral({chainId:e,seamlessAddress:t,forwardFeeToken:r,poolId:n,positionId:i,adjustAmount:s,depositData:o}){try{let l=chunkDK433OVO_js.S(e).TRADING_ROUTER,{hexData:g,executionGasFee:a}=await chunkDK433OVO_js.xa.buildHexDataAndExecutionGasFee({abi:chunkDK433OVO_js.T,method:"adjustCollateral",args:[o,i,s],chainId:e}),{createAt:d,txId:u,signData:m}=await chunkDK433OVO_js.xa.buildSignData({from:t,to:l,data:g,chainId:e}),f=await this.api.adjustCollateralForwarderTxApi({from:t,to:l,value:a.toString(),gas:chunkDK433OVO_js.d.toString(),txId:u,createdAt:d.toString(),deadline:m.deadline,data:g,poolIds:[n],forwardFeeToken:r},e);if(f.data?.txHash){for(let R=0;R<5;R++)try{if((await this.api.fetchForwarderGetApi({requestId:f.data.requestId})).data?.status===9)return {code:0,data:{txId:u,hash:f.data.txHash}};R<4&&await new Promise(I=>setTimeout(I,1e3));}catch(x){this.logger.error("Poll adjustCollateral transaction error:",x),R<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}return {code:-1,data:null,message:"Your request timed out, please try again"}}catch(l){return {code:-1,data:null,message:l.message}}}};var N=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkDK433OVO_js.b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return chunkDK433OVO_js.S(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkDK433OVO_js.Z(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var de=class extends N{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkDK433OVO_js.da(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkDK433OVO_js.ca(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let r=t==="DisputeFiled"?"caseId":"appealCaseId";for(let n of e.logs)try{let i=viem.decodeEventLog({abi:chunkDK433OVO_js.m,data:n.data,topics:n.topics});if(i.eventName===t&&i.args&&r in i.args)return i.args[r]}catch{continue}return null}async submitAppeal(e,t,r){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",i=await this.client.utils.needsApproval(n,this.config.chainId,t,r,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",i),i&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let{txId:s,hash:o,receipt:l}=await chunkDK433OVO_js.Ca({chainId:this.config.chainId,account:n,abi:chunkDK433OVO_js.m,method:"fileDispute",args:[e,t],poolIds:[e],to:this.getAddressConfig().DISPUTE_COURT});return {transaction:l,txId:s,hash:o}}async getCaseIdFromTransaction(e){let r=await chunkDK433OVO_js.g(this.config.chainId).getTransactionReceipt({hash:e});return this.getCaseIdFromReceiptLogs(r,"DisputeFiled")}async voteForAppeal({caseId:e,validator:t,isFor:r,deadline:n,v:i,r:s,s:o}){let l=await this.getDisputeCourtContract(),g=await l.estimateGas.vote([e,t,r?1:0,n,i,s,o]),a=await this.client.utils.getGasLimitByRatio(g),d=await this.client.utils.getGasPriceByRatio(),u=await l.write.vote([e,t,r?1:0,n,i,s,o],{gasLimit:a,gasPrice:d});return await chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),r=await t.estimateGas.claimBond([e]),n=await this.client.utils.getGasLimitByRatio(r),i=await this.client.utils.getGasPriceByRatio(),s=await t.write.claimBond([e],{gasLimit:n,gasPrice:i});return chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:s})}async claimReimbursement(e,t,r,n){let i=await this.getReimbursementContract(),s=await i.estimateGas.claimReimbursement([e,t,r,n]),o=await this.client.utils.getGasLimitByRatio(s),l=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimReimbursement([e,t,r,n],{gasLimit:o,gasPrice:l});return chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:g})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e){let t=await this.getDisputeCourtContract(),r=await this.client.utils.getGasPriceByRatio(),n=await this.client.utils.getGasLimitByRatio(await t.estimateGas.fileDisputeFromStaker([e])),i=await t.write.fileDisputeFromStaker([e],{gasLimit:n,gasPrice:r}),s=await chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:i}),o=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(o==null)throw new p("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:o}}async appealReconsideration(e,t,r){let n=await this.getDisputeCourtContract(),i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",s=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(i,this.config.chainId,t,r,s)){let f=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:s});if(f.code!==0)throw new p("TRANSACTION_FAILED",f.message)}let l=await n.estimateGas.appeal([e]),g=await this.client.utils.getGasLimitByRatio(l),a=await this.client.utils.getGasPriceByRatio(),d=await n.write.appeal([e],{gasLimit:g,gasPrice:a}),u=await chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:d}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new p("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,r){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:await this.configManager.getAccessToken()??""})}};var ue=class extends N{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),r=await chunkDK433OVO_js.X(this.config.chainId,t.brokerAddress),n=await r.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(n),s=await this.client.utils.getGasPriceByRatio(),o=await r.write.claimRebate([e],{gasPrice:s,gasLimit:i});return chunkDK433OVO_js.g(this.config.chainId).waitForTransactionReceipt({hash:o})}};var zt=(a=>(a[a.UnderReview=1]="UnderReview",a[a.InitialVote=2]="InitialVote",a[a.PublicNotice=3]="PublicNotice",a[a.UnderReconsideration=4]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=6]="Failed",a[a.PlatformRuling=7]="PlatformRuling",a[a.PlatformRevoked=8]="PlatformRevoked",a[a.SettlementVoting=10]="SettlementVoting",a[a.SettlementFailed=11]="SettlementFailed",a))(zt||{}),jt=(a=>(a[a.InitialVoting=1]="InitialVoting",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=4]="Failed",a[a.PlatformRuling=6]="PlatformRuling",a[a.PlatformRevoked=7]="PlatformRevoked",a[a.ReconsiderationVoting=8]="ReconsiderationVoting",a[a.AppealRevert=9]="AppealRevert",a[a.NotAppealFailed=10]="NotAppealFailed",a))(jt||{}),Qt=(n=>(n[n.UnderReview=1]="UnderReview",n[n.PublicNotice=2]="PublicNotice",n[n.UnderReconsideration=3]="UnderReconsideration",n[n.Completed=4]="Completed",n))(Qt||{}),Jt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Jt||{}),Yt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Yt||{}),Xt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Xt||{}),Zt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Zt||{}),er=(r=>(r[r.Appeal=1]="Appeal",r[r.Reconsideration=2]="Reconsideration",r[r.Settlement=3]="Settlement",r))(er||{}),tr=(r=>(r[r.NoVote=0]="NoVote",r[r.Supported=1]="Supported",r[r.Rejected=2]="Rejected",r))(tr||{}),rr=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(rr||{}),nr=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))(nr||{});var Re=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new te(e),this.logger=new chunkDK433OVO_js.ja({logLevel:e.logLevel});let t=chunkDK433OVO_js.Q.getInstance();chunkDK433OVO_js.i()?.hasSigner()||(t.setConfigManager(this.configManager),chunkDK433OVO_js.h(this.configManager)),t.getMarkets().then(),this.utils=new ae(this.configManager,this.logger),this.api=new le(this.configManager,this.logger),this.account=new oe(this.configManager,this.logger,this.utils,this),this.seamless=new pe(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new re(this.configManager,this.utils,this.api),this.position=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new se(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new Z(this.configManager,this.logger),this.appeal=new de(this,this.configManager),this.referrals=new ue(this);}auth(e){this.configManager.auth(e),chunkDK433OVO_js.Q.getInstance().setConfigManager(this.configManager),chunkDK433OVO_js.h(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 bs="1.0.24-beta.21";
2
- Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkDK433OVO_js.qa}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkDK433OVO_js.pa}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkDK433OVO_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.E}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.B}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkDK433OVO_js.p}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.D}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkDK433OVO_js.G}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.s}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkDK433OVO_js.ja}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkDK433OVO_js.v}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkDK433OVO_js.q}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkDK433OVO_js.t}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkDK433OVO_js.Q}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.y}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkDK433OVO_js.r}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.C}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.x}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.w}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.u}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.F}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.z}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkDK433OVO_js.A}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkDK433OVO_js.va}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkDK433OVO_js.Fa}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkDK433OVO_js.ua}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkDK433OVO_js.sa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkDK433OVO_js.ra}});Object.defineProperty(exports,"execution",{enumerable:true,get:function(){return chunkDK433OVO_js.xa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkDK433OVO_js.Aa}});Object.defineProperty(exports,"forwarder",{enumerable:true,get:function(){return chunkDK433OVO_js.ya}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkDK433OVO_js.oa}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkDK433OVO_js.na}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkDK433OVO_js.N}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkDK433OVO_js.I}});Object.defineProperty(exports,"getGasByRatio",{enumerable:true,get:function(){return chunkDK433OVO_js.ta}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkDK433OVO_js.O}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkDK433OVO_js.P}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkDK433OVO_js.J}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkDK433OVO_js.K}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkDK433OVO_js.H}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkDK433OVO_js.L}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkDK433OVO_js.Ea}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkDK433OVO_js.Da}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkDK433OVO_js.g}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkDK433OVO_js.fa}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkDK433OVO_js.M}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkDK433OVO_js.wa}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkDK433OVO_js.j}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkDK433OVO_js.R}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkDK433OVO_js.Ha}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkDK433OVO_js.Ba}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkDK433OVO_js.Ia}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkDK433OVO_js.Ga}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkDK433OVO_js.ia}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkDK433OVO_js.ga}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkDK433OVO_js.ha}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkDK433OVO_js.h}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkDK433OVO_js.ea}});Object.defineProperty(exports,"signAndSubmit",{enumerable:true,get:function(){return chunkDK433OVO_js.Ca}});Object.defineProperty(exports,"transactions",{enumerable:true,get:function(){return chunkDK433OVO_js.za}});exports.AppealCaseTypeEnum=er;exports.AppealClaimStatusEnum=Xt;exports.AppealNodeStateEnum=tr;exports.AppealNodeVotedStateEnum=Zt;exports.AppealReconsiderationType=jt;exports.AppealStage=Qt;exports.AppealStatus=nr;exports.AppealType=zt;exports.Direction=Mn;exports.IsVoteNodeEnum=rr;exports.MyxClient=Re;exports.NodeTypeEnum=Jt;exports.OperationType=E;exports.OrderStatus=Dn;exports.OrderType=ie;exports.SDK_VERSION=bs;exports.TimeInForce=En;exports.TriggerType=xn;exports.VoteTypeEnum=Yt;exports.fromViemWalletClient=Ae;exports.normalizeSigner=ee;
1
+ 'use strict';var chunkIPAJM2TY_js=require('./chunk-IPAJM2TY.js'),kt=require('mitt'),cryptoEs=require('crypto-es'),St=require('reconnecting-websocket'),viem=require('viem'),Pe=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var kt__default=/*#__PURE__*/_interopDefault(kt);var St__default=/*#__PURE__*/_interopDefault(St);var Pe__default=/*#__PURE__*/_interopDefault(Pe);var Q=(c,e)=>cryptoEs.MD5(c,{outputLength:32}).toString(cryptoEs.Hex);var J=c=>{switch(c.request){case "signin":return Q(c.request)}return Q(JSON.stringify(c))},$=c=>{let{topic:e,params:t}=c;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 Q(JSON.stringify({topic:e,params:t}))}},qe=({type:c})=>c==="pong"||c==="signin"||c==="subv2"||c==="unsubv2"||c==="ping"||c==="pong",Ct=c=>{switch(c){case "order":case "position":case "ticker.*":return c;default:let[e]=c.split(".");return e}},Ke=c=>{switch(Ct(c.type)){case "ticker":{let[,t=""]=c.type.split(".");return {...c,type:$({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=c.type.split("."),[r,n]=t.split("_");return {...c,type:$({topic:"candle",params:{globalId:parseInt(r),resolution:n}}),globalId:parseInt(r),resolution:n}}}return c};var p=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 ze={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},Y=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=kt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:r,...n}=t;this.config={...ze,...n},this.logger=new chunkIPAJM2TY_js.ja({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 r={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 St__default.default(this.config.url,this.config.protocols,r),this.setupEventListeners(e,t);}catch(r){t(r);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async r=>{this.eventBus.emit("open",r),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=r=>{this.handleMessage(r);},this.ws.onclose=r=>{this.eventBus.emit("close",r),this.stopHeartbeatTimer();},this.ws.onerror=r=>{this.eventBus.emit("error",r),t(r);},this.ws.addEventListener("reconnecting",r=>{this.eventBus.emit("reconnecting",{detail:r.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,r)=>{let n=J(e);this.waitingRequests.has(n)?(this.waitingRequests.get(n)?.onSuccess.add(t),this.waitingRequests.get(n)?.onError.add(r)):this.waitingRequests.set(n,{onSuccess:new Set([t]),onError:new Set([r])}),this.send(e);})}subscribe(e,t){let r=Array.isArray(e)?e:[e],n=[],i=new Set;r.forEach(s=>{let o=$(s);if(!i.has(o))if(i.add(o),this.subscriptions.has(o))this.subscriptions.get(o).callbacks.add(t);else {let l={id:o,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(o,l),n.push(o),this.logger.debug(`create new subscription: ${o}`);}}),n.length>0&&this.send({request:"subv2",args:n});}unsubscribe(e,t){if(!e)return;let r=Array.isArray(e)?e:[e],n=[],i=new Set;r.forEach(s=>{let o=$(s);if(i.has(o))return;i.add(o);let l=this.subscriptions.get(o);l&&(l.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${o}`),l.callbacks.size===0&&(this.subscriptions.delete(o),n.push(o),this.logger.debug(`subscription ${o} has no callbacks, will unsubscribe`)));}),n.length>0&&this.send({request:"unsubv2",args:n});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new p("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(qe(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=J({request:e.type,args:""});break;default:t=J({request:e.type,args:e.data.data});break}let r=this.waitingRequests.get(t),n=e.data.code===9200;n?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),r?.onError.size&&!n&&r.onError.forEach(i=>{i(new p("REQUEST_FAILED","Request failed"));}),r?.onSuccess.size&&n&&r.onSuccess.forEach(i=>{i(e.data);});}handleSubscriptionMessage(e){let t=Ke(e),r=t.type,n=this.subscriptions.get(r);n&&n.callbacks.forEach(i=>{try{i(t);}catch(s){this.logger.error(`Callback Error (${r}): ${s}`);}});}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||ze.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 je=[56,59144,42161],Qe=[59141,421614,97],Je=[97,421614];var X={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 r=X.MainNet;e.getConfig().isBetaMode?r=X.BetaNet:e.getConfig().isTestnet&&(r=X.TestNet),this.wsClient=new Y({logLevel:this.configManager.getConfig()?.logLevel,url:r,...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 r=Array.isArray(e)?e:[e];this.wsClient.subscribe(r.map(n=>({topic:"ticker",params:{globalId:n}})),t);}unsubscribeTickers(e,t){let r=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(r.map(n=>({topic:"ticker",params:{globalId:n}})),t);}subscribeKline(e,t,r){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}unsubscribeKline(e,t,r){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new p("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 Pt(c){return typeof c.getAddresses=="function"&&typeof c.getAddress!="function"&&typeof c.signMessage=="function"&&typeof c.sendTransaction=="function"}function Rt(c){let e=c;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function Ae(c){let e=c;return {async getAddress(){let[t]=await c.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let r=typeof t=="string"?t:{raw:t};return await c.signMessage({message:r})},signTransaction:t=>c.signTransaction(t),async sendTransaction(t){let r=t.to;if(!r)throw new Error("sendTransaction: to is required");return {hash:await c.sendTransaction({to:r,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 Ye(c){let e=c,t=c;return {getAddress:()=>c.getAddress(),signMessage:r=>c.signMessage(r),async sendTransaction(r){let n={...r};r.value!=null&&(n.value=BigInt(r.value)),r.gasLimit!=null&&(n.gasLimit=BigInt(r.gasLimit)),r.gasPrice!=null&&(n.gasPrice=BigInt(r.gasPrice)),r.maxFeePerGas!=null&&(n.maxFeePerGas=BigInt(r.maxFeePerGas)),r.maxPriorityFeePerGas!=null&&(n.maxPriorityFeePerGas=BigInt(r.maxPriorityFeePerGas));try{let s=(await c.sendTransaction(n)).hash;if(!s)throw new Error("sendTransaction: no hash in response");return {hash:s}}catch(i){let s=typeof i=="object"&&i!==null?String(i.message):"";if(i instanceof TypeError||s.includes("BigInt")||s.includes("bigint")){let o={...r};r.value!=null&&(o.value=`0x${BigInt(r.value).toString(16)}`),r.gasLimit!=null&&(o.gasLimit=`0x${BigInt(r.gasLimit).toString(16)}`),r.gasPrice!=null&&(o.gasPrice=`0x${BigInt(r.gasPrice).toString(16)}`),r.maxFeePerGas!=null&&(o.maxFeePerGas=`0x${BigInt(r.maxFeePerGas).toString(16)}`),r.maxPriorityFeePerGas!=null&&(o.maxPriorityFeePerGas=`0x${BigInt(r.maxPriorityFeePerGas).toString(16)}`);let g=(await c.sendTransaction(o)).hash;if(!g)throw new Error("sendTransaction: no hash in response");return {hash:g}}throw i}},signTransaction:typeof e.signTransaction=="function"?r=>t.signTransaction(r):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(r){return t.signTypedData(r.domain,r.types,r.message)}}:typeof t._signTypedData=="function"?{async signTypedData(r){return t._signTypedData(r.domain,r.types,r.message)}}:{}}}function ee(c){return Pt(c)?Ae(c):Rt(c)?Ye(c):c}function Xe(c){let e=chunkIPAJM2TY_js.f(c),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${c} has no jsonRPCUrl configured`);return t[0]}var Ie={};function Mt(c){if(!Ie[c]){let e=chunkIPAJM2TY_js.f(c);Ie[c]={id:c,name:e.label||`Chain ${c}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[Xe(c)]}}};}return Ie[c]}async function Ze(c,e){let t=Xe(e),r=Mt(e),n=await c.getAddress();return viem.createWalletClient({account:n,chain:r,transport:viem.custom({request:async s=>{if(s.method==="eth_accounts")return [n];if(s.method==="eth_sendTransaction"){let g=s.params?.[0]??{},{hash:a}=await c.sendTransaction({to:g.to,data:g.data,value:g.value!=null?BigInt(g.value):void 0,gasLimit:g.gas!=null?BigInt(g.gas):void 0,gasPrice:g.gasPrice!=null?BigInt(g.gasPrice):void 0,maxFeePerGas:g.maxFeePerGas!=null?BigInt(g.maxFeePerGas):void 0,maxPriorityFeePerGas:g.maxPriorityFeePerGas!=null?BigInt(g.maxPriorityFeePerGas):void 0});return a}if(s.method==="eth_signTypedData_v4"||s.method==="eth_signTypedData"){if(!c.signTypedData){let f=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(f.error)throw new Error(f.error.message);return f.result}let g=s.params?.[1];if(typeof g!="string")throw new Error("Invalid eth_signTypedData_v4 params");let a=JSON.parse(g),{EIP712Domain:d,...u}=a.types;return await c.signTypedData({domain:a.domain,types:u,primaryType:a.primaryType,message:a.message})}let l=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(l.error)throw new Error(l.error.message);return l.result}})})}var te=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.getWalletClient?.()||this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let r=(await this.config.walletClient.getAddresses())[0];if(r)return r}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new p("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.getWalletClient){let n=0;for(;n<1e4;){let i=this.config.getWalletClient();if(i)return i;await new Promise(s=>setTimeout(s,200)),n+=200;}throw new p("INVALID_SIGNER","WalletClient not available after chain switch")}if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await Ze(this._normalizedSigner,e);throw new p("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?ee(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:r,chainId:n}=e;if(t){if(!Qe.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of TESTNET_CHAIN_IDS`)}else if(r){if(!Je.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!je.includes(n))throw new p("INVALID_CHAIN_ID",`chainId ${n} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,r)=>{this._getAccessTokenQueue.push({resolve:t,reject:r,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 chunkIPAJM2TY_js.ha("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let r=3600;if(t.expireAt){let n=Math.floor(Date.now()/1e3);r=t.expireAt-n,r<=0&&(chunkIPAJM2TY_js.ha("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return chunkIPAJM2TY_js.ha("\u274C Received empty accessToken"),null}catch(t){return chunkIPAJM2TY_js.ia("\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 re=class{constructor(e,t,r){this.configManager=e,this.utils=t,this.api=r;}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 r=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:r})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:r})).data}async addFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:r})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:r})).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:r}){let n=await chunkIPAJM2TY_js.$(t);try{return {code:0,data:await n.read.getPoolInfo([e,r])}}catch(i){return {code:-1,message:i.message}}}};var ne=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async listPositions(e,t){let r=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:r??"",address:e,positionId:t})).data}}catch(n){return this.logger.error("Error fetching positions:",n),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:r,...e,address:t})).data}}async getForwardEip712Domain(e){let r=await(await chunkIPAJM2TY_js.ba(e)).read.eip712Domain();return {name:r[1],version:r[2],chainId:r[3],verifyingContract:r[4]}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:r,quoteToken:n,chainId:i,address:s}){try{let o=!1;if(Number(r)>0&&(o=await this.utils.needsApproval(s,i,n,r,chunkIPAJM2TY_js.S(i).TRADING_ROUTER)),!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let l=BigInt(0),g=BigInt(r)>0?BigInt(r):0n,a=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:s}),d=a.code===0?a.data??0n:0n,u=BigInt(0);d<g&&(u=g-d,l=u);let m={token:n,amount:l.toString()};if(o){let xe=await this.utils.approveAuthorization({chainId:i,quoteAddress:n,amount:viem.maxUint256.toString(),spenderAddress:chunkIPAJM2TY_js.S(i).TRADING_ROUTER});if(xe.code!==0)throw new Error(xe.message)}let f=chunkIPAJM2TY_js.S(i).TRADING_ROUTER,{hexData:b,executionGasFee:A}=await chunkIPAJM2TY_js.xa.buildHexDataAndExecutionGasFee({abi:chunkIPAJM2TY_js.T,method:"adjustCollateral",args:[m,t,r],chainId:i}),{createAt:R,txId:x,signData:I,gasEscrow:B}=await chunkIPAJM2TY_js.xa.buildSignData({from:s,to:f,data:b,chainId:i}),D=await chunkIPAJM2TY_js.Y(i),ct=await D.estimateGas.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A}),{gasLimit:gt,gasPrice:lt}=await chunkIPAJM2TY_js.ta(i,ct),ve=await D.write.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A,gasLimit:gt,gasPrice:lt}),pt=await chunkIPAJM2TY_js.za.waitForTransactionReceipt(i,ve);return {code:0,data:{hash:ve,txId:x,receipt:pt}}}catch(o){return {code:-1,message:o.message}}}};var Dt={IOC:0},M=Dt.IOC;var ie={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},xn={NONE:0,GTE:1,LTE:2},E={INCREASE:0,DECREASE:1},Mn={LONG:0,SHORT:1},En={IOC:0},Dn={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var se=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async createIncreaseOrder(e,t){try{let r=BigInt(e.collateralAmount)+BigInt(t),n=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=n.code===0?n.data??0n:0n,s=BigInt(0),o=r-i;o>BigInt(0)&&(s=o);let l={token:e.executionFeeToken,amount:s.toString()},g={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:E.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:M,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},a=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkIPAJM2TY_js.S(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");if(a){let b=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkIPAJM2TY_js.S(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await chunkIPAJM2TY_js.V(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...g,positionId:e.positionId});let b=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...l},g]);u=await d.write.placeOrderWithPosition([e.positionId.toString(),{...l},g],{gasLimit:b*chunkIPAJM2TY_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:g,depositData:l});let A=await d.estimateGas.placeOrderWithSalt(["1",{...l},g]);u=await d.write.placeOrderWithSalt(["1",{...l},g],{gasLimit:A*chunkIPAJM2TY_js.c[e.chainId]/100n});}let m=await chunkIPAJM2TY_js.g(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(r){return this.logger.error("Error placing order:",r),{code:-1,message:r?.message}}}async closeAllPositions(e,t){try{let r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n=t.map(a=>a.positionId.toString()),i=t.map(a=>({user:a.address,poolId:a.poolId,orderType:a.orderType,triggerType:a.triggerType,operation:E.DECREASE,direction:a.direction,collateralAmount:a.collateralAmount,size:a.size,price:a.price,timeInForce:M,postOnly:a.postOnly,slippagePct:a.slippagePct,leverage:a.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",r,n,i),!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let s=await chunkIPAJM2TY_js.V(e),o=await s.estimateGas.placeOrdersWithPosition([r,n,i]),l=await s.write.placeOrdersWithPosition([r,n,i],{gasLimit:o*chunkIPAJM2TY_js.c[e]/100n}),g=await chunkIPAJM2TY_js.g(e).waitForTransactionReceipt({hash:l});return {code:0,message:"close all positions success",transactionHash:l,blockNumber:g?.blockNumber,gasUsed:g?.gasUsed?.toString(),status:g?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:g}}catch(r){return {code:-1,message:r?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:M,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},r=BigInt(e.collateralAmount),n=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=n.code===0?n.data??0n:0n,s=BigInt(0),o=r-i;o>BigInt(0)&&(s=o);let l={token:e.executionFeeToken,amount:s.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let g=await chunkIPAJM2TY_js.V(e.chainId),a;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,l,{data:t}]);let m=await g.estimateGas.placeOrderWithPosition([e.positionId.toString(),l,t]);a=await g.write.placeOrderWithPosition([e.positionId.toString(),l,t],{gasLimit:m*chunkIPAJM2TY_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,l,{data:t}]);let f=await g.estimateGas.placeOrderWithSalt(["1",l,t]);a=await g.write.placeOrderWithSalt(["1",l,t],{gasLimit:f*chunkIPAJM2TY_js.c[e.chainId]/100n});}let d=await chunkIPAJM2TY_js.g(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkIPAJM2TY_js.V(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let l=[{user:e.address,poolId:e.poolId,orderType:ie.STOP,triggerType:e.tpTriggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:M,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:ie.STOP,triggerType:e.slTriggerType,operation:E.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:M,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],g={token:"0x0000000000000000000000000000000000000000",amount:"0"},a;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([g,[e.positionId.toString(),e.positionId.toString()],l]);a=await t.write.placeOrdersWithPosition([g,[e.positionId.toString(),e.positionId.toString()],l],{gasLimit:m*chunkIPAJM2TY_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",l);let m=1,f=await t.estimateGas.placeOrdersWithSalt([g,[m.toString(),m.toString()],l]);a=await t.write.placeOrdersWithSalt([g,[m.toString(),m.toString()],l],{gasLimit:f*chunkIPAJM2TY_js.c[e.chainId]/100n});}let d=await chunkIPAJM2TY_js.g(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}let r={user:e.address,poolId:e.poolId,orderType:ie.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:E.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:M,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},n={token:"0x0000000000000000000000000000000000000000",amount:"0"},i;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",r);let l=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),n,r]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),n,r],{gasLimit:l*chunkIPAJM2TY_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",r);let l=1,g=await t.estimateGas.placeOrderWithSalt([l.toString(),n,r]);i=await t.write.placeOrderWithSalt([l.toString(),n,r],{gasLimit:g*chunkIPAJM2TY_js.c[e.chainId]/100n});}let s=await chunkIPAJM2TY_js.g(e.chainId).waitForTransactionReceipt({hash:i});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:i,blockNumber:s?.blockNumber,gasUsed:s?.gasUsed?.toString(),status:s?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:s}}}catch(r){return {code:-1,message:r?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkIPAJM2TY_js.V(t)).write.cancelOrders([e]);return await chunkIPAJM2TY_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"cancel all orders success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkIPAJM2TY_js.V(t)).write.cancelOrder([e]);return await chunkIPAJM2TY_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"cancel order success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=await(await chunkIPAJM2TY_js.V(t)).write.cancelOrders([e]);return await chunkIPAJM2TY_js.g(t).waitForTransactionReceipt({hash:n}),{code:0,message:"Orders canceled success"}}catch(r){return this.logger.error("Error canceling orders:",r),{code:-1,message:r?.message}}}async updateOrderTpSl(e,t,r,n,i,s){let o=await this.utils.getNetworkFee(i,r),l={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:s?e.tpSize:"0",tpPrice:s?e.tpPrice:"0",slSize:s?e.slSize:"0",slPrice:s?e.slPrice:"0"}},g={token:t,amount:o.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let a=await chunkIPAJM2TY_js.V(r);this.logger.info("updateOrderTpSl params",l);try{if(await this.utils.needsApproval(n,r,e.executionFeeToken,o.toString(),chunkIPAJM2TY_js.S(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkIPAJM2TY_js.S(r).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let u=await a.estimateGas.updateOrder([g,l]),m=await a.write.updateOrder([g,l],{gasLimit:u*chunkIPAJM2TY_js.c[r]/100n}),f=await chunkIPAJM2TY_js.g(r).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",f),{code:0,data:f,message:"update order success"}}catch(d){return this.logger.error("Error updating order:",d),{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(r){return this.logger.error("Error fetching orders:",r),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:r,...e,address:t})).data}}async cancelPriceOrder({chainId:e,txtId:t}){let r=o=>viem.isHex(o)?viem.padHex(o,{size:32}):viem.padHex(viem.toHex(o),{size:32}),i=await(await chunkIPAJM2TY_js.Y(e)).write?.cancel([r(t)]);return {code:0,data:await chunkIPAJM2TY_js.g(e).waitForTransactionReceipt({hash:i})}}catch(){return {code:-1,message:"Failed to cancel order"}}};var ae=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,r,n){try{if(!r||typeof r=="string"&&!r.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let i=n??chunkIPAJM2TY_js.S(t).Account,o=await chunkIPAJM2TY_js.U(t,r).read.allowance([e,i]);return {code:0,data:String(o)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await chunkIPAJM2TY_js.ma(i)}}async needsApproval(e,t,r,n,i){try{let o=(await this.getApproveQuoteAmount(e,t,r,i)).data,l=BigInt(o),g=BigInt(n);return l<g}catch(s){return this.logger.error("Error checking approval needs:",s),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:r,spenderAddress:n}){try{let i=await chunkIPAJM2TY_js.W(e,t),s=r??viem.maxUint256,o=n??chunkIPAJM2TY_js.S(e).Account,l=await this.getGasPriceByRatio(),g=await i.write.approve([o,s],{gasPrice:l});return await chunkIPAJM2TY_js.g(e).waitForTransactionReceipt({hash:g}),{code:0,message:"Approval success"}}catch(i){return this.logger.error("Approval error:",i),{code:-1,message:i?.message}}}async getUserTradingFeeRate(e,t,r,n){let s=this.configManager.getConfig().brokerAddress;try{let o=chunkIPAJM2TY_js.Z(r,s),l=n??await this.configManager.getSignerAddress(r),g=await o.read.getUserFeeRate([l,e,t]);return {code:0,data:{takerFeeRate:g[0].toString(),makerFeeRate:g[1].toString(),baseTakerFeeRate:g[2].toString(),baseMakerFeeRate:g[3].toString()}}}catch(o){return this.logger.error("Error getting user trading fee rate:",o),{code:-1,message:o?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkIPAJM2TY_js._(t,0)).read.getExecutionFee([e])).toString()}catch(r){return this.logger.error("Error getting network fee:",r),"0"}}async getOraclePrice(e,t){try{let r=await chunkIPAJM2TY_js.Ea(t,e);if(!r)throw new Error("Failed to get price data");return r}catch(r){throw this.logger.error("Error getting oracle price:",r),r}}async buildUpdatePriceParams(e,t){let r=await this.getOraclePrice(e,t);if(!r)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:r.vaa,publishTime:r.publishTime,oracleType:r.oracleType,value:r.value,price:r.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 p("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof p)return e.message;let r=await chunkIPAJM2TY_js.ma(e);return r?r.error:JSON.stringify(e)}catch(r){return r?.message??r?.toString()??t}}async checkSeamlessGas(e,t,r){let i=await(await chunkIPAJM2TY_js._(t,0)).read.getForwardFeeByToken([r]),o=await chunkIPAJM2TY_js.U(t,r).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(o)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:r}){try{return {code:0,data:await(await chunkIPAJM2TY_js.$(e,0)).read.getPoolInfo([t,r])}}catch(n){return this.logger.error("Error getting pool info:",n),{code:-1,message:n?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof p)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 r=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);r&&r[1]&&(t=r[1]);}if(t){let r=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(r){let n=Object.keys(chunkIPAJM2TY_js.ka).find(i=>i.toLowerCase()===r);if(n)return chunkIPAJM2TY_js.ka[n]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkIPAJM2TY_js.sa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,r=chunkIPAJM2TY_js.e[t];return chunkIPAJM2TY_js.ra(e,r?.gasLimitRatio??1.3)}async generateTxId(){return chunkIPAJM2TY_js.xa.generateTxId()}};var oe=class{constructor(e,t,r,n){this.configManager=e,this.logger=t,this.utils=r,this.client=n;}async withRetry(e,t=3,r=300){let n;for(let i=0;i<t;i++)try{return await e()}catch(s){n=s,i<t-1&&await new Promise(o=>setTimeout(o,r));}throw n}async getTradeFlow(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:r,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:r}){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let n=chunkIPAJM2TY_js.U(e,r),i=await this.configManager.getSignerAddress(e);return {code:0,data:await n.read.balanceOf([t||i])}}async updateAndWithdraw(e,t,r,n,i){try{let o=await(await chunkIPAJM2TY_js.aa(i)).write.updateAndWithdraw([e,t,r,n]);return {code:0,data:await chunkIPAJM2TY_js.g(i).waitForTransactionReceipt({hash:o})}}catch(s){return {code:-1,message:s.message}}}async deposit({amount:e,tokenAddress:t,chainId:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"",i=chunkIPAJM2TY_js.S(r);try{if(await this.utils.needsApproval(n,r,t,e,i.Account)){let a=await this.utils.approveAuthorization({chainId:r,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:i.Account});if(a.code!==0)throw new Error(a.message)}let l=await(await chunkIPAJM2TY_js.aa(r)).write.deposit([n,t,e]);return {code:0,data:await chunkIPAJM2TY_js.g(r).waitForTransactionReceipt({hash:l})}}catch(s){return {code:-1,message:s.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:r}){try{let n=await this.getAccountInfo(t,r,e);if(n.code!==0)throw new p("REQUEST_FAILED","Failed to get account info");let i=await this.client.appeal.getAppealStatus(e,t,r),s=n.data,o=BigInt(s?.quoteProfit??0),l=BigInt(s?.freeMargin??0),g=BigInt(s?.lockedMargin??0),a=i?.code===0?i.data:null,d=a?.status===1?BigInt(a?.lockedMargin??0):0n;return {code:0,data:l+o-g-d}}catch(n){return {code:-1,message:n.message}}}async getAccountInfo(e,t,r){let n=await chunkIPAJM2TY_js.$(e);try{return {code:0,data:await n.read.getAccountInfo([r,t])}}catch(i){return {code:-1,message:i.message}}}async getAccountVipInfo(e,t){let r=this.configManager.getConfig(),n=chunkIPAJM2TY_js.Z(e,r.brokerAddress),s=await chunkIPAJM2TY_js.g(e).getBlock({blockTag:"latest"}),o=Number(s?.timestamp??BigInt(Pe__default.default().unix()))+300;try{let l=await n.read.userFeeData([t]),g;try{g=await this.withRetry(()=>n.read.userNonces([t]));}catch{g=0n;}return {code:0,data:{nonce:g.toString(),deadline:o,...l}}}catch(l){return {code:-1,message:l.message}}}async getAccountVipInfoByBackend(e,t,r,n){let i=await this.configManager.getAccessToken()??"";try{let s=await this.client.api.getAccountVipInfo({address:e,accessToken:i,chainId:t,deadline:r,nonce:n});if(s.code!==9200)throw new p("REQUEST_FAILED",s.msg??"Failed to get account vip info");return {code:0,data:s.data}}catch(s){return {code:-1,message:s.message}}}async setUserFeeData(e,t,r,n,i){let s=this.configManager.getConfig();if(r<Pe__default.default().unix())throw new p("REQUEST_FAILED","Invalid deadline, please try again");try{let o=await chunkIPAJM2TY_js.X(t,s.brokerAddress),l={user:e,nonce:n.nonce,deadline:r,feeData:{tier:n.tier,referrer:n.referrer||viem.zeroAddress,totalReferralRebatePct:n.totalReferralRebatePct,referrerRebatePct:n.referrerRebatePct,expiry:n.expiry},signature:i},g=await o.read.userNonces([e]);if(parseInt(g.toString())+1!==parseInt(n.nonce.toString()))throw new p("REQUEST_FAILED","Invalid nonce, please try again");let a=await o.write.setUserFeeData([l]);return {code:0,data:await chunkIPAJM2TY_js.g(t).waitForTransactionReceipt({hash:a})}}catch(o){return {code:-1,message:o.message}}}};function it(c,e){return `${encodeURIComponent(c)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Bt(c,e){return it(e,c[e])}function Gt(c,e){return c[e].map(r=>it(e,r)).join("&")}function Wt(c){let e=c||{};return Object.keys(e).filter(r=>typeof e[r]<"u").map(r=>Array.isArray(e[r])?Gt(e,r):Bt(e,r)).join("&")}function Te(c){let e=Wt(c);return e?`?${e}`:""}var ge=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 p("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",r=await this.configManager.getSignerAddress(e.chainId);if(!r)throw new p("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:r}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkIPAJM2TY_js.o.get(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async post(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkIPAJM2TY_js.o.post(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async put(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return chunkIPAJM2TY_js.o.put(this.buildRequestPath(e),t,lodashEs.merge(i,n))}async delete(e,{auth:t=false,...r}={}){let n=t?await this.buildAuthParams():{};return chunkIPAJM2TY_js.o.delete(this.buildRequestPath(e),lodashEs.merge(n,r))}};var le=class extends ge{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkIPAJM2TY_js.o.get(`${this.getHost()}/v2/agent/forwarder/get${Te(e)}`)}async getPoolList(){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkIPAJM2TY_js.o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async adjustCollateralForwarderTxApi(e,t){return chunkIPAJM2TY_js.o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkIPAJM2TY_js.o.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 chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${Te({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...r}){return await chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/position/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,r){return await chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/order/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,r){return await chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${r}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:r,limit:n,interval:i}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:n,interval:i})}async getKlineLatestBar(e){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getTransactionOnline({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/execution/list`,r,{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,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:n,nonce:i}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:r,deadline:n,nonce:i},{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:r}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:r},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getProfitLock(e){return this.get("/openapi/gateway/scan/market/profit-lock",e,{auth:true})}async getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:n}){return chunkIPAJM2TY_js.o.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:r,myx_openapi_access_token:n}})}};var st=async c=>{try{let e=await c.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 Ut={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"}]},ot=2,Vt="0x55d398326f99059ff775485246999027b3197955";function Ht(c){let e=viem.hexToBytes(c);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),r=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:r}}async function qt(c,e,t,r,n,i,s,o){let l=chunkIPAJM2TY_js.U(e,t),g=await st(l),[a]=await c.getAddresses();if(!a)throw new p("INVALID_SIGNER","No account for signPermit");let d={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:r,spender:n,value:i,nonce:s,deadline:o},m=await c.signTypedData({account:a,domain:{...g,chainId:g.chainId},types:d,primaryType:"Permit",message:u});return Ht(m)}var pe=class{constructor(e,t,r,n,i){this.configManager=e,this.logger=t,this.utils=r,this.account=n,this.api=i;}async onCheckRelayer(e,t,r,n,i){let o=await(await chunkIPAJM2TY_js.ba(r)).read.isUserRelayerEnabled([e,t]),g=await(await chunkIPAJM2TY_js._(r)).read.getForwardFeeByToken([n]),a=BigInt(g)*BigInt(ot);i=i??a.toString();let d=await this.utils.needsApproval(e,r,n,i,chunkIPAJM2TY_js.S(r).TRADING_ROUTER);return o&&!d}async getContractAbiAndAddressByFunctionName(e,t){let r=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],n=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return r.includes(e)?{abi:chunkIPAJM2TY_js.T,address:chunkIPAJM2TY_js.S(t).TRADING_ROUTER}:i.includes(e)?{abi:chunkIPAJM2TY_js.n,address:chunkIPAJM2TY_js.S(t).Account}:n.includes(e)?{abi:chunkIPAJM2TY_js.k,address:this.configManager.getConfig().brokerAddress}:{abi:chunkIPAJM2TY_js.T,address:chunkIPAJM2TY_js.S(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let n=await chunkIPAJM2TY_js.j(t),i=chunkIPAJM2TY_js.S(t),[s]=await n.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let o=chunkIPAJM2TY_js.U(t,r);try{let l=await o.read.nonces([s]),g=await qt(n,t,r,s,i.TRADING_ROUTER,viem.maxUint256,l,e);return [{token:r,owner:s,spender:i.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:g.v,r:g.r,s:g.s}]}catch(l){if(chunkIPAJM2TY_js.la(l))throw l;let g=l instanceof Error?l.message:String(l);throw new p("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${g}`)}}async getForwardEip712Domain(e){let r=await(await chunkIPAJM2TY_js.ba(e)).read.eip712Domain();return {name:r[1],version:r[2],chainId:r[3],verifyingContract:r[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:r,forwardFeeToken:n,functionName:i,orderParams:s,value:o="0",gas:l="800000"}){let g=await(await chunkIPAJM2TY_js.ba(e)).read.nonces([t]),a=Pe__default.default().add(60,"minute").unix(),d=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),f=viem.encodeFunctionData({abi:u,functionName:i,args:s}),b=await r({domain:d,functionHash:f,to:m,nonce:g.toString(),deadline:a}),A=await this.api.forwarderTxApi({from:t,to:m,value:o??"0",gas:l,nonce:g.toString(),data:f,deadline:a,signature:b,forwardFeeToken:n},e);if(A.data?.txHash){for(let I=0;I<5;I++)try{if((await this.api.fetchForwarderGetApi({requestId:A.data.requestId})).data?.status===9)return {code:0};I<4&&await new Promise(D=>setTimeout(D,1e3));}catch(B){this.logger.error("Poll transaction from chain error:",B),I<4&&await new Promise(D=>setTimeout(D,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:r,gas:n,deadline:i,data:s,nonce:o,forwardFeeToken:l},g){let a=await this.getForwardEip712Domain(g),d=await chunkIPAJM2TY_js.j(g),[u]=await d.getAddresses();if(!u)throw new p("INVALID_SIGNER","Missing signer for forwarderTx");let m=await d.signTypedData({account:u,domain:a,types:Ut,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(r??"0"),gas:BigInt(n),nonce:BigInt(o),deadline:BigInt(i),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:r,gas:n,nonce:o,data:s,deadline:i,signature:m,forwardFeeToken:l},g)}async approveBalance(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let n=await chunkIPAJM2TY_js.W(e,t),i=chunkIPAJM2TY_js.S(e);return await n.write?.approve([i.TRADING_ROUTER,r])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:n}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:r,address:i,tokenAddress:n})).data,b=await(await chunkIPAJM2TY_js._(r)).read.getForwardFeeByToken([n]),A=BigInt(b)*BigInt(ot);if(A>0&&A>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new p("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:i,approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:n});let s=Pe__default.default().add(60,"minute").unix(),o=[];if(e)try{n===Vt?(await this.approveBalance(r,n,viem.maxUint256.toString()))?.hash&&(o=[]):o=await this.getUSDPermitParams(s,r,n);}catch(u){if(chunkIPAJM2TY_js.la(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),o=[];}let l=await chunkIPAJM2TY_js.ba(r,1),g=await(await chunkIPAJM2TY_js.ba(r)).read.nonces([i]),a=viem.encodeFunctionData({abi:chunkIPAJM2TY_js.l,functionName:"permitAndApproveForwarder",args:[t,e,o]}),d;try{d=await this.forwarderTx({from:i,to:l.address,value:"0",gas:"800000",nonce:g.toString(),data:a,deadline:s,forwardFeeToken:n},r);}catch(u){if(chunkIPAJM2TY_js.la(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(d.data?.txHash){for(let f=0;f<5;f++)try{if((await this.api.fetchForwarderGetApi({requestId:d.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};f<4&&await new Promise(A=>setTimeout(A,1e3));}catch(b){this.logger.error("Poll transaction from chain error:",b),f<4&&await new Promise(A=>setTimeout(A,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:r}){try{let n=chunkIPAJM2TY_js.S(e).TRADING_ROUTER,s=await chunkIPAJM2TY_js.U(e,t).read.allowance([r,n]);return {code:0,data:String(s)}}catch(n){return {code:-1,message:n?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkIPAJM2TY_js.ba(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:r,functionName:n,data:i,seamlessAddress:s}){if(!e||!viem.isAddress(e))throw new p("PARAM_ERROR","address (master) is missing or invalid");if(!s||!viem.isAddress(s))throw new p("PARAM_ERROR","seamlessAddress is missing or invalid");if(!r||!viem.isAddress(r))throw new p("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(i))throw new p("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,r))throw new p("INSUFFICIENT_BALANCE","Insufficient relay fee");let l=await chunkIPAJM2TY_js.ba(t),g,{abi:a,address:d}=await this.getContractAbiAndAddressByFunctionName(n,t);try{g=viem.encodeFunctionData({abi:a,functionName:n,args:i});}catch(m){throw new p("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(n)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await l.read.nonces([s]);return {from:s,to:d,value:"0",gas:"800000",deadline:Pe__default.default().add(60,"minute").unix(),data:g,nonce:u.toString(),forwardFeeToken:r}}async adjustCollateral({chainId:e,seamlessAddress:t,forwardFeeToken:r,poolId:n,positionId:i,adjustAmount:s,depositData:o}){try{let l=chunkIPAJM2TY_js.S(e).TRADING_ROUTER,{hexData:g,executionGasFee:a}=await chunkIPAJM2TY_js.xa.buildHexDataAndExecutionGasFee({abi:chunkIPAJM2TY_js.T,method:"adjustCollateral",args:[o,i,s],chainId:e}),{createAt:d,txId:u,signData:m}=await chunkIPAJM2TY_js.xa.buildSignData({from:t,to:l,data:g,chainId:e}),f=await this.api.adjustCollateralForwarderTxApi({from:t,to:l,value:a.toString(),gas:chunkIPAJM2TY_js.d.toString(),txId:u,createdAt:d.toString(),deadline:m.deadline,data:g,poolIds:[n],forwardFeeToken:r},e);if(f.data?.txHash){for(let R=0;R<5;R++)try{if((await this.api.fetchForwarderGetApi({requestId:f.data.requestId})).data?.status===9)return {code:0,data:{txId:u,hash:f.data.txHash}};R<4&&await new Promise(I=>setTimeout(I,1e3));}catch(x){this.logger.error("Poll adjustCollateral transaction error:",x),R<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}return {code:-1,data:null,message:"Your request timed out, please try again"}}catch(l){return {code:-1,data:null,message:l.message}}}};var N=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkIPAJM2TY_js.b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return chunkIPAJM2TY_js.S(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkIPAJM2TY_js.Z(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var de=class extends N{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkIPAJM2TY_js.da(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkIPAJM2TY_js.ca(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let r=t==="DisputeFiled"?"caseId":"appealCaseId";for(let n of e.logs)try{let i=viem.decodeEventLog({abi:chunkIPAJM2TY_js.m,data:n.data,topics:n.topics});if(i.eventName===t&&i.args&&r in i.args)return i.args[r]}catch{continue}return null}async submitAppeal(e,t,r){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",i=await this.client.utils.needsApproval(n,this.config.chainId,t,r,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",i),i&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let{txId:s,hash:o,receipt:l}=await chunkIPAJM2TY_js.Ca({chainId:this.config.chainId,account:n,abi:chunkIPAJM2TY_js.m,method:"fileDispute",args:[e,t],poolIds:[e],to:this.getAddressConfig().DISPUTE_COURT});return {transaction:l,txId:s,hash:o}}async getCaseIdFromTransaction(e){let r=await chunkIPAJM2TY_js.g(this.config.chainId).getTransactionReceipt({hash:e});return this.getCaseIdFromReceiptLogs(r,"DisputeFiled")}async voteForAppeal({caseId:e,validator:t,isFor:r,deadline:n,v:i,r:s,s:o}){let l=await this.getDisputeCourtContract(),g=await l.estimateGas.vote([e,t,r?1:0,n,i,s,o]),a=await this.client.utils.getGasLimitByRatio(g),d=await this.client.utils.getGasPriceByRatio(),u=await l.write.vote([e,t,r?1:0,n,i,s,o],{gasLimit:a,gasPrice:d});return await chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),r=await t.estimateGas.claimBond([e]),n=await this.client.utils.getGasLimitByRatio(r),i=await this.client.utils.getGasPriceByRatio(),s=await t.write.claimBond([e],{gasLimit:n,gasPrice:i});return chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:s})}async claimReimbursement(e,t,r,n){let i=await this.getReimbursementContract(),s=await i.estimateGas.claimReimbursement([e,t,r,n]),o=await this.client.utils.getGasLimitByRatio(s),l=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimReimbursement([e,t,r,n],{gasLimit:o,gasPrice:l});return chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:g})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e){let t=await this.getDisputeCourtContract(),r=await this.client.utils.getGasPriceByRatio(),n=await this.client.utils.getGasLimitByRatio(await t.estimateGas.fileDisputeFromVoter([e])),i=await t.write.fileDisputeFromVoter([e],{gasLimit:n,gasPrice:r}),s=await chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:i}),o=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(o==null)throw new p("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:o}}async appealReconsideration(e,t,r){let n=await this.getDisputeCourtContract(),i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",s=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(i,this.config.chainId,t,r,s)){let f=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:s});if(f.code!==0)throw new p("TRANSACTION_FAILED",f.message)}let l=await n.estimateGas.appeal([e]),g=await this.client.utils.getGasLimitByRatio(l),a=await this.client.utils.getGasPriceByRatio(),d=await n.write.appeal([e],{gasLimit:g,gasPrice:a}),u=await chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:d}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new p("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,r){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:await this.configManager.getAccessToken()??""})}};var ue=class extends N{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),r=await chunkIPAJM2TY_js.X(this.config.chainId,t.brokerAddress),n=await r.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(n),s=await this.client.utils.getGasPriceByRatio(),o=await r.write.claimRebate([e],{gasPrice:s,gasLimit:i});return chunkIPAJM2TY_js.g(this.config.chainId).waitForTransactionReceipt({hash:o})}};var zt=(a=>(a[a.UnderReview=1]="UnderReview",a[a.InitialVote=2]="InitialVote",a[a.PublicNotice=3]="PublicNotice",a[a.UnderReconsideration=4]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=6]="Failed",a[a.PlatformRuling=7]="PlatformRuling",a[a.PlatformRevoked=8]="PlatformRevoked",a[a.SettlementVoting=10]="SettlementVoting",a[a.SettlementFailed=11]="SettlementFailed",a))(zt||{}),jt=(a=>(a[a.InitialVoting=1]="InitialVoting",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=4]="Failed",a[a.PlatformRuling=6]="PlatformRuling",a[a.PlatformRevoked=7]="PlatformRevoked",a[a.ReconsiderationVoting=8]="ReconsiderationVoting",a[a.AppealRevert=9]="AppealRevert",a[a.NotAppealFailed=10]="NotAppealFailed",a))(jt||{}),Qt=(n=>(n[n.UnderReview=1]="UnderReview",n[n.PublicNotice=2]="PublicNotice",n[n.UnderReconsideration=3]="UnderReconsideration",n[n.Completed=4]="Completed",n))(Qt||{}),Jt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Jt||{}),Yt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Yt||{}),Xt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Xt||{}),Zt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Zt||{}),er=(r=>(r[r.Appeal=1]="Appeal",r[r.Reconsideration=2]="Reconsideration",r[r.Settlement=3]="Settlement",r))(er||{}),tr=(r=>(r[r.NoVote=0]="NoVote",r[r.Supported=1]="Supported",r[r.Rejected=2]="Rejected",r))(tr||{}),rr=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(rr||{}),nr=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))(nr||{});var Re=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new te(e),this.logger=new chunkIPAJM2TY_js.ja({logLevel:e.logLevel});let t=chunkIPAJM2TY_js.Q.getInstance();chunkIPAJM2TY_js.i()?.hasSigner()||(t.setConfigManager(this.configManager),chunkIPAJM2TY_js.h(this.configManager)),t.getMarkets().then(),this.utils=new ae(this.configManager,this.logger),this.api=new le(this.configManager,this.logger),this.account=new oe(this.configManager,this.logger,this.utils,this),this.seamless=new pe(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new re(this.configManager,this.utils,this.api),this.position=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new se(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new Z(this.configManager,this.logger),this.appeal=new de(this,this.configManager),this.referrals=new ue(this);}auth(e){this.configManager.auth(e),chunkIPAJM2TY_js.Q.getInstance().setConfigManager(this.configManager),chunkIPAJM2TY_js.h(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 bs="1.0.24-beta.22";
2
+ Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkIPAJM2TY_js.qa}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkIPAJM2TY_js.pa}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkIPAJM2TY_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.E}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.B}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkIPAJM2TY_js.p}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.D}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkIPAJM2TY_js.G}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.s}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ja}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkIPAJM2TY_js.v}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkIPAJM2TY_js.q}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkIPAJM2TY_js.t}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Q}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.y}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkIPAJM2TY_js.r}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.C}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.x}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.w}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.u}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.F}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.z}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkIPAJM2TY_js.A}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkIPAJM2TY_js.va}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Fa}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ua}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkIPAJM2TY_js.sa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ra}});Object.defineProperty(exports,"execution",{enumerable:true,get:function(){return chunkIPAJM2TY_js.xa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Aa}});Object.defineProperty(exports,"forwarder",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ya}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkIPAJM2TY_js.oa}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkIPAJM2TY_js.na}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkIPAJM2TY_js.N}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkIPAJM2TY_js.I}});Object.defineProperty(exports,"getGasByRatio",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ta}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkIPAJM2TY_js.O}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkIPAJM2TY_js.P}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkIPAJM2TY_js.J}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkIPAJM2TY_js.K}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkIPAJM2TY_js.H}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkIPAJM2TY_js.L}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ea}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Da}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkIPAJM2TY_js.g}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkIPAJM2TY_js.fa}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkIPAJM2TY_js.M}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkIPAJM2TY_js.wa}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkIPAJM2TY_js.j}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkIPAJM2TY_js.R}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ha}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ba}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ia}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ga}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ia}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ga}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ha}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkIPAJM2TY_js.h}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkIPAJM2TY_js.ea}});Object.defineProperty(exports,"signAndSubmit",{enumerable:true,get:function(){return chunkIPAJM2TY_js.Ca}});Object.defineProperty(exports,"transactions",{enumerable:true,get:function(){return chunkIPAJM2TY_js.za}});exports.AppealCaseTypeEnum=er;exports.AppealClaimStatusEnum=Xt;exports.AppealNodeStateEnum=tr;exports.AppealNodeVotedStateEnum=Zt;exports.AppealReconsiderationType=jt;exports.AppealStage=Qt;exports.AppealStatus=nr;exports.AppealType=zt;exports.Direction=Mn;exports.IsVoteNodeEnum=rr;exports.MyxClient=Re;exports.NodeTypeEnum=Jt;exports.OperationType=E;exports.OrderStatus=Dn;exports.OrderType=ie;exports.SDK_VERSION=bs;exports.TimeInForce=En;exports.TriggerType=xn;exports.VoteTypeEnum=Yt;exports.fromViemWalletClient=Ae;exports.normalizeSigner=ee;