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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {ja,Q as Q$1,i,h,ha,ia,S,U,ma,W,g,Z as Z$1,_,Ea,$ as $$1,ka,sa,e,ra,xa,o,aa,X as X$1,ba,T,n,k,j,la,l,d,Y as Y$1,ta,za,V,c,da,ca,m,Ca,b,f}from'./chunk-IP7EOW6I.mjs';export{qa as COMMON_LP_AMOUNT_DECIMALS,pa as COMMON_PRICE_DECIMALS,a as ChainId,E as CloseTypeEnum,B as DirectionEnum,p as ErrorCode,D as ExecTypeEnum,G as ForwarderGetStatus,s as HttpKlineIntervalEnum,ja as Logger,v as MarketCapType,q as MarketPoolState,t as MarketType,Q as MxSDK,y as OperationEnum,r as OracleType,C as OrderStatusEnum,x as OrderTypeEnum,w as SearchSecondTypeEnum,u as SearchTypeEnum,F as TradeFlowAccountTypeEnum,z as TradeFlowTypeEnum,A as TriggerTypeEnum,va as approve,Fa as base,ua as bigintAmountSlipperCalculator,sa as bigintTradingGasPriceWithRatio,ra as bigintTradingGasToRatioCalculator,xa as execution,Aa as formatUnits,ya as forwarder,oa as getAllowanceApproved,na as getBalanceOf,N as getBaseDetail,I as getBaseUrlByEnv,ta as getGasByRatio,O as getMarketDetail,P as getMarketList,J as getOraclePrice,K as getPoolDetail,H as getPoolList,L as getPoolOpenOrders,Ea as getPriceData,Da as getPricesData,g as getPublicClient,fa as getSdkLogSink,M as getTickerData,wa as getTokenInfo,j as getWalletClient,R as getWalletProvider,Ha as market,Ba as parseUnits,Ia as pool,Ga as quote,ia as sdkError,ga as sdkLog,ha as sdkWarn,h as setConfigManagerForViem,ea as setSdkLogSink,Ca as signAndSubmit,za as transactions}from'./chunk-IP7EOW6I.mjs';import kt from'mitt';import {MD5,Hex}from'crypto-es';import St from'reconnecting-websocket';import {maxUint256,zeroAddress,encodeFunctionData,isAddress,padHex,decodeEventLog,createWalletClient,custom,isHex,toHex,hexToBytes}from'viem';import Pe from'dayjs';import {merge}from'lodash-es';var Q=(c,e)=>MD5(c,{outputLength:32}).toString(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();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 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(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=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=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 createWalletClient({account:n,chain:r,transport: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 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&&(ha("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return ha("\u274C Received empty accessToken"),null}catch(t){return 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 $$1(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 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,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:maxUint256.toString(),spenderAddress:S(i).TRADING_ROUTER});if(xe.code!==0)throw new Error(xe.message)}let f=S(i).TRADING_ROUTER,{hexData:b,executionGasFee:A}=await xa.buildHexDataAndExecutionGasFee({abi:T,method:"adjustCollateral",args:[m,t,r],chainId:i}),{createAt:R,txId:x,signData:I,gasEscrow:B}=await xa.buildSignData({from:s,to:f,data:b,chainId:i}),D=await Y$1(i),ct=await D.estimateGas.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A}),{gasLimit:gt,gasPrice:lt}=await ta(i,ct),ve=await D.write.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A,gasLimit:gt,gasPrice:lt}),pt=await 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$1={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,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:maxUint256.toString(),spenderAddress:S(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await V(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...g$1,positionId:e.positionId});let b=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...l},g$1]);u=await d.write.placeOrderWithPosition([e.positionId.toString(),{...l},g$1],{gasLimit:b*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:g$1,depositData:l});let A=await d.estimateGas.placeOrderWithSalt(["1",{...l},g$1]);u=await d.write.placeOrderWithSalt(["1",{...l},g$1],{gasLimit:A*c[e.chainId]/100n});}let m=await 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 V(e),o=await s.estimateGas.placeOrdersWithPosition([r,n,i]),l=await s.write.placeOrdersWithPosition([r,n,i],{gasLimit:o*c[e]/100n}),g$1=await g(e).waitForTransactionReceipt({hash:l});return {code:0,message:"close all positions success",transactionHash:l,blockNumber:g$1?.blockNumber,gasUsed:g$1?.gasUsed?.toString(),status:g$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:g$1}}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$1=await V(e.chainId),a;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,l,{data:t}]);let m=await g$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),l,t]);a=await g$1.write.placeOrderWithPosition([e.positionId.toString(),l,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,l,{data:t}]);let f=await g$1.estimateGas.placeOrderWithSalt(["1",l,t]);a=await g$1.write.placeOrderWithSalt(["1",l,t],{gasLimit:f*c[e.chainId]/100n});}let d=await 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 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$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},a;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([g$1,[e.positionId.toString(),e.positionId.toString()],l]);a=await t.write.placeOrdersWithPosition([g$1,[e.positionId.toString(),e.positionId.toString()],l],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",l);let m=1,f=await t.estimateGas.placeOrdersWithSalt([g$1,[m.toString(),m.toString()],l]);a=await t.write.placeOrdersWithSalt([g$1,[m.toString(),m.toString()],l],{gasLimit:f*c[e.chainId]/100n});}let d=await 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*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*c[e.chainId]/100n});}let s=await 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 V(t)).write.cancelOrders([e]);return await 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 V(t)).write.cancelOrder([e]);return await 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 V(t)).write.cancelOrders([e]);return await 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$1={token:t,amount:o.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let a=await V(r);this.logger.info("updateOrderTpSl params",l);try{if(await this.utils.needsApproval(n,r,e.executionFeeToken,o.toString(),S(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:S(r).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let u=await a.estimateGas.updateOrder([g$1,l]),m=await a.write.updateOrder([g$1,l],{gasLimit:u*c[r]/100n}),f=await 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=>isHex(o)?padHex(o,{size:32}):padHex(toHex(o),{size:32}),i=await(await Y$1(e)).write?.cancel([r(t)]);return {code:0,data:await 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??S(t).Account,o=await 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 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 W(e,t),s=r??maxUint256,o=n??S(e).Account,l=await this.getGasPriceByRatio(),g$1=await i.write.approve([o,s],{gasPrice:l});return await g(e).waitForTransactionReceipt({hash:g$1}),{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=Z$1(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 _(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 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 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 _(t,0)).read.getForwardFeeByToken([r]),o=await 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 $$1(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(ka).find(i=>i.toLowerCase()===r);if(n)return ka[n]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await sa(e)).gasPrice}async getGasLimitByRatio(e$1){let t=this.configManager.getConfig().chainId,r=e[t];return ra(e$1,r?.gasLimitRatio??1.3)}async generateTxId(){return 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=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 aa(i)).write.updateAndWithdraw([e,t,r,n]);return {code:0,data:await 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=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:maxUint256.toString(),spenderAddress:i.Account});if(a.code!==0)throw new Error(a.message)}let l=await(await aa(r)).write.deposit([n,t,e]);return {code:0,data:await 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 $$1(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=Z$1(e,r.brokerAddress),s=await g(e).getBlock({blockTag:"latest"}),o=Number(s?.timestamp??BigInt(Pe().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().unix())throw new p("REQUEST_FAILED","Invalid deadline, please try again");try{let o=await X$1(t,s.brokerAddress),l={user:e,nonce:n.nonce,deadline:r,feeData:{tier:n.tier,referrer:n.referrer||zeroAddress,totalReferralRebatePct:n.totalReferralRebatePct,referrerRebatePct:n.referrerRebatePct,expiry:n.expiry},signature:i},g$1=await o.read.userNonces([e]);if(parseInt(g$1.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 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 o.get(this.buildRequestPath(e),t,merge(i,n))}async post(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return o.post(this.buildRequestPath(e),t,merge(i,n))}async put(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return o.put(this.buildRequestPath(e),t,merge(i,n))}async delete(e,{auth:t=false,...r}={}){let n=t?await this.buildAuthParams():{};return o.delete(this.buildRequestPath(e),merge(n,r))}};var le=class extends ge{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...r}){return o.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return o.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await o.get(`${this.getHost()}/v2/agent/forwarder/get${Te(e)}`)}async getPoolList(){return o.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async adjustCollateralForwarderTxApi(e,t){return o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return 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 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 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 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 o.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:n,interval:i})}async getKlineLatestBar(e){return o.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return o.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return o.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return 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 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 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return o.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return o.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return 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 o.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return o.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:n,nonce:i}){return 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 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 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=hexToBytes(c);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),r=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=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 ba(r)).read.isUserRelayerEnabled([e,t]),g=await(await _(r)).read.getForwardFeeByToken([n]),a=BigInt(g)*BigInt(ot);i=i??a.toString();let d=await this.utils.needsApproval(e,r,n,i,S(r).TRADING_ROUTER);return o&&!d}async getContractAbiAndAddressByFunctionName(e,t){let r=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],n$1=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return r.includes(e)?{abi:T,address:S(t).TRADING_ROUTER}:i.includes(e)?{abi:n,address:S(t).Account}:n$1.includes(e)?{abi:k,address:this.configManager.getConfig().brokerAddress}:{abi:T,address: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 j(t),i=S(t),[s]=await n.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let o=U(t,r);try{let l=await o.read.nonces([s]),g=await qt(n,t,r,s,i.TRADING_ROUTER,maxUint256,l,e);return [{token:r,owner:s,spender:i.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:g.v,r:g.r,s:g.s}]}catch(l){if(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 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 ba(e)).read.nonces([t]),a=Pe().add(60,"minute").unix(),d=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),f=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 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 W(e,t),i=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 _(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().add(60,"minute").unix(),o=[];if(e)try{n===Vt?(await this.approveBalance(r,n,maxUint256.toString()))?.hash&&(o=[]):o=await this.getUSDPermitParams(s,r,n);}catch(u){if(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$1=await ba(r,1),g=await(await ba(r)).read.nonces([i]),a=encodeFunctionData({abi:l,functionName:"permitAndApproveForwarder",args:[t,e,o]}),d;try{d=await this.forwarderTx({from:i,to:l$1.address,value:"0",gas:"800000",nonce:g.toString(),data:a,deadline:s,forwardFeeToken:n},r);}catch(u){if(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=S(e).TRADING_ROUTER,s=await 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 ba(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:r,functionName:n,data:i,seamlessAddress:s}){if(!e||!isAddress(e))throw new p("PARAM_ERROR","address (master) is missing or invalid");if(!s||!isAddress(s))throw new p("PARAM_ERROR","seamlessAddress is missing or invalid");if(!r||!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 ba(t),g,{abi:a,address:d}=await this.getContractAbiAndAddressByFunctionName(n,t);try{g=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().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=S(e).TRADING_ROUTER,{hexData:g,executionGasFee:a}=await xa.buildHexDataAndExecutionGasFee({abi:T,method:"adjustCollateral",args:[o,i,s],chainId:e}),{createAt:d$1,txId:u,signData:m}=await xa.buildSignData({from:t,to:l,data:g,chainId:e}),f=await this.api.adjustCollateralForwarderTxApi({from:t,to:l,value:a.toString(),gas:d.toString(),txId:u,createdAt:d$1.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||!b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return S(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return Z$1(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 da(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return 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=decodeEventLog({abi: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 Ca({chainId:this.config.chainId,account:n,abi: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 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$1=await l.estimateGas.vote([e,t,r?1:0,n,i,s,o]),a=await this.client.utils.getGasLimitByRatio(g$1),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 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 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$1=await i.write.claimReimbursement([e,t,r,n],{gasLimit:o,gasPrice:l});return g(this.config.chainId).waitForTransactionReceipt({hash:g$1})}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 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$1=await this.client.utils.getGasLimitByRatio(l),a=await this.client.utils.getGasPriceByRatio(),d=await n.write.appeal([e],{gasLimit:g$1,gasPrice:a}),u=await 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 X$1(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 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 ja({logLevel:e.logLevel});let t=Q$1.getInstance();i()?.hasSigner()||(t.setConfigManager(this.configManager),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),Q$1.getInstance().setConfigManager(this.configManager),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.20";
1
+ import {ja,Q as Q$1,i,h,ha,ia,S,U,ma,W,g,Z as Z$1,_,Ea,$ as $$1,ka,sa,e,ra,xa,o,aa,X as X$1,ba,T,n,k,j,la,l,d,Y as Y$1,ta,za,V,c,da,ca,m,Ca,b,f}from'./chunk-3AYVAJKM.mjs';export{qa as COMMON_LP_AMOUNT_DECIMALS,pa as COMMON_PRICE_DECIMALS,a as ChainId,E as CloseTypeEnum,B as DirectionEnum,p as ErrorCode,D as ExecTypeEnum,G as ForwarderGetStatus,s as HttpKlineIntervalEnum,ja as Logger,v as MarketCapType,q as MarketPoolState,t as MarketType,Q as MxSDK,y as OperationEnum,r as OracleType,C as OrderStatusEnum,x as OrderTypeEnum,w as SearchSecondTypeEnum,u as SearchTypeEnum,F as TradeFlowAccountTypeEnum,z as TradeFlowTypeEnum,A as TriggerTypeEnum,va as approve,Fa as base,ua as bigintAmountSlipperCalculator,sa as bigintTradingGasPriceWithRatio,ra as bigintTradingGasToRatioCalculator,xa as execution,Aa as formatUnits,ya as forwarder,oa as getAllowanceApproved,na as getBalanceOf,N as getBaseDetail,I as getBaseUrlByEnv,ta as getGasByRatio,O as getMarketDetail,P as getMarketList,J as getOraclePrice,K as getPoolDetail,H as getPoolList,L as getPoolOpenOrders,Ea as getPriceData,Da as getPricesData,g as getPublicClient,fa as getSdkLogSink,M as getTickerData,wa as getTokenInfo,j as getWalletClient,R as getWalletProvider,Ha as market,Ba as parseUnits,Ia as pool,Ga as quote,ia as sdkError,ga as sdkLog,ha as sdkWarn,h as setConfigManagerForViem,ea as setSdkLogSink,Ca as signAndSubmit,za as transactions}from'./chunk-3AYVAJKM.mjs';import kt from'mitt';import {MD5,Hex}from'crypto-es';import St from'reconnecting-websocket';import {maxUint256,zeroAddress,encodeFunctionData,isAddress,padHex,decodeEventLog,createWalletClient,custom,isHex,toHex,hexToBytes}from'viem';import Pe from'dayjs';import {merge}from'lodash-es';var Q=(c,e)=>MD5(c,{outputLength:32}).toString(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();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 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(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=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=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 createWalletClient({account:n,chain:r,transport: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 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&&(ha("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return ha("\u274C Received empty accessToken"),null}catch(t){return 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 $$1(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 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,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:maxUint256.toString(),spenderAddress:S(i).TRADING_ROUTER});if(xe.code!==0)throw new Error(xe.message)}let f=S(i).TRADING_ROUTER,{hexData:b,executionGasFee:A}=await xa.buildHexDataAndExecutionGasFee({abi:T,method:"adjustCollateral",args:[m,t,r],chainId:i}),{createAt:R,txId:x,signData:I,gasEscrow:B}=await xa.buildSignData({from:s,to:f,data:b,chainId:i}),D=await Y$1(i),ct=await D.estimateGas.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A}),{gasLimit:gt,gasPrice:lt}=await ta(i,ct),ve=await D.write.submit([x,{...I,createdAt:BigInt(R),gasEscrow:B},[e]],{value:A,gasLimit:gt,gasPrice:lt}),pt=await 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$1={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,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:maxUint256.toString(),spenderAddress:S(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await V(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...g$1,positionId:e.positionId});let b=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...l},g$1]);u=await d.write.placeOrderWithPosition([e.positionId.toString(),{...l},g$1],{gasLimit:b*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:g$1,depositData:l});let A=await d.estimateGas.placeOrderWithSalt(["1",{...l},g$1]);u=await d.write.placeOrderWithSalt(["1",{...l},g$1],{gasLimit:A*c[e.chainId]/100n});}let m=await 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 V(e),o=await s.estimateGas.placeOrdersWithPosition([r,n,i]),l=await s.write.placeOrdersWithPosition([r,n,i],{gasLimit:o*c[e]/100n}),g$1=await g(e).waitForTransactionReceipt({hash:l});return {code:0,message:"close all positions success",transactionHash:l,blockNumber:g$1?.blockNumber,gasUsed:g$1?.gasUsed?.toString(),status:g$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:g$1}}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$1=await V(e.chainId),a;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,l,{data:t}]);let m=await g$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),l,t]);a=await g$1.write.placeOrderWithPosition([e.positionId.toString(),l,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,l,{data:t}]);let f=await g$1.estimateGas.placeOrderWithSalt(["1",l,t]);a=await g$1.write.placeOrderWithSalt(["1",l,t],{gasLimit:f*c[e.chainId]/100n});}let d=await 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 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$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},a;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([g$1,[e.positionId.toString(),e.positionId.toString()],l]);a=await t.write.placeOrdersWithPosition([g$1,[e.positionId.toString(),e.positionId.toString()],l],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",l);let m=1,f=await t.estimateGas.placeOrdersWithSalt([g$1,[m.toString(),m.toString()],l]);a=await t.write.placeOrdersWithSalt([g$1,[m.toString(),m.toString()],l],{gasLimit:f*c[e.chainId]/100n});}let d=await 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*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*c[e.chainId]/100n});}let s=await 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 V(t)).write.cancelOrders([e]);return await 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 V(t)).write.cancelOrder([e]);return await 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 V(t)).write.cancelOrders([e]);return await 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$1={token:t,amount:o.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let a=await V(r);this.logger.info("updateOrderTpSl params",l);try{if(await this.utils.needsApproval(n,r,e.executionFeeToken,o.toString(),S(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:S(r).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let u=await a.estimateGas.updateOrder([g$1,l]),m=await a.write.updateOrder([g$1,l],{gasLimit:u*c[r]/100n}),f=await 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=>isHex(o)?padHex(o,{size:32}):padHex(toHex(o),{size:32}),i=await(await Y$1(e)).write?.cancel([r(t)]);return {code:0,data:await 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??S(t).Account,o=await 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 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 W(e,t),s=r??maxUint256,o=n??S(e).Account,l=await this.getGasPriceByRatio(),g$1=await i.write.approve([o,s],{gasPrice:l});return await g(e).waitForTransactionReceipt({hash:g$1}),{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=Z$1(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 _(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 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 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 _(t,0)).read.getForwardFeeByToken([r]),o=await 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 $$1(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(ka).find(i=>i.toLowerCase()===r);if(n)return ka[n]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await sa(e)).gasPrice}async getGasLimitByRatio(e$1){let t=this.configManager.getConfig().chainId,r=e[t];return ra(e$1,r?.gasLimitRatio??1.3)}async generateTxId(){return 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=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 aa(i)).write.updateAndWithdraw([e,t,r,n]);return {code:0,data:await 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=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:maxUint256.toString(),spenderAddress:i.Account});if(a.code!==0)throw new Error(a.message)}let l=await(await aa(r)).write.deposit([n,t,e]);return {code:0,data:await 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 $$1(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=Z$1(e,r.brokerAddress),s=await g(e).getBlock({blockTag:"latest"}),o=Number(s?.timestamp??BigInt(Pe().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().unix())throw new p("REQUEST_FAILED","Invalid deadline, please try again");try{let o=await X$1(t,s.brokerAddress),l={user:e,nonce:n.nonce,deadline:r,feeData:{tier:n.tier,referrer:n.referrer||zeroAddress,totalReferralRebatePct:n.totalReferralRebatePct,referrerRebatePct:n.referrerRebatePct,expiry:n.expiry},signature:i},g$1=await o.read.userNonces([e]);if(parseInt(g$1.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 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 o.get(this.buildRequestPath(e),t,merge(i,n))}async post(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return o.post(this.buildRequestPath(e),t,merge(i,n))}async put(e,t,{auth:r=false,...n}={}){let i=r?await this.buildAuthParams():{};return o.put(this.buildRequestPath(e),t,merge(i,n))}async delete(e,{auth:t=false,...r}={}){let n=t?await this.buildAuthParams():{};return o.delete(this.buildRequestPath(e),merge(n,r))}};var le=class extends ge{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...r}){return o.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return o.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await o.get(`${this.getHost()}/v2/agent/forwarder/get${Te(e)}`)}async getPoolList(){return o.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async adjustCollateralForwarderTxApi(e,t){return o.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return 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 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 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 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 o.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:n,interval:i})}async getKlineLatestBar(e){return o.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return o.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return o.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return 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 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 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 o.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return o.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return o.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return 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 o.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return o.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:n,nonce:i}){return 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 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 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=hexToBytes(c);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),r=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=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 ba(r)).read.isUserRelayerEnabled([e,t]),g=await(await _(r)).read.getForwardFeeByToken([n]),a=BigInt(g)*BigInt(ot);i=i??a.toString();let d=await this.utils.needsApproval(e,r,n,i,S(r).TRADING_ROUTER);return o&&!d}async getContractAbiAndAddressByFunctionName(e,t){let r=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],n$1=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return r.includes(e)?{abi:T,address:S(t).TRADING_ROUTER}:i.includes(e)?{abi:n,address:S(t).Account}:n$1.includes(e)?{abi:k,address:this.configManager.getConfig().brokerAddress}:{abi:T,address: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 j(t),i=S(t),[s]=await n.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let o=U(t,r);try{let l=await o.read.nonces([s]),g=await qt(n,t,r,s,i.TRADING_ROUTER,maxUint256,l,e);return [{token:r,owner:s,spender:i.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:g.v,r:g.r,s:g.s}]}catch(l){if(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 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 ba(e)).read.nonces([t]),a=Pe().add(60,"minute").unix(),d=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),f=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 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 W(e,t),i=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 _(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().add(60,"minute").unix(),o=[];if(e)try{n===Vt?(await this.approveBalance(r,n,maxUint256.toString()))?.hash&&(o=[]):o=await this.getUSDPermitParams(s,r,n);}catch(u){if(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$1=await ba(r,1),g=await(await ba(r)).read.nonces([i]),a=encodeFunctionData({abi:l,functionName:"permitAndApproveForwarder",args:[t,e,o]}),d;try{d=await this.forwarderTx({from:i,to:l$1.address,value:"0",gas:"800000",nonce:g.toString(),data:a,deadline:s,forwardFeeToken:n},r);}catch(u){if(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=S(e).TRADING_ROUTER,s=await 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 ba(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:r,functionName:n,data:i,seamlessAddress:s}){if(!e||!isAddress(e))throw new p("PARAM_ERROR","address (master) is missing or invalid");if(!s||!isAddress(s))throw new p("PARAM_ERROR","seamlessAddress is missing or invalid");if(!r||!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 ba(t),g,{abi:a,address:d}=await this.getContractAbiAndAddressByFunctionName(n,t);try{g=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().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=S(e).TRADING_ROUTER,{hexData:g,executionGasFee:a}=await xa.buildHexDataAndExecutionGasFee({abi:T,method:"adjustCollateral",args:[o,i,s],chainId:e}),{createAt:d$1,txId:u,signData:m}=await xa.buildSignData({from:t,to:l,data:g,chainId:e}),f=await this.api.adjustCollateralForwarderTxApi({from:t,to:l,value:a.toString(),gas:d.toString(),txId:u,createdAt:d$1.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||!b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return S(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return Z$1(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 da(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return 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=decodeEventLog({abi: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 Ca({chainId:this.config.chainId,account:n,abi: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 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$1=await l.estimateGas.vote([e,t,r?1:0,n,i,s,o]),a=await this.client.utils.getGasLimitByRatio(g$1),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 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 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$1=await i.write.claimReimbursement([e,t,r,n],{gasLimit:o,gasPrice:l});return g(this.config.chainId).waitForTransactionReceipt({hash:g$1})}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 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$1=await this.client.utils.getGasLimitByRatio(l),a=await this.client.utils.getGasPriceByRatio(),d=await n.write.appeal([e],{gasLimit:g$1,gasPrice:a}),u=await 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 X$1(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 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 ja({logLevel:e.logLevel});let t=Q$1.getInstance();i()?.hasSigner()||(t.setConfigManager(this.configManager),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),Q$1.getInstance().setConfigManager(this.configManager),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
2
  export{er as AppealCaseTypeEnum,Xt as AppealClaimStatusEnum,tr as AppealNodeStateEnum,Zt as AppealNodeVotedStateEnum,jt as AppealReconsiderationType,Qt as AppealStage,nr as AppealStatus,zt as AppealType,Mn as Direction,rr as IsVoteNodeEnum,Re as MyxClient,Jt as NodeTypeEnum,E as OperationType,Dn as OrderStatus,ie as OrderType,bs as SDK_VERSION,En as TimeInForce,xn as TriggerType,Yt as VoteTypeEnum,Ae as fromViemWalletClient,ee as normalizeSigner};
package/dist/lp.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkVEIU6D43_js=require('./chunk-VEIU6D43.js');Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkVEIU6D43_js.qa}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkVEIU6D43_js.pa}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkVEIU6D43_js.Fa}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkVEIU6D43_js.Ea}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkVEIU6D43_js.Da}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkVEIU6D43_js.Ha}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkVEIU6D43_js.Ia}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkVEIU6D43_js.Ga}});
1
+ 'use strict';var chunkDK433OVO_js=require('./chunk-DK433OVO.js');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,"base",{enumerable:true,get:function(){return chunkDK433OVO_js.Fa}});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,"market",{enumerable:true,get:function(){return chunkDK433OVO_js.Ha}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkDK433OVO_js.Ia}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkDK433OVO_js.Ga}});
package/dist/lp.mjs CHANGED
@@ -1 +1 @@
1
- export{qa as COMMON_LP_AMOUNT_DECIMALS,pa as COMMON_PRICE_DECIMALS,Fa as base,Ea as getPriceData,Da as getPricesData,Ha as market,Ia as pool,Ga as quote}from'./chunk-IP7EOW6I.mjs';
1
+ export{qa as COMMON_LP_AMOUNT_DECIMALS,pa as COMMON_PRICE_DECIMALS,Fa as base,Ea as getPriceData,Da as getPricesData,Ha as market,Ia as pool,Ga as quote}from'./chunk-3AYVAJKM.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myx-trade/sdk",
3
- "version": "1.0.24-beta.20",
3
+ "version": "1.0.24-beta.21",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"