@myx-trade/sdk 1.0.16 → 1.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkGXRYSS6I_js=require('./chunk-GXRYSS6I.js'),ct=require('mitt'),cryptoEs=require('crypto-es'),pt=require('reconnecting-websocket'),viem=require('viem'),xe=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ct__default=/*#__PURE__*/_interopDefault(ct);var pt__default=/*#__PURE__*/_interopDefault(pt);var xe__default=/*#__PURE__*/_interopDefault(xe);var B=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var G=o=>{switch(o.request){case "signin":return B(o.request)}return B(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 B(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 _e={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__default.default();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 chunkGXRYSS6I_js.ga({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__default.default(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(r=>{let p=L(r);if(!i.has(p))if(i.add(p),this.subscriptions.has(p))this.subscriptions.get(p).callbacks.add(t);else {let s={id:p,topic:r.topic,callbacks:new Set([t])};this.subscriptions.set(p,s),a.push(p),this.logger.debug(`create new subscription: ${p}`);}}),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(r=>{let p=L(r);if(i.has(p))return;i.add(p);let s=this.subscriptions.get(p);s&&(s.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${p}`),s.callbacks.size===0&&(this.subscriptions.delete(p),a.push(p),this.logger.debug(`subscription ${p} 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(r){this.logger.error(`Callback Error (${n}): ${r}`);}});}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 Be=[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.signMessage=="function"&&typeof o.sendTransaction=="function"}function ut(o){return typeof o.getAddress=="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}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;return {getAddress:()=>o.getAddress(),signMessage:t=>o.signMessage(t),async sendTransaction(t){return {hash:(await o.sendTransaction({...t,value:t.value!=null?BigInt(t.value):void 0,gasLimit:t.gasLimit!=null?BigInt(t.gasLimit):void 0})).hash}},signTransaction:e.signTransaction,...typeof e.signTypedData=="function"?{async signTypedData(t){return e.signTypedData(t.domain,t.types,t.message)}}:{}}}function z(o){return lt(o)?ue(o):ut(o)?We(o):o}function qe(o){let e=chunkGXRYSS6I_js.e(o),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.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=chunkGXRYSS6I_js.e(o);me[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return me[o]}async function ze(o,e){let t=qe(e),n=yt(e),a=await o.getAddress();return viem.createWalletClient({account:a,chain:n,transport:viem.custom({request:async r=>{if(r.method==="eth_accounts")return [a];if(r.method==="eth_sendTransaction"){let c=r.params?.[0]??{},{hash:d}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return d}if(r.method==="eth_signTypedData_v4"||r.method==="eth_signTypedData"){if(!o.signTypedData)throw new Error("ISigner.signTypedData required for eth_signTypedData_v4");let c=r.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let d=JSON.parse(c);return await o.signTypedData({domain:d.domain,types:d.types,primaryType:d.primaryType,message:d.message})}let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:r.method,params:r.params??[]})})).json();if(s.error)throw new Error(s.error.message);return s.result}})})}var $=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[t]=await this.config.walletClient.getAddresses();if(t)return t}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){this.clear(),this.config={...this.config,...e},e.signer!=null&&(this._normalizedSigner=z(e.signer)),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(!Be.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 chunkGXRYSS6I_js.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&&(chunkGXRYSS6I_js.ea("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return chunkGXRYSS6I_js.ea("\u274C Received empty accessToken"),null}catch(t){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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:r}){this.configManager.getConfig();try{let s=await this.utils.getOraclePrice(e,i);if(!s)throw new Error("Failed to get price data");let c={poolId:e,oracleType:s.oracleType,publishTime:s.publishTime,oracleUpdateData:s?.vaa??"0"},d=!1;Number(n)>0&&(d=await this.utils.needsApproval(r,i,a,n,chunkGXRYSS6I_js.Q(i).TRADING_ROUTER));let u=BigInt(0),y=BigInt(n)>0?BigInt(n):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:r}),h=m.code===0?m.data??0n:0n,x=BigInt(0);h<y&&(x=y-h,u=x);let I={token:a,amount:u.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let we=await chunkGXRYSS6I_js.T(i);if(d){let C=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:viem.maxUint256.toString(),spenderAddress:chunkGXRYSS6I_js.Q(i).TRADING_ROUTER});if(C.code!==0)throw new Error(C.message)}let ae=await we.write.updatePriceAndAdjustCollateral([[c],I,t,n],{value:BigInt(s?.value??"1"),gas:BigInt(1e7)*chunkGXRYSS6I_js.c[i]/100n});return await chunkGXRYSS6I_js.f(i).waitForTransactionReceipt({hash:ae}),{code:0,data:{hash:ae},message:"Adjust collateral transaction submitted"}}catch(s){return {code:-1,message:s.message}}}};var ht={IOC:0},R=ht.IOC;var K={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 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,r=BigInt(0),p=n-i;p>BigInt(0)&&(r=p);let s={token:e.executionFeeToken,amount:r.toString()},c={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},d=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkGXRYSS6I_js.Q(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(d){let x=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkGXRYSS6I_js.Q(e.chainId).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let u=await chunkGXRYSS6I_js.T(e.chainId),y;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c,positionId:e.positionId});let x=await u.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...s},c]);y=await u.write.placeOrderWithPosition([e.positionId.toString(),{...s},c],{gasLimit:x*chunkGXRYSS6I_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c,depositData:s});let I=await u.estimateGas.placeOrderWithSalt(["1",{...s},c]);y=await u.write.placeOrderWithSalt(["1",{...s},c],{gasLimit:I*chunkGXRYSS6I_js.c[e.chainId]/100n});}let m=await chunkGXRYSS6I_js.f(e.chainId).waitForTransactionReceipt({hash:y});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:y,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(d=>d.positionId.toString()),i=t.map(d=>({user:d.address,poolId:d.poolId,orderType:d.orderType,triggerType:d.triggerType,operation:S.DECREASE,direction:d.direction,collateralAmount:d.collateralAmount,size:d.size,price:d.price,timeInForce:R,postOnly:d.postOnly,slippagePct:d.slippagePct,leverage:d.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",n,a,i),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await chunkGXRYSS6I_js.T(e),p=await r.estimateGas.placeOrdersWithPosition([n,a,i]),s=await r.write.placeOrdersWithPosition([n,a,i],{gasLimit:p*chunkGXRYSS6I_js.c[e]/100n}),c=await chunkGXRYSS6I_js.f(e).waitForTransactionReceipt({hash:s});return {code:0,message:"close all positions success",transactionHash:s,blockNumber:c?.blockNumber,gasUsed:c?.gasUsed?.toString(),status:c?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c}}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,r=BigInt(0),p=n-i;p>BigInt(0)&&(r=p);let s={token:e.executionFeeToken,amount:r.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c=await chunkGXRYSS6I_js.T(e.chainId),d;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,s,{data:t}]);let m=await c.estimateGas.placeOrderWithPosition([e.positionId.toString(),s,t]);d=await c.write.placeOrderWithPosition([e.positionId.toString(),s,t],{gasLimit:m*chunkGXRYSS6I_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,s,{data:t}]);let h=await c.estimateGas.placeOrderWithSalt(["1",s,t]);d=await c.write.placeOrderWithSalt(["1",s,t],{gasLimit:h*chunkGXRYSS6I_js.c[e.chainId]/100n});}let u=await chunkGXRYSS6I_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,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 chunkGXRYSS6I_js.T(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let s=[{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={token:"0x0000000000000000000000000000000000000000",amount:"0"},d;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s]);d=await t.write.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s],{gasLimit:m*chunkGXRYSS6I_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",s);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c,[m.toString(),m.toString()],s]);d=await t.write.placeOrdersWithSalt([c,[m.toString(),m.toString()],s],{gasLimit:h*chunkGXRYSS6I_js.c[e.chainId]/100n});}let u=await chunkGXRYSS6I_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,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 s=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),a,n]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),a,n],{gasLimit:s*chunkGXRYSS6I_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",n);let s=1,c=await t.estimateGas.placeOrderWithSalt([s.toString(),a,n]);i=await t.write.placeOrderWithSalt([s.toString(),a,n],{gasLimit:c*chunkGXRYSS6I_js.c[e.chainId]/100n});}let r=await chunkGXRYSS6I_js.f(e.chainId).waitForTransactionReceipt({hash:i});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:i,blockNumber:r?.blockNumber,gasUsed:r?.gasUsed?.toString(),status:r?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:r}}}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 chunkGXRYSS6I_js.T(t)).write.cancelOrders([e]);return await chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.T(t)).write.cancelOrder([e]);return await chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.T(t)).write.cancelOrders([e]);return await chunkGXRYSS6I_js.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,r){let p=await this.utils.getNetworkFee(i,n),s={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:r?e.tpSize:"0",tpPrice:r?e.tpPrice:"0",slSize:r?e.slSize:"0",slPrice:r?e.slPrice:"0"}},c={token:t,amount:p.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await chunkGXRYSS6I_js.T(n);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,p.toString(),chunkGXRYSS6I_js.Q(n).TRADING_ROUTER)){let x=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkGXRYSS6I_js.Q(n).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let y=await d.estimateGas.updateOrder([c,s]),m=await d.write.updateOrder([c,s],{gasLimit:y*chunkGXRYSS6I_js.c[n]/100n}),h=await chunkGXRYSS6I_js.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=viem.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??chunkGXRYSS6I_js.Q(t).Account,p=await chunkGXRYSS6I_js.S(t,n).read.allowance([e,i]);return {code:0,data:String(p)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await chunkGXRYSS6I_js.ha(i)}}async needsApproval(e,t,n,a,i){try{let p=(await this.getApproveQuoteAmount(e,t,n,i)).data,s=BigInt(p),c=BigInt(a);return s<c}catch(r){return this.logger.error("Error checking approval needs:",r),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:n,spenderAddress:a}){try{let i=await chunkGXRYSS6I_js.U(e,t),r=n??viem.maxUint256,p=a??chunkGXRYSS6I_js.Q(e).Account,s=await this.getGasPriceByRatio(),c=await i.write.approve([p,r],{gasPrice:s});return await chunkGXRYSS6I_js.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 r=this.configManager.getConfig().brokerAddress;try{let p=chunkGXRYSS6I_js.W(n,r),s=a??await this.configManager.getSignerAddress(n),c=await p.read.getUserFeeRate([s,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(p){return this.logger.error("Error getting user trading fee rate:",p),{code:-1,message:p?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkGXRYSS6I_js.X(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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.X(t,0)).read.getForwardFeeByToken([n]),p=await chunkGXRYSS6I_js.S(t,n).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(p)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:n}){try{return {code:0,data:await(await chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.na(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=chunkGXRYSS6I_js.d[t];return chunkGXRYSS6I_js.ma(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(r){a=r,i<t-1&&await new Promise(p=>setTimeout(p,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=chunkGXRYSS6I_js.S(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 p=await(await chunkGXRYSS6I_js.Z(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await chunkGXRYSS6I_js.f(i).waitForTransactionReceipt({hash:p})}}catch(r){return {code:-1,message:r.message}}}async deposit({amount:e,tokenAddress:t,chainId:n}){let a=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"",i=chunkGXRYSS6I_js.Q(n);try{if(await this.utils.needsApproval(a,n,t,e,i.Account)){let d=await this.utils.approveAuthorization({chainId:n,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:i.Account});if(d.code!==0)throw new Error(d.message)}let s=await(await chunkGXRYSS6I_js.Z(n)).write.deposit([a,t,e]);return {code:0,data:await chunkGXRYSS6I_js.f(n).waitForTransactionReceipt({hash:s})}}catch(r){return {code:-1,message:r.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),r=a.data,p=BigInt(r?.quoteProfit??0),s=BigInt(r?.freeMargin??0),c=BigInt(r?.lockedMargin??0),d=i?.code===0?i.data:null,u=d?.status===1?BigInt(d?.lockedMargin??0):0n;return {code:0,data:s+p-c-u}}catch(a){return {code:-1,message:a.message}}}async getAccountInfo(e,t,n){let a=await chunkGXRYSS6I_js.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=chunkGXRYSS6I_js.W(e,n.brokerAddress),r=await chunkGXRYSS6I_js.f(e).getBlock({blockTag:"latest"}),p=Number(r?.timestamp??BigInt(xe__default.default().unix()))+300;try{let s=await this.getCurrentFeeDataEpoch(e);this.logger.debug("setUserFeeDataEpoch-->",s);let c=await a.read.userFeeData([s,t]),d;try{d=await this.withRetry(()=>a.read.userNonces([t]));}catch{d=0n;}return {code:0,data:{...c,nonce:d.toString(),deadline:p}}}catch(s){return {code:-1,message:s.message}}}async getAccountVipInfoByBackend(e,t,n,a){let i=await this.configManager.getAccessToken()??"";try{let r=await this.client.api.getAccountVipInfo({address:e,accessToken:i,chainId:t,deadline:n,nonce:a});if(r.code!==9200)throw new l("REQUEST_FAILED",r.msg??"Failed to get account vip info");return {code:0,data:r.data}}catch(r){return {code:-1,message:r.message}}}async getCurrentFeeDataEpoch(e){let t=this.configManager.getConfig();return await(await chunkGXRYSS6I_js.W(e,t.brokerAddress)).read.currentFeeDataEpoch()}async setUserFeeData(e,t,n,a,i){let r=this.configManager.getConfig();if(n<xe__default.default().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let p=await chunkGXRYSS6I_js.V(t,r.brokerAddress),s=await this.getCurrentFeeDataEpoch(t),c={user:e,nonce:a.nonce,deadline:n,feeDataEpoch:s.toString(),feeData:{tier:a.tier,referrer:a.referrer||viem.zeroAddress,totalReferralRebatePct:a.totalReferralRebatePct,referrerRebatePct:a.referrerRebatePct},signature:i},d=await p.read.userNonces([e]);if(parseInt(d.toString())+1!==parseInt(a.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let u=await p.write.setUserFeeData([c]);return {code:0,data:await chunkGXRYSS6I_js.f(t).waitForTransactionReceipt({hash:u})}}catch(p){return {code:-1,message:p.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Tt(o,e){return Qe(e,o[e])}function Pt(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])?Pt(e,n):Tt(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 chunkGXRYSS6I_js.m.get(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async post(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return chunkGXRYSS6I_js.m.post(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async put(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return chunkGXRYSS6I_js.m.put(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async delete(e,{auth:t=false,...n}={}){let a=t?await this.buildAuthParams():{};return chunkGXRYSS6I_js.m.delete(this.buildRequestPath(e),lodashEs.merge(a,n))}};var Z=class extends X{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...n}){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkGXRYSS6I_js.m.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkGXRYSS6I_js.m.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n,limit:a,interval:i})}async getKlineLatestBar(e){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n}){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n}){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n}){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkGXRYSS6I_js.m.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n,deadline:a,nonce:i}){return chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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 chunkGXRYSS6I_js.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=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),n=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:n}}async function Mt(o,e,t,n,a,i,r,p){let s=chunkGXRYSS6I_js.S(e,t),c=await je(s),[d]=await o.getAddresses();if(!d)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"}]},y={owner:n,spender:a,value:i,nonce:r,deadline:p},m=await o.signTypedData({account:d,domain:{...c,chainId:c.chainId},types:u,primaryType:"Permit",message:y});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 r=await(await chunkGXRYSS6I_js._(n)).read.isUserRelayerEnabled([e,t]),p=await this.utils.needsApproval(e,n,a,viem.maxUint256.toString(),chunkGXRYSS6I_js.Q(n).TRADING_ROUTER);return r&&!p}async getContractAbiAndAddressByFunctionName(e,t){let n=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],a=["setUserFeeData"],i=["updateAndWithdraw","deposit"];return n.includes(e)?{abi:chunkGXRYSS6I_js.R,address:chunkGXRYSS6I_js.Q(t).TRADING_ROUTER}:i.includes(e)?{abi:chunkGXRYSS6I_js.l,address:chunkGXRYSS6I_js.Q(t).Account}:(console.log("functionName==>",e),console.log("brokerFunctions.includes(functionName)->",a.includes(e)),a.includes(e)?{abi:chunkGXRYSS6I_js.i,address:this.configManager.getConfig().brokerAddress}:{abi:chunkGXRYSS6I_js.R,address:chunkGXRYSS6I_js.Q(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 chunkGXRYSS6I_js.h(t),i=chunkGXRYSS6I_js.Q(t),[r]=await a.getAddresses();if(!r)throw new l("INVALID_SIGNER","No account");let p=chunkGXRYSS6I_js.S(t,n);try{let s=await p.read.nonces([r]),c=await Mt(a,t,n,r,i.TRADING_ROUTER,viem.maxUint256,s,e);return [{token:n,owner:r,spender:i.TRADING_ROUTER,value:viem.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 chunkGXRYSS6I_js._(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:r,value:p="0",gas:s="800000"}){let c=await(await chunkGXRYSS6I_js._(e)).read.nonces([t]),d=xe__default.default().add(60,"minute").unix(),u=await this.getForwardEip712Domain(e),{abi:y,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),h=viem.encodeFunctionData({abi:y,functionName:i,args:r}),x=await n({domain:u,functionHash:h,to:m,nonce:c.toString(),deadline:d}),I=await this.api.forwarderTxApi({from:t,to:m,value:p??"0",gas:s,nonce:c.toString(),data:h,deadline:d,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:r,nonce:p,forwardFeeToken:s},c){let d=await this.getForwardEip712Domain(c),u=await chunkGXRYSS6I_js.h(c),[y]=await u.getAddresses();if(!y)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await u.signTypedData({account:y,domain:d,types:vt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(n??"0"),gas:BigInt(a),nonce:BigInt(p),deadline:BigInt(i),data:r}});return await this.api.forwarderTxApi({from:e,to:t,value:n,gas:a,nonce:p,data:r,deadline:i,signature:m,forwardFeeToken:s},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 chunkGXRYSS6I_js.X(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 r=xe__default.default().add(60,"minute").unix(),p=[];if(e)try{p=await this.getUSDPermitParams(r,n,a);}catch(y){this.logger.warn("Failed to get USD permit params, proceeding without permit:",y),p=[];}let s=await chunkGXRYSS6I_js._(n,1),c=await(await chunkGXRYSS6I_js._(n)).read.nonces([i]),d=viem.encodeFunctionData({abi:chunkGXRYSS6I_js.j,functionName:"permitAndApproveForwarder",args:[t,e,p]}),u=await this.forwarderTx({from:i,to:s.address,value:"0",gas:"800000",nonce:c.toString(),data:d,deadline:r,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 chunkGXRYSS6I_js._(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:n,functionName:a,data:i,seamlessAddress:r}){if(!e||!viem.isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!r||!viem.isAddress(r))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!n||!viem.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 s=await chunkGXRYSS6I_js._(t),c,{abi:d,address:u}=await this.getContractAbiAndAddressByFunctionName(a,t);try{c=viem.encodeFunctionData({abi:d,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 y=await s.read.nonces([r]);return {from:r,to:u,value:"0",gas:"800000",deadline:xe__default.default().add(60,"minute").unix(),data:c,nonce:y.toString(),forwardFeeToken:n}}};var E=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkGXRYSS6I_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkGXRYSS6I_js.Q(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkGXRYSS6I_js.W(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var te=class extends E{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkGXRYSS6I_js.aa(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkGXRYSS6I_js.$(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let n=t==="DisputeFiled"?"caseId":"appealCaseId";for(let a of e.logs)try{let i=viem.decodeEventLog({abi:chunkGXRYSS6I_js.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 r=await this.getDisputeCourtContract(),p=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),s=BigInt(p[0].value.toString()||"1"),c=await r.estimateGas.fileDispute([p,e,t],{value:s}),d=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),y=await r.write.fileDispute([p,e,t],{value:s,gasLimit:d,gasPrice:u}),m=await chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:y}),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:p}){let s=await this.getDisputeCourtContract(),c=await s.estimateGas.vote([e,t,n?1:0,a,i,r,p]),d=await this.client.utils.getGasLimitByRatio(c),u=await this.client.utils.getGasPriceByRatio(),y=await s.write.vote([e,t,n?1:0,a,i,r,p],{gasLimit:d,gasPrice:u});return await chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:y})}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(),r=await t.write.claimBond([e],{gasLimit:a,gasPrice:i});return chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:r})}async claimReimbursement(e,t,n,a){let i=await this.getReimbursementContract(),r=await i.estimateGas.claimReimbursement([e,t,n,a]),p=await this.client.utils.getGasLimitByRatio(r),s=await this.client.utils.getGasPriceByRatio(),c=await i.write.claimReimbursement([e,t,n,a],{gasLimit:p,gasPrice:s});return chunkGXRYSS6I_js.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(),r=await this.client.utils.getGasLimitByRatio(await a.estimateGas.fileDisputeFromStaker([e,t,n])),p=await a.write.fileDisputeFromStaker([e,t,n],{gasLimit:r,gasPrice:i}),s=await chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:p}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,n){let a=await this.getDisputeCourtContract(),i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",r=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(i,this.config.chainId,t,n,r)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:r});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let s=await a.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),u=await a.write.appeal([e],{gasLimit:c,gasPrice:d}),y=await chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),m=this.getCaseIdFromReceiptLogs(y,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:y,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 E{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),n=await chunkGXRYSS6I_js.V(this.config.chainId,t.brokerAddress),a=await n.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(a),r=await this.client.utils.getGasPriceByRatio(),p=await n.write.claimRebate([e],{gasPrice:r,gasLimit:i});return chunkGXRYSS6I_js.f(this.config.chainId).waitForTransactionReceipt({hash:p})}};var Dt=(s=>(s[s.UnderReview=1]="UnderReview",s[s.InitialVote=2]="InitialVote",s[s.PublicNotice=3]="PublicNotice",s[s.UnderReconsideration=4]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=6]="Failed",s[s.PlatformRuling=7]="PlatformRuling",s[s.PlatformRevoked=8]="PlatformRevoked",s))(Dt||{}),Ft=(d=>(d[d.InitialVoting=1]="InitialVoting",d[d.PublicNotice=2]="PublicNotice",d[d.UnderReconsideration=3]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=4]="Failed",d[d.PlatformRuling=6]="PlatformRuling",d[d.PlatformRevoked=7]="PlatformRevoked",d[d.ReconsiderationVoting=8]="ReconsiderationVoting",d[d.AppealRevert=9]="AppealRevert",d[d.NotAppealFailed=10]="NotAppealFailed",d))(Ft||{}),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||{}),_t=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(_t||{}),Bt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Bt||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),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 $(e),this.logger=new chunkGXRYSS6I_js.ga({logLevel:e.logLevel});let t=chunkGXRYSS6I_js.O.getInstance();t.setConfigManager(this.configManager),chunkGXRYSS6I_js.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 Zi="1.0.16";
|
|
2
|
-
Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return
|
|
1
|
+
'use strict';var chunkYDBHYUPH_js=require('./chunk-YDBHYUPH.js'),ct=require('mitt'),cryptoEs=require('crypto-es'),pt=require('reconnecting-websocket'),viem=require('viem'),xe=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ct__default=/*#__PURE__*/_interopDefault(ct);var pt__default=/*#__PURE__*/_interopDefault(pt);var xe__default=/*#__PURE__*/_interopDefault(xe);var _=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.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__default.default();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 chunkYDBHYUPH_js.ga({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__default.default(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=chunkYDBHYUPH_js.e(o),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.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=chunkYDBHYUPH_js.e(o);me[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.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 viem.createWalletClient({account:a,chain:n,transport:viem.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 chunkYDBHYUPH_js.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&&(chunkYDBHYUPH_js.ea("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return chunkYDBHYUPH_js.ea("\u274C Received empty accessToken"),null}catch(t){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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={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,chunkYDBHYUPH_js.Q(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 chunkYDBHYUPH_js.T(i);if(p){let C=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:viem.maxUint256.toString(),spenderAddress:chunkYDBHYUPH_js.Q(i).TRADING_ROUTER});if(C.code!==0)throw new Error(C.message)}let ae=await we.write.updatePriceAndAdjustCollateral([[c],I,t,n],{value:BigInt(r?.value??"1"),gas:BigInt(1e7)*chunkYDBHYUPH_js.c[i]/100n});return await chunkYDBHYUPH_js.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={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,chunkYDBHYUPH_js.Q(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:viem.maxUint256.toString(),spenderAddress:chunkYDBHYUPH_js.Q(e.chainId).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let u=await chunkYDBHYUPH_js.T(e.chainId),g;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c,positionId:e.positionId});let x=await u.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...r},c]);g=await u.write.placeOrderWithPosition([e.positionId.toString(),{...r},c],{gasLimit:x*chunkYDBHYUPH_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c,depositData:r});let I=await u.estimateGas.placeOrderWithSalt(["1",{...r},c]);g=await u.write.placeOrderWithSalt(["1",{...r},c],{gasLimit:I*chunkYDBHYUPH_js.c[e.chainId]/100n});}let m=await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.T(e),d=await s.estimateGas.placeOrdersWithPosition([n,a,i]),r=await s.write.placeOrdersWithPosition([n,a,i],{gasLimit:d*chunkYDBHYUPH_js.c[e]/100n}),c=await chunkYDBHYUPH_js.f(e).waitForTransactionReceipt({hash:r});return {code:0,message:"close all positions success",transactionHash:r,blockNumber:c?.blockNumber,gasUsed:c?.gasUsed?.toString(),status:c?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c}}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=await chunkYDBHYUPH_js.T(e.chainId),p;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,r,{data:t}]);let m=await c.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,t]);p=await c.write.placeOrderWithPosition([e.positionId.toString(),r,t],{gasLimit:m*chunkYDBHYUPH_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,r,{data:t}]);let h=await c.estimateGas.placeOrderWithSalt(["1",r,t]);p=await c.write.placeOrderWithSalt(["1",r,t],{gasLimit:h*chunkYDBHYUPH_js.c[e.chainId]/100n});}let u=await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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={token:"0x0000000000000000000000000000000000000000",amount:"0"},p;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],r]);p=await t.write.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],r],{gasLimit:m*chunkYDBHYUPH_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",r);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c,[m.toString(),m.toString()],r]);p=await t.write.placeOrdersWithSalt([c,[m.toString(),m.toString()],r],{gasLimit:h*chunkYDBHYUPH_js.c[e.chainId]/100n});}let u=await chunkYDBHYUPH_js.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*chunkYDBHYUPH_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",n);let r=1,c=await t.estimateGas.placeOrderWithSalt([r.toString(),a,n]);i=await t.write.placeOrderWithSalt([r.toString(),a,n],{gasLimit:c*chunkYDBHYUPH_js.c[e.chainId]/100n});}let s=await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.T(t)).write.cancelOrders([e]);return await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.T(t)).write.cancelOrder([e]);return await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.T(t)).write.cancelOrders([e]);return await chunkYDBHYUPH_js.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={token:t,amount:d.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let p=await chunkYDBHYUPH_js.T(n);this.logger.info("updateOrderTpSl params",r);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,d.toString(),chunkYDBHYUPH_js.Q(n).TRADING_ROUTER)){let x=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkYDBHYUPH_js.Q(n).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let g=await p.estimateGas.updateOrder([c,r]),m=await p.write.updateOrder([c,r],{gasLimit:g*chunkYDBHYUPH_js.c[n]/100n}),h=await chunkYDBHYUPH_js.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=viem.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??chunkYDBHYUPH_js.Q(t).Account,d=await chunkYDBHYUPH_js.S(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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.U(e,t),s=n??viem.maxUint256,d=a??chunkYDBHYUPH_js.Q(e).Account,r=await this.getGasPriceByRatio(),c=await i.write.approve([d,s],{gasPrice:r});return await chunkYDBHYUPH_js.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=chunkYDBHYUPH_js.W(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 chunkYDBHYUPH_js.X(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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.X(t,0)).read.getForwardFeeByToken([n]),d=await chunkYDBHYUPH_js.S(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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.na(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=chunkYDBHYUPH_js.d[t];return chunkYDBHYUPH_js.ma(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=chunkYDBHYUPH_js.S(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 chunkYDBHYUPH_js.Z(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await chunkYDBHYUPH_js.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=chunkYDBHYUPH_js.Q(n);try{if(await this.utils.needsApproval(a,n,t,e,i.Account)){let p=await this.utils.approveAuthorization({chainId:n,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:i.Account});if(p.code!==0)throw new Error(p.message)}let r=await(await chunkYDBHYUPH_js.Z(n)).write.deposit([a,t,e]);return {code:0,data:await chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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=chunkYDBHYUPH_js.W(e,n.brokerAddress),s=await chunkYDBHYUPH_js.f(e).getBlock({blockTag:"latest"}),d=Number(s?.timestamp??BigInt(xe__default.default().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 chunkYDBHYUPH_js.W(e,t.brokerAddress)).read.currentFeeDataEpoch()}async setUserFeeData(e,t,n,a,i){let s=this.configManager.getConfig();if(n<xe__default.default().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let d=await chunkYDBHYUPH_js.V(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||viem.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async post(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return chunkYDBHYUPH_js.m.post(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async put(e,t,{auth:n=false,...a}={}){let i=n?await this.buildAuthParams():{};return chunkYDBHYUPH_js.m.put(this.buildRequestPath(e),t,lodashEs.merge(i,a))}async delete(e,{auth:t=false,...n}={}){let a=t?await this.buildAuthParams():{};return chunkYDBHYUPH_js.m.delete(this.buildRequestPath(e),lodashEs.merge(a,n))}};var Z=class extends X{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...n}){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkYDBHYUPH_js.m.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkYDBHYUPH_js.m.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n,limit:a,interval:i})}async getKlineLatestBar(e){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n}){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n}){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n}){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkYDBHYUPH_js.m.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n,deadline:a,nonce:i}){return chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),n=viem.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=chunkYDBHYUPH_js.S(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 chunkYDBHYUPH_js._(n)).read.isUserRelayerEnabled([e,t]),d=await this.utils.needsApproval(e,n,a,viem.maxUint256.toString(),chunkYDBHYUPH_js.Q(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:chunkYDBHYUPH_js.R,address:chunkYDBHYUPH_js.Q(t).TRADING_ROUTER}:i.includes(e)?{abi:chunkYDBHYUPH_js.l,address:chunkYDBHYUPH_js.Q(t).Account}:(console.log("functionName==>",e),console.log("brokerFunctions.includes(functionName)->",a.includes(e)),a.includes(e)?{abi:chunkYDBHYUPH_js.i,address:this.configManager.getConfig().brokerAddress}:{abi:chunkYDBHYUPH_js.R,address:chunkYDBHYUPH_js.Q(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 chunkYDBHYUPH_js.h(t),i=chunkYDBHYUPH_js.Q(t),[s]=await a.getAddresses();if(!s)throw new l("INVALID_SIGNER","No account");let d=chunkYDBHYUPH_js.S(t,n);try{let r=await d.read.nonces([s]),c=await Et(a,t,n,s,i.TRADING_ROUTER,viem.maxUint256,r,e);return [{token:n,owner:s,spender:i.TRADING_ROUTER,value:viem.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 chunkYDBHYUPH_js._(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 chunkYDBHYUPH_js._(e)).read.nonces([t]),p=xe__default.default().add(60,"minute").unix(),u=await this.getForwardEip712Domain(e),{abi:g,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e),h=viem.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.X(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__default.default().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 chunkYDBHYUPH_js._(n,1),c=await(await chunkYDBHYUPH_js._(n)).read.nonces([i]),p=viem.encodeFunctionData({abi:chunkYDBHYUPH_js.j,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 chunkYDBHYUPH_js._(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:n,functionName:a,data:i,seamlessAddress:s}){if(!e||!viem.isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!s||!viem.isAddress(s))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!n||!viem.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 chunkYDBHYUPH_js._(t),c,{abi:p,address:u}=await this.getContractAbiAndAddressByFunctionName(a,t);try{c=viem.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__default.default().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||!chunkYDBHYUPH_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkYDBHYUPH_js.Q(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkYDBHYUPH_js.W(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 chunkYDBHYUPH_js.aa(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkYDBHYUPH_js.$(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let n=t==="DisputeFiled"?"caseId":"appealCaseId";for(let a of e.logs)try{let i=viem.decodeEventLog({abi:chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.V(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 chunkYDBHYUPH_js.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 chunkYDBHYUPH_js.ga({logLevel:e.logLevel});let t=chunkYDBHYUPH_js.O.getInstance();t.setConfigManager(this.configManager),chunkYDBHYUPH_js.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
|
+
Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkYDBHYUPH_js.la}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ka}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkYDBHYUPH_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.C}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.z}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkYDBHYUPH_js.n}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.B}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkYDBHYUPH_js.E}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.q}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ga}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkYDBHYUPH_js.t}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkYDBHYUPH_js.o}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkYDBHYUPH_js.r}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkYDBHYUPH_js.O}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.w}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkYDBHYUPH_js.p}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.A}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.v}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.u}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.s}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.D}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.x}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkYDBHYUPH_js.y}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkYDBHYUPH_js.pa}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkYDBHYUPH_js.va}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkYDBHYUPH_js.oa}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkYDBHYUPH_js.na}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ma}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ta}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ja}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ia}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkYDBHYUPH_js.L}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkYDBHYUPH_js.G}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkYDBHYUPH_js.M}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkYDBHYUPH_js.N}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkYDBHYUPH_js.H}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkYDBHYUPH_js.I}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkYDBHYUPH_js.F}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkYDBHYUPH_js.J}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ra}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkYDBHYUPH_js.qa}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkYDBHYUPH_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ca}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkYDBHYUPH_js.K}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkYDBHYUPH_js.sa}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkYDBHYUPH_js.h}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkYDBHYUPH_js.P}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkYDBHYUPH_js.xa}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ua}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ya}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkYDBHYUPH_js.wa}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkYDBHYUPH_js.fa}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkYDBHYUPH_js.da}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ea}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkYDBHYUPH_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkYDBHYUPH_js.ba}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=Bt;exports.AppealNodeStateEnum=Ut;exports.AppealNodeVotedStateEnum=_t;exports.AppealReconsiderationType=Dt;exports.AppealStage=Ot;exports.AppealStatus=qt;exports.AppealType=Ft;exports.Direction=ma;exports.IsVoteNodeEnum=Wt;exports.MyxClient=Ie;exports.NodeTypeEnum=Lt;exports.OperationType=S;exports.OrderStatus=ya;exports.OrderType=K;exports.SDK_VERSION=Xi;exports.TimeInForce=ga;exports.TriggerType=ua;exports.VoteTypeEnum=Nt;exports.fromViemWalletClient=ue;exports.normalizeSigner=$;
|