@myx-trade/sdk 1.0.17 → 1.0.18
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/chunk-SH7ETUSA.js +2 -0
- package/dist/chunk-UKJZVOPA.mjs +2 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/lp.js +1 -1
- package/dist/lp.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-CAB3LYKU.mjs +0 -2
- package/dist/chunk-YDBHYUPH.js +0 -2
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {ga as ga$1,O,g,ea,fa,Q as Q$1,S as S$1,ha,U as U$1,f,W as W$1,X as X$1,ra,Y,na,d,ma as ma$1,m,Z as Z$1,V as V$1,_ as _$1,R as R$1,l as l$1,i,h,j as j$1,T,c,aa,$ as $$1,k,b,e}from'./chunk-CAB3LYKU.mjs';export{la as COMMON_LP_AMOUNT_DECIMALS,ka as COMMON_PRICE_DECIMALS,a as ChainId,C as CloseTypeEnum,z as DirectionEnum,n as ErrorCode,B as ExecTypeEnum,E as ForwarderGetStatus,q as HttpKlineIntervalEnum,ga as Logger,t as MarketCapType,o as MarketPoolState,r as MarketType,O as MxSDK,w as OperationEnum,p as OracleType,A as OrderStatusEnum,v as OrderTypeEnum,u as SearchSecondTypeEnum,s as SearchTypeEnum,D as TradeFlowAccountTypeEnum,x as TradeFlowTypeEnum,y as TriggerTypeEnum,pa as approve,va as base,oa as bigintAmountSlipperCalculator,na as bigintTradingGasPriceWithRatio,ma as bigintTradingGasToRatioCalculator,ta as formatUnits,ja as getAllowanceApproved,ia as getBalanceOf,L as getBaseDetail,G as getBaseUrlByEnv,M as getMarketDetail,N as getMarketList,H as getOraclePrice,I as getPoolDetail,F as getPoolList,J as getPoolOpenOrders,ra as getPriceData,qa as getPricesData,f as getPublicClient,ca as getSdkLogSink,K as getTickerData,sa as getTokenInfo,h as getWalletClient,P as getWalletProvider,xa as market,ua as parseUnits,ya as pool,wa as quote,fa as sdkError,da as sdkLog,ea as sdkWarn,g as setConfigManagerForViem,ba as setSdkLogSink}from'./chunk-CAB3LYKU.mjs';import ct from'mitt';import {MD5,Hex}from'crypto-es';import pt from'reconnecting-websocket';import {decodeEventLog,maxUint256,zeroAddress,encodeFunctionData,isAddress,createWalletClient,custom,hexToBytes,toHex}from'viem';import xe from'dayjs';import {merge}from'lodash-es';var _=(o,e)=>MD5(o,{outputLength:32}).toString(Hex);var G=o=>{switch(o.request){case "signin":return _(o.request)}return _(JSON.stringify(o))},L=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return _(JSON.stringify({topic:e,params:t}))}},Le=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",dt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Ne=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:L({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[n,a]=t.split("_");return {...o,type:L({topic:"candle",params:{globalId:parseInt(n),resolution:a}}),globalId:parseInt(n),resolution:a}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Be={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},U=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=ct();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:n,...a}=t;this.config={...Be,...a},this.logger=new ga$1({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 n={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new pt(this.config.url,this.config.protocols,n),this.setupEventListeners(e,t);}catch(n){t(n);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async n=>{this.eventBus.emit("open",n),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=n=>{this.handleMessage(n);},this.ws.onclose=n=>{this.eventBus.emit("close",n),this.stopHeartbeatTimer();},this.ws.onerror=n=>{this.eventBus.emit("error",n),t(n);},this.ws.addEventListener("reconnecting",n=>{this.eventBus.emit("reconnecting",{detail:n.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,n)=>{let a=G(e);this.waitingRequests.has(a)?(this.waitingRequests.get(a)?.onSuccess.add(t),this.waitingRequests.get(a)?.onError.add(n)):this.waitingRequests.set(a,{onSuccess:new Set([t]),onError:new Set([n])}),this.send(e);})}subscribe(e,t){let n=Array.isArray(e)?e:[e],a=[],i=new Set;n.forEach(s=>{let d=L(s);if(!i.has(d))if(i.add(d),this.subscriptions.has(d))this.subscriptions.get(d).callbacks.add(t);else {let r={id:d,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(d,r),a.push(d),this.logger.debug(`create new subscription: ${d}`);}}),a.length>0&&this.send({request:"subv2",args:a});}unsubscribe(e,t){if(!e)return;let n=Array.isArray(e)?e:[e],a=[],i=new Set;n.forEach(s=>{let d=L(s);if(i.has(d))return;i.add(d);let r=this.subscriptions.get(d);r&&(r.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${d}`),r.callbacks.size===0&&(this.subscriptions.delete(d),a.push(d),this.logger.debug(`subscription ${d} has no callbacks, will unsubscribe`)));}),a.length>0&&this.send({request:"unsubv2",args:a});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(Le(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=G({request:e.type,args:""});break;default:t=G({request:e.type,args:e.data.data});break}let n=this.waitingRequests.get(t),a=e.data.code===9200;a?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),n?.onError.size&&!a&&n.onError.forEach(i=>{i(new l("REQUEST_FAILED","Request failed"));}),n?.onSuccess.size&&a&&n.onSuccess.forEach(i=>{i(e.data);});}handleSubscriptionMessage(e){let t=Ne(e),n=t.type,a=this.subscriptions.get(n);a&&a.callbacks.forEach(i=>{try{i(t);}catch(s){this.logger.error(`Callback Error (${n}): ${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||Be.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 _e=[56,59144,42161],Ge=[59141,421614,97],Ue=[97,421614];var W={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var q=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let n=W.MainNet;e.getConfig().isBetaMode?n=W.BetaNet:e.getConfig().isTestnet&&(n=W.TestNet),this.wsClient=new U({logLevel:this.configManager.getConfig()?.logLevel,url:n,...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 n=Array.isArray(e)?e:[e];this.wsClient.subscribe(n.map(a=>({topic:"ticker",params:{globalId:a}})),t);}unsubscribeTickers(e,t){let n=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(n.map(a=>({topic:"ticker",params:{globalId:a}})),t);}subscribeKline(e,t,n){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},n);}unsubscribeKline(e,t,n){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},n);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function lt(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function ut(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function ue(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let n=typeof t=="string"?t:{raw:t};return await o.signMessage({message:n})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let n=t.to;if(!n)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:n,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 We(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:n=>o.signMessage(n),async sendTransaction(n){let a={...n};n.value!=null&&(a.value=BigInt(n.value)),n.gasLimit!=null&&(a.gasLimit=BigInt(n.gasLimit)),n.gasPrice!=null&&(a.gasPrice=BigInt(n.gasPrice)),n.maxFeePerGas!=null&&(a.maxFeePerGas=BigInt(n.maxFeePerGas)),n.maxPriorityFeePerGas!=null&&(a.maxPriorityFeePerGas=BigInt(n.maxPriorityFeePerGas));try{let s=(await o.sendTransaction(a)).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 d={...n};n.value!=null&&(d.value=`0x${BigInt(n.value).toString(16)}`),n.gasLimit!=null&&(d.gasLimit=`0x${BigInt(n.gasLimit).toString(16)}`),n.gasPrice!=null&&(d.gasPrice=`0x${BigInt(n.gasPrice).toString(16)}`),n.maxFeePerGas!=null&&(d.maxFeePerGas=`0x${BigInt(n.maxFeePerGas).toString(16)}`),n.maxPriorityFeePerGas!=null&&(d.maxPriorityFeePerGas=`0x${BigInt(n.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(d)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw i}},signTransaction:typeof e.signTransaction=="function"?n=>t.signTransaction(n):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(n){return t.signTypedData(n.domain,n.types,n.message)}}:typeof t._signTypedData=="function"?{async signTypedData(n){return t._signTypedData(n.domain,n.types,n.message)}}:{}}}function $(o){return lt(o)?ue(o):ut(o)?We(o):o}function qe(o){let e$1=e(o),t=[...e$1.privateJsonRPCUrl?[e$1.privateJsonRPCUrl]:[],...Array.isArray(e$1.publicJsonRPCUrl)?[...e$1.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var me={};function yt(o){if(!me[o]){let e$1=e(o);me[o]={id:o,name:e$1.label||`Chain ${o}`,nativeCurrency:e$1.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return me[o]}async function $e(o,e){let t=qe(e),n=yt(e),a=await o.getAddress();return createWalletClient({account:a,chain:n,transport:custom({request:async s=>{if(s.method==="eth_accounts")return [a];if(s.method==="eth_sendTransaction"){let c=s.params?.[0]??{},{hash:p}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return p}if(s.method==="eth_signTypedData_v4"||s.method==="eth_signTypedData"){if(!o.signTypedData){let g=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(g.error)throw new Error(g.error.message);return g.result}let c=s.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let p=JSON.parse(c);return await o.signTypedData({domain:p.domain,types:p.types,primaryType:p.primaryType,message:p.message})}let r=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(r.error)throw new Error(r.error.message);return r.result}})})}var z=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let n=(await this.config.walletClient.getAddresses())[0];if(n)return n}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await $e(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?$(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:n,chainId:a}=e;if(t){if(!Ge.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of TESTNET_CHAIN_IDS`)}else if(n){if(!Ue.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!_e.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,n)=>{this._getAccessTokenQueue.push({resolve:t,reject:n,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 ea("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let n=3600;if(t.expireAt){let a=Math.floor(Date.now()/1e3);n=t.expireAt-a,n<=0&&(ea("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return ea("\u274C Received empty accessToken"),null}catch(t){return fa("\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 V=class{constructor(e,t,n){this.configManager=e,this.utils=t,this.api=n;}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 n=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:n})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:n})).data}async addFavorite(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:n})).data}async removeFavorite(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:n})).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:n}){let a=await Y(t);try{return {code:0,data:await a.read.getPoolInfo([e,n])}}catch(i){return {code:-1,message:i.message}}}};var H=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async listPositions(e,t){let n=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:n??"",address:e,positionId:t})).data}}catch(a){return this.logger.error("Error fetching positions:",a),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:n,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:n,quoteToken:a,chainId:i,address:s}){this.configManager.getConfig();try{let r=await this.utils.getOraclePrice(e,i);if(!r)throw new Error("Failed to get price data");let c$1={poolId:e,oracleType:r.oracleType,publishTime:r.publishTime,oracleUpdateData:r?.vaa??"0"},p=!1;Number(n)>0&&(p=await this.utils.needsApproval(s,i,a,n,Q$1(i).TRADING_ROUTER));let u=BigInt(0),g=BigInt(n)>0?BigInt(n):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:s}),h=m.code===0?m.data??0n:0n,x=BigInt(0);h<g&&(x=g-h,u=x);let I={token:a,amount:u.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let we=await T(i);if(p){let C=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:maxUint256.toString(),spenderAddress:Q$1(i).TRADING_ROUTER});if(C.code!==0)throw new Error(C.message)}let ae=await we.write.updatePriceAndAdjustCollateral([[c$1],I,t,n],{value:BigInt(r?.value??"1"),gas:BigInt(1e7)*c[i]/100n});return await f(i).waitForTransactionReceipt({hash:ae}),{code:0,data:{hash:ae},message:"Adjust collateral transaction submitted"}}catch(r){return {code:-1,message:r.message}}}};var ht={IOC:0},R=ht.IOC;var K={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},ua={NONE:0,GTE:1,LTE:2},S={INCREASE:0,DECREASE:1},ma={LONG:0,SHORT:1},ga={IOC:0},ya={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var Q=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async createIncreaseOrder(e,t){try{let n=BigInt(e.collateralAmount)+BigInt(t),a=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=a.code===0?a.data??0n:0n,s=BigInt(0),d=n-i;d>BigInt(0)&&(s=d);let r={token:e.executionFeeToken,amount:s.toString()},c$1={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:S.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},p=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,Q$1(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(p){let x=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:Q$1(e.chainId).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let u=await T(e.chainId),g;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c$1,positionId:e.positionId});let x=await u.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...r},c$1]);g=await u.write.placeOrderWithPosition([e.positionId.toString(),{...r},c$1],{gasLimit:x*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c$1,depositData:r});let I=await u.estimateGas.placeOrderWithSalt(["1",{...r},c$1]);g=await u.write.placeOrderWithSalt(["1",{...r},c$1],{gasLimit:I*c[e.chainId]/100n});}let m=await f(e.chainId).waitForTransactionReceipt({hash:g});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:g,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(n){return this.logger.error("Error placing order:",n),{code:-1,message:n?.message}}}async closeAllPositions(e,t){try{let n={token:"0x0000000000000000000000000000000000000000",amount:"0"},a=t.map(p=>p.positionId.toString()),i=t.map(p=>({user:p.address,poolId:p.poolId,orderType:p.orderType,triggerType:p.triggerType,operation:S.DECREASE,direction:p.direction,collateralAmount:p.collateralAmount,size:p.size,price:p.price,timeInForce:R,postOnly:p.postOnly,slippagePct:p.slippagePct,leverage:p.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",n,a,i),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let s=await T(e),d=await s.estimateGas.placeOrdersWithPosition([n,a,i]),r=await s.write.placeOrdersWithPosition([n,a,i],{gasLimit:d*c[e]/100n}),c$1=await f(e).waitForTransactionReceipt({hash:r});return {code:0,message:"close all positions success",transactionHash:r,blockNumber:c$1?.blockNumber,gasUsed:c$1?.gasUsed?.toString(),status:c$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c$1}}catch(n){return {code:-1,message:n?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},n=BigInt(e.collateralAmount),a=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=a.code===0?a.data??0n:0n,s=BigInt(0),d=n-i;d>BigInt(0)&&(s=d);let r={token:e.executionFeeToken,amount:s.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c$1=await T(e.chainId),p;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,r,{data:t}]);let m=await c$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,t]);p=await c$1.write.placeOrderWithPosition([e.positionId.toString(),r,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,r,{data:t}]);let h=await c$1.estimateGas.placeOrderWithSalt(["1",r,t]);p=await c$1.write.placeOrderWithSalt(["1",r,t],{gasLimit:h*c[e.chainId]/100n});}let u=await f(e.chainId).waitForTransactionReceipt({hash:p});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:p,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await T(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let r=[{user:e.address,poolId:e.poolId,orderType:K.STOP,triggerType:e.tpTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},{user:e.address,poolId:e.poolId,orderType:K.STOP,triggerType:e.slTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},p;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],r]);p=await t.write.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],r],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",r);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],r]);p=await t.write.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],r],{gasLimit:h*c[e.chainId]/100n});}let u=await f(e.chainId).waitForTransactionReceipt({hash:p});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:p,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}let n={user:e.address,poolId:e.poolId,orderType:K.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},a={token:"0x0000000000000000000000000000000000000000",amount:"0"},i;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",n);let r=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),a,n]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),a,n],{gasLimit:r*c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",n);let r=1,c$1=await t.estimateGas.placeOrderWithSalt([r.toString(),a,n]);i=await t.write.placeOrderWithSalt([r.toString(),a,n],{gasLimit:c$1*c[e.chainId]/100n});}let s=await f(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(n){return {code:-1,message:n?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await T(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"cancel all orders success"}}catch(n){return {code:-1,message:n?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await T(t)).write.cancelOrder([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"cancel order success"}}catch(n){return {code:-1,message:n?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await T(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"Orders canceled success"}}catch(n){return this.logger.error("Error canceling orders:",n),{code:-1,message:n?.message}}}async updateOrderTpSl(e,t,n,a,i,s){let d=await this.utils.getNetworkFee(i,n),r={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"}},c$1={token:t,amount:d.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let p=await T(n);this.logger.info("updateOrderTpSl params",r);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,d.toString(),Q$1(n).TRADING_ROUTER)){let x=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:Q$1(n).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let g=await p.estimateGas.updateOrder([c$1,r]),m=await p.write.updateOrder([c$1,r],{gasLimit:g*c[n]/100n}),h=await f(n).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(u){return this.logger.error("Error updating order:",u),{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(n){return this.logger.error("Error fetching orders:",n),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:n,...e,address:t})).data}}};var Ve=[{type:"error",name:"AddressEmptyCode",inputs:[{type:"address",name:"target"}]},{type:"error",name:"ERC1967InvalidImplementation",inputs:[{type:"address",name:"implementation"}]},{type:"error",name:"ERC1967NonPayable",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InvalidInitialization",inputs:[]},{type:"error",name:"NotAddressManager",inputs:[]},{type:"error",name:"NotAllowedIdentifier",inputs:[]},{type:"error",name:"NotDependencyManager",inputs:[]},{type:"error",name:"NotInitializing",inputs:[]},{type:"error",name:"NotProxyAdmin",inputs:[]},{type:"error",name:"UUPSUnauthorizedCallContext",inputs:[]},{type:"error",name:"UUPSUnsupportedProxiableUUID",inputs:[{type:"bytes32",name:"slot"}]},{type:"event",anonymous:false,name:"BlockHeader",inputs:[{type:"uint256",name:"blockNumber",indexed:false},{type:"uint256",name:"blockTimestamp",indexed:false},{type:"uint256",name:"sequence",indexed:false}]},{type:"event",anonymous:false,name:"CollateralAccepted",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"quoteDebt",indexed:false},{type:"uint256",name:"baseCollateral",indexed:false},{type:"uint256",name:"quoteCollateral",indexed:false},{type:"uint256",name:"totalQuoteDebt",indexed:false},{type:"uint256",name:"totalBaseCollateral",indexed:false}]},{type:"event",anonymous:false,name:"CollateralAdjusted",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"beforeCollateralAmount",indexed:false},{type:"uint256",name:"afterCollateralAmount",indexed:false}]},{type:"event",anonymous:false,name:"EnterDispute",inputs:[{type:"bytes32",name:"poolId",indexed:false}]},{type:"event",anonymous:false,name:"Exchanged",inputs:[{type:"address",name:"user",indexed:false},{type:"address",name:"source",indexed:false},{type:"address",name:"target",indexed:false},{type:"uint256",name:"sourceAmount",indexed:false},{type:"uint256",name:"targetAmount",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"ExecutionMatched",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256[]",name:"triggerOrderIds",indexed:false},{type:"uint256[]",name:"matchedOrderIds",indexed:false},{type:"uint8",name:"matchType",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"ExitDispute",inputs:[{type:"bytes32",name:"poolId",indexed:false}]},{type:"event",anonymous:false,name:"FeeDistributed",inputs:[{type:"address",name:"user",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"int32",name:"tradingFeeRate",indexed:false},{type:"bool",name:"isMaker",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"uint256",name:"baseTradingFee",indexed:false},{type:"uint256",name:"brokerTradingFee",indexed:false},{type:"address",name:"broker",indexed:false},{type:"uint256",name:"referralRebate",indexed:false},{type:"uint256",name:"referrerRebate",indexed:false},{type:"address",name:"referrer",indexed:false},{type:"int256",name:"reserveFee",indexed:false}]},{type:"event",anonymous:false,name:"FundingRateUpdated",inputs:[{type:"uint64",name:"epochs",indexed:false},{type:"uint64",name:"duration",indexed:false},{type:"uint64",name:"previousEpochTime",indexed:false},{type:"uint64",name:"lastEpochTime",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"int256",name:"fundingRate",indexed:false},{type:"int256",name:"fundingRateTracker",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"Initialized",inputs:[{type:"uint64",name:"version",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityLockUpdated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint64",name:"windowAnchor",indexed:false},{type:"uint256",name:"priceFloor",indexed:false},{type:"uint256",name:"priceCeiling",indexed:false},{type:"int256",name:"openInterest",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityMigrated",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"fromPoolId",indexed:false},{type:"bytes32",name:"toPoolId",indexed:false},{type:"uint256",name:"lpAmountIn",indexed:false},{type:"uint256",name:"lpAmountOut",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderCancelled",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"string",name:"reason",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderCreated",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint8",name:"poolType",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"uint256",name:"triggerPrice",indexed:false},{type:"uint8",name:"triggerType",indexed:false},{type:"uint256",name:"minQuoteOut",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderExecuted",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"executor",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"MarketCreated",inputs:[{type:"bytes32",name:"marketId",indexed:false},{type:"address",name:"deployer",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint32",name:"baseReserveRatio",indexed:false},{type:"uint32",name:"quoteReserveRatio",indexed:false},{type:"uint64",name:"oracleFeeUsd",indexed:false},{type:"uint64",name:"oracleRefundFeeUsd",indexed:false},{type:"uint128",name:"poolPrimeThreshold",indexed:false}]},{type:"event",anonymous:false,name:"OrderCancelled",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"OrderFilled",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint8",name:"orderType",indexed:false},{type:"uint256",name:"orderSize",indexed:false},{type:"uint256",name:"fillSize",indexed:false},{type:"uint256",name:"filledSize",indexed:false},{type:"uint256",name:"orderPrice",indexed:false},{type:"uint256",name:"fillPrice",indexed:false},{type:"int256",name:"realizedPnl",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"int256",name:"fundingFee",indexed:false},{type:"uint256",name:"executionFeeAmount",indexed:false},{type:"address",name:"keeper",indexed:false}]},{type:"event",anonymous:false,name:"OrderMarkedADL",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"available",indexed:false},{type:"uint256",name:"requested",indexed:false}]},{type:"event",anonymous:false,name:"OrderPlaced",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint8",name:"orderType",indexed:false},{type:"uint8",name:"operation",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint8",name:"triggerType",indexed:false},{type:"uint256",name:"collateralAmount",indexed:false},{type:"uint256",name:"size",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint8",name:"tif",indexed:false},{type:"bool",name:"postOnly",indexed:false},{type:"uint16",name:"slippagePct",indexed:false},{type:"uint256",name:"executionFeeAmount",indexed:false},{type:"uint16",name:"userLeverage",indexed:false}]},{type:"event",anonymous:false,name:"OrderUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"size",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint256",name:"tpSize",indexed:false},{type:"uint256",name:"tpPrice",indexed:false},{type:"uint256",name:"slSize",indexed:false},{type:"uint256",name:"slPrice",indexed:false}]},{type:"event",anonymous:false,name:"PoolActivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint8",name:"oracleType",indexed:false},{type:"bytes32",name:"oracleFeedId",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeactivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeployed",inputs:[{type:"bytes32",name:"marketId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"deployer",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"address",name:"basePoolToken",indexed:false},{type:"address",name:"quotePoolToken",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeposited",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"address",name:"underlyingToken",indexed:false},{type:"address",name:"poolToken",indexed:false},{type:"uint256",name:"underlyingIn",indexed:false},{type:"uint256",name:"poolTokenOut",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"exchangeRate",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"PoolFundDistributed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"profits",indexed:false},{type:"uint256",name:"genesisProfits",indexed:false},{type:"uint256",name:"basePoolAmount",indexed:false},{type:"uint256",name:"quotePoolAmount",indexed:false},{type:"uint256",name:"genesisBasePoolAmount",indexed:false},{type:"uint256",name:"genesisQuotePoolAmount",indexed:false},{type:"uint256",name:"exchangedBaseFromProfits",indexed:false},{type:"uint256",name:"exchangedBaseAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolFundingFeeSettled",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"int256",name:"prevFundingRateTracker",indexed:false},{type:"int256",name:"nextFundingRateTracker",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"fundingFee",indexed:false}]},{type:"event",anonymous:false,name:"PoolPreDeactivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"PoolPrimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint256",name:"baseAmount",indexed:false},{type:"uint256",name:"quoteAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolRebateClaimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"PoolRefunded",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"receiver",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint256",name:"baseAmount",indexed:false},{type:"uint256",name:"quoteAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolReprimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"primer",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"PoolSettlementRecorded",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"poolEntryPrice",indexed:false},{type:"int256",name:"realizedPnl",indexed:false}]},{type:"event",anonymous:false,name:"PoolWithdrawn",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"address",name:"underlyingToken",indexed:false},{type:"address",name:"poolToken",indexed:false},{type:"uint256",name:"poolTokenIn",indexed:false},{type:"uint256",name:"underlyingOut",indexed:false},{type:"uint256",name:"rebateOut",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"exchangeRate",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionEarlyClosed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"executeSize",indexed:false},{type:"uint256",name:"executePrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionForceClosed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"executePrice",indexed:false},{type:"string",name:"reason",indexed:false}]},{type:"event",anonymous:false,name:"PositionLiquidated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"liquidationSize",indexed:false},{type:"uint256",name:"liquidationPrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionNFTMinted",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"oldPositionId",indexed:false},{type:"bytes32",name:"newPositionId",indexed:false},{type:"uint256",name:"tokenId",indexed:false},{type:"address",name:"owner",indexed:false},{type:"address",name:"recipient",indexed:false}]},{type:"event",anonymous:false,name:"PositionRiskControlDataMigrated",inputs:[{type:"bytes32",name:"from",indexed:false},{type:"bytes32",name:"to",indexed:false}]},{type:"event",anonymous:false,name:"PositionRiskControlDataUpdated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"freeAmount",indexed:false},{type:"uint256",name:"lockedAmount",indexed:false}]},{type:"event",anonymous:false,name:"PositionTransfer",inputs:[{type:"address",name:"from",indexed:false},{type:"address",name:"to",indexed:false},{type:"bytes32",name:"positionId",indexed:false}]},{type:"event",anonymous:false,name:"PositionUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"owner",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"beforeSize",indexed:false},{type:"uint256",name:"afterSize",indexed:false},{type:"uint256",name:"beforeCollateralAmount",indexed:false},{type:"uint256",name:"afterCollateralAmount",indexed:false},{type:"uint256",name:"entryPrice",indexed:false},{type:"int256",name:"fundingRateIndex",indexed:false},{type:"uint8",name:"riskTier",indexed:false},{type:"uint256",name:"earlyClosePrice",indexed:false}]},{type:"event",anonymous:false,name:"ReferralRebateClaimed",inputs:[{type:"address",name:"user",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"ReserveRebateCollected",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"address",name:"keeper",indexed:false},{type:"uint256",name:"poolAmount",indexed:false},{type:"uint256",name:"stakingAmount",indexed:false},{type:"uint256",name:"keeperAmount",indexed:false},{type:"uint256",name:"treasuryAmount",indexed:false},{type:"uint256",name:"reservedAmount",indexed:false},{type:"uint256",name:"ecoFundAmount",indexed:false}]},{type:"event",anonymous:false,name:"ReserveRebateDisbursed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"address",name:"keeper",indexed:false},{type:"uint256",name:"poolAmount",indexed:false},{type:"uint256",name:"stakingAmount",indexed:false},{type:"uint256",name:"keeperAmount",indexed:false},{type:"uint256",name:"treasuryAmount",indexed:false},{type:"uint256",name:"reservedAmount",indexed:false},{type:"uint256",name:"ecoFundAmount",indexed:false}]},{type:"event",anonymous:false,name:"TradingFeeTierUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"uint8",name:"feeType",indexed:false},{type:"uint8",name:"tier",indexed:false},{type:"uint32",name:"takerFeeRate",indexed:false},{type:"int32",name:"makerFeeRate",indexed:false},{type:"bool",name:"isEnabled",indexed:false}]},{type:"event",anonymous:false,name:"Upgraded",inputs:[{type:"address",name:"implementation",indexed:true}]},{type:"event",anonymous:false,name:"UserFeeDataUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"signer",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint8",name:"tier",indexed:false},{type:"address",name:"referrer",indexed:false},{type:"uint32",name:"totalReferralRebatePct",indexed:false},{type:"uint32",name:"referrerRebatePct",indexed:false}]},{type:"event",anonymous:false,name:"UserSettlementRecorded",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"int256",name:"charge",indexed:false},{type:"int256",name:"realizedPnl",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"int256",name:"fundingFee",indexed:false}]},{type:"event",anonymous:false,name:"UserSpecialFeeTierUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint8",name:"oldTier",indexed:false},{type:"uint8",name:"newTier",indexed:false}]},{type:"function",name:"UPGRADE_INTERFACE_VERSION",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"string"}]},{type:"function",name:"emitCollateralAccepted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"quoteDebt"},{type:"uint256",name:"baseCollateral"},{type:"uint256",name:"quoteCollateral"},{type:"uint256",name:"totalQuoteDebt"},{type:"uint256",name:"totalBaseCollateral"}]}],outputs:[]},{type:"function",name:"emitCollateralAdjusted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint8",name:"direction"},{type:"uint256",name:"beforeCollateralAmount"},{type:"uint256",name:"afterCollateralAmount"}]}],outputs:[]},{type:"function",name:"emitEnterDispute",constant:false,payable:false,inputs:[{type:"bytes32",name:"poolId"}],outputs:[]},{type:"function",name:"emitExchanged",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"address",name:"source"},{type:"address",name:"target"},{type:"uint256",name:"sourceAmount"},{type:"uint256",name:"targetAmount"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitExecutionMatched",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256[]",name:"triggerOrderIds"},{type:"uint256[]",name:"matchedOrderIds"},{type:"uint8",name:"matchType"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitExitDispute",constant:false,payable:false,inputs:[{type:"bytes32",name:"poolId"}],outputs:[]},{type:"function",name:"emitFundingRateUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint64",name:"epochs"},{type:"uint64",name:"duration"},{type:"uint64",name:"previousEpochTime"},{type:"uint64",name:"lastEpochTime"},{type:"bytes32",name:"poolId"},{type:"int256",name:"fundingRate"},{type:"int256",name:"fundingRateTracker"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitLiquidityLockUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint64",name:"windowAnchor"},{type:"uint256",name:"priceFloor"},{type:"uint256",name:"priceCeiling"},{type:"int256",name:"openInterest"}]}],outputs:[]},{type:"function",name:"emitLiquidityMigrated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"fromPoolId"},{type:"bytes32",name:"toPoolId"},{type:"uint256",name:"lpAmountIn"},{type:"uint256",name:"lpAmountOut"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderCancelled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"bytes32",name:"poolId"},{type:"string",name:"reason"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderCreated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint8",name:"poolType"},{type:"uint256",name:"amount"},{type:"uint256",name:"triggerPrice"},{type:"uint8",name:"triggerType"},{type:"uint256",name:"minQuoteOut"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderExecuted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"bytes32",name:"poolId"},{type:"address",name:"executor"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitMarketCreated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"marketId"},{type:"address",name:"deployer"},{type:"address",name:"quoteToken"},{type:"uint32",name:"baseReserveRatio"},{type:"uint32",name:"quoteReserveRatio"},{type:"uint64",name:"oracleFeeUsd"},{type:"uint64",name:"oracleRefundFeeUsd"},{type:"uint128",name:"poolPrimeThreshold"}]}],outputs:[]},{type:"function",name:"emitOrderCancelled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitOrderFilled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint8",name:"orderType"},{type:"uint256",name:"orderSize"},{type:"uint256",name:"fillSize"},{type:"uint256",name:"filledSize"},{type:"uint256",name:"orderPrice"},{type:"uint256",name:"fillPrice"},{type:"int256",name:"realizedPnl"},{type:"int256",name:"tradingFee"},{type:"int256",name:"fundingFee"},{type:"uint256",name:"executionFeeAmount"},{type:"address",name:"keeper"}]}],outputs:[]},{type:"function",name:"emitOrderMarkedADL",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"available"},{type:"uint256",name:"requested"}]}],outputs:[]},{type:"function",name:"emitOrderPlaced",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint8",name:"orderType"},{type:"uint8",name:"operation"},{type:"uint8",name:"direction"},{type:"uint8",name:"triggerType"},{type:"uint256",name:"collateralAmount"},{type:"uint256",name:"size"},{type:"uint256",name:"price"},{type:"uint8",name:"tif"},{type:"bool",name:"postOnly"},{type:"uint16",name:"slippagePct"},{type:"uint256",name:"executionFeeAmount"},{type:"uint16",name:"userLeverage"}]}],outputs:[]},{type:"function",name:"emitOrderUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"size"},{type:"uint256",name:"price"},{type:"uint256",name:"tpSize"},{type:"uint256",name:"tpPrice"},{type:"uint256",name:"slSize"},{type:"uint256",name:"slPrice"}]}],outputs:[]},{type:"function",name:"emitPoolActivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint8",name:"oracleType"},{type:"bytes32",name:"oracleFeedId"}]}],outputs:[]},{type:"function",name:"emitPoolDeactivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitPoolDeployed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"marketId"},{type:"bytes32",name:"poolId"},{type:"address",name:"deployer"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"address",name:"basePoolToken"},{type:"address",name:"quotePoolToken"}]}],outputs:[]},{type:"function",name:"emitPoolDeposited",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"address",name:"underlyingToken"},{type:"address",name:"poolToken"},{type:"uint256",name:"underlyingIn"},{type:"uint256",name:"poolTokenOut"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"exchangeRate"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitPoolFundDistributed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"profits"},{type:"uint256",name:"genesisProfits"},{type:"uint256",name:"basePoolAmount"},{type:"uint256",name:"quotePoolAmount"},{type:"uint256",name:"genesisBasePoolAmount"},{type:"uint256",name:"genesisQuotePoolAmount"},{type:"uint256",name:"exchangedBaseFromProfits"},{type:"uint256",name:"exchangedBaseAmount"}]}],outputs:[]},{type:"function",name:"emitPoolFundingFeeSettled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"int256",name:"prevFundingRateTracker"},{type:"int256",name:"nextFundingRateTracker"},{type:"uint256",name:"price"},{type:"uint8",name:"direction"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"fundingFee"}]}],outputs:[]},{type:"function",name:"emitPoolPreDeactivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitPoolPrimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint256",name:"baseAmount"},{type:"uint256",name:"quoteAmount"}]}],outputs:[]},{type:"function",name:"emitPoolRebateClaimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitPoolRefunded",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"receiver"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint256",name:"baseAmount"},{type:"uint256",name:"quoteAmount"}]}],outputs:[]},{type:"function",name:"emitPoolReprimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"primer"},{type:"address",name:"token"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitPoolSettlementRecorded",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"poolEntryPrice"},{type:"int256",name:"realizedPnl"}]}],outputs:[]},{type:"function",name:"emitPoolWithdrawn",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"address",name:"underlyingToken"},{type:"address",name:"poolToken"},{type:"uint256",name:"poolTokenIn"},{type:"uint256",name:"underlyingOut"},{type:"uint256",name:"rebateOut"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"exchangeRate"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitPositionEarlyClosed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"executeSize"},{type:"uint256",name:"executePrice"}]}],outputs:[]},{type:"function",name:"emitPositionForceClosed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"executePrice"},{type:"string",name:"reason"}]}],outputs:[]},{type:"function",name:"emitPositionLiquidated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"liquidationSize"},{type:"uint256",name:"liquidationPrice"}]}],outputs:[]},{type:"function",name:"emitPositionNFTMinted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"bytes32",name:"oldPositionId"},{type:"bytes32",name:"newPositionId"},{type:"uint256",name:"tokenId"},{type:"address",name:"owner"},{type:"address",name:"recipient"}]}],outputs:[]},{type:"function",name:"emitPositionRiskControlDataMigrated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"from"},{type:"bytes32",name:"to"}]}],outputs:[]},{type:"function",name:"emitPositionRiskControlDataUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"freeAmount"},{type:"uint256",name:"lockedAmount"}]}],outputs:[]},{type:"function",name:"emitPositionTransfer",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"from"},{type:"address",name:"to"},{type:"bytes32",name:"positionId"}]}],outputs:[]},{type:"function",name:"emitPositionUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"owner"},{type:"bytes32",name:"positionId"},{type:"bytes32",name:"poolId"},{type:"uint8",name:"direction"},{type:"uint256",name:"orderId"},{type:"uint256",name:"beforeSize"},{type:"uint256",name:"afterSize"},{type:"uint256",name:"beforeCollateralAmount"},{type:"uint256",name:"afterCollateralAmount"},{type:"uint256",name:"entryPrice"},{type:"int256",name:"fundingRateIndex"},{type:"uint8",name:"riskTier"},{type:"uint256",name:"earlyClosePrice"}]}],outputs:[]},{type:"function",name:"emitReferralRebateClaimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"address",name:"token"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitReserveRebateCollected",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"token"},{type:"uint256",name:"amount"},{type:"address",name:"keeper"},{type:"uint256",name:"poolAmount"},{type:"uint256",name:"stakingAmount"},{type:"uint256",name:"keeperAmount"},{type:"uint256",name:"treasuryAmount"},{type:"uint256",name:"reservedAmount"},{type:"uint256",name:"ecoFundAmount"}]}],outputs:[]},{type:"function",name:"emitReserveRebateDisbursed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"token"},{type:"uint256",name:"amount"},{type:"address",name:"keeper"},{type:"uint256",name:"poolAmount"},{type:"uint256",name:"stakingAmount"},{type:"uint256",name:"keeperAmount"},{type:"uint256",name:"treasuryAmount"},{type:"uint256",name:"reservedAmount"},{type:"uint256",name:"ecoFundAmount"}]}],outputs:[]},{type:"function",name:"emitTradingFeeTierUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"uint8",name:"feeType"},{type:"uint8",name:"tier"},{type:"uint32",name:"takerFeeRate"},{type:"int32",name:"makerFeeRate"},{type:"bool",name:"isEnabled"}]}],outputs:[]},{type:"function",name:"emitUserFeeDataUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"signer"},{type:"address",name:"user"},{type:"uint8",name:"tier"},{type:"address",name:"referrer"},{type:"uint32",name:"totalReferralRebatePct"},{type:"uint32",name:"referrerRebatePct"}]}],outputs:[]},{type:"function",name:"emitUserFeeSettlementAndDistributed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"int256",name:"charge"},{type:"int256",name:"realizedPnl"},{type:"int256",name:"tradingFee"},{type:"int256",name:"fundingFee"},{type:"int32",name:"tradingFeeRate"},{type:"bool",name:"isMaker"},{type:"uint256",name:"baseTradingFee"},{type:"uint256",name:"brokerTradingFee"},{type:"address",name:"broker"},{type:"uint256",name:"referralRebate"},{type:"uint256",name:"referrerRebate"},{type:"address",name:"referrer"},{type:"int256",name:"reserveFee"}]}],outputs:[]},{type:"function",name:"emitUserSpecialFeeTierUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"uint8",name:"oldTier"},{type:"uint8",name:"newTier"}]}],outputs:[]},{type:"function",name:"getAddressManager",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"address"}]},{type:"function",name:"getDependencyAddress",constant:true,stateMutability:"view",payable:false,inputs:[{type:"bytes32",name:"identifier"}],outputs:[{type:"address"}]},{type:"function",name:"getImplementation",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"address"}]},{type:"function",name:"initialize",constant:false,payable:false,inputs:[{type:"address",name:"addressManager"}],outputs:[]},{type:"function",name:"isBlockHeaderEmitted",constant:true,stateMutability:"view",payable:false,inputs:[{type:"uint256",name:"blockNumber"}],outputs:[{type:"bool"}]},{type:"function",name:"proxiableUUID",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"registerContract",constant:false,payable:false,inputs:[{type:"bytes32[]",name:"identifiers"}],outputs:[]},{type:"function",name:"sequencer",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"upgradeTo",constant:false,stateMutability:"payable",payable:true,inputs:[{type:"address",name:"newImplementation"},{type:"bytes",name:"data"}],outputs:[]},{type:"function",name:"upgradeToAndCall",constant:false,stateMutability:"payable",payable:true,inputs:[{type:"address",name:"newImplementation"},{type:"bytes",name:"data"}],outputs:[]}];var ge={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var j=class{constructor(e,t){this.configManager=e,this.logger=t;}getOrderIdFromTransaction(e){if(!e||!e.logs)return null;for(let t=0;t<e.logs.length;t++){let n=e.logs[t];this.logger.info(`Log ${t}:`,{address:n.address,topics:n.topics,data:n.data});try{let a=decodeEventLog({abi:Ve,data:n.data??"0x",topics:n.topics??[]}),i=a.args;if(a.eventName==="OrderPlaced"&&i?.orderId!=null)return String(i.orderId)}catch{continue}}return null}async getApproveQuoteAmount(e,t,n,a){try{if(!n||typeof n=="string"&&!n.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let i=a??Q$1(t).Account,d=await S$1(t,n).read.allowance([e,i]);return {code:0,data:String(d)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await ha(i)}}async needsApproval(e,t,n,a,i){try{let d=(await this.getApproveQuoteAmount(e,t,n,i)).data,r=BigInt(d),c=BigInt(a);return r<c}catch(s){return this.logger.error("Error checking approval needs:",s),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:n,spenderAddress:a}){try{let i=await U$1(e,t),s=n??maxUint256,d=a??Q$1(e).Account,r=await this.getGasPriceByRatio(),c=await i.write.approve([d,s],{gasPrice:r});return await f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(i){return this.logger.error("Approval error:",i),{code:-1,message:i?.message}}}async getUserTradingFeeRate(e,t,n,a){let s=this.configManager.getConfig().brokerAddress;try{let d=W$1(n,s),r=a??await this.configManager.getSignerAddress(n),c=await d.read.getUserFeeRate([r,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(d){return this.logger.error("Error getting user trading fee rate:",d),{code:-1,message:d?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await X$1(t,0)).read.getExecutionFee([e])).toString()}catch(n){return this.logger.error("Error getting network fee:",n),"0"}}async getOraclePrice(e,t){try{let n=await ra(t,e);if(!n)throw new Error("Failed to get price data");return n}catch(n){throw this.logger.error("Error getting oracle price:",n),n}}async buildUpdatePriceParams(e,t){let n=await this.getOraclePrice(e,t);if(!n)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:n.vaa,publishTime:n.publishTime,oracleType:n.oracleType,value:n.value,price:n.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let n=await ha(e);return n?n.error:JSON.stringify(e)}catch(n){return n?.message??n?.toString()??t}}async checkSeamlessGas(e,t,n){let i=await(await X$1(t,0)).read.getForwardFeeByToken([n]),d=await S$1(t,n).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(d)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:n}){try{return {code:0,data:await(await Y(e,0)).read.getPoolInfo([t,n])}}catch(a){return this.logger.error("Error getting pool info:",a),{code:-1,message:a?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let n=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);n&&n[1]&&(t=n[1]);}if(t){let n=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(n){let a=Object.keys(ge).find(i=>i.toLowerCase()===n);if(a)return ge[a]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await na(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=d[t];return ma$1(e,n?.gasLimitRatio??1.3)}};var J=class{constructor(e,t,n,a){this.configManager=e,this.logger=t,this.utils=n,this.client=a;}async withRetry(e,t=3,n=300){let a;for(let i=0;i<t;i++)try{return await e()}catch(s){a=s,i<t-1&&await new Promise(d=>setTimeout(d,n));}throw a}async getTradeFlow(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:n,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:n}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=S$1(e,n),i=await this.configManager.getSignerAddress(e);return {code:0,data:await a.read.balanceOf([t||i])}}async updateAndWithdraw(e,t,n,a,i){try{let d=await(await Z$1(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await f(i).waitForTransactionReceipt({hash:d})}}catch(s){return {code:-1,message:s.message}}}async deposit({amount:e,tokenAddress:t,chainId:n}){let a=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"",i=Q$1(n);try{if(await this.utils.needsApproval(a,n,t,e,i.Account)){let p=await this.utils.approveAuthorization({chainId:n,quoteAddress:t,amount:maxUint256.toString(),spenderAddress:i.Account});if(p.code!==0)throw new Error(p.message)}let r=await(await Z$1(n)).write.deposit([a,t,e]);return {code:0,data:await f(n).waitForTransactionReceipt({hash:r})}}catch(s){return {code:-1,message:s.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:n}){try{let a=await this.getAccountInfo(t,n,e);if(a.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let i=await this.client.appeal.getAppealStatus(e,t,n),s=a.data,d=BigInt(s?.quoteProfit??0),r=BigInt(s?.freeMargin??0),c=BigInt(s?.lockedMargin??0),p=i?.code===0?i.data:null,u=p?.status===1?BigInt(p?.lockedMargin??0):0n;return {code:0,data:r+d-c-u}}catch(a){return {code:-1,message:a.message}}}async getAccountInfo(e,t,n){let a=await Y(e);try{return {code:0,data:await a.read.getAccountInfo([n,t])}}catch(i){return {code:-1,message:i.message}}}async getAccountVipInfo(e,t){let n=this.configManager.getConfig(),a=W$1(e,n.brokerAddress),s=await f(e).getBlock({blockTag:"latest"}),d=Number(s?.timestamp??BigInt(xe().unix()))+300;try{let r=await this.getCurrentFeeDataEpoch(e);this.logger.debug("setUserFeeDataEpoch-->",r);let c=await a.read.userFeeData([r,t]),p;try{p=await this.withRetry(()=>a.read.userNonces([t]));}catch{p=0n;}return {code:0,data:{...c,nonce:p.toString(),deadline:d}}}catch(r){return {code:-1,message:r.message}}}async getAccountVipInfoByBackend(e,t,n,a){let i=await this.configManager.getAccessToken()??"";try{let s=await this.client.api.getAccountVipInfo({address:e,accessToken:i,chainId:t,deadline:n,nonce:a});if(s.code!==9200)throw new l("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 getCurrentFeeDataEpoch(e){let t=this.configManager.getConfig();return await(await W$1(e,t.brokerAddress)).read.currentFeeDataEpoch()}async setUserFeeData(e,t,n,a,i){let s=this.configManager.getConfig();if(n<xe().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let d=await V$1(t,s.brokerAddress),r=await this.getCurrentFeeDataEpoch(t),c={user:e,nonce:a.nonce,deadline:n,feeDataEpoch:r.toString(),feeData:{tier:a.tier,referrer:a.referrer||zeroAddress,totalReferralRebatePct:a.totalReferralRebatePct,referrerRebatePct:a.referrerRebatePct},signature:i},p=await d.read.userNonces([e]);if(parseInt(p.toString())+1!==parseInt(a.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let u=await d.write.setUserFeeData([c]);return {code:0,data:await f(t).waitForTransactionReceipt({hash:u})}}catch(d){return {code:-1,message:d.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Pt(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(n=>Qe(e,n)).join("&")}function kt(o){let e=o||{};return Object.keys(e).filter(n=>typeof e[n]<"u").map(n=>Array.isArray(e[n])?Tt(e,n):Pt(e,n)).join("&")}function ye(o){let e=kt(o);return e?`?${e}`:""}var X=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",n=await this.configManager.getSignerAddress(e.chainId);if(!n)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:n}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return m.get(this.buildRequestPath(e),t,merge(i,a))}async post(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return m.post(this.buildRequestPath(e),t,merge(i,a))}async put(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return m.put(this.buildRequestPath(e),t,merge(i,a))}async delete(e,{auth:t=false,...n}={}){let a=t?await this.buildAuthParams():{};return m.delete(this.buildRequestPath(e),merge(a,n))}};var Z=class extends X{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return m.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await m.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return m.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return m.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return m.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 m.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return m.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${ye({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,positionId:n}){return await m.get(`${this.getHost()}/openapi/gateway/scan/position/open`,{positionId:n},{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t){return await m.get(`${this.getHost()}/openapi/gateway/scan/order/open`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,n){return await m.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${n}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:n,limit:a,interval:i}){return m.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n,limit:a,interval:i})}async getKlineLatestBar(e){return m.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return m.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return m.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async removeFavorite({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return m.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...n}){return m.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return m.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n,deadline:a,nonce:i}){return m.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:n,deadline:a,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:n}){return m.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:n},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:n,accessToken:a}){return m.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:n,myx_openapi_access_token:a}})}};var je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var vt={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"}]},Rt=2;function St(o){let e=hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),n=toHex(e.slice(32,64));return {v:e[64],r:t,s:n}}async function Et(o,e,t,n,a,i,s,d){let r=S$1(e,t),c=await je(r),[p]=await o.getAddresses();if(!p)throw new l("INVALID_SIGNER","No account for signPermit");let u={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},g={owner:n,spender:a,value:i,nonce:s,deadline:d},m=await o.signTypedData({account:p,domain:{...c,chainId:c.chainId},types:u,primaryType:"Permit",message:g});return St(m)}var ee=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async onCheckRelayer(e,t,n,a){let s=await(await _$1(n)).read.isUserRelayerEnabled([e,t]),d=await this.utils.needsApproval(e,n,a,maxUint256.toString(),Q$1(n).TRADING_ROUTER);return s&&!d}async getContractAbiAndAddressByFunctionName(e,t){let n=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],a=["setUserFeeData"],i$1=["updateAndWithdraw","deposit"];return n.includes(e)?{abi:R$1,address:Q$1(t).TRADING_ROUTER}:i$1.includes(e)?{abi:l$1,address:Q$1(t).Account}:(console.log("functionName==>",e),console.log("brokerFunctions.includes(functionName)->",a.includes(e)),a.includes(e)?{abi:i,address:this.configManager.getConfig().brokerAddress}:{abi:R$1,address:Q$1(t).TRADING_ROUTER})}async getUSDPermitParams(e,t,n){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let a=await h(t),i=Q$1(t),[s]=await a.getAddresses();if(!s)throw new l("INVALID_SIGNER","No account");let d=S$1(t,n);try{let r=await d.read.nonces([s]),c=await Et(a,t,n,s,i.TRADING_ROUTER,maxUint256,r,e);return [{token:n,owner:s,spender:i.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch{throw new l("INVALID_PRIVATE_KEY","Invalid private key generated")}}async getForwardEip712Domain(e){let n=await(await _$1(e)).read.eip712Domain();return {name:n[1],version:n[2],chainId:n[3],verifyingContract:n[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:n,forwardFeeToken:a,functionName:i,orderParams:s,value:d="0",gas:r="800000"}){let c=await(await _$1(e)).read.nonces([t]),p=xe().add(60,"minute").unix(),u=await this.getForwardEip712Domain(e),{abi:g,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),h=encodeFunctionData({abi:g,functionName:i,args:s}),x=await n({domain:u,functionHash:h,to:m,nonce:c.toString(),deadline:p}),I=await this.api.forwarderTxApi({from:t,to:m,value:d??"0",gas:r,nonce:c.toString(),data:h,deadline:p,signature:x,forwardFeeToken:a},e);if(I.data?.txHash){for(let C=0;C<5;C++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};C<4&&await new Promise(ie=>setTimeout(ie,1e3));}catch(Ae){this.logger.error("Poll transaction from chain error:",Ae),C<4&&await new Promise(ie=>setTimeout(ie,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:n,gas:a,deadline:i,data:s,nonce:d,forwardFeeToken:r},c){let p=await this.getForwardEip712Domain(c),u=await h(c),[g]=await u.getAddresses();if(!g)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await u.signTypedData({account:g,domain:p,types:vt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(n??"0"),gas:BigInt(a),nonce:BigInt(d),deadline:BigInt(i),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:n,gas:a,nonce:d,data:s,deadline:i,signature:m,forwardFeeToken:r},c)}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:n,forwardFeeToken:a}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:n,address:i,tokenAddress:a})).data,x=await(await X$1(n)).read.getForwardFeeByToken([a]),I=BigInt(x)*BigInt(Rt);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}let s=xe().add(60,"minute").unix(),d=[];if(e)try{d=await this.getUSDPermitParams(s,n,a);}catch(g){this.logger.warn("Failed to get USD permit params, proceeding without permit:",g),d=[];}let r=await _$1(n,1),c=await(await _$1(n)).read.nonces([i]),p=encodeFunctionData({abi:j$1,functionName:"permitAndApproveForwarder",args:[t,e,d]}),u=await this.forwarderTx({from:i,to:r.address,value:"0",gas:"800000",nonce:c.toString(),data:p,deadline:s,forwardFeeToken:a},n);if(u.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:u.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(x){this.logger.error("Poll transaction from chain error:",x),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await _$1(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:n,functionName:a,data:i,seamlessAddress:s}){if(!e||!isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!s||!isAddress(s))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!n||!isAddress(n))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(i))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,n))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let r=await _$1(t),c,{abi:p,address:u}=await this.getContractAbiAndAddressByFunctionName(a,t);try{c=encodeFunctionData({abi:p,functionName:a,args:i});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(a)}: ${m.message}. Check args shape and that no address field is undefined.`)}let g=await r.read.nonces([s]);return {from:s,to:u,value:"0",gas:"800000",deadline:xe().add(60,"minute").unix(),data:c,nonce:g.toString(),forwardFeeToken:n}}};var M=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return Q$1(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return W$1(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var te=class extends M{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return aa(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return $$1(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let n=t==="DisputeFiled"?"caseId":"appealCaseId";for(let a of e.logs)try{let i=decodeEventLog({abi:k,data:a.data,topics:a.topics});if(i.eventName===t&&i.args&&n in i.args)return i.args[n]}catch{continue}return null}async submitAppeal(e,t,n){let a=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",i=await this.client.utils.needsApproval(a,this.config.chainId,t,n,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 s=await this.getDisputeCourtContract(),d=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),r=BigInt(d[0].value.toString()||"1"),c=await s.estimateGas.fileDispute([d,e,t],{value:r}),p=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),g=await s.write.fileDispute([d,e,t],{value:r,gasLimit:p,gasPrice:u}),m=await f(this.config.chainId).waitForTransactionReceipt({hash:g}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:n,deadline:a,v:i,r:s,s:d}){let r=await this.getDisputeCourtContract(),c=await r.estimateGas.vote([e,t,n?1:0,a,i,s,d]),p=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),g=await r.write.vote([e,t,n?1:0,a,i,s,d],{gasLimit:p,gasPrice:u});return await f(this.config.chainId).waitForTransactionReceipt({hash:g})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),n=await t.estimateGas.claimBond([e]),a=await this.client.utils.getGasLimitByRatio(n),i=await this.client.utils.getGasPriceByRatio(),s=await t.write.claimBond([e],{gasLimit:a,gasPrice:i});return f(this.config.chainId).waitForTransactionReceipt({hash:s})}async claimReimbursement(e,t,n,a){let i=await this.getReimbursementContract(),s=await i.estimateGas.claimReimbursement([e,t,n,a]),d=await this.client.utils.getGasLimitByRatio(s),r=await this.client.utils.getGasPriceByRatio(),c=await i.write.claimReimbursement([e,t,n,a],{gasLimit:d,gasPrice:r});return f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,n){let a=await this.getDisputeCourtContract(),i=await this.client.utils.getGasPriceByRatio(),s=await this.client.utils.getGasLimitByRatio(await a.estimateGas.fileDisputeFromStaker([e,t,n])),d=await a.write.fileDisputeFromStaker([e,t,n],{gasLimit:s,gasPrice:i}),r=await f(this.config.chainId).waitForTransactionReceipt({hash:d}),c=this.getCaseIdFromReceiptLogs(r,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:r,caseId:c}}async appealReconsideration(e,t,n){let a=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,n,s)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:s});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let r=await a.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(r),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.appeal([e],{gasLimit:c,gasPrice:p}),g=await f(this.config.chainId).waitForTransactionReceipt({hash:u}),m=this.getCaseIdFromReceiptLogs(g,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:g,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,n){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:n,accessToken:await this.configManager.getAccessToken()??""})}};var ne=class extends M{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),n=await V$1(this.config.chainId,t.brokerAddress),a=await n.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),d=await n.write.claimRebate([e],{gasPrice:s,gasLimit:i});return f(this.config.chainId).waitForTransactionReceipt({hash:d})}};var Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.InitialVote=2]="InitialVote",r[r.PublicNotice=3]="PublicNotice",r[r.UnderReconsideration=4]="UnderReconsideration",r[r.Won=5]="Won",r[r.Failed=6]="Failed",r[r.PlatformRuling=7]="PlatformRuling",r[r.PlatformRevoked=8]="PlatformRevoked",r))(Ft||{}),Dt=(p=>(p[p.InitialVoting=1]="InitialVoting",p[p.PublicNotice=2]="PublicNotice",p[p.UnderReconsideration=3]="UnderReconsideration",p[p.Won=5]="Won",p[p.Failed=4]="Failed",p[p.PlatformRuling=6]="PlatformRuling",p[p.PlatformRevoked=7]="PlatformRevoked",p[p.ReconsiderationVoting=8]="ReconsiderationVoting",p[p.AppealRevert=9]="AppealRevert",p[p.NotAppealFailed=10]="NotAppealFailed",p))(Dt||{}),Ot=(a=>(a[a.UnderReview=1]="UnderReview",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Completed=4]="Completed",a))(Ot||{}),Lt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Lt||{}),Nt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Nt||{}),Bt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Bt||{}),_t=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(_t||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),Ut=(n=>(n[n.NoVote=0]="NoVote",n[n.Supported=1]="Supported",n[n.Rejected=2]="Rejected",n))(Ut||{}),Wt=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Wt||{}),qt=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))(qt||{});var Ie=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new z(e),this.logger=new ga$1({logLevel:e.logLevel});let t=O.getInstance();t.setConfigManager(this.configManager),g(this.configManager),t.getMarkets().then(),this.utils=new j(this.configManager,this.logger),this.api=new Z(this.configManager,this.logger),this.account=new J(this.configManager,this.logger,this.utils,this),this.seamless=new ee(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new V(this.configManager,this.utils,this.api),this.position=new H(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new Q(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new q(this.configManager,this.logger),this.appeal=new te(this,this.configManager),this.referrals=new ne(this);}auth(e){this.configManager.auth(e);}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 Xi="1.0.17";
|
|
2
|
-
export{
|
|
1
|
+
import {ha,P,h,g,fa as fa$1,ga as ga$1,R as R$1,T,ia,V as V$1,f,X as X$1,Y as Y$1,sa,Z,oa,d,na,n,_,W as W$1,$ as $$1,S as S$1,m,j as j$1,i,k,U as U$1,c,ba,aa,l as l$1,b,e}from'./chunk-UKJZVOPA.mjs';export{ma as COMMON_LP_AMOUNT_DECIMALS,la as COMMON_PRICE_DECIMALS,a as ChainId,D as CloseTypeEnum,A as DirectionEnum,o as ErrorCode,C as ExecTypeEnum,F as ForwarderGetStatus,r as HttpKlineIntervalEnum,ha as Logger,u as MarketCapType,p as MarketPoolState,s as MarketType,P as MxSDK,x as OperationEnum,q as OracleType,B as OrderStatusEnum,w as OrderTypeEnum,v as SearchSecondTypeEnum,t as SearchTypeEnum,E as TradeFlowAccountTypeEnum,y as TradeFlowTypeEnum,z as TriggerTypeEnum,qa as approve,wa as base,pa as bigintAmountSlipperCalculator,oa as bigintTradingGasPriceWithRatio,na as bigintTradingGasToRatioCalculator,ua as formatUnits,ka as getAllowanceApproved,ja as getBalanceOf,M as getBaseDetail,H as getBaseUrlByEnv,N as getMarketDetail,O as getMarketList,I as getOraclePrice,J as getPoolDetail,G as getPoolList,K as getPoolOpenOrders,sa as getPriceData,ra as getPricesData,f as getPublicClient,da as getSdkLogSink,L as getTickerData,ta as getTokenInfo,i as getWalletClient,Q as getWalletProvider,ya as market,va as parseUnits,za as pool,xa as quote,ga as sdkError,ea as sdkLog,fa as sdkWarn,g as setConfigManagerForViem,ca as setSdkLogSink}from'./chunk-UKJZVOPA.mjs';import pt from'mitt';import {MD5,Hex}from'crypto-es';import lt from'reconnecting-websocket';import {decodeEventLog,maxUint256,zeroAddress,encodeFunctionData,isAddress,createWalletClient,custom,hexToBytes,toHex}from'viem';import xe from'dayjs';import {merge}from'lodash-es';var U=(o,e)=>MD5(o,{outputLength:32}).toString(Hex);var W=o=>{switch(o.request){case "signin":return U(o.request)}return U(JSON.stringify(o))},L=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return U(JSON.stringify({topic:e,params:t}))}},Ne=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",ct=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Be=o=>{switch(ct(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:L({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[n,a]=t.split("_");return {...o,type:L({topic:"candle",params:{globalId:parseInt(n),resolution:a}}),globalId:parseInt(n),resolution:a}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var _e={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=pt();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:n,...a}=t;this.config={..._e,...a},this.logger=new ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let n={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 lt(this.config.url,this.config.protocols,n),this.setupEventListeners(e,t);}catch(n){t(n);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async n=>{this.eventBus.emit("open",n),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=n=>{this.handleMessage(n);},this.ws.onclose=n=>{this.eventBus.emit("close",n),this.stopHeartbeatTimer();},this.ws.onerror=n=>{this.eventBus.emit("error",n),t(n);},this.ws.addEventListener("reconnecting",n=>{this.eventBus.emit("reconnecting",{detail:n.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,n)=>{let a=W(e);this.waitingRequests.has(a)?(this.waitingRequests.get(a)?.onSuccess.add(t),this.waitingRequests.get(a)?.onError.add(n)):this.waitingRequests.set(a,{onSuccess:new Set([t]),onError:new Set([n])}),this.send(e);})}subscribe(e,t){let n=Array.isArray(e)?e:[e],a=[],i=new Set;n.forEach(s=>{let d=L(s);if(!i.has(d))if(i.add(d),this.subscriptions.has(d))this.subscriptions.get(d).callbacks.add(t);else {let r={id:d,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(d,r),a.push(d),this.logger.debug(`create new subscription: ${d}`);}}),a.length>0&&this.send({request:"subv2",args:a});}unsubscribe(e,t){if(!e)return;let n=Array.isArray(e)?e:[e],a=[],i=new Set;n.forEach(s=>{let d=L(s);if(i.has(d))return;i.add(d);let r=this.subscriptions.get(d);r&&(r.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${d}`),r.callbacks.size===0&&(this.subscriptions.delete(d),a.push(d),this.logger.debug(`subscription ${d} has no callbacks, will unsubscribe`)));}),a.length>0&&this.send({request:"unsubv2",args:a});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(Ne(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=W({request:e.type,args:""});break;default:t=W({request:e.type,args:e.data.data});break}let n=this.waitingRequests.get(t),a=e.data.code===9200;a?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),n?.onError.size&&!a&&n.onError.forEach(i=>{i(new l("REQUEST_FAILED","Request failed"));}),n?.onSuccess.size&&a&&n.onSuccess.forEach(i=>{i(e.data);});}handleSubscriptionMessage(e){let t=Be(e),n=t.type,a=this.subscriptions.get(n);a&&a.callbacks.forEach(i=>{try{i(t);}catch(s){this.logger.error(`Callback Error (${n}): ${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||_e.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 Ge=[56,59144,42161],Ue=[59141,421614,97],We=[97,421614];var $={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 n=$.MainNet;e.getConfig().isBetaMode?n=$.BetaNet:e.getConfig().isTestnet&&(n=$.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:n,...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 n=Array.isArray(e)?e:[e];this.wsClient.subscribe(n.map(a=>({topic:"ticker",params:{globalId:a}})),t);}unsubscribeTickers(e,t){let n=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(n.map(a=>({topic:"ticker",params:{globalId:a}})),t);}subscribeKline(e,t,n){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},n);}unsubscribeKline(e,t,n){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},n);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function ut(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function mt(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function ue(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let n=typeof t=="string"?t:{raw:t};return await o.signMessage({message:n})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let n=t.to;if(!n)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:n,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 qe(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:n=>o.signMessage(n),async sendTransaction(n){let a={...n};n.value!=null&&(a.value=BigInt(n.value)),n.gasLimit!=null&&(a.gasLimit=BigInt(n.gasLimit)),n.gasPrice!=null&&(a.gasPrice=BigInt(n.gasPrice)),n.maxFeePerGas!=null&&(a.maxFeePerGas=BigInt(n.maxFeePerGas)),n.maxPriorityFeePerGas!=null&&(a.maxPriorityFeePerGas=BigInt(n.maxPriorityFeePerGas));try{let s=(await o.sendTransaction(a)).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 d={...n};n.value!=null&&(d.value=`0x${BigInt(n.value).toString(16)}`),n.gasLimit!=null&&(d.gasLimit=`0x${BigInt(n.gasLimit).toString(16)}`),n.gasPrice!=null&&(d.gasPrice=`0x${BigInt(n.gasPrice).toString(16)}`),n.maxFeePerGas!=null&&(d.maxFeePerGas=`0x${BigInt(n.maxFeePerGas).toString(16)}`),n.maxPriorityFeePerGas!=null&&(d.maxPriorityFeePerGas=`0x${BigInt(n.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(d)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw i}},signTransaction:typeof e.signTransaction=="function"?n=>t.signTransaction(n):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(n){return t.signTypedData(n.domain,n.types,n.message)}}:typeof t._signTypedData=="function"?{async signTypedData(n){return t._signTypedData(n.domain,n.types,n.message)}}:{}}}function V(o){return ut(o)?ue(o):mt(o)?qe(o):o}function $e(o){let e$1=e(o),t=[...e$1.privateJsonRPCUrl?[e$1.privateJsonRPCUrl]:[],...Array.isArray(e$1.publicJsonRPCUrl)?[...e$1.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var me={};function ft(o){if(!me[o]){let e$1=e(o);me[o]={id:o,name:e$1.label||`Chain ${o}`,nativeCurrency:e$1.nativeCurrency,rpcUrls:{default:{http:[$e(o)]}}};}return me[o]}async function ze(o,e){let t=$e(e),n=ft(e),a=await o.getAddress();return createWalletClient({account:a,chain:n,transport:custom({request:async s=>{if(s.method==="eth_accounts")return [a];if(s.method==="eth_sendTransaction"){let c=s.params?.[0]??{},{hash:p}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return p}if(s.method==="eth_signTypedData_v4"||s.method==="eth_signTypedData"){if(!o.signTypedData){let g=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(g.error)throw new Error(g.error.message);return g.result}let c=s.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let p=JSON.parse(c);return await o.signTypedData({domain:p.domain,types:p.types,primaryType:p.primaryType,message:p.message})}let r=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(r.error)throw new Error(r.error.message);return r.result}})})}var H=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let n=(await this.config.walletClient.getAddresses())[0];if(n)return n}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await ze(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?V(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:n,chainId:a}=e;if(t){if(!Ue.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of TESTNET_CHAIN_IDS`)}else if(n){if(!We.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!Ge.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,n)=>{this._getAccessTokenQueue.push({resolve:t,reject:n,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return fa$1("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let n=3600;if(t.expireAt){let a=Math.floor(Date.now()/1e3);n=t.expireAt-a,n<=0&&(fa$1("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return fa$1("\u274C Received empty accessToken"),null}catch(t){return ga$1("\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 K=class{constructor(e,t,n){this.configManager=e,this.utils=t,this.api=n;}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 n=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:n})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:n})).data}async addFavorite(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:n})).data}async removeFavorite(e,t){let n=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:n})).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:n}){let a=await Z(t);try{return {code:0,data:await a.read.getPoolInfo([e,n])}}catch(i){return {code:-1,message:i.message}}}};var Q=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async listPositions(e,t){let n=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:n??"",address:e,positionId:t})).data}}catch(a){return this.logger.error("Error fetching positions:",a),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:n,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:n,quoteToken:a,chainId:i,address:s}){this.configManager.getConfig();try{let r=await this.utils.getOraclePrice(e,i);if(!r)throw new Error("Failed to get price data");let c$1={poolId:e,oracleType:r.oracleType,publishTime:r.publishTime,oracleUpdateData:r?.vaa??"0"},p=!1;Number(n)>0&&(p=await this.utils.needsApproval(s,i,a,n,R$1(i).TRADING_ROUTER));let u=BigInt(0),g=BigInt(n)>0?BigInt(n):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:s}),h=m.code===0?m.data??0n:0n,x=BigInt(0);h<g&&(x=g-h,u=x);let I={token:a,amount:u.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let we=await U$1(i);if(p){let C=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:maxUint256.toString(),spenderAddress:R$1(i).TRADING_ROUTER});if(C.code!==0)throw new Error(C.message)}let se=await we.write.updatePriceAndAdjustCollateral([[c$1],I,t,n],{value:BigInt(r?.value??"1"),gas:BigInt(1e7)*c[i]/100n});return await f(i).waitForTransactionReceipt({hash:se}),{code:0,data:{hash:se},message:"Adjust collateral transaction submitted"}}catch(r){return {code:-1,message:r.message}}}};var bt={IOC:0},R=bt.IOC;var j={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},ma={NONE:0,GTE:1,LTE:2},S={INCREASE:0,DECREASE:1},ga={LONG:0,SHORT:1},ya={IOC:0},fa={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var J=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async createIncreaseOrder(e,t){try{let n=BigInt(e.collateralAmount)+BigInt(t),a=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=a.code===0?a.data??0n:0n,s=BigInt(0),d=n-i;d>BigInt(0)&&(s=d);let r={token:e.executionFeeToken,amount:s.toString()},c$1={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:S.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},p=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,R$1(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(p){let x=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(e.chainId).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let u=await U$1(e.chainId),g;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c$1,positionId:e.positionId});let x=await u.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...r},c$1]);g=await u.write.placeOrderWithPosition([e.positionId.toString(),{...r},c$1],{gasLimit:x*c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c$1,depositData:r});let I=await u.estimateGas.placeOrderWithSalt(["1",{...r},c$1]);g=await u.write.placeOrderWithSalt(["1",{...r},c$1],{gasLimit:I*c[e.chainId]/100n});}let m=await f(e.chainId).waitForTransactionReceipt({hash:g});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:g,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(n){return this.logger.error("Error placing order:",n),{code:-1,message:n?.message}}}async closeAllPositions(e,t){try{let n={token:"0x0000000000000000000000000000000000000000",amount:"0"},a=t.map(p=>p.positionId.toString()),i=t.map(p=>({user:p.address,poolId:p.poolId,orderType:p.orderType,triggerType:p.triggerType,operation:S.DECREASE,direction:p.direction,collateralAmount:p.collateralAmount,size:p.size,price:p.price,timeInForce:R,postOnly:p.postOnly,slippagePct:p.slippagePct,leverage:p.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",n,a,i),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let s=await U$1(e),d=await s.estimateGas.placeOrdersWithPosition([n,a,i]),r=await s.write.placeOrdersWithPosition([n,a,i],{gasLimit:d*c[e]/100n}),c$1=await f(e).waitForTransactionReceipt({hash:r});return {code:0,message:"close all positions success",transactionHash:r,blockNumber:c$1?.blockNumber,gasUsed:c$1?.gasUsed?.toString(),status:c$1?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c$1}}catch(n){return {code:-1,message:n?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},n=BigInt(e.collateralAmount),a=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),i=a.code===0?a.data??0n:0n,s=BigInt(0),d=n-i;d>BigInt(0)&&(s=d);let r={token:e.executionFeeToken,amount:s.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c$1=await U$1(e.chainId),p;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,r,{data:t}]);let m=await c$1.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,t]);p=await c$1.write.placeOrderWithPosition([e.positionId.toString(),r,t],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,r,{data:t}]);let h=await c$1.estimateGas.placeOrderWithSalt(["1",r,t]);p=await c$1.write.placeOrderWithSalt(["1",r,t],{gasLimit:h*c[e.chainId]/100n});}let u=await f(e.chainId).waitForTransactionReceipt({hash:p});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:p,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await U$1(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let r=[{user:e.address,poolId:e.poolId,orderType:j.STOP,triggerType:e.tpTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize??"0",price:e.tpPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},{user:e.address,poolId:e.poolId,orderType:j.STOP,triggerType:e.slTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c$1={token:"0x0000000000000000000000000000000000000000",amount:"0"},p;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],r]);p=await t.write.placeOrdersWithPosition([c$1,[e.positionId.toString(),e.positionId.toString()],r],{gasLimit:m*c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",r);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],r]);p=await t.write.placeOrdersWithSalt([c$1,[m.toString(),m.toString()],r],{gasLimit:h*c[e.chainId]/100n});}let u=await f(e.chainId).waitForTransactionReceipt({hash:p});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:p,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}let n={user:e.address,poolId:e.poolId,orderType:j.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:S.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},a={token:"0x0000000000000000000000000000000000000000",amount:"0"},i;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",n);let r=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),a,n]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),a,n],{gasLimit:r*c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",n);let r=1,c$1=await t.estimateGas.placeOrderWithSalt([r.toString(),a,n]);i=await t.write.placeOrderWithSalt([r.toString(),a,n],{gasLimit:c$1*c[e.chainId]/100n});}let s=await f(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(n){return {code:-1,message:n?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await U$1(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"cancel all orders success"}}catch(n){return {code:-1,message:n?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await U$1(t)).write.cancelOrder([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"cancel order success"}}catch(n){return {code:-1,message:n?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await(await U$1(t)).write.cancelOrders([e]);return await f(t).waitForTransactionReceipt({hash:a}),{code:0,message:"Orders canceled success"}}catch(n){return this.logger.error("Error canceling orders:",n),{code:-1,message:n?.message}}}async updateOrderTpSl(e,t,n,a,i,s){let d=await this.utils.getNetworkFee(i,n),r={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"}},c$1={token:t,amount:d.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let p=await U$1(n);this.logger.info("updateOrderTpSl params",r);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,d.toString(),R$1(n).TRADING_ROUTER)){let x=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:maxUint256.toString(),spenderAddress:R$1(n).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let g=await p.estimateGas.updateOrder([c$1,r]),m=await p.write.updateOrder([c$1,r],{gasLimit:g*c[n]/100n}),h=await f(n).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(u){return this.logger.error("Error updating order:",u),{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(n){return this.logger.error("Error fetching orders:",n),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:n,...e,address:t})).data}}};var He=[{type:"error",name:"AddressEmptyCode",inputs:[{type:"address",name:"target"}]},{type:"error",name:"ERC1967InvalidImplementation",inputs:[{type:"address",name:"implementation"}]},{type:"error",name:"ERC1967NonPayable",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InvalidInitialization",inputs:[]},{type:"error",name:"NotAddressManager",inputs:[]},{type:"error",name:"NotAllowedIdentifier",inputs:[]},{type:"error",name:"NotDependencyManager",inputs:[]},{type:"error",name:"NotInitializing",inputs:[]},{type:"error",name:"NotProxyAdmin",inputs:[]},{type:"error",name:"UUPSUnauthorizedCallContext",inputs:[]},{type:"error",name:"UUPSUnsupportedProxiableUUID",inputs:[{type:"bytes32",name:"slot"}]},{type:"event",anonymous:false,name:"BlockHeader",inputs:[{type:"uint256",name:"blockNumber",indexed:false},{type:"uint256",name:"blockTimestamp",indexed:false},{type:"uint256",name:"sequence",indexed:false}]},{type:"event",anonymous:false,name:"CollateralAccepted",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"quoteDebt",indexed:false},{type:"uint256",name:"baseCollateral",indexed:false},{type:"uint256",name:"quoteCollateral",indexed:false},{type:"uint256",name:"totalQuoteDebt",indexed:false},{type:"uint256",name:"totalBaseCollateral",indexed:false}]},{type:"event",anonymous:false,name:"CollateralAdjusted",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"beforeCollateralAmount",indexed:false},{type:"uint256",name:"afterCollateralAmount",indexed:false}]},{type:"event",anonymous:false,name:"EnterDispute",inputs:[{type:"bytes32",name:"poolId",indexed:false}]},{type:"event",anonymous:false,name:"Exchanged",inputs:[{type:"address",name:"user",indexed:false},{type:"address",name:"source",indexed:false},{type:"address",name:"target",indexed:false},{type:"uint256",name:"sourceAmount",indexed:false},{type:"uint256",name:"targetAmount",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"ExecutionMatched",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256[]",name:"triggerOrderIds",indexed:false},{type:"uint256[]",name:"matchedOrderIds",indexed:false},{type:"uint8",name:"matchType",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"ExitDispute",inputs:[{type:"bytes32",name:"poolId",indexed:false}]},{type:"event",anonymous:false,name:"FeeDistributed",inputs:[{type:"address",name:"user",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"int32",name:"tradingFeeRate",indexed:false},{type:"bool",name:"isMaker",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"uint256",name:"baseTradingFee",indexed:false},{type:"uint256",name:"brokerTradingFee",indexed:false},{type:"address",name:"broker",indexed:false},{type:"uint256",name:"referralRebate",indexed:false},{type:"uint256",name:"referrerRebate",indexed:false},{type:"address",name:"referrer",indexed:false},{type:"int256",name:"reserveFee",indexed:false}]},{type:"event",anonymous:false,name:"FundingRateUpdated",inputs:[{type:"uint64",name:"epochs",indexed:false},{type:"uint64",name:"duration",indexed:false},{type:"uint64",name:"previousEpochTime",indexed:false},{type:"uint64",name:"lastEpochTime",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"int256",name:"fundingRate",indexed:false},{type:"int256",name:"fundingRateTracker",indexed:false},{type:"uint256",name:"price",indexed:false}]},{type:"event",anonymous:false,name:"Initialized",inputs:[{type:"uint64",name:"version",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityLockUpdated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint64",name:"windowAnchor",indexed:false},{type:"uint256",name:"priceFloor",indexed:false},{type:"uint256",name:"priceCeiling",indexed:false},{type:"int256",name:"openInterest",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityMigrated",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"fromPoolId",indexed:false},{type:"bytes32",name:"toPoolId",indexed:false},{type:"uint256",name:"lpAmountIn",indexed:false},{type:"uint256",name:"lpAmountOut",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderCancelled",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"string",name:"reason",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderCreated",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint8",name:"poolType",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"uint256",name:"triggerPrice",indexed:false},{type:"uint8",name:"triggerType",indexed:false},{type:"uint256",name:"minQuoteOut",indexed:false}]},{type:"event",anonymous:false,name:"LiquidityStopOrderExecuted",inputs:[{type:"uint256",name:"orderId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"executor",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"MarketCreated",inputs:[{type:"bytes32",name:"marketId",indexed:false},{type:"address",name:"deployer",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint32",name:"baseReserveRatio",indexed:false},{type:"uint32",name:"quoteReserveRatio",indexed:false},{type:"uint64",name:"oracleFeeUsd",indexed:false},{type:"uint64",name:"oracleRefundFeeUsd",indexed:false},{type:"uint128",name:"poolPrimeThreshold",indexed:false}]},{type:"event",anonymous:false,name:"OrderCancelled",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"OrderFilled",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint8",name:"orderType",indexed:false},{type:"uint256",name:"orderSize",indexed:false},{type:"uint256",name:"fillSize",indexed:false},{type:"uint256",name:"filledSize",indexed:false},{type:"uint256",name:"orderPrice",indexed:false},{type:"uint256",name:"fillPrice",indexed:false},{type:"int256",name:"realizedPnl",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"int256",name:"fundingFee",indexed:false},{type:"uint256",name:"executionFeeAmount",indexed:false},{type:"address",name:"keeper",indexed:false}]},{type:"event",anonymous:false,name:"OrderMarkedADL",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"available",indexed:false},{type:"uint256",name:"requested",indexed:false}]},{type:"event",anonymous:false,name:"OrderPlaced",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint8",name:"orderType",indexed:false},{type:"uint8",name:"operation",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint8",name:"triggerType",indexed:false},{type:"uint256",name:"collateralAmount",indexed:false},{type:"uint256",name:"size",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint8",name:"tif",indexed:false},{type:"bool",name:"postOnly",indexed:false},{type:"uint16",name:"slippagePct",indexed:false},{type:"uint256",name:"executionFeeAmount",indexed:false},{type:"uint16",name:"userLeverage",indexed:false}]},{type:"event",anonymous:false,name:"OrderUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"size",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint256",name:"tpSize",indexed:false},{type:"uint256",name:"tpPrice",indexed:false},{type:"uint256",name:"slSize",indexed:false},{type:"uint256",name:"slPrice",indexed:false}]},{type:"event",anonymous:false,name:"PoolActivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint8",name:"oracleType",indexed:false},{type:"bytes32",name:"oracleFeedId",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeactivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeployed",inputs:[{type:"bytes32",name:"marketId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"deployer",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"address",name:"basePoolToken",indexed:false},{type:"address",name:"quotePoolToken",indexed:false}]},{type:"event",anonymous:false,name:"PoolDeposited",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"address",name:"underlyingToken",indexed:false},{type:"address",name:"poolToken",indexed:false},{type:"uint256",name:"underlyingIn",indexed:false},{type:"uint256",name:"poolTokenOut",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"exchangeRate",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"PoolFundDistributed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"profits",indexed:false},{type:"uint256",name:"genesisProfits",indexed:false},{type:"uint256",name:"basePoolAmount",indexed:false},{type:"uint256",name:"quotePoolAmount",indexed:false},{type:"uint256",name:"genesisBasePoolAmount",indexed:false},{type:"uint256",name:"genesisQuotePoolAmount",indexed:false},{type:"uint256",name:"exchangedBaseFromProfits",indexed:false},{type:"uint256",name:"exchangedBaseAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolFundingFeeSettled",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"int256",name:"prevFundingRateTracker",indexed:false},{type:"int256",name:"nextFundingRateTracker",indexed:false},{type:"uint256",name:"price",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"fundingFee",indexed:false}]},{type:"event",anonymous:false,name:"PoolPreDeactivated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"string",name:"remark",indexed:false}]},{type:"event",anonymous:false,name:"PoolPrimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint256",name:"baseAmount",indexed:false},{type:"uint256",name:"quoteAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolRebateClaimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"PoolRefunded",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"receiver",indexed:false},{type:"address",name:"baseToken",indexed:false},{type:"address",name:"quoteToken",indexed:false},{type:"uint256",name:"baseAmount",indexed:false},{type:"uint256",name:"quoteAmount",indexed:false}]},{type:"event",anonymous:false,name:"PoolReprimed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"primer",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"PoolSettlementRecorded",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"poolEntryPrice",indexed:false},{type:"int256",name:"realizedPnl",indexed:false}]},{type:"event",anonymous:false,name:"PoolWithdrawn",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"user",indexed:false},{type:"address",name:"recipient",indexed:false},{type:"address",name:"underlyingToken",indexed:false},{type:"address",name:"poolToken",indexed:false},{type:"uint256",name:"poolTokenIn",indexed:false},{type:"uint256",name:"underlyingOut",indexed:false},{type:"uint256",name:"rebateOut",indexed:false},{type:"uint256",name:"oraclePrice",indexed:false},{type:"uint256",name:"exchangeRate",indexed:false},{type:"uint256",name:"poolTokenPrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionEarlyClosed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"executeSize",indexed:false},{type:"uint256",name:"executePrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionForceClosed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"executePrice",indexed:false},{type:"string",name:"reason",indexed:false}]},{type:"event",anonymous:false,name:"PositionLiquidated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"positionSize",indexed:false},{type:"uint256",name:"liquidationSize",indexed:false},{type:"uint256",name:"liquidationPrice",indexed:false}]},{type:"event",anonymous:false,name:"PositionNFTMinted",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"oldPositionId",indexed:false},{type:"bytes32",name:"newPositionId",indexed:false},{type:"uint256",name:"tokenId",indexed:false},{type:"address",name:"owner",indexed:false},{type:"address",name:"recipient",indexed:false}]},{type:"event",anonymous:false,name:"PositionRiskControlDataMigrated",inputs:[{type:"bytes32",name:"from",indexed:false},{type:"bytes32",name:"to",indexed:false}]},{type:"event",anonymous:false,name:"PositionRiskControlDataUpdated",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"uint256",name:"freeAmount",indexed:false},{type:"uint256",name:"lockedAmount",indexed:false}]},{type:"event",anonymous:false,name:"PositionTransfer",inputs:[{type:"address",name:"from",indexed:false},{type:"address",name:"to",indexed:false},{type:"bytes32",name:"positionId",indexed:false}]},{type:"event",anonymous:false,name:"PositionUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"owner",indexed:false},{type:"bytes32",name:"positionId",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint8",name:"direction",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"uint256",name:"beforeSize",indexed:false},{type:"uint256",name:"afterSize",indexed:false},{type:"uint256",name:"beforeCollateralAmount",indexed:false},{type:"uint256",name:"afterCollateralAmount",indexed:false},{type:"uint256",name:"entryPrice",indexed:false},{type:"int256",name:"fundingRateIndex",indexed:false},{type:"uint8",name:"riskTier",indexed:false},{type:"uint256",name:"earlyClosePrice",indexed:false}]},{type:"event",anonymous:false,name:"ReferralRebateClaimed",inputs:[{type:"address",name:"user",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false}]},{type:"event",anonymous:false,name:"ReserveRebateCollected",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"address",name:"keeper",indexed:false},{type:"uint256",name:"poolAmount",indexed:false},{type:"uint256",name:"stakingAmount",indexed:false},{type:"uint256",name:"keeperAmount",indexed:false},{type:"uint256",name:"treasuryAmount",indexed:false},{type:"uint256",name:"reservedAmount",indexed:false},{type:"uint256",name:"ecoFundAmount",indexed:false}]},{type:"event",anonymous:false,name:"ReserveRebateDisbursed",inputs:[{type:"bytes32",name:"poolId",indexed:false},{type:"address",name:"token",indexed:false},{type:"uint256",name:"amount",indexed:false},{type:"address",name:"keeper",indexed:false},{type:"uint256",name:"poolAmount",indexed:false},{type:"uint256",name:"stakingAmount",indexed:false},{type:"uint256",name:"keeperAmount",indexed:false},{type:"uint256",name:"treasuryAmount",indexed:false},{type:"uint256",name:"reservedAmount",indexed:false},{type:"uint256",name:"ecoFundAmount",indexed:false}]},{type:"event",anonymous:false,name:"TradingFeeTierUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"uint8",name:"feeType",indexed:false},{type:"uint8",name:"tier",indexed:false},{type:"uint32",name:"takerFeeRate",indexed:false},{type:"int32",name:"makerFeeRate",indexed:false},{type:"bool",name:"isEnabled",indexed:false}]},{type:"event",anonymous:false,name:"Upgraded",inputs:[{type:"address",name:"implementation",indexed:true}]},{type:"event",anonymous:false,name:"UserFeeDataUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"signer",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint8",name:"tier",indexed:false},{type:"address",name:"referrer",indexed:false},{type:"uint32",name:"totalReferralRebatePct",indexed:false},{type:"uint32",name:"referrerRebatePct",indexed:false}]},{type:"event",anonymous:false,name:"UserSettlementRecorded",inputs:[{type:"address",name:"user",indexed:false},{type:"bytes32",name:"poolId",indexed:false},{type:"uint256",name:"orderId",indexed:false},{type:"int256",name:"charge",indexed:false},{type:"int256",name:"realizedPnl",indexed:false},{type:"int256",name:"tradingFee",indexed:false},{type:"int256",name:"fundingFee",indexed:false}]},{type:"event",anonymous:false,name:"UserSpecialFeeTierUpdated",inputs:[{type:"address",name:"broker",indexed:false},{type:"address",name:"user",indexed:false},{type:"uint8",name:"oldTier",indexed:false},{type:"uint8",name:"newTier",indexed:false}]},{type:"function",name:"UPGRADE_INTERFACE_VERSION",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"string"}]},{type:"function",name:"emitCollateralAccepted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"quoteDebt"},{type:"uint256",name:"baseCollateral"},{type:"uint256",name:"quoteCollateral"},{type:"uint256",name:"totalQuoteDebt"},{type:"uint256",name:"totalBaseCollateral"}]}],outputs:[]},{type:"function",name:"emitCollateralAdjusted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint8",name:"direction"},{type:"uint256",name:"beforeCollateralAmount"},{type:"uint256",name:"afterCollateralAmount"}]}],outputs:[]},{type:"function",name:"emitEnterDispute",constant:false,payable:false,inputs:[{type:"bytes32",name:"poolId"}],outputs:[]},{type:"function",name:"emitExchanged",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"address",name:"source"},{type:"address",name:"target"},{type:"uint256",name:"sourceAmount"},{type:"uint256",name:"targetAmount"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitExecutionMatched",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256[]",name:"triggerOrderIds"},{type:"uint256[]",name:"matchedOrderIds"},{type:"uint8",name:"matchType"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitExitDispute",constant:false,payable:false,inputs:[{type:"bytes32",name:"poolId"}],outputs:[]},{type:"function",name:"emitFundingRateUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint64",name:"epochs"},{type:"uint64",name:"duration"},{type:"uint64",name:"previousEpochTime"},{type:"uint64",name:"lastEpochTime"},{type:"bytes32",name:"poolId"},{type:"int256",name:"fundingRate"},{type:"int256",name:"fundingRateTracker"},{type:"uint256",name:"price"}]}],outputs:[]},{type:"function",name:"emitLiquidityLockUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint64",name:"windowAnchor"},{type:"uint256",name:"priceFloor"},{type:"uint256",name:"priceCeiling"},{type:"int256",name:"openInterest"}]}],outputs:[]},{type:"function",name:"emitLiquidityMigrated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"fromPoolId"},{type:"bytes32",name:"toPoolId"},{type:"uint256",name:"lpAmountIn"},{type:"uint256",name:"lpAmountOut"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderCancelled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"bytes32",name:"poolId"},{type:"string",name:"reason"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderCreated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint8",name:"poolType"},{type:"uint256",name:"amount"},{type:"uint256",name:"triggerPrice"},{type:"uint8",name:"triggerType"},{type:"uint256",name:"minQuoteOut"}]}],outputs:[]},{type:"function",name:"emitLiquidityStopOrderExecuted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"uint256",name:"orderId"},{type:"bytes32",name:"poolId"},{type:"address",name:"executor"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitMarketCreated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"marketId"},{type:"address",name:"deployer"},{type:"address",name:"quoteToken"},{type:"uint32",name:"baseReserveRatio"},{type:"uint32",name:"quoteReserveRatio"},{type:"uint64",name:"oracleFeeUsd"},{type:"uint64",name:"oracleRefundFeeUsd"},{type:"uint128",name:"poolPrimeThreshold"}]}],outputs:[]},{type:"function",name:"emitOrderCancelled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitOrderFilled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint8",name:"orderType"},{type:"uint256",name:"orderSize"},{type:"uint256",name:"fillSize"},{type:"uint256",name:"filledSize"},{type:"uint256",name:"orderPrice"},{type:"uint256",name:"fillPrice"},{type:"int256",name:"realizedPnl"},{type:"int256",name:"tradingFee"},{type:"int256",name:"fundingFee"},{type:"uint256",name:"executionFeeAmount"},{type:"address",name:"keeper"}]}],outputs:[]},{type:"function",name:"emitOrderMarkedADL",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"available"},{type:"uint256",name:"requested"}]}],outputs:[]},{type:"function",name:"emitOrderPlaced",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint8",name:"orderType"},{type:"uint8",name:"operation"},{type:"uint8",name:"direction"},{type:"uint8",name:"triggerType"},{type:"uint256",name:"collateralAmount"},{type:"uint256",name:"size"},{type:"uint256",name:"price"},{type:"uint8",name:"tif"},{type:"bool",name:"postOnly"},{type:"uint16",name:"slippagePct"},{type:"uint256",name:"executionFeeAmount"},{type:"uint16",name:"userLeverage"}]}],outputs:[]},{type:"function",name:"emitOrderUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"size"},{type:"uint256",name:"price"},{type:"uint256",name:"tpSize"},{type:"uint256",name:"tpPrice"},{type:"uint256",name:"slSize"},{type:"uint256",name:"slPrice"}]}],outputs:[]},{type:"function",name:"emitPoolActivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint8",name:"oracleType"},{type:"bytes32",name:"oracleFeedId"}]}],outputs:[]},{type:"function",name:"emitPoolDeactivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitPoolDeployed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"marketId"},{type:"bytes32",name:"poolId"},{type:"address",name:"deployer"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"address",name:"basePoolToken"},{type:"address",name:"quotePoolToken"}]}],outputs:[]},{type:"function",name:"emitPoolDeposited",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"address",name:"underlyingToken"},{type:"address",name:"poolToken"},{type:"uint256",name:"underlyingIn"},{type:"uint256",name:"poolTokenOut"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"exchangeRate"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitPoolFundDistributed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"profits"},{type:"uint256",name:"genesisProfits"},{type:"uint256",name:"basePoolAmount"},{type:"uint256",name:"quotePoolAmount"},{type:"uint256",name:"genesisBasePoolAmount"},{type:"uint256",name:"genesisQuotePoolAmount"},{type:"uint256",name:"exchangedBaseFromProfits"},{type:"uint256",name:"exchangedBaseAmount"}]}],outputs:[]},{type:"function",name:"emitPoolFundingFeeSettled",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"int256",name:"prevFundingRateTracker"},{type:"int256",name:"nextFundingRateTracker"},{type:"uint256",name:"price"},{type:"uint8",name:"direction"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"fundingFee"}]}],outputs:[]},{type:"function",name:"emitPoolPreDeactivated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"string",name:"remark"}]}],outputs:[]},{type:"function",name:"emitPoolPrimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint256",name:"baseAmount"},{type:"uint256",name:"quoteAmount"}]}],outputs:[]},{type:"function",name:"emitPoolRebateClaimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitPoolRefunded",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"receiver"},{type:"address",name:"baseToken"},{type:"address",name:"quoteToken"},{type:"uint256",name:"baseAmount"},{type:"uint256",name:"quoteAmount"}]}],outputs:[]},{type:"function",name:"emitPoolReprimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"primer"},{type:"address",name:"token"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitPoolSettlementRecorded",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"poolEntryPrice"},{type:"int256",name:"realizedPnl"}]}],outputs:[]},{type:"function",name:"emitPoolWithdrawn",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"user"},{type:"address",name:"recipient"},{type:"address",name:"underlyingToken"},{type:"address",name:"poolToken"},{type:"uint256",name:"poolTokenIn"},{type:"uint256",name:"underlyingOut"},{type:"uint256",name:"rebateOut"},{type:"uint256",name:"oraclePrice"},{type:"uint256",name:"exchangeRate"},{type:"uint256",name:"poolTokenPrice"}]}],outputs:[]},{type:"function",name:"emitPositionEarlyClosed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"executeSize"},{type:"uint256",name:"executePrice"}]}],outputs:[]},{type:"function",name:"emitPositionForceClosed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"executePrice"},{type:"string",name:"reason"}]}],outputs:[]},{type:"function",name:"emitPositionLiquidated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"orderId"},{type:"uint256",name:"positionSize"},{type:"uint256",name:"liquidationSize"},{type:"uint256",name:"liquidationPrice"}]}],outputs:[]},{type:"function",name:"emitPositionNFTMinted",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"bytes32",name:"oldPositionId"},{type:"bytes32",name:"newPositionId"},{type:"uint256",name:"tokenId"},{type:"address",name:"owner"},{type:"address",name:"recipient"}]}],outputs:[]},{type:"function",name:"emitPositionRiskControlDataMigrated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"from"},{type:"bytes32",name:"to"}]}],outputs:[]},{type:"function",name:"emitPositionRiskControlDataUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"bytes32",name:"positionId"},{type:"uint256",name:"freeAmount"},{type:"uint256",name:"lockedAmount"}]}],outputs:[]},{type:"function",name:"emitPositionTransfer",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"from"},{type:"address",name:"to"},{type:"bytes32",name:"positionId"}]}],outputs:[]},{type:"function",name:"emitPositionUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"owner"},{type:"bytes32",name:"positionId"},{type:"bytes32",name:"poolId"},{type:"uint8",name:"direction"},{type:"uint256",name:"orderId"},{type:"uint256",name:"beforeSize"},{type:"uint256",name:"afterSize"},{type:"uint256",name:"beforeCollateralAmount"},{type:"uint256",name:"afterCollateralAmount"},{type:"uint256",name:"entryPrice"},{type:"int256",name:"fundingRateIndex"},{type:"uint8",name:"riskTier"},{type:"uint256",name:"earlyClosePrice"}]}],outputs:[]},{type:"function",name:"emitReferralRebateClaimed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"address",name:"token"},{type:"uint256",name:"amount"}]}],outputs:[]},{type:"function",name:"emitReserveRebateCollected",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"token"},{type:"uint256",name:"amount"},{type:"address",name:"keeper"},{type:"uint256",name:"poolAmount"},{type:"uint256",name:"stakingAmount"},{type:"uint256",name:"keeperAmount"},{type:"uint256",name:"treasuryAmount"},{type:"uint256",name:"reservedAmount"},{type:"uint256",name:"ecoFundAmount"}]}],outputs:[]},{type:"function",name:"emitReserveRebateDisbursed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"bytes32",name:"poolId"},{type:"address",name:"token"},{type:"uint256",name:"amount"},{type:"address",name:"keeper"},{type:"uint256",name:"poolAmount"},{type:"uint256",name:"stakingAmount"},{type:"uint256",name:"keeperAmount"},{type:"uint256",name:"treasuryAmount"},{type:"uint256",name:"reservedAmount"},{type:"uint256",name:"ecoFundAmount"}]}],outputs:[]},{type:"function",name:"emitTradingFeeTierUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"uint8",name:"feeType"},{type:"uint8",name:"tier"},{type:"uint32",name:"takerFeeRate"},{type:"int32",name:"makerFeeRate"},{type:"bool",name:"isEnabled"}]}],outputs:[]},{type:"function",name:"emitUserFeeDataUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"signer"},{type:"address",name:"user"},{type:"uint8",name:"tier"},{type:"address",name:"referrer"},{type:"uint32",name:"totalReferralRebatePct"},{type:"uint32",name:"referrerRebatePct"}]}],outputs:[]},{type:"function",name:"emitUserFeeSettlementAndDistributed",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"user"},{type:"bytes32",name:"poolId"},{type:"uint256",name:"orderId"},{type:"int256",name:"charge"},{type:"int256",name:"realizedPnl"},{type:"int256",name:"tradingFee"},{type:"int256",name:"fundingFee"},{type:"int32",name:"tradingFeeRate"},{type:"bool",name:"isMaker"},{type:"uint256",name:"baseTradingFee"},{type:"uint256",name:"brokerTradingFee"},{type:"address",name:"broker"},{type:"uint256",name:"referralRebate"},{type:"uint256",name:"referrerRebate"},{type:"address",name:"referrer"},{type:"int256",name:"reserveFee"}]}],outputs:[]},{type:"function",name:"emitUserSpecialFeeTierUpdated",constant:false,payable:false,inputs:[{type:"tuple",name:"params",components:[{type:"address",name:"broker"},{type:"address",name:"user"},{type:"uint8",name:"oldTier"},{type:"uint8",name:"newTier"}]}],outputs:[]},{type:"function",name:"getAddressManager",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"address"}]},{type:"function",name:"getDependencyAddress",constant:true,stateMutability:"view",payable:false,inputs:[{type:"bytes32",name:"identifier"}],outputs:[{type:"address"}]},{type:"function",name:"getImplementation",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"address"}]},{type:"function",name:"initialize",constant:false,payable:false,inputs:[{type:"address",name:"addressManager"}],outputs:[]},{type:"function",name:"isBlockHeaderEmitted",constant:true,stateMutability:"view",payable:false,inputs:[{type:"uint256",name:"blockNumber"}],outputs:[{type:"bool"}]},{type:"function",name:"proxiableUUID",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"registerContract",constant:false,payable:false,inputs:[{type:"bytes32[]",name:"identifiers"}],outputs:[]},{type:"function",name:"sequencer",constant:true,stateMutability:"view",payable:false,inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"upgradeTo",constant:false,stateMutability:"payable",payable:true,inputs:[{type:"address",name:"newImplementation"},{type:"bytes",name:"data"}],outputs:[]},{type:"function",name:"upgradeToAndCall",constant:false,stateMutability:"payable",payable:true,inputs:[{type:"address",name:"newImplementation"},{type:"bytes",name:"data"}],outputs:[]}];var ge={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var Y=class{constructor(e,t){this.configManager=e,this.logger=t;}getOrderIdFromTransaction(e){if(!e||!e.logs)return null;for(let t=0;t<e.logs.length;t++){let n=e.logs[t];this.logger.info(`Log ${t}:`,{address:n.address,topics:n.topics,data:n.data});try{let a=decodeEventLog({abi:He,data:n.data??"0x",topics:n.topics??[]}),i=a.args;if(a.eventName==="OrderPlaced"&&i?.orderId!=null)return String(i.orderId)}catch{continue}}return null}async getApproveQuoteAmount(e,t,n,a){try{if(!n||typeof n=="string"&&!n.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let i=a??R$1(t).Account,d=await T(t,n).read.allowance([e,i]);return {code:0,data:String(d)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await ia(i)}}async needsApproval(e,t,n,a,i){try{let d=(await this.getApproveQuoteAmount(e,t,n,i)).data,r=BigInt(d),c=BigInt(a);return r<c}catch(s){return this.logger.error("Error checking approval needs:",s),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:n,spenderAddress:a}){try{let i=await V$1(e,t),s=n??maxUint256,d=a??R$1(e).Account,r=await this.getGasPriceByRatio(),c=await i.write.approve([d,s],{gasPrice:r});return await f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(i){return this.logger.error("Approval error:",i),{code:-1,message:i?.message}}}async getUserTradingFeeRate(e,t,n,a){let s=this.configManager.getConfig().brokerAddress;try{let d=X$1(n,s),r=a??await this.configManager.getSignerAddress(n),c=await d.read.getUserFeeRate([r,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(d){return this.logger.error("Error getting user trading fee rate:",d),{code:-1,message:d?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await Y$1(t,0)).read.getExecutionFee([e])).toString()}catch(n){return this.logger.error("Error getting network fee:",n),"0"}}async getOraclePrice(e,t){try{let n=await sa(t,e);if(!n)throw new Error("Failed to get price data");return n}catch(n){throw this.logger.error("Error getting oracle price:",n),n}}async buildUpdatePriceParams(e,t){let n=await this.getOraclePrice(e,t);if(!n)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:n.vaa,publishTime:n.publishTime,oracleType:n.oracleType,value:n.value,price:n.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let n=await ia(e);return n?n.error:JSON.stringify(e)}catch(n){return n?.message??n?.toString()??t}}async checkSeamlessGas(e,t,n){let i=await(await Y$1(t,0)).read.getForwardFeeByToken([n]),d=await T(t,n).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(d)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:n}){try{return {code:0,data:await(await Z(e,0)).read.getPoolInfo([t,n])}}catch(a){return this.logger.error("Error getting pool info:",a),{code:-1,message:a?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let n=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);n&&n[1]&&(t=n[1]);}if(t){let n=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(n){let a=Object.keys(ge).find(i=>i.toLowerCase()===n);if(a)return ge[a]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await oa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=d[t];return na(e,n?.gasLimitRatio??1.3)}};var X=class{constructor(e,t,n,a){this.configManager=e,this.logger=t,this.utils=n,this.client=a;}async withRetry(e,t=3,n=300){let a;for(let i=0;i<t;i++)try{return await e()}catch(s){a=s,i<t-1&&await new Promise(d=>setTimeout(d,n));}throw a}async getTradeFlow(e,t){let n=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:n,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:n}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=T(e,n),i=await this.configManager.getSignerAddress(e);return {code:0,data:await a.read.balanceOf([t||i])}}async updateAndWithdraw(e,t,n,a,i){try{let d=await(await _(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await f(i).waitForTransactionReceipt({hash:d})}}catch(s){return {code:-1,message:s.message}}}async deposit({amount:e,tokenAddress:t,chainId:n}){let a=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"",i=R$1(n);try{if(await this.utils.needsApproval(a,n,t,e,i.Account)){let p=await this.utils.approveAuthorization({chainId:n,quoteAddress:t,amount:maxUint256.toString(),spenderAddress:i.Account});if(p.code!==0)throw new Error(p.message)}let r=await(await _(n)).write.deposit([a,t,e]);return {code:0,data:await f(n).waitForTransactionReceipt({hash:r})}}catch(s){return {code:-1,message:s.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:n}){try{let a=await this.getAccountInfo(t,n,e);if(a.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let i=await this.client.appeal.getAppealStatus(e,t,n),s=a.data,d=BigInt(s?.quoteProfit??0),r=BigInt(s?.freeMargin??0),c=BigInt(s?.lockedMargin??0),p=i?.code===0?i.data:null,u=p?.status===1?BigInt(p?.lockedMargin??0):0n;return {code:0,data:r+d-c-u}}catch(a){return {code:-1,message:a.message}}}async getAccountInfo(e,t,n){let a=await Z(e);try{return {code:0,data:await a.read.getAccountInfo([n,t])}}catch(i){return {code:-1,message:i.message}}}async getAccountVipInfo(e,t){let n=this.configManager.getConfig(),a=X$1(e,n.brokerAddress),s=await f(e).getBlock({blockTag:"latest"}),d=Number(s?.timestamp??BigInt(xe().unix()))+300;try{let r=await this.getCurrentFeeDataEpoch(e);this.logger.debug("setUserFeeDataEpoch-->",r);let c=await a.read.userFeeData([r,t]),p;try{p=await this.withRetry(()=>a.read.userNonces([t]));}catch{p=0n;}return {code:0,data:{...c,nonce:p.toString(),deadline:d}}}catch(r){return {code:-1,message:r.message}}}async getAccountVipInfoByBackend(e,t,n,a){let i=await this.configManager.getAccessToken()??"";try{let s=await this.client.api.getAccountVipInfo({address:e,accessToken:i,chainId:t,deadline:n,nonce:a});if(s.code!==9200)throw new l("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 getCurrentFeeDataEpoch(e){let t=this.configManager.getConfig();return await(await X$1(e,t.brokerAddress)).read.currentFeeDataEpoch()}async setUserFeeData(e,t,n,a,i){let s=this.configManager.getConfig();if(n<xe().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let d=await W$1(t,s.brokerAddress),r=await this.getCurrentFeeDataEpoch(t),c={user:e,nonce:a.nonce,deadline:n,feeDataEpoch:r.toString(),feeData:{tier:a.tier,referrer:a.referrer||zeroAddress,totalReferralRebatePct:a.totalReferralRebatePct,referrerRebatePct:a.referrerRebatePct},signature:i},p=await d.read.userNonces([e]);if(parseInt(p.toString())+1!==parseInt(a.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let u=await d.write.setUserFeeData([c]);return {code:0,data:await f(t).waitForTransactionReceipt({hash:u})}}catch(d){return {code:-1,message:d.message}}}};function je(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Tt(o,e){return je(e,o[e])}function kt(o,e){return o[e].map(n=>je(e,n)).join("&")}function Ct(o){let e=o||{};return Object.keys(e).filter(n=>typeof e[n]<"u").map(n=>Array.isArray(e[n])?kt(e,n):Tt(e,n)).join("&")}function ye(o){let e=Ct(o);return e?`?${e}`:""}var ee=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",n=await this.configManager.getSignerAddress(e.chainId);if(!n)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:n}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:n$1=false,...a}={}){let i=n$1?await this.buildAuthParams():{};return n.get(this.buildRequestPath(e),t,merge(i,a))}async post(e,t,{auth:n$1=false,...a}={}){let i=n$1?await this.buildAuthParams():{};return n.post(this.buildRequestPath(e),t,merge(i,a))}async put(e,t,{auth:n$1=false,...a}={}){let i=n$1?await this.buildAuthParams():{};return n.put(this.buildRequestPath(e),t,merge(i,a))}async delete(e,{auth:t=false,...n$1}={}){let a=t?await this.buildAuthParams():{};return n.delete(this.buildRequestPath(e),merge(a,n$1))}};var te=class extends ee{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n$1,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await n.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return n.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return n.get(`${this.getHost()}/openapi/gateway/quote/price/oracles`,{chainId:e,poolIds:t.join(",")});throw new Error("Invalid pool id")}async getPoolDetail(e,t){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${ye({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,positionId:n$1}){return await n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,{positionId:n$1},{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t){return await n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,n$1){return await n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${n$1}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:n$1,limit:a,interval:i}){return n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n$1,limit:a,interval:i})}async getKlineLatestBar(e){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,n$1,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,n$1,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async removeFavorite({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,n$1,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,n$1,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,n$1,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n$1,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n$1,deadline:a,nonce:i}){return n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:n$1,deadline:a,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:n$1}){return n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:n$1},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:n$1,accessToken:a}){return n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:n$1,myx_openapi_access_token:a}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},St=2;function Et(o){let e=hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=toHex(e.slice(0,32)),n=toHex(e.slice(32,64));return {v:e[64],r:t,s:n}}async function Mt(o,e,t,n,a,i,s,d){let r=T(e,t),c=await Je(r),[p]=await o.getAddresses();if(!p)throw new l("INVALID_SIGNER","No account for signPermit");let u={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},g={owner:n,spender:a,value:i,nonce:s,deadline:d},m=await o.signTypedData({account:p,domain:{...c,chainId:c.chainId},types:u,primaryType:"Permit",message:g});return Et(m)}var ne=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async onCheckRelayer(e,t,n,a){let s=await(await $$1(n)).read.isUserRelayerEnabled([e,t]),d=await this.utils.needsApproval(e,n,a,maxUint256.toString(),R$1(n).TRADING_ROUTER);return s&&!d}async getContractAbiAndAddressByFunctionName(e,t){let n=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],a=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return n.includes(e)?{abi:S$1,address:R$1(t).TRADING_ROUTER}:i.includes(e)?{abi:m,address:R$1(t).Account}:(console.log("functionName==>",e),console.log("brokerFunctions.includes(functionName)->",a.includes(e)),a.includes(e)?{abi:j$1,address:this.configManager.getConfig().brokerAddress}:{abi:S$1,address:R$1(t).TRADING_ROUTER})}async getUSDPermitParams(e,t,n){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let a=await i(t),i$1=R$1(t),[s]=await a.getAddresses();if(!s)throw new l("INVALID_SIGNER","No account");let d=T(t,n);try{let r=await d.read.nonces([s]),c=await Mt(a,t,n,s,i$1.TRADING_ROUTER,maxUint256,r,e);return [{token:n,owner:s,spender:i$1.TRADING_ROUTER,value:maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch{throw new l("INVALID_PRIVATE_KEY","Invalid private key generated")}}async getForwardEip712Domain(e){let n=await(await $$1(e)).read.eip712Domain();return {name:n[1],version:n[2],chainId:n[3],verifyingContract:n[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:n,forwardFeeToken:a,functionName:i,orderParams:s,value:d="0",gas:r="800000"}){let c=await(await $$1(e)).read.nonces([t]),p=xe().add(60,"minute").unix(),u=await this.getForwardEip712Domain(e),{abi:g,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),h=encodeFunctionData({abi:g,functionName:i,args:s}),x=await n({domain:u,functionHash:h,to:m,nonce:c.toString(),deadline:p}),I=await this.api.forwarderTxApi({from:t,to:m,value:d??"0",gas:r,nonce:c.toString(),data:h,deadline:p,signature:x,forwardFeeToken:a},e);if(I.data?.txHash){for(let C=0;C<5;C++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};C<4&&await new Promise(re=>setTimeout(re,1e3));}catch(Ae){this.logger.error("Poll transaction from chain error:",Ae),C<4&&await new Promise(re=>setTimeout(re,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:n,gas:a,deadline:i$1,data:s,nonce:d,forwardFeeToken:r},c){let p=await this.getForwardEip712Domain(c),u=await i(c),[g]=await u.getAddresses();if(!g)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await u.signTypedData({account:g,domain:p,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(n??"0"),gas:BigInt(a),nonce:BigInt(d),deadline:BigInt(i$1),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:n,gas:a,nonce:d,data:s,deadline:i$1,signature:m,forwardFeeToken:r},c)}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:n,forwardFeeToken:a}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:n,address:i,tokenAddress:a})).data,x=await(await Y$1(n)).read.getForwardFeeByToken([a]),I=BigInt(x)*BigInt(St);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}let s=xe().add(60,"minute").unix(),d=[];if(e)try{d=await this.getUSDPermitParams(s,n,a);}catch(g){this.logger.warn("Failed to get USD permit params, proceeding without permit:",g),d=[];}let r=await $$1(n,1),c=await(await $$1(n)).read.nonces([i]),p=encodeFunctionData({abi:k,functionName:"permitAndApproveForwarder",args:[t,e,d]}),u=await this.forwarderTx({from:i,to:r.address,value:"0",gas:"800000",nonce:c.toString(),data:p,deadline:s,forwardFeeToken:a},n);if(u.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:u.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(x){this.logger.error("Poll transaction from chain error:",x),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await $$1(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:n,functionName:a,data:i,seamlessAddress:s}){if(!e||!isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!s||!isAddress(s))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!n||!isAddress(n))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(i))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,n))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let r=await $$1(t),c,{abi:p,address:u}=await this.getContractAbiAndAddressByFunctionName(a,t);try{c=encodeFunctionData({abi:p,functionName:a,args:i});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(a)}: ${m.message}. Check args shape and that no address field is undefined.`)}let g=await r.read.nonces([s]);return {from:s,to:u,value:"0",gas:"800000",deadline:xe().add(60,"minute").unix(),data:c,nonce:g.toString(),forwardFeeToken:n}}};var M=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return R$1(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return X$1(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends M{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let n=t==="DisputeFiled"?"caseId":"appealCaseId";for(let a of e.logs)try{let i=decodeEventLog({abi:l$1,data:a.data,topics:a.topics});if(i.eventName===t&&i.args&&n in i.args)return i.args[n]}catch{continue}return null}async submitAppeal(e,t,n){let a=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",i=await this.client.utils.needsApproval(a,this.config.chainId,t,n,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 s=await this.getDisputeCourtContract(),d=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),r=BigInt(d[0].value.toString()||"1"),c=await s.estimateGas.fileDispute([d,e,t],{value:r}),p=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),g=await s.write.fileDispute([d,e,t],{value:r,gasLimit:p,gasPrice:u}),m=await f(this.config.chainId).waitForTransactionReceipt({hash:g}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:n,deadline:a,v:i,r:s,s:d}){let r=await this.getDisputeCourtContract(),c=await r.estimateGas.vote([e,t,n?1:0,a,i,s,d]),p=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),g=await r.write.vote([e,t,n?1:0,a,i,s,d],{gasLimit:p,gasPrice:u});return await f(this.config.chainId).waitForTransactionReceipt({hash:g})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),n=await t.estimateGas.claimBond([e]),a=await this.client.utils.getGasLimitByRatio(n),i=await this.client.utils.getGasPriceByRatio(),s=await t.write.claimBond([e],{gasLimit:a,gasPrice:i});return f(this.config.chainId).waitForTransactionReceipt({hash:s})}async claimReimbursement(e,t,n,a){let i=await this.getReimbursementContract(),s=await i.estimateGas.claimReimbursement([e,t,n,a]),d=await this.client.utils.getGasLimitByRatio(s),r=await this.client.utils.getGasPriceByRatio(),c=await i.write.claimReimbursement([e,t,n,a],{gasLimit:d,gasPrice:r});return f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,n){let a=await this.getDisputeCourtContract(),i=await this.client.utils.getGasPriceByRatio(),s=await this.client.utils.getGasLimitByRatio(await a.estimateGas.fileDisputeFromStaker([e,t,n])),d=await a.write.fileDisputeFromStaker([e,t,n],{gasLimit:s,gasPrice:i}),r=await f(this.config.chainId).waitForTransactionReceipt({hash:d}),c=this.getCaseIdFromReceiptLogs(r,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:r,caseId:c}}async appealReconsideration(e,t,n){let a=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,n,s)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:s});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let r=await a.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(r),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.appeal([e],{gasLimit:c,gasPrice:p}),g=await f(this.config.chainId).waitForTransactionReceipt({hash:u}),m=this.getCaseIdFromReceiptLogs(g,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:g,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,n){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:n,accessToken:await this.configManager.getAccessToken()??""})}};var ie=class extends M{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),n=await W$1(this.config.chainId,t.brokerAddress),a=await n.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),d=await n.write.claimRebate([e],{gasPrice:s,gasLimit:i});return f(this.config.chainId).waitForTransactionReceipt({hash:d})}};var Dt=(r=>(r[r.UnderReview=1]="UnderReview",r[r.InitialVote=2]="InitialVote",r[r.PublicNotice=3]="PublicNotice",r[r.UnderReconsideration=4]="UnderReconsideration",r[r.Won=5]="Won",r[r.Failed=6]="Failed",r[r.PlatformRuling=7]="PlatformRuling",r[r.PlatformRevoked=8]="PlatformRevoked",r))(Dt||{}),Ot=(p=>(p[p.InitialVoting=1]="InitialVoting",p[p.PublicNotice=2]="PublicNotice",p[p.UnderReconsideration=3]="UnderReconsideration",p[p.Won=5]="Won",p[p.Failed=4]="Failed",p[p.PlatformRuling=6]="PlatformRuling",p[p.PlatformRevoked=7]="PlatformRevoked",p[p.ReconsiderationVoting=8]="ReconsiderationVoting",p[p.AppealRevert=9]="AppealRevert",p[p.NotAppealFailed=10]="NotAppealFailed",p))(Ot||{}),Lt=(a=>(a[a.UnderReview=1]="UnderReview",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Completed=4]="Completed",a))(Lt||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Bt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Bt||{}),_t=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(_t||{}),Gt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Gt||{}),Ut=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Ut||{}),Wt=(n=>(n[n.NoVote=0]="NoVote",n[n.Supported=1]="Supported",n[n.Rejected=2]="Rejected",n))(Wt||{}),qt=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(qt||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var Ie=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new H(e),this.logger=new ha({logLevel:e.logLevel});let t=P.getInstance();h()?.hasSigner()||(t.setConfigManager(this.configManager),g(this.configManager)),t.getMarkets().then(),this.utils=new Y(this.configManager,this.logger),this.api=new te(this.configManager,this.logger),this.account=new X(this.configManager,this.logger,this.utils,this),this.seamless=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new K(this.configManager,this.utils,this.api),this.position=new Q(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new J(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new ie(this);}auth(e){this.configManager.auth(e),P.getInstance().setConfigManager(this.configManager),g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Zi="1.0.18";
|
|
2
|
+
export{Ut as AppealCaseTypeEnum,_t as AppealClaimStatusEnum,Wt as AppealNodeStateEnum,Gt as AppealNodeVotedStateEnum,Ot as AppealReconsiderationType,Lt as AppealStage,$t as AppealStatus,Dt as AppealType,ga as Direction,qt as IsVoteNodeEnum,Ie as MyxClient,Nt as NodeTypeEnum,S as OperationType,fa as OrderStatus,j as OrderType,Zi as SDK_VERSION,ya as TimeInForce,ma as TriggerType,Bt as VoteTypeEnum,ue as fromViemWalletClient,V as normalizeSigner};
|