@myx-trade/sdk 1.0.13 → 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-C5JAWLE4.js +2 -0
- package/dist/chunk-INAGQFCM.mjs +2 -0
- package/dist/index.d.mts +21 -3
- package/dist/index.d.ts +21 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/lp.js +1 -1
- package/dist/lp.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-LZPUSLKV.js +0 -2
- package/dist/chunk-SUD7V524.mjs +0 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkLZPUSLKV_js=require('./chunk-LZPUSLKV.js'),rt=require('mitt'),cryptoEs=require('crypto-es'),ot=require('reconnecting-websocket'),viem=require('viem'),xe=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var rt__default=/*#__PURE__*/_interopDefault(rt);var ot__default=/*#__PURE__*/_interopDefault(ot);var xe__default=/*#__PURE__*/_interopDefault(xe);var W=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var q=o=>{switch(o.request){case "signin":return W(o.request)}return W(JSON.stringify(o))},_=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 W(JSON.stringify({topic:e,params:t}))}},De=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",st=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Oe=o=>{switch(st(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:_({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[n,a]=t.split("_");return {...o,type:_({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 Fe={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},z=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=rt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:n,...a}=t;this.config={...Fe,...a},this.logger=new chunkLZPUSLKV_js.ea({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 ot__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=q(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 r=_(s);if(!i.has(r))if(i.add(r),this.subscriptions.has(r))this.subscriptions.get(r).callbacks.add(t);else {let d={id:r,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(r,d),a.push(r),this.logger.debug(`create new subscription: ${r}`);}}),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 r=_(s);if(i.has(r))return;i.add(r);let d=this.subscriptions.get(r);d&&(d.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${r}`),d.callbacks.size===0&&(this.subscriptions.delete(r),a.push(r),this.logger.debug(`subscription ${r} 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(De(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=q({request:e.type,args:""});break;default:t=q({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=Oe(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||Fe.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 Le=[56,59144,42161],Ne=[59141,421614,97],_e=[97,421614];var $={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var V=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let n=$.MainNet;e.getConfig().isBetaMode?n=$.BetaNet:e.getConfig().isTestnet&&(n=$.TestNet),this.wsClient=new z({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 dt(o){return typeof o.getAddresses=="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function ct(o){return typeof o.getAddress=="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function me(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let n=typeof t=="string"?t:{raw:t};return await o.signMessage({message:n})},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 Be(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}},...typeof e.signTypedData=="function"?{async signTypedData(t){return e.signTypedData(t.domain,t.types,t.message)}}:{}}}function H(o){return dt(o)?me(o):ct(o)?Be(o):o}function Ge(o){let e=chunkLZPUSLKV_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 ge={};function ut(o){if(!ge[o]){let e=chunkLZPUSLKV_js.e(o);ge[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[Ge(o)]}}};}return ge[o]}async function Ue(o,e){let t=Ge(e),n=ut(e),i={address:await o.getAddress(),type:"local",async signMessage({message:r}){let d=typeof r=="string"?r:r.raw;return await o.signMessage(d)},async signTypedData(r){if(!o.signTypedData)throw new Error("ISigner.signTypedData required for this operation");return await o.signTypedData({domain:r.domain,types:r.types,primaryType:r.primaryType,message:r.message})},source:"custom"};return viem.createWalletClient({account:i,chain:n,transport:viem.custom({request:async r=>{if(r.method==="eth_sendTransaction"){let c=r.params?.[0]??{},{hash:u}=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 u}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 u=JSON.parse(c);return await o.signTypedData({domain:u.domain,types:u.types,primaryType:u.primaryType,message:u.message})}let p=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(p.error)throw new Error(p.error.message);return p.result}})})}var K=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 Ue(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=H(e.signer)),this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:n,chainId:a}=e;if(t){if(!Ne.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of TESTNET_CHAIN_IDS`)}else if(n){if(!_e.includes(a))throw new l("INVALID_CHAIN_ID",`chainId ${a} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!Le.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 chunkLZPUSLKV_js.ca("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&&(chunkLZPUSLKV_js.ca("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return chunkLZPUSLKV_js.ca("\u274C Received empty accessToken"),null}catch(t){return chunkLZPUSLKV_js.da("\u274C Failed to refresh accessToken:",t),null}}setAccessToken(e,t=3600){this.accessToken=e,this.accessTokenExpiry=Date.now()+t*1e3;}getCurrentAccessToken(){return this.accessToken}isAccessTokenValid(){return !!this.accessToken}clearAccessToken(){this.accessToken=void 0,this.accessTokenExpiry=void 0;}getConfig(){return this.config}};var Q=class{constructor(e,t,n){this.configManager=e,this.utils=t,this.api=n;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){this.configManager.getConfig();return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){this.configManager.getConfig();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}};var j=class{constructor(e,t,n,a,i){this.configManager=e,this.logger=t,this.utils=n,this.account=a,this.api=i;}async 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}){let r=this.configManager.getConfig();try{let d=await this.utils.getOraclePrice(e,i);if(!d)throw new Error("Failed to get price data");let p={poolId:e,oracleType:d.oracleType,publishTime:d.publishTime,oracleUpdateData:d?.vaa??"0"},c=!1;Number(n)>0&&(c=await this.utils.needsApproval(s,i,a,n,chunkLZPUSLKV_js.Q(i).TRADING_ROUTER));let u=BigInt(0),m=BigInt(n)>0?BigInt(n):0n,g=await this.account.getAvailableMarginBalance({poolId:e,chainId:i,address:s}),h=g.code===0?g.data??0n:0n,x=BigInt(0);h<m&&(x=m-h,u=x);let I={token:a,amount:u.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let S=await chunkLZPUSLKV_js.T(i,r.brokerAddress);if(c){let k=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:viem.maxUint256.toString(),spenderAddress:chunkLZPUSLKV_js.Q(i).TRADING_ROUTER});if(k.code!==0)throw new Error(k.message)}let P=await S.write.updatePriceAndAdjustCollateral([[p],I,t,n],{value:BigInt(d?.value??"1"),gas:BigInt(1e7)*chunkLZPUSLKV_js.c[i]/100n});return await chunkLZPUSLKV_js.f(i).waitForTransactionReceipt({hash:P}),{code:0,data:{hash:P},message:"Adjust collateral transaction submitted"}}catch(d){return {code:-1,message:d.message}}}};var gt={IOC:0},R=gt.IOC;var J={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},da={NONE:0,GTE:1,LTE:2},M={INCREASE:0,DECREASE:1},ca={LONG:0,SHORT:1},pa={IOC:0},la={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var Y=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,n){try{let a=await this.utils.getNetworkFee(n,e.chainId),i=BigInt(a);e.tpSize&&BigInt(e.tpSize)>0&&(i+=BigInt(a)),e.slSize&&BigInt(e.slSize)>0&&(i+=BigInt(a));let s=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),d=r.code===0?r.data??0n:0n,p=s+i,c=BigInt(0),u=p-d;u>BigInt(0)&&(c=u);let m={token:e.executionFeeToken,amount:c.toString()},g={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:M.INCREASE,direction:e.direction,collateralAmount:s.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"},h=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkLZPUSLKV_js.Q(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(h){let k=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkLZPUSLKV_js.Q(e.chainId).TRADING_ROUTER});if(k.code!==0)throw new Error(k.message)}let x=await chunkLZPUSLKV_js.T(e.chainId,this.configManager.getConfig().brokerAddress),I;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...g,positionId:e.positionId});let k=await x.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...m},g]);I=await x.write.placeOrderWithPosition([e.positionId.toString(),{...m},g],{gasLimit:k*chunkLZPUSLKV_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:g,depositData:m});let O=await x.estimateGas.placeOrderWithSalt(["1",{...m},g]);I=await x.write.placeOrderWithSalt(["1",{...m},g],{gasLimit:O*chunkLZPUSLKV_js.c[e.chainId]/100n});}let S=await chunkLZPUSLKV_js.f(e.chainId).waitForTransactionReceipt({hash:I});return {code:0,message:"create increase 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(a){return this.logger.error("Error placing order:",a),{code:-1,message:a?.message}}}async closeAllPositions(e,t){try{let n=this.configManager.getConfig(),a={token:"0x0000000000000000000000000000000000000000",amount:"0"},i=t.map(u=>u.positionId.toString()),s=t.map(u=>({user:u.address,poolId:u.poolId,orderType:u.orderType,triggerType:u.triggerType,operation:M.DECREASE,direction:u.direction,collateralAmount:u.collateralAmount,size:u.size,price:u.price,timeInForce:R,postOnly:u.postOnly,slippagePct:u.slippagePct,leverage:u.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0}));if(this.logger.info("closeAllPositions params--->",a,i,s),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await chunkLZPUSLKV_js.T(e,this.configManager.getConfig().brokerAddress),d=await r.estimateGas.placeOrdersWithPosition([a,i,s]),p=await r.write.placeOrdersWithPosition([a,i,s],{gasLimit:d*chunkLZPUSLKV_js.c[e]/100n}),c=await chunkLZPUSLKV_js.f(e).waitForTransactionReceipt({hash:p});return {code:0,message:"close all positions success",transactionHash:p,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:M.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},n={token:"0x0000000000000000000000000000000000000000",amount:"0"};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await chunkLZPUSLKV_js.T(e.chainId,this.configManager.getConfig().brokerAddress),i;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,n,{data:t}]);let d=await a.estimateGas.placeOrderWithPosition([e.positionId.toString(),n,t]);i=await a.write.placeOrderWithPosition([e.positionId.toString(),n,t],{gasLimit:d*chunkLZPUSLKV_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,n,{data:t}]);let p=await a.estimateGas.placeOrderWithSalt(["1",n,t]);i=await a.write.placeOrderWithSalt(["1",n,t],{gasLimit:p*chunkLZPUSLKV_js.c[e.chainId]/100n});}let s=await chunkLZPUSLKV_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(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkLZPUSLKV_js.T(e.chainId,this.configManager.getConfig().brokerAddress);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let d=[{user:e.address,poolId:e.poolId,orderType:J.STOP,triggerType:e.tpTriggerType,operation:M.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"},{user:e.address,poolId:e.poolId,orderType:J.STOP,triggerType:e.slTriggerType,operation:M.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"}],p={token:"0x0000000000000000000000000000000000000000",amount:"0"},c;if(e.positionId){let g=await t.estimateGas.placeOrdersWithPosition([p,[e.positionId.toString(),e.positionId.toString()],d]);c=await t.write.placeOrdersWithPosition([p,[e.positionId.toString(),e.positionId.toString()],d],{gasLimit:g*chunkLZPUSLKV_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",d);let g=1,h=await t.estimateGas.placeOrdersWithSalt([p,[g.toString(),g.toString()],d]);c=await t.write.placeOrdersWithSalt([p,[g.toString(),g.toString()],d],{gasLimit:h*chunkLZPUSLKV_js.c[e.chainId]/100n});}let u=await chunkLZPUSLKV_js.f(e.chainId).waitForTransactionReceipt({hash:c});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:c,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}let n={user:e.address,poolId:e.poolId,orderType:J.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:M.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"},a={token:"0x0000000000000000000000000000000000000000",amount:"0"},i;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",n);let d=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),a,n]);i=await t.write.placeOrderWithPosition([e.positionId.toString(),a,n],{gasLimit:d*chunkLZPUSLKV_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",n);let d=1,p=await t.estimateGas.placeOrderWithSalt([d.toString(),a,n]);i=await t.write.placeOrderWithSalt([d.toString(),a,n],{gasLimit:p*chunkLZPUSLKV_js.c[e.chainId]/100n});}let s=await chunkLZPUSLKV_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 chunkLZPUSLKV_js.T(t,this.configManager.getConfig().brokerAddress)).write.cancelOrders([e]);return await chunkLZPUSLKV_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 chunkLZPUSLKV_js.T(t,this.configManager.getConfig().brokerAddress)).write.cancelOrder([e]);return await chunkLZPUSLKV_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 chunkLZPUSLKV_js.T(t,this.configManager.getConfig().brokerAddress)).write.cancelOrders([e]);return await chunkLZPUSLKV_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 r=this.configManager.getConfig(),d=await this.utils.getNetworkFee(i,n),p={orderId:e.orderId,size:e.size,price:e.price,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 u=await chunkLZPUSLKV_js.T(n,r.brokerAddress);this.logger.info("updateOrderTpSl params",p);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,d.toString(),chunkLZPUSLKV_js.Q(n).TRADING_ROUTER)){let I=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkLZPUSLKV_js.Q(n).TRADING_ROUTER});if(I.code!==0)throw new Error(I.message)}let g=await u.estimateGas.updateOrder([c,p]),h=await u.write.updateOrder([c,p],{gasLimit:g*chunkLZPUSLKV_js.c[n]/100n}),x=await chunkLZPUSLKV_js.f(n).waitForTransactionReceipt({hash:h});return this.logger.info("updateOrderTpSl receipt",x),{code:0,data:x,message:"update order success"}}catch(m){return this.logger.error("Error updating order:",m),{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 qe=[{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 ye={"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 X=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:qe,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??chunkLZPUSLKV_js.Q(t).Account,r=await chunkLZPUSLKV_js.R(t,n).read.allowance([e,i]);return {code:0,data:String(r)}}catch(i){throw this.logger.error("Error getting allowance:",i),typeof i=="string"?i:await chunkLZPUSLKV_js.fa(i)}}async needsApproval(e,t,n,a,i){try{let r=(await this.getApproveQuoteAmount(e,t,n,i)).data,d=BigInt(r),p=BigInt(a);return d<p}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 chunkLZPUSLKV_js.S(e,t),s=n??viem.maxUint256,r=a??chunkLZPUSLKV_js.Q(e).Account,d=await this.getGasPriceByRatio(),p=await i.write.approve([r,s],{gasPrice:d});return await chunkLZPUSLKV_js.f(e).waitForTransactionReceipt({hash:p}),{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 r=chunkLZPUSLKV_js.U(n,s),d=a??await this.configManager.getSignerAddress(n),p=await r.read.getUserFeeRate([d,e,t]);return {code:0,data:{takerFeeRate:p[0].toString(),makerFeeRate:p[1].toString(),baseTakerFeeRate:p[2].toString(),baseMakerFeeRate:p[3].toString()}}}catch(r){return this.logger.error("Error getting user trading fee rate:",r),{code:-1,message:r?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkLZPUSLKV_js.V(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 chunkLZPUSLKV_js.pa(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 chunkLZPUSLKV_js.fa(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 chunkLZPUSLKV_js.V(t,0)).read.getForwardFeeByToken([n]),r=await chunkLZPUSLKV_js.R(t,n).read.balanceOf([e]);return !(BigInt(i)>0n&&BigInt(r)<BigInt(i))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:n}){try{return {code:0,data:await(await chunkLZPUSLKV_js.W(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(ye).find(i=>i.toLowerCase()===n);if(a)return ye[a]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkLZPUSLKV_js.la(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=chunkLZPUSLKV_js.d[t];return chunkLZPUSLKV_js.ka(e,n?.gasLimitRatio??1.3)}};var Z=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(r=>setTimeout(r,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=chunkLZPUSLKV_js.R(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 r=await(await chunkLZPUSLKV_js.X(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await chunkLZPUSLKV_js.f(i).waitForTransactionReceipt({hash:r})}}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=chunkLZPUSLKV_js.Q(n);try{if(await this.utils.needsApproval(a,n,t,e,i.Account)){let c=await this.utils.approveAuthorization({chainId:n,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:i.Account});if(c.code!==0)throw new Error(c.message)}let d=await(await chunkLZPUSLKV_js.X(n)).write.deposit([a,t,e]);return {code:0,data:await chunkLZPUSLKV_js.f(n).waitForTransactionReceipt({hash:d})}}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,r=BigInt(s?.quoteProfit??0),d=BigInt(s?.freeMargin??0),p=BigInt(s?.lockedMargin??0),c=i?.code===0?i.data:null,u=c?.status===1?BigInt(c?.lockedMargin??0):0n;return {code:0,data:d+r-p-u}}catch(a){return {code:-1,message:a.message}}}async getAccountInfo(e,t,n){let a=await chunkLZPUSLKV_js.W(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=chunkLZPUSLKV_js.U(e,n.brokerAddress),s=await chunkLZPUSLKV_js.f(e).getBlock({blockTag:"latest"}),r=Number(s?.timestamp??BigInt(xe__default.default().unix()))+300,d=await this.configManager.getAccessToken()??"";try{let p=await this.client.api.getCurrentEpoch({address:t,accessToken:d,broker:n.brokerAddress});if(p.code!==9200)throw new l("REQUEST_FAILED",p.msg??"Failed to get current epoch");let c=await a.read.userFeeData([p?.data??0,t]),u;try{u=await this.withRetry(()=>a.read.userNonces([t]));}catch{u=0n;}return {code:0,data:{...c,nonce:u.toString(),deadline:r}}}catch(p){return {code:-1,message:p.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 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");let r={user:e,nonce:a.nonce,deadline:n,feeData:{tier:a.tier,referrer:a.referrer||viem.zeroAddress,totalReferralRebatePct:a.totalReferralRebatePct,referrerRebatePct:a.referrerRebatePct},signature:i};try{let d=await chunkLZPUSLKV_js.T(t,s.brokerAddress),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 c=await d.write.setUserFeeData([r]);return {code:0,data:await chunkLZPUSLKV_js.f(t).waitForTransactionReceipt({hash:c})}}catch(d){return {code:-1,message:d.message}}}};function Ve(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function It(o,e){return Ve(e,o[e])}function wt(o,e){return o[e].map(n=>Ve(e,n)).join("&")}function At(o){let e=o||{};return Object.keys(e).filter(n=>typeof e[n]<"u").map(n=>Array.isArray(e[n])?wt(e,n):It(e,n)).join("&")}function fe(o){let e=At(o);return e?`?${e}`:""}var te=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 chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.delete(this.buildRequestPath(e),lodashEs.merge(a,n))}};var ne=class extends te{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...n}){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkLZPUSLKV_js.m.get(`${this.getHost()}/v2/agent/forwarder/get${fe(e)}`)}async getPoolList(){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${fe({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,positionId:n}){return await chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n,limit:a,interval:i})}async getKlineLatestBar(e){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n}){return chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n}){return chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n}){return chunkLZPUSLKV_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 chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkLZPUSLKV_js.m.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n,deadline:a,nonce:i}){return chunkLZPUSLKV_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 chunkLZPUSLKV_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 chunkLZPUSLKV_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 He=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 Tt={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"}]},Pt=2;function Ct(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 vt(o,e,t,n,a,i,s,r){let d=chunkLZPUSLKV_js.R(e,t),p=await He(d),[c]=await o.getAddresses();if(!c)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"}]},m={owner:n,spender:a,value:i,nonce:s,deadline:r},g=await o.signTypedData({account:c,domain:{...p,chainId:p.chainId},types:u,primaryType:"Permit",message:m});return Ct(g)}var ie=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 chunkLZPUSLKV_js.Y(n)).read.isUserRelayerEnabled([e,t]),r=await this.utils.needsApproval(e,n,a,viem.maxUint256.toString(),chunkLZPUSLKV_js.Q(n).TRADING_ROUTER);return s&&!r}async getContractAbiAndAddressByFunctionName(e,t){let n=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral","setUserFeeData"],a=["updateAndWithdraw","deposit"];return n.includes(e)?{abi:chunkLZPUSLKV_js.i,address:this.configManager.getConfig().brokerAddress}:a.includes(e)?{abi:chunkLZPUSLKV_js.l,address:chunkLZPUSLKV_js.Q(t).Account}:{abi:chunkLZPUSLKV_js.i,address:this.configManager.getConfig().brokerAddress}}async getUSDPermitParams(e,t,n){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let a=await chunkLZPUSLKV_js.h(t),i=chunkLZPUSLKV_js.Q(t),[s]=await a.getAddresses();if(!s)throw new l("INVALID_SIGNER","No account");let r=chunkLZPUSLKV_js.R(t,n);try{let d=await r.read.nonces([s]),p=await vt(a,t,n,s,i.TRADING_ROUTER,viem.maxUint256,d,e);return [{token:n,owner:s,spender:i.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:p.v,r:p.r,s:p.s}]}catch{throw new l("INVALID_PRIVATE_KEY","Invalid private key generated")}}async getForwardEip712Domain(e){let n=await(await chunkLZPUSLKV_js.Y(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:r="0"}){let d=await(await chunkLZPUSLKV_js.Y(e)).read.nonces([t]),p=xe__default.default().add(60,"minute").unix(),c=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(i,e);console.log("contractAddress:",m),console.log("orderParams-->",s);let g=viem.encodeFunctionData({abi:u,functionName:i,args:s}),h=await n({domain:c,functionHash:g,to:m,nonce:d.toString(),deadline:p});console.log("signFunction signature-->",h);let x=await this.api.forwarderTxApi({from:t,to:m,value:r??"0",gas:"800000",nonce:d.toString(),data:g,deadline:p,signature:h,forwardFeeToken:a},e);if(x.data?.txHash){for(let P=0;P<5;P++)try{if((await this.api.fetchForwarderGetApi({requestId:x.data.requestId})).data?.status===9)return {code:0};P<4&&await new Promise(O=>setTimeout(O,1e3));}catch(k){this.logger.error("Poll transaction from chain error:",k),P<4&&await new Promise(O=>setTimeout(O,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:r,forwardFeeToken:d},p){let c=await this.getForwardEip712Domain(p),u=await chunkLZPUSLKV_js.h(p),[m]=await u.getAddresses();if(!m)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let g=await u.signTypedData({account:m,domain:c,types:Tt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(n??"0"),gas:BigInt(a),nonce:BigInt(r),deadline:BigInt(i),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:n,gas:a,nonce:r,data:s,deadline:i,signature:g,forwardFeeToken:d},p)}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:n,forwardFeeToken:a}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(n):"";if(e){let g=(await this.account.getWalletQuoteTokenBalance({chainId:n,address:i,tokenAddress:a})).data,x=await(await chunkLZPUSLKV_js.V(n)).read.getForwardFeeByToken([a]),I=BigInt(x)*BigInt(Pt);if(I>0&&I>BigInt(g))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}let s=xe__default.default().add(60,"minute").unix(),r=[];if(e)try{r=await this.getUSDPermitParams(s,n,a);}catch(m){this.logger.warn("Failed to get USD permit params, proceeding without permit:",m),r=[];}let d=await chunkLZPUSLKV_js.Y(n,1),p=await(await chunkLZPUSLKV_js.Y(n)).read.nonces([i]),c=viem.encodeFunctionData({abi:chunkLZPUSLKV_js.j,functionName:"permitAndApproveForwarder",args:[t,e,r]}),u=await this.forwarderTx({from:i,to:d.address,value:"0",gas:"800000",nonce:p.toString(),data:c,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 chunkLZPUSLKV_js.Y(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:n,functionName:a,data:i,seamlessAddress:s}){let r=this.configManager.getConfig().brokerAddress;if(!r||!viem.isAddress(r))throw new l("INVALID_BROKER_ADDRESS","brokerAddress is missing or invalid; pass brokerAddress in MyxClient constructor / updateClientChainId");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 p=await chunkLZPUSLKV_js.Y(t),c;try{c=viem.encodeFunctionData({abi:chunkLZPUSLKV_js.i,functionName:a,args:i});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for Broker.${String(a)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await p.read.nonces([s]);return {from:s,to:r,value:"0",gas:"800000",deadline:xe__default.default().add(60,"minute").unix(),data:c,nonce:u.toString(),forwardFeeToken:n}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkLZPUSLKV_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkLZPUSLKV_js.Q(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkLZPUSLKV_js.U(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var se=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkLZPUSLKV_js._(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkLZPUSLKV_js.Z(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:chunkLZPUSLKV_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(),r=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),d=BigInt(r[0].value.toString()||"1"),p=await s.estimateGas.fileDispute([r,e,t],{value:d}),c=await this.client.utils.getGasLimitByRatio(p),u=await this.client.utils.getGasPriceByRatio(),m=await s.write.fileDispute([r,e,t],{value:d,gasLimit:c,gasPrice:u}),g=await chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:m}),h=this.getCaseIdFromReceiptLogs(g,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:g,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:n,deadline:a,v:i,r:s,s:r}){let d=await this.getDisputeCourtContract(),p=await d.estimateGas.vote([e,t,n?1:0,a,i,s,r]),c=await this.client.utils.getGasLimitByRatio(p),u=await this.client.utils.getGasPriceByRatio(),m=await d.write.vote([e,t,n?1:0,a,i,s,r],{gasLimit:c,gasPrice:u});return await chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:m})}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 chunkLZPUSLKV_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]),r=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),p=await i.write.claimReimbursement([e,t,n,a],{gasLimit:r,gasPrice:d});return chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:p})}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])),r=await a.write.fileDisputeFromStaker([e,t,n],{gasLimit:s,gasPrice:i}),d=await chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:r}),p=this.getCaseIdFromReceiptLogs(d,"DisputeFiled");if(p==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:d,caseId:p}}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 d=await a.estimateGas.appeal([e]),p=await this.client.utils.getGasLimitByRatio(d),c=await this.client.utils.getGasPriceByRatio(),u=await a.write.appeal([e],{gasLimit:p,gasPrice:c}),m=await chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),g=this.getCaseIdFromReceiptLogs(m,"AppealFiled");if(g==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:m,appealCaseId:g,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 re=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),n=await chunkLZPUSLKV_js.T(this.config.chainId,t.brokerAddress),a=await n.estimateGas.claimRebate([e]),i=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),r=await n.write.claimRebate([e],{gasPrice:s,gasLimit:i});return chunkLZPUSLKV_js.f(this.config.chainId).waitForTransactionReceipt({hash:r})}};var Rt=(d=>(d[d.UnderReview=1]="UnderReview",d[d.InitialVote=2]="InitialVote",d[d.PublicNotice=3]="PublicNotice",d[d.UnderReconsideration=4]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=6]="Failed",d[d.PlatformRuling=7]="PlatformRuling",d[d.PlatformRevoked=8]="PlatformRevoked",d))(Rt||{}),Mt=(c=>(c[c.InitialVoting=1]="InitialVoting",c[c.PublicNotice=2]="PublicNotice",c[c.UnderReconsideration=3]="UnderReconsideration",c[c.Won=5]="Won",c[c.Failed=4]="Failed",c[c.PlatformRuling=6]="PlatformRuling",c[c.PlatformRevoked=7]="PlatformRevoked",c[c.ReconsiderationVoting=8]="ReconsiderationVoting",c[c.AppealRevert=9]="AppealRevert",c[c.NotAppealFailed=10]="NotAppealFailed",c))(Mt||{}),Et=(a=>(a[a.UnderReview=1]="UnderReview",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Completed=4]="Completed",a))(Et||{}),Dt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Dt||{}),Ot=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Ot||{}),Ft=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Ft||{}),Lt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Lt||{}),Nt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Nt||{}),_t=(n=>(n[n.NoVote=0]="NoVote",n[n.Supported=1]="Supported",n[n.Rejected=2]="Rejected",n))(_t||{}),Bt=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Bt||{}),Gt=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))(Gt||{});var Ie=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new K(e),this.logger=new chunkLZPUSLKV_js.ea({logLevel:e.logLevel});let t=chunkLZPUSLKV_js.O.getInstance();t.setConfigManager(this.configManager),chunkLZPUSLKV_js.g(this.configManager),t.getMarkets().then(),this.utils=new X(this.configManager,this.logger),this.api=new ne(this.configManager,this.logger),this.account=new Z(this.configManager,this.logger,this.utils,this),this.seamless=new ie(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new Q(this.configManager,this.utils,this.api),this.position=new j(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new Y(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new V(this.configManager,this.logger),this.appeal=new se(this,this.configManager),this.referrals=new re(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 Ki="1.0.13";
|
|
2
|
-
Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return
|
|
1
|
+
'use strict';var chunkC5JAWLE4_js=require('./chunk-C5JAWLE4.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 chunkC5JAWLE4_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=chunkC5JAWLE4_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=chunkC5JAWLE4_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 chunkC5JAWLE4_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&&(chunkC5JAWLE4_js.ea("Received expired token, using default expiry"),n=3600);}return this.setAccessToken(t.accessToken,n),t.accessToken}else return chunkC5JAWLE4_js.ea("\u274C Received empty accessToken"),null}catch(t){return chunkC5JAWLE4_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 chunkC5JAWLE4_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,chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(i);if(d){let C=await this.utils.approveAuthorization({chainId:i,quoteAddress:a,amount:viem.maxUint256.toString(),spenderAddress:chunkC5JAWLE4_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)*chunkC5JAWLE4_js.c[i]/100n});return await chunkC5JAWLE4_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,chunkC5JAWLE4_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:chunkC5JAWLE4_js.Q(e.chainId).TRADING_ROUTER});if(x.code!==0)throw new Error(x.message)}let u=await chunkC5JAWLE4_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*chunkC5JAWLE4_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*chunkC5JAWLE4_js.c[e.chainId]/100n});}let m=await chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(e),p=await r.estimateGas.placeOrdersWithPosition([n,a,i]),s=await r.write.placeOrdersWithPosition([n,a,i],{gasLimit:p*chunkC5JAWLE4_js.c[e]/100n}),c=await chunkC5JAWLE4_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 chunkC5JAWLE4_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*chunkC5JAWLE4_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*chunkC5JAWLE4_js.c[e.chainId]/100n});}let u=await chunkC5JAWLE4_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 chunkC5JAWLE4_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*chunkC5JAWLE4_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*chunkC5JAWLE4_js.c[e.chainId]/100n});}let u=await chunkC5JAWLE4_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*chunkC5JAWLE4_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*chunkC5JAWLE4_js.c[e.chainId]/100n});}let r=await chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(t)).write.cancelOrders([e]);return await chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(t)).write.cancelOrder([e]);return await chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(t)).write.cancelOrders([e]);return await chunkC5JAWLE4_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 chunkC5JAWLE4_js.T(n);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(a,n,e.executionFeeToken,p.toString(),chunkC5JAWLE4_js.Q(n).TRADING_ROUTER)){let x=await this.utils.approveAuthorization({chainId:n,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkC5JAWLE4_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*chunkC5JAWLE4_js.c[n]/100n}),h=await chunkC5JAWLE4_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??chunkC5JAWLE4_js.Q(t).Account,p=await chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.U(e,t),r=n??viem.maxUint256,p=a??chunkC5JAWLE4_js.Q(e).Account,s=await this.getGasPriceByRatio(),c=await i.write.approve([p,r],{gasPrice:s});return await chunkC5JAWLE4_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=chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.X(t,0)).read.getForwardFeeByToken([n]),p=await chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.na(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,n=chunkC5JAWLE4_js.d[t];return chunkC5JAWLE4_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=chunkC5JAWLE4_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 chunkC5JAWLE4_js.Z(i)).write.updateAndWithdraw([e,t,n,a]);return {code:0,data:await chunkC5JAWLE4_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=chunkC5JAWLE4_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 chunkC5JAWLE4_js.Z(n)).write.deposit([a,t,e]);return {code:0,data:await chunkC5JAWLE4_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 chunkC5JAWLE4_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=chunkC5JAWLE4_js.W(e,n.brokerAddress),r=await chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,n,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkC5JAWLE4_js.m.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:n,limit:a,interval:i})}async getKlineLatestBar(e){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...n}){return chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...n}){return chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...n}){return chunkC5JAWLE4_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 chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,n,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkC5JAWLE4_js.m.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:n,deadline:a,nonce:i}){return chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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=chunkC5JAWLE4_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 chunkC5JAWLE4_js._(n)).read.isUserRelayerEnabled([e,t]),p=await this.utils.needsApproval(e,n,a,viem.maxUint256.toString(),chunkC5JAWLE4_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:chunkC5JAWLE4_js.R,address:chunkC5JAWLE4_js.Q(t).TRADING_ROUTER}:i.includes(e)?{abi:chunkC5JAWLE4_js.l,address:chunkC5JAWLE4_js.Q(t).Account}:(console.log("functionName==>",e),console.log("brokerFunctions.includes(functionName)->",a.includes(e)),a.includes(e)?{abi:chunkC5JAWLE4_js.i,address:this.configManager.getConfig().brokerAddress}:{abi:chunkC5JAWLE4_js.R,address:chunkC5JAWLE4_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 chunkC5JAWLE4_js.h(t),i=chunkC5JAWLE4_js.Q(t),[r]=await a.getAddresses();if(!r)throw new l("INVALID_SIGNER","No account");let p=chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js._(n,1),c=await(await chunkC5JAWLE4_js._(n)).read.nonces([i]),d=viem.encodeFunctionData({abi:chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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||!chunkC5JAWLE4_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkC5JAWLE4_js.Q(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkC5JAWLE4_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 chunkC5JAWLE4_js.aa(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkC5JAWLE4_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:chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_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 chunkC5JAWLE4_js.ga({logLevel:e.logLevel});let t=chunkC5JAWLE4_js.O.getInstance();t.setConfigManager(this.configManager),chunkC5JAWLE4_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.14";
|
|
2
|
+
Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkC5JAWLE4_js.la}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ka}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkC5JAWLE4_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.C}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.z}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkC5JAWLE4_js.n}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.B}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkC5JAWLE4_js.E}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.q}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ga}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkC5JAWLE4_js.t}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkC5JAWLE4_js.o}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkC5JAWLE4_js.r}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkC5JAWLE4_js.O}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.w}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkC5JAWLE4_js.p}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.A}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.v}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.u}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.s}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.D}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.x}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkC5JAWLE4_js.y}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkC5JAWLE4_js.pa}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkC5JAWLE4_js.va}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkC5JAWLE4_js.oa}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkC5JAWLE4_js.na}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ma}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ta}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ja}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ia}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkC5JAWLE4_js.L}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkC5JAWLE4_js.G}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkC5JAWLE4_js.M}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkC5JAWLE4_js.N}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkC5JAWLE4_js.H}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkC5JAWLE4_js.I}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkC5JAWLE4_js.F}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkC5JAWLE4_js.J}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ra}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkC5JAWLE4_js.qa}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkC5JAWLE4_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ca}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkC5JAWLE4_js.K}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkC5JAWLE4_js.sa}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkC5JAWLE4_js.h}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkC5JAWLE4_js.P}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkC5JAWLE4_js.xa}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ua}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ya}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkC5JAWLE4_js.wa}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkC5JAWLE4_js.fa}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkC5JAWLE4_js.da}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ea}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkC5JAWLE4_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkC5JAWLE4_js.ba}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=_t;exports.AppealNodeStateEnum=Ut;exports.AppealNodeVotedStateEnum=Bt;exports.AppealReconsiderationType=Ft;exports.AppealStage=Ot;exports.AppealStatus=qt;exports.AppealType=Dt;exports.Direction=ga;exports.IsVoteNodeEnum=Wt;exports.MyxClient=Ie;exports.NodeTypeEnum=Lt;exports.OperationType=S;exports.OrderStatus=fa;exports.OrderType=K;exports.SDK_VERSION=Zi;exports.TimeInForce=ya;exports.TriggerType=ma;exports.VoteTypeEnum=Nt;exports.fromViemWalletClient=ue;exports.normalizeSigner=z;
|