@myx-trade/sdk 1.0.22 → 1.0.23-beta.2

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.
@@ -46,7 +46,7 @@ declare enum TriggerType$1 {
46
46
  SL = 2
47
47
  }
48
48
  interface TpSl {
49
- amount: number;
49
+ amount: number | string;
50
50
  triggerPrice: number | string;
51
51
  triggerType: TriggerType$1;
52
52
  }
@@ -609,14 +609,14 @@ interface Deposit {
609
609
  chainId: ChainId;
610
610
  poolId: string;
611
611
  decimals?: number;
612
- amount: number;
612
+ amount: string | number;
613
613
  slippage: number;
614
614
  tpsl?: DepositTpSl[];
615
615
  }
616
616
  interface WithdrawParams {
617
617
  chainId: ChainId;
618
618
  poolId: string;
619
- amount: number;
619
+ amount: number | string;
620
620
  slippage: number;
621
621
  }
622
622
  interface RewardsParams {
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-DBOkga-6.mjs';
2
- export { U as AccessTokenResponse, R as AccessTokenType, u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, a0 as ChainIdRequest, w as CreatePoolRequest, L as DashboardType, a9 as Direction, J as ErrorCode, a5 as FavoritesDefaultItem, a1 as FavoritesType, $ as MarketCapType, W as MarketPool, X as MarketPoolResponse, V as MarketPoolState, _ as MarketType, N as NetWorkFee, I as ObjectType, a8 as OperationType, ac as Order, ad as OrderStatus, a6 as OrderType, Z as PoolOpenOrder, ab as Position, Y as PriceType, a2 as SearchResultContractItem, a3 as SearchResultCookItem, a4 as SearchResultEarnItem, Q as StatDashBoardResponse, aa as TimeInForce, x as TpSLParams, y as TpSl, ae as TradingResult, a7 as TriggerType, af as UpdateOrderTpSlParams, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-DBOkga-6.mjs';
1
+ import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-Btw0KF7k.mjs';
2
+ export { U as AccessTokenResponse, R as AccessTokenType, u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, a0 as ChainIdRequest, w as CreatePoolRequest, L as DashboardType, a9 as Direction, J as ErrorCode, a5 as FavoritesDefaultItem, a1 as FavoritesType, $ as MarketCapType, W as MarketPool, X as MarketPoolResponse, V as MarketPoolState, _ as MarketType, N as NetWorkFee, I as ObjectType, a8 as OperationType, ac as Order, ad as OrderStatus, a6 as OrderType, Z as PoolOpenOrder, ab as Position, Y as PriceType, a2 as SearchResultContractItem, a3 as SearchResultCookItem, a4 as SearchResultEarnItem, Q as StatDashBoardResponse, aa as TimeInForce, x as TpSLParams, y as TpSl, ae as TradingResult, a7 as TriggerType, af as UpdateOrderTpSlParams, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-Btw0KF7k.mjs';
3
3
  import * as viem from 'viem';
4
4
  import { WalletClient, Address, PublicClient, Abi } from 'viem';
5
5
  export { formatUnits, parseUnits } from 'viem';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-DBOkga-6.js';
2
- export { U as AccessTokenResponse, R as AccessTokenType, u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, a0 as ChainIdRequest, w as CreatePoolRequest, L as DashboardType, a9 as Direction, J as ErrorCode, a5 as FavoritesDefaultItem, a1 as FavoritesType, $ as MarketCapType, W as MarketPool, X as MarketPoolResponse, V as MarketPoolState, _ as MarketType, N as NetWorkFee, I as ObjectType, a8 as OperationType, ac as Order, ad as OrderStatus, a6 as OrderType, Z as PoolOpenOrder, ab as Position, Y as PriceType, a2 as SearchResultContractItem, a3 as SearchResultCookItem, a4 as SearchResultEarnItem, Q as StatDashBoardResponse, aa as TimeInForce, x as TpSLParams, y as TpSl, ae as TradingResult, a7 as TriggerType, af as UpdateOrderTpSlParams, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-DBOkga-6.js';
1
+ import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-Btw0KF7k.js';
2
+ export { U as AccessTokenResponse, R as AccessTokenType, u as AddTpSLParams, D as COMMON_LP_AMOUNT_DECIMALS, z as COMMON_PRICE_DECIMALS, v as CancelTpSLParams, a0 as ChainIdRequest, w as CreatePoolRequest, L as DashboardType, a9 as Direction, J as ErrorCode, a5 as FavoritesDefaultItem, a1 as FavoritesType, $ as MarketCapType, W as MarketPool, X as MarketPoolResponse, V as MarketPoolState, _ as MarketType, N as NetWorkFee, I as ObjectType, a8 as OperationType, ac as Order, ad as OrderStatus, a6 as OrderType, Z as PoolOpenOrder, ab as Position, Y as PriceType, a2 as SearchResultContractItem, a3 as SearchResultCookItem, a4 as SearchResultEarnItem, Q as StatDashBoardResponse, aa as TimeInForce, x as TpSLParams, y as TpSl, ae as TradingResult, a7 as TriggerType, af as UpdateOrderTpSlParams, q as base, G as getPriceData, E as getPricesData, t as market, s as pool, r as quote } from './index-Btw0KF7k.js';
3
3
  import * as viem from 'viem';
4
4
  import { WalletClient, Address, PublicClient, Abi } from 'viem';
5
5
  export { formatUnits, parseUnits } from 'viem';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkUNEIP5PG_js=require('./chunk-UNEIP5PG.js'),lt=require('mitt'),cryptoEs=require('crypto-es'),ut=require('reconnecting-websocket'),viem=require('viem'),Ae=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var lt__default=/*#__PURE__*/_interopDefault(lt);var ut__default=/*#__PURE__*/_interopDefault(ut);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var $=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var V=o=>{switch(o.request){case "signin":return $(o.request)}return $(JSON.stringify(o))},N=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return $(JSON.stringify({topic:e,params:t}))}},Be=({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}},_e=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:N({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[i,r]=t.split("_");return {...o,type:N({topic:"candle",params:{globalId:parseInt(i),resolution:r}}),globalId:parseInt(i),resolution:r}}}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 Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=lt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:i,...r}=t;this.config={...Ge,...r},this.logger=new chunkUNEIP5PG_js.ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let i={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 ut__default.default(this.config.url,this.config.protocols,i),this.setupEventListeners(e,t);}catch(i){t(i);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async i=>{this.eventBus.emit("open",i),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=i=>{this.handleMessage(i);},this.ws.onclose=i=>{this.eventBus.emit("close",i),this.stopHeartbeatTimer();},this.ws.onerror=i=>{this.eventBus.emit("error",i),t(i);},this.ws.addEventListener("reconnecting",i=>{this.eventBus.emit("reconnecting",{detail:i.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,i)=>{let r=V(e);this.waitingRequests.has(r)?(this.waitingRequests.get(r)?.onSuccess.add(t),this.waitingRequests.get(r)?.onError.add(i)):this.waitingRequests.set(r,{onSuccess:new Set([t]),onError:new Set([i])}),this.send(e);})}subscribe(e,t){let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let c=N(a);if(!n.has(c))if(n.add(c),this.subscriptions.has(c))this.subscriptions.get(c).callbacks.add(t);else {let g={id:c,topic:a.topic,callbacks:new Set([t])};this.subscriptions.set(c,g),r.push(c),this.logger.debug(`create new subscription: ${c}`);}}),r.length>0&&this.send({request:"subv2",args:r});}unsubscribe(e,t){if(!e)return;let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let c=N(a);if(n.has(c))return;n.add(c);let g=this.subscriptions.get(c);g&&(g.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${c}`),g.callbacks.size===0&&(this.subscriptions.delete(c),r.push(c),this.logger.debug(`subscription ${c} has no callbacks, will unsubscribe`)));}),r.length>0&&this.send({request:"unsubv2",args:r});}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(Be(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=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let i=this.waitingRequests.get(t),r=e.data.code===9200;r?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),i?.onError.size&&!r&&i.onError.forEach(n=>{n(new l("REQUEST_FAILED","Request failed"));}),i?.onSuccess.size&&r&&i.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=_e(e),i=t.type,r=this.subscriptions.get(i);r&&r.callbacks.forEach(n=>{try{n(t);}catch(a){this.logger.error(`Callback Error (${i}): ${a}`);}});}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||Ge.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 We=[56,59144,42161],Ue=[59141,421614,97],$e=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var z=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let i=H.MainNet;e.getConfig().isBetaMode?i=H.BetaNet:e.getConfig().isTestnet&&(i=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:i,...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 i=Array.isArray(e)?e:[e];this.wsClient.subscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}unsubscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}subscribeKline(e,t,i){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}unsubscribeKline(e,t,i){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}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 pt(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function mt(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function 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 i=typeof t=="string"?t:{raw:t};return await o.signMessage({message:i})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let i=t.to;if(!i)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:i,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 Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:i=>o.signMessage(i),async sendTransaction(i){let r={...i};i.value!=null&&(r.value=BigInt(i.value)),i.gasLimit!=null&&(r.gasLimit=BigInt(i.gasLimit)),i.gasPrice!=null&&(r.gasPrice=BigInt(i.gasPrice)),i.maxFeePerGas!=null&&(r.maxFeePerGas=BigInt(i.maxFeePerGas)),i.maxPriorityFeePerGas!=null&&(r.maxPriorityFeePerGas=BigInt(i.maxPriorityFeePerGas));try{let a=(await o.sendTransaction(r)).hash;if(!a)throw new Error("sendTransaction: no hash in response");return {hash:a}}catch(n){let a=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||a.includes("BigInt")||a.includes("bigint")){let c={...i};i.value!=null&&(c.value=`0x${BigInt(i.value).toString(16)}`),i.gasLimit!=null&&(c.gasLimit=`0x${BigInt(i.gasLimit).toString(16)}`),i.gasPrice!=null&&(c.gasPrice=`0x${BigInt(i.gasPrice).toString(16)}`),i.maxFeePerGas!=null&&(c.maxFeePerGas=`0x${BigInt(i.maxFeePerGas).toString(16)}`),i.maxPriorityFeePerGas!=null&&(c.maxPriorityFeePerGas=`0x${BigInt(i.maxPriorityFeePerGas).toString(16)}`);let d=(await o.sendTransaction(c)).hash;if(!d)throw new Error("sendTransaction: no hash in response");return {hash:d}}throw n}},signTransaction:typeof e.signTransaction=="function"?i=>t.signTransaction(i):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(i){return t.signTypedData(i.domain,i.types,i.message)}}:typeof t._signTypedData=="function"?{async signTypedData(i){return t._signTypedData(i.domain,i.types,i.message)}}:{}}}function K(o){return pt(o)?me(o):mt(o)?Ve(o):o}function qe(o){let e=chunkUNEIP5PG_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 fe={};function bt(o){if(!fe[o]){let e=chunkUNEIP5PG_js.e(o);fe[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),i=bt(e),r=await o.getAddress();return viem.createWalletClient({account:r,chain:i,transport:viem.custom({request:async a=>{if(a.method==="eth_accounts")return [r];if(a.method==="eth_sendTransaction"){let d=a.params?.[0]??{},{hash:s}=await o.sendTransaction({to:d.to,data:d.data,value:d.value!=null?BigInt(d.value):void 0,gasLimit:d.gas!=null?BigInt(d.gas):void 0,gasPrice:d.gasPrice!=null?BigInt(d.gasPrice):void 0,maxFeePerGas:d.maxFeePerGas!=null?BigInt(d.maxFeePerGas):void 0,maxPriorityFeePerGas:d.maxPriorityFeePerGas!=null?BigInt(d.maxPriorityFeePerGas):void 0});return s}if(a.method==="eth_signTypedData_v4"||a.method==="eth_signTypedData"){if(!o.signTypedData){let h=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(h.error)throw new Error(h.error.message);return h.result}let d=a.params?.[1];if(typeof d!="string")throw new Error("Invalid eth_signTypedData_v4 params");let s=JSON.parse(d),{EIP712Domain:u,...p}=s.types;return await o.signTypedData({domain:s.domain,types:p,primaryType:s.primaryType,message:s.message})}let g=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(g.error)throw new Error(g.error.message);return g.result}})})}var j=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.getWalletClient?.()||this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let i=(await this.config.walletClient.getAddresses())[0];if(i)return i}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.getWalletClient){let r=0;for(;r<1e4;){let n=this.config.getWalletClient();if(n)return n;await new Promise(a=>setTimeout(a,200)),r+=200;}throw new l("INVALID_SIGNER","WalletClient not available after chain switch")}if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?K(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:i,chainId:r}=e;if(t){if(!Ue.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of TESTNET_CHAIN_IDS`)}else if(i){if(!$e.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,i)=>{this._getAccessTokenQueue.push({resolve:t,reject:i,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 chunkUNEIP5PG_js.fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let i=3600;if(t.expireAt){let r=Math.floor(Date.now()/1e3);i=t.expireAt-r,i<=0&&(chunkUNEIP5PG_js.fa("Received expired token, using default expiry"),i=3600);}return this.setAccessToken(t.accessToken,i),t.accessToken}else return chunkUNEIP5PG_js.fa("\u274C Received empty accessToken"),null}catch(t){return chunkUNEIP5PG_js.ga("\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,i){this.configManager=e,this.utils=t,this.api=i;}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 i=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:i})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:i})).data}async addFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:i})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:i})).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:i}){let r=await chunkUNEIP5PG_js.Z(t);try{return {code:0,data:await r.read.getPoolInfo([e,i])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async listPositions(e,t){let i=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:i??"",address:e,positionId:t})).data}}catch(r){return this.logger.error("Error fetching positions:",r),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:i,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:i,quoteToken:r,chainId:n,address:a}){this.configManager.getConfig();try{let g=await this.utils.getOraclePrice(e,n);if(!g)throw new Error("Failed to get price data");let d={poolId:e,oracleType:g.oracleType,publishTime:g.publishTime,oracleUpdateData:g?.vaa??"0"},s=!1;Number(i)>0&&(s=await this.utils.needsApproval(a,n,r,i,chunkUNEIP5PG_js.R(n).TRADING_ROUTER));let u=BigInt(0),p=BigInt(i)>0?BigInt(i):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:a}),h=m.code===0?m.data??0n:0n,w=BigInt(0);h<p&&(w=p-h,u=w);let I={token:r,amount:u.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let Ce=await chunkUNEIP5PG_js.U(n);if(s){let S=await this.utils.approveAuthorization({chainId:n,quoteAddress:r,amount:viem.maxUint256.toString(),spenderAddress:chunkUNEIP5PG_js.R(n).TRADING_ROUTER});if(S.code!==0)throw new Error(S.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[d],I,t,i],{value:BigInt(g?.value??"1"),gas:BigInt(1e7)*chunkUNEIP5PG_js.c[n]/100n});return await chunkUNEIP5PG_js.f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(g){return {code:-1,message:g.message}}}};var wt={IOC:0},R=wt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},lr={NONE:0,GTE:1,LTE:2},v={INCREASE:0,DECREASE:1},ur={LONG:0,SHORT:1},pr={IOC:0},mr={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async createIncreaseOrder(e,t){try{let i=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),c=i-n;c>BigInt(0)&&(a=c);let g={token:e.executionFeeToken,amount:a.toString()},d={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:v.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},s=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkUNEIP5PG_js.R(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(s){let w=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkUNEIP5PG_js.R(e.chainId).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let u=await chunkUNEIP5PG_js.U(e.chainId),p;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...d,positionId:e.positionId});let w=await u.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...g},d]);p=await u.write.placeOrderWithPosition([e.positionId.toString(),{...g},d],{gasLimit:w*chunkUNEIP5PG_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:d,depositData:g});let I=await u.estimateGas.placeOrderWithSalt(["1",{...g},d]);p=await u.write.placeOrderWithSalt(["1",{...g},d],{gasLimit:I*chunkUNEIP5PG_js.c[e.chainId]/100n});}let m=await chunkUNEIP5PG_js.f(e.chainId).waitForTransactionReceipt({hash:p});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:p,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(i){return this.logger.error("Error placing order:",i),{code:-1,message:i?.message}}}async closeAllPositions(e,t){try{let i={token:"0x0000000000000000000000000000000000000000",amount:"0"},r=t.map(s=>s.positionId.toString()),n=t.map(s=>({user:s.address,poolId:s.poolId,orderType:s.orderType,triggerType:s.triggerType,operation:v.DECREASE,direction:s.direction,collateralAmount:s.collateralAmount,size:s.size,price:s.price,timeInForce:R,postOnly:s.postOnly,slippagePct:s.slippagePct,leverage:s.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",i,r,n),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await chunkUNEIP5PG_js.U(e),c=await a.estimateGas.placeOrdersWithPosition([i,r,n]),g=await a.write.placeOrdersWithPosition([i,r,n],{gasLimit:c*chunkUNEIP5PG_js.c[e]/100n}),d=await chunkUNEIP5PG_js.f(e).waitForTransactionReceipt({hash:g});return {code:0,message:"close all positions success",transactionHash:g,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}catch(i){return {code:-1,message:i?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:v.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},i=BigInt(e.collateralAmount),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),c=i-n;c>BigInt(0)&&(a=c);let g={token:e.executionFeeToken,amount:a.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await chunkUNEIP5PG_js.U(e.chainId),s;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,g,{data:t}]);let m=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),g,t]);s=await d.write.placeOrderWithPosition([e.positionId.toString(),g,t],{gasLimit:m*chunkUNEIP5PG_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,g,{data:t}]);let h=await d.estimateGas.placeOrderWithSalt(["1",g,t]);s=await d.write.placeOrderWithSalt(["1",g,t],{gasLimit:h*chunkUNEIP5PG_js.c[e.chainId]/100n});}let u=await chunkUNEIP5PG_js.f(e.chainId).waitForTransactionReceipt({hash:s});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:s,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 chunkUNEIP5PG_js.U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let g=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:v.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:Y.STOP,triggerType:e.slTriggerType,operation:v.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}],d={token:"0x0000000000000000000000000000000000000000",amount:"0"},s;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([d,[e.positionId.toString(),e.positionId.toString()],g]);s=await t.write.placeOrdersWithPosition([d,[e.positionId.toString(),e.positionId.toString()],g],{gasLimit:m*chunkUNEIP5PG_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",g);let m=1,h=await t.estimateGas.placeOrdersWithSalt([d,[m.toString(),m.toString()],g]);s=await t.write.placeOrdersWithSalt([d,[m.toString(),m.toString()],g],{gasLimit:h*chunkUNEIP5PG_js.c[e.chainId]/100n});}let u=await chunkUNEIP5PG_js.f(e.chainId).waitForTransactionReceipt({hash:s});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:s,blockNumber:u?.blockNumber,gasUsed:u?.gasUsed?.toString(),status:u?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:u}}}let i={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:v.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},r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",i);let g=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,i]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),r,i],{gasLimit:g*chunkUNEIP5PG_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",i);let g=1,d=await t.estimateGas.placeOrderWithSalt([g.toString(),r,i]);n=await t.write.placeOrderWithSalt([g.toString(),r,i],{gasLimit:d*chunkUNEIP5PG_js.c[e.chainId]/100n});}let a=await chunkUNEIP5PG_js.f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:a?.blockNumber,gasUsed:a?.gasUsed?.toString(),status:a?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:a}}}catch(i){return {code:-1,message:i?.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 r=await(await chunkUNEIP5PG_js.U(t)).write.cancelOrders([e]);return await chunkUNEIP5PG_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel all orders success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkUNEIP5PG_js.U(t)).write.cancelOrder([e]);return await chunkUNEIP5PG_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel order success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkUNEIP5PG_js.U(t)).write.cancelOrders([e]);return await chunkUNEIP5PG_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"Orders canceled success"}}catch(i){return this.logger.error("Error canceling orders:",i),{code:-1,message:i?.message}}}async updateOrderTpSl(e,t,i,r,n,a){let c=await this.utils.getNetworkFee(n,i),g={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:a?e.tpSize:"0",tpPrice:a?e.tpPrice:"0",slSize:a?e.slSize:"0",slPrice:a?e.slPrice:"0"}},d={token:t,amount:c.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let s=await chunkUNEIP5PG_js.U(i);this.logger.info("updateOrderTpSl params",g);try{if(await this.utils.needsApproval(r,i,e.executionFeeToken,c.toString(),chunkUNEIP5PG_js.R(i).TRADING_ROUTER)){let w=await this.utils.approveAuthorization({chainId:i,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkUNEIP5PG_js.R(i).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let p=await s.estimateGas.updateOrder([d,g]),m=await s.write.updateOrder([d,g],{gasLimit:p*chunkUNEIP5PG_js.c[i]/100n}),h=await chunkUNEIP5PG_js.f(i).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(i){return this.logger.error("Error fetching orders:",i),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:i,...e,address:t})).data}}};var he={"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 Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,i,r){try{if(!i||typeof i=="string"&&!i.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=r??chunkUNEIP5PG_js.R(t).Account,c=await chunkUNEIP5PG_js.T(t,i).read.allowance([e,n]);return {code:0,data:String(c)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await chunkUNEIP5PG_js.ja(n)}}async needsApproval(e,t,i,r,n){try{let c=(await this.getApproveQuoteAmount(e,t,i,n)).data,g=BigInt(c),d=BigInt(r);return g<d}catch(a){return this.logger.error("Error checking approval needs:",a),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:i,spenderAddress:r}){try{let n=await chunkUNEIP5PG_js.V(e,t),a=i??viem.maxUint256,c=r??chunkUNEIP5PG_js.R(e).Account,g=await this.getGasPriceByRatio(),d=await n.write.approve([c,a],{gasPrice:g});return await chunkUNEIP5PG_js.f(e).waitForTransactionReceipt({hash:d}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,i,r){let a=this.configManager.getConfig().brokerAddress;try{let c=chunkUNEIP5PG_js.X(i,a),g=r??await this.configManager.getSignerAddress(i),d=await c.read.getUserFeeRate([g,e,t]);return {code:0,data:{takerFeeRate:d[0].toString(),makerFeeRate:d[1].toString(),baseTakerFeeRate:d[2].toString(),baseMakerFeeRate:d[3].toString()}}}catch(c){return this.logger.error("Error getting user trading fee rate:",c),{code:-1,message:c?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkUNEIP5PG_js.Y(t,0)).read.getExecutionFee([e])).toString()}catch(i){return this.logger.error("Error getting network fee:",i),"0"}}async getOraclePrice(e,t){try{let i=await chunkUNEIP5PG_js.ta(t,e);if(!i)throw new Error("Failed to get price data");return i}catch(i){throw this.logger.error("Error getting oracle price:",i),i}}async buildUpdatePriceParams(e,t){let i=await this.getOraclePrice(e,t);if(!i)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:i.vaa,publishTime:i.publishTime,oracleType:i.oracleType,value:i.value,price:i.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 i=await chunkUNEIP5PG_js.ja(e);return i?i.error:JSON.stringify(e)}catch(i){return i?.message??i?.toString()??t}}async checkSeamlessGas(e,t,i){let n=await(await chunkUNEIP5PG_js.Y(t,0)).read.getForwardFeeByToken([i]),c=await chunkUNEIP5PG_js.T(t,i).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(c)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:i}){try{return {code:0,data:await(await chunkUNEIP5PG_js.Z(e,0)).read.getPoolInfo([t,i])}}catch(r){return this.logger.error("Error getting pool info:",r),{code:-1,message:r?.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 i=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);i&&i[1]&&(t=i[1]);}if(t){let i=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(i){let r=Object.keys(he).find(n=>n.toLowerCase()===i);if(r)return he[r]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkUNEIP5PG_js.pa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,i=chunkUNEIP5PG_js.d[t];return chunkUNEIP5PG_js.oa(e,i?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,i,r){this.configManager=e,this.logger=t,this.utils=i,this.client=r;}async withRetry(e,t=3,i=300){let r;for(let n=0;n<t;n++)try{return await e()}catch(a){r=a,n<t-1&&await new Promise(c=>setTimeout(c,i));}throw r}async getTradeFlow(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:i,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:i}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=chunkUNEIP5PG_js.T(e,i),n=await this.configManager.getSignerAddress(e);return {code:0,data:await r.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,i,r,n){try{let c=await(await chunkUNEIP5PG_js._(n)).write.updateAndWithdraw([e,t,i,r]);return {code:0,data:await chunkUNEIP5PG_js.f(n).waitForTransactionReceipt({hash:c})}}catch(a){return {code:-1,message:a.message}}}async deposit({amount:e,tokenAddress:t,chainId:i}){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"",n=chunkUNEIP5PG_js.R(i);try{if(await this.utils.needsApproval(r,i,t,e,n.Account)){let s=await this.utils.approveAuthorization({chainId:i,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:n.Account});if(s.code!==0)throw new Error(s.message)}let g=await(await chunkUNEIP5PG_js._(i)).write.deposit([r,t,e]);return {code:0,data:await chunkUNEIP5PG_js.f(i).waitForTransactionReceipt({hash:g})}}catch(a){return {code:-1,message:a.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:i}){try{let r=await this.getAccountInfo(t,i,e);if(r.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,i),a=r.data,c=BigInt(a?.quoteProfit??0),g=BigInt(a?.freeMargin??0),d=BigInt(a?.lockedMargin??0),s=n?.code===0?n.data:null,u=s?.status===1?BigInt(s?.lockedMargin??0):0n;return {code:0,data:g+c-d-u}}catch(r){return {code:-1,message:r.message}}}async getAccountInfo(e,t,i){let r=await chunkUNEIP5PG_js.Z(e);try{return {code:0,data:await r.read.getAccountInfo([i,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let i=this.configManager.getConfig(),r=chunkUNEIP5PG_js.X(e,i.brokerAddress),a=await chunkUNEIP5PG_js.f(e).getBlock({blockTag:"latest"}),c=Number(a?.timestamp??BigInt(Ae__default.default().unix()))+300;try{let g=await r.read.userFeeData([t]),d;try{d=await this.withRetry(()=>r.read.userNonces([t]));}catch{d=0n;}return {code:0,data:{nonce:d.toString(),deadline:c,...g}}}catch(g){return {code:-1,message:g.message}}}async getAccountVipInfoByBackend(e,t,i,r){let n=await this.configManager.getAccessToken()??"";try{let a=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:i,nonce:r});if(a.code!==9200)throw new l("REQUEST_FAILED",a.msg??"Failed to get account vip info");return {code:0,data:a.data}}catch(a){return {code:-1,message:a.message}}}async setUserFeeData(e,t,i,r,n){let a=this.configManager.getConfig();if(i<Ae__default.default().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let c=await chunkUNEIP5PG_js.W(t,a.brokerAddress),g={user:e,nonce:r.nonce,deadline:i,feeData:{tier:r.tier,referrer:r.referrer||viem.zeroAddress,totalReferralRebatePct:r.totalReferralRebatePct,referrerRebatePct:r.referrerRebatePct,expiry:r.expiry},signature:n},d=await c.read.userNonces([e]);if(parseInt(d.toString())+1!==parseInt(r.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let s=await c.write.setUserFeeData([g]);return {code:0,data:await chunkUNEIP5PG_js.f(t).waitForTransactionReceipt({hash:s})}}catch(c){return {code:-1,message:c.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(i=>Qe(e,i)).join("&")}function Pt(o){let e=o||{};return Object.keys(e).filter(i=>typeof e[i]<"u").map(i=>Array.isArray(e[i])?Tt(e,i):Ct(e,i)).join("&")}function be(o){let e=Pt(o);return e?`?${e}`:""}var ie=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()??"",i=await this.configManager.getSignerAddress(e.chainId);if(!i)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:i}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUNEIP5PG_js.n.get(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async post(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUNEIP5PG_js.n.post(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async put(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUNEIP5PG_js.n.put(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async delete(e,{auth:t=false,...i}={}){let r=t?await this.buildAuthParams():{};return chunkUNEIP5PG_js.n.delete(this.buildRequestPath(e),lodashEs.merge(r,i))}};var re=class extends ie{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkUNEIP5PG_js.n.get(`${this.getHost()}/v2/agent/forwarder/get${be(e)}`)}async getPoolList(){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkUNEIP5PG_js.n.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/quote/price/oracles`,{chainId:e,poolIds:t.join(",")});throw new Error("Invalid pool id")}async getPoolDetail(e,t){return await chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${be({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...i}){return await chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,i){return await chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,i){return await chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${i}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:i,limit:r,interval:n}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:i,limit:r,interval:n})}async getKlineLatestBar(e){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async addFavoritesBatch(e){return this.post("/openapi/gateway/scan/market/add-favorites-batch",e,{auth:true})}async removeFavorite({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:i,deadline:r,nonce:n}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:i,deadline:r,nonce:n},{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:i}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:i},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:r}){return chunkUNEIP5PG_js.n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:i,myx_openapi_access_token:r}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,vt="0x55d398326f99059ff775485246999027b3197955";function kt(o){let e=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),i=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:i}}async function Mt(o,e,t,i,r,n,a,c){let g=chunkUNEIP5PG_js.T(e,t),d=await Je(g),[s]=await o.getAddresses();if(!s)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"}]},p={owner:i,spender:r,value:n,nonce:a,deadline:c},m=await o.signTypedData({account:s,domain:{...d,chainId:d.chainId},types:u,primaryType:"Permit",message:p});return kt(m)}var ne=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async onCheckRelayer(e,t,i,r,n){let c=await(await chunkUNEIP5PG_js.$(i)).read.isUserRelayerEnabled([e,t]),d=await(await chunkUNEIP5PG_js.Y(i)).read.getForwardFeeByToken([r]),s=BigInt(d)*BigInt(Xe);n=n??s.toString();let u=await this.utils.needsApproval(e,i,r,n,chunkUNEIP5PG_js.R(i).TRADING_ROUTER);return c&&!u}async getContractAbiAndAddressByFunctionName(e,t){let i=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],r=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return i.includes(e)?{abi:chunkUNEIP5PG_js.S,address:chunkUNEIP5PG_js.R(t).TRADING_ROUTER}:n.includes(e)?{abi:chunkUNEIP5PG_js.m,address:chunkUNEIP5PG_js.R(t).Account}:r.includes(e)?{abi:chunkUNEIP5PG_js.j,address:this.configManager.getConfig().brokerAddress}:{abi:chunkUNEIP5PG_js.S,address:chunkUNEIP5PG_js.R(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkUNEIP5PG_js.i(t),n=chunkUNEIP5PG_js.R(t),[a]=await r.getAddresses();if(!a)throw new l("INVALID_SIGNER","No account");let c=chunkUNEIP5PG_js.T(t,i);try{let g=await c.read.nonces([a]),d=await Mt(r,t,i,a,n.TRADING_ROUTER,viem.maxUint256,g,e);return [{token:i,owner:a,spender:n.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:d.v,r:d.r,s:d.s}]}catch(g){if(chunkUNEIP5PG_js.ia(g))throw g;let d=g instanceof Error?g.message:String(g);throw new l("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${d}`)}}async getForwardEip712Domain(e){let i=await(await chunkUNEIP5PG_js.$(e)).read.eip712Domain();return {name:i[1],version:i[2],chainId:i[3],verifyingContract:i[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:i,forwardFeeToken:r,functionName:n,orderParams:a,value:c="0",gas:g="800000"}){let d=await(await chunkUNEIP5PG_js.$(e)).read.nonces([t]),s=Ae__default.default().add(60,"minute").unix(),u=await this.getForwardEip712Domain(e),{abi:p,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),h=viem.encodeFunctionData({abi:p,functionName:n,args:a}),w=await i({domain:u,functionHash:h,to:m,nonce:d.toString(),deadline:s}),I=await this.api.forwarderTxApi({from:t,to:m,value:c??"0",gas:g,nonce:d.toString(),data:h,deadline:s,signature:w,forwardFeeToken:r},e);if(I.data?.txHash){for(let S=0;S<5;S++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};S<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Te){this.logger.error("Poll transaction from chain error:",Te),S<4&&await new Promise(ce=>setTimeout(ce,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:i,gas:r,deadline:n,data:a,nonce:c,forwardFeeToken:g},d){let s=await this.getForwardEip712Domain(d),u=await chunkUNEIP5PG_js.i(d),[p]=await u.getAddresses();if(!p)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await u.signTypedData({account:p,domain:s,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(i??"0"),gas:BigInt(r),nonce:BigInt(c),deadline:BigInt(n),data:a}});return await this.api.forwarderTxApi({from:e,to:t,value:i,gas:r,nonce:c,data:a,deadline:n,signature:m,forwardFeeToken:g},d)}async approveBalance(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkUNEIP5PG_js.V(e,t),n=chunkUNEIP5PG_js.R(e);return await r.write?.approve([n.TRADING_ROUTER,i])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:i,address:n,tokenAddress:r})).data,w=await(await chunkUNEIP5PG_js.Y(i)).read.getForwardFeeByToken([r]),I=BigInt(w)*BigInt(Xe);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r});let a=Ae__default.default().add(60,"minute").unix(),c=[];if(e)try{r===vt?(await this.approveBalance(i,r,viem.maxUint256.toString()))?.hash&&(c=[]):c=await this.getUSDPermitParams(a,i,r);}catch(p){if(chunkUNEIP5PG_js.ia(p))return {code:-1,data:null,message:"User Rejected"};if(p?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};this.logger.warn("Failed to get USD permit params, proceeding without permit:",p),c=[];}let g=await chunkUNEIP5PG_js.$(i,1),d=await(await chunkUNEIP5PG_js.$(i)).read.nonces([n]),s=viem.encodeFunctionData({abi:chunkUNEIP5PG_js.k,functionName:"permitAndApproveForwarder",args:[t,e,c]}),u;try{u=await this.forwarderTx({from:n,to:g.address,value:"0",gas:"800000",nonce:d.toString(),data:s,deadline:a,forwardFeeToken:r},i);}catch(p){if(chunkUNEIP5PG_js.ia(p))return {code:-1,data:null,message:"User Rejected"};if(p?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};throw p}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(w){this.logger.error("Poll transaction from chain error:",w),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 getApproveBalance({chainId:e,forwardFeeToken:t,address:i}){try{let r=chunkUNEIP5PG_js.R(e).TRADING_ROUTER,a=await chunkUNEIP5PG_js.T(e,t).read.allowance([i,r]);return {code:0,data:String(a)}}catch(r){return {code:-1,message:r?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkUNEIP5PG_js.$(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:i,functionName:r,data:n,seamlessAddress:a}){if(!e||!viem.isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!a||!viem.isAddress(a))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!i||!viem.isAddress(i))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))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,i))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let g=await chunkUNEIP5PG_js.$(t),d,{abi:s,address:u}=await this.getContractAbiAndAddressByFunctionName(r,t);try{d=viem.encodeFunctionData({abi:s,functionName:r,args:n});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(r)}: ${m.message}. Check args shape and that no address field is undefined.`)}let p=await g.read.nonces([a]);return {from:a,to:u,value:"0",gas:"800000",deadline:Ae__default.default().add(60,"minute").unix(),data:d,nonce:p.toString(),forwardFeeToken:i}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkUNEIP5PG_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkUNEIP5PG_js.R(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkUNEIP5PG_js.X(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkUNEIP5PG_js.ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkUNEIP5PG_js.aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let i=t==="DisputeFiled"?"caseId":"appealCaseId";for(let r of e.logs)try{let n=viem.decodeEventLog({abi:chunkUNEIP5PG_js.l,data:r.data,topics:r.topics});if(n.eventName===t&&n.args&&i in n.args)return n.args[i]}catch{continue}return null}async submitAppeal(e,t,i){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(r,this.config.chainId,t,i,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let a=await this.getDisputeCourtContract(),c=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),g=BigInt(c[0].value.toString()||"1"),d=await a.estimateGas.fileDispute([c,e,t],{value:g}),s=await this.client.utils.getGasLimitByRatio(d),u=await this.client.utils.getGasPriceByRatio(),p=await a.write.fileDispute([c,e,t],{value:g,gasLimit:s,gasPrice:u}),m=await chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:p}),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:i,deadline:r,v:n,r:a,s:c}){let g=await this.getDisputeCourtContract(),d=await g.estimateGas.vote([e,t,i?1:0,r,n,a,c]),s=await this.client.utils.getGasLimitByRatio(d),u=await this.client.utils.getGasPriceByRatio(),p=await g.write.vote([e,t,i?1:0,r,n,a,c],{gasLimit:s,gasPrice:u});return await chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:p})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),i=await t.estimateGas.claimBond([e]),r=await this.client.utils.getGasLimitByRatio(i),n=await this.client.utils.getGasPriceByRatio(),a=await t.write.claimBond([e],{gasLimit:r,gasPrice:n});return chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:a})}async claimReimbursement(e,t,i,r){let n=await this.getReimbursementContract(),a=await n.estimateGas.claimReimbursement([e,t,i,r]),c=await this.client.utils.getGasLimitByRatio(a),g=await this.client.utils.getGasPriceByRatio(),d=await n.write.claimReimbursement([e,t,i,r],{gasLimit:c,gasPrice:g});return chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:d})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e){let t=await this.getDisputeCourtContract(),i=await this.client.utils.getGasPriceByRatio(),r=await this.client.utils.getGasLimitByRatio(await t.estimateGas.fileDisputeFromStaker([e])),n=await t.write.fileDisputeFromStaker([e],{gasLimit:r,gasPrice:i}),a=await chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:n}),c=this.getCaseIdFromReceiptLogs(a,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:a,caseId:c}}async appealReconsideration(e,t,i){let r=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",a=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,i,a)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:a});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let g=await r.estimateGas.appeal([e]),d=await this.client.utils.getGasLimitByRatio(g),s=await this.client.utils.getGasPriceByRatio(),u=await r.write.appeal([e],{gasLimit:d,gasPrice:s}),p=await chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),m=this.getCaseIdFromReceiptLogs(p,"AppealFiled");if(m==null)throw new l("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:p,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,i){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:await this.configManager.getAccessToken()??""})}};var se=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),i=await chunkUNEIP5PG_js.W(this.config.chainId,t.brokerAddress),r=await i.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(r),a=await this.client.utils.getGasPriceByRatio(),c=await i.write.claimRebate([e],{gasPrice:a,gasLimit:n});return chunkUNEIP5PG_js.f(this.config.chainId).waitForTransactionReceipt({hash:c})}};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[s.SettlementVoting=10]="SettlementVoting",s[s.SettlementFailed=11]="SettlementFailed",s))(Dt||{}),Ot=(s=>(s[s.InitialVoting=1]="InitialVoting",s[s.PublicNotice=2]="PublicNotice",s[s.UnderReconsideration=3]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=4]="Failed",s[s.PlatformRuling=6]="PlatformRuling",s[s.PlatformRevoked=7]="PlatformRevoked",s[s.ReconsiderationVoting=8]="ReconsiderationVoting",s[s.AppealRevert=9]="AppealRevert",s[s.NotAppealFailed=10]="NotAppealFailed",s))(Ot||{}),Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.PublicNotice=2]="PublicNotice",r[r.UnderReconsideration=3]="UnderReconsideration",r[r.Completed=4]="Completed",r))(Ft||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Lt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Lt||{}),Bt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Bt||{}),_t=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(_t||{}),Gt=(i=>(i[i.Appeal=1]="Appeal",i[i.Reconsideration=2]="Reconsideration",i[i.Settlement=3]="Settlement",i))(Gt||{}),Wt=(i=>(i[i.NoVote=0]="NoVote",i[i.Supported=1]="Supported",i[i.Rejected=2]="Rejected",i))(Wt||{}),Ut=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Ut||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var xe=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new chunkUNEIP5PG_js.ha({logLevel:e.logLevel});let t=chunkUNEIP5PG_js.P.getInstance();chunkUNEIP5PG_js.h()?.hasSigner()||(t.setConfigManager(this.configManager),chunkUNEIP5PG_js.g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new re(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(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 X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new se(this);}auth(e){this.configManager.auth(e),chunkUNEIP5PG_js.P.getInstance().setConfigManager(this.configManager),chunkUNEIP5PG_js.g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Xn="1.0.22";
2
- Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkUNEIP5PG_js.na}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ma}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkUNEIP5PG_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.D}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.A}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkUNEIP5PG_js.o}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.C}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkUNEIP5PG_js.F}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.r}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ha}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkUNEIP5PG_js.u}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkUNEIP5PG_js.p}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkUNEIP5PG_js.s}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkUNEIP5PG_js.P}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.x}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkUNEIP5PG_js.q}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.B}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.w}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.v}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.t}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.E}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.y}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkUNEIP5PG_js.z}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ra}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkUNEIP5PG_js.xa}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkUNEIP5PG_js.qa}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkUNEIP5PG_js.pa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkUNEIP5PG_js.oa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkUNEIP5PG_js.va}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkUNEIP5PG_js.la}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ka}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkUNEIP5PG_js.M}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkUNEIP5PG_js.H}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkUNEIP5PG_js.N}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkUNEIP5PG_js.O}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkUNEIP5PG_js.I}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkUNEIP5PG_js.J}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkUNEIP5PG_js.G}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkUNEIP5PG_js.K}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ta}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkUNEIP5PG_js.sa}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkUNEIP5PG_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkUNEIP5PG_js.da}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkUNEIP5PG_js.L}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ua}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkUNEIP5PG_js.i}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkUNEIP5PG_js.Q}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkUNEIP5PG_js.za}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkUNEIP5PG_js.wa}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkUNEIP5PG_js.Aa}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ya}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ga}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ea}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkUNEIP5PG_js.fa}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkUNEIP5PG_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkUNEIP5PG_js.ca}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=Bt;exports.AppealNodeStateEnum=Wt;exports.AppealNodeVotedStateEnum=_t;exports.AppealReconsiderationType=Ot;exports.AppealStage=Ft;exports.AppealStatus=$t;exports.AppealType=Dt;exports.Direction=ur;exports.IsVoteNodeEnum=Ut;exports.MyxClient=xe;exports.NodeTypeEnum=Nt;exports.OperationType=v;exports.OrderStatus=mr;exports.OrderType=Y;exports.SDK_VERSION=Xn;exports.TimeInForce=pr;exports.TriggerType=lr;exports.VoteTypeEnum=Lt;exports.fromViemWalletClient=me;exports.normalizeSigner=K;
1
+ 'use strict';var chunkE6HWUEQ7_js=require('./chunk-E6HWUEQ7.js'),pt=require('mitt'),cryptoEs=require('crypto-es'),dt=require('reconnecting-websocket'),viem=require('viem'),Ie=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var pt__default=/*#__PURE__*/_interopDefault(pt);var dt__default=/*#__PURE__*/_interopDefault(dt);var Ie__default=/*#__PURE__*/_interopDefault(Ie);var U=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var V=o=>{switch(o.request){case "signin":return U(o.request)}return U(JSON.stringify(o))},F=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return U(JSON.stringify({topic:e,params:t}))}},Ne=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",lt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Be=o=>{switch(lt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:F({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[r,i]=t.split("_");return {...o,type:F({topic:"candle",params:{globalId:parseInt(r),resolution:i}}),globalId:parseInt(r),resolution:i}}}return o};var p=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=pt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:r,...i}=t;this.config={...Ge,...i},this.logger=new chunkE6HWUEQ7_js.ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let r={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new dt__default.default(this.config.url,this.config.protocols,r),this.setupEventListeners(e,t);}catch(r){t(r);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async r=>{this.eventBus.emit("open",r),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=r=>{this.handleMessage(r);},this.ws.onclose=r=>{this.eventBus.emit("close",r),this.stopHeartbeatTimer();},this.ws.onerror=r=>{this.eventBus.emit("error",r),t(r);},this.ws.addEventListener("reconnecting",r=>{this.eventBus.emit("reconnecting",{detail:r.detail||0}),this.isFirstConnection=false;}),this.ws.addEventListener("maxreconnectattempts",()=>{this.eventBus.emit("maxreconnectattempts",void 0);}));}pong(e){this.send({request:"pong",args:e});}request(e){return new Promise((t,r)=>{let i=V(e);this.waitingRequests.has(i)?(this.waitingRequests.get(i)?.onSuccess.add(t),this.waitingRequests.get(i)?.onError.add(r)):this.waitingRequests.set(i,{onSuccess:new Set([t]),onError:new Set([r])}),this.send(e);})}subscribe(e,t){let r=Array.isArray(e)?e:[e],i=[],n=new Set;r.forEach(s=>{let c=F(s);if(!n.has(c))if(n.add(c),this.subscriptions.has(c))this.subscriptions.get(c).callbacks.add(t);else {let g={id:c,topic:s.topic,callbacks:new Set([t])};this.subscriptions.set(c,g),i.push(c),this.logger.debug(`create new subscription: ${c}`);}}),i.length>0&&this.send({request:"subv2",args:i});}unsubscribe(e,t){if(!e)return;let r=Array.isArray(e)?e:[e],i=[],n=new Set;r.forEach(s=>{let c=F(s);if(n.has(c))return;n.add(c);let g=this.subscriptions.get(c);g&&(g.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${c}`),g.callbacks.size===0&&(this.subscriptions.delete(c),i.push(c),this.logger.debug(`subscription ${c} has no callbacks, will unsubscribe`)));}),i.length>0&&this.send({request:"unsubv2",args:i});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new p("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(Ne(t)){this.handleAckMessage(t);return}this.handleSubscriptionMessage(t);}catch(t){this.logger.error(`Failed to parse WebSocket message: ${t}`);}}handleAckMessage(e){let t;switch(e.type){case "signin":t=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let r=this.waitingRequests.get(t),i=e.data.code===9200;i?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),r?.onError.size&&!i&&r.onError.forEach(n=>{n(new p("REQUEST_FAILED","Request failed"));}),r?.onSuccess.size&&i&&r.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=Be(e),r=t.type,i=this.subscriptions.get(r);i&&i.callbacks.forEach(n=>{try{n(t);}catch(s){this.logger.error(`Callback Error (${r}): ${s}`);}});}resubscribeAll(){if(this.subscriptions.size===0)return;this.logger.debug("resubscribe all...");let e=Array.from(this.subscriptions.values()).map(t=>t.id);e.length>0&&(this.send({request:"subv2",args:e}),this.logger.debug(`resubscribe ${e.length} topics`));}timeoutHeartbeat(){this.stopHeartbeatTimer(),Date.now()-this.lastMessageTime>(this.config.noMessageTimeout||Ge.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 We=[56,59144,42161],$e=[59141,421614,97],Ue=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var K=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let r=H.MainNet;e.getConfig().isBetaMode?r=H.BetaNet:e.getConfig().isTestnet&&(r=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:r,...this.configManager.getConfig()?.socketConfig,onBeforeReSubscribe:()=>{if(this.clientAuth)return this.auth(true).then(()=>{this.logger.debug("reconnect auth success");})}});}get isConnected(){return this.wsClient.isConnected()}connect(){this.wsClient.connect();}disconnect(){this.wsClient.disconnect();}reconnect(){this.wsClient.reconnect();}subscribeTickers(e,t){let r=Array.isArray(e)?e:[e];this.wsClient.subscribe(r.map(i=>({topic:"ticker",params:{globalId:i}})),t);}unsubscribeTickers(e,t){let r=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(r.map(i=>({topic:"ticker",params:{globalId:i}})),t);}subscribeKline(e,t,r){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}unsubscribeKline(e,t,r){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},r);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new p("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function ut(o){return typeof o.getAddresses=="function"&&typeof o.getAddress!="function"&&typeof o.signMessage=="function"&&typeof o.sendTransaction=="function"}function mt(o){let e=o;return typeof e.getAddress=="function"&&typeof e.signMessage=="function"&&(typeof e.sendTransaction=="function"||typeof e.provider<"u")}function he(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 r=typeof t=="string"?t:{raw:t};return await o.signMessage({message:r})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let r=t.to;if(!r)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:r,data:t.data,value:t.value!=null?BigInt(t.value):void 0,gas:t.gasLimit!=null?BigInt(t.gasLimit):void 0,gasPrice:t.gasPrice!=null?BigInt(t.gasPrice):void 0,maxFeePerGas:t.maxFeePerGas!=null?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas!=null?BigInt(t.maxPriorityFeePerGas):void 0})}},...typeof e.signTypedData=="function"?{async signTypedData(t){return await e.signTypedData(t)}}:{}}}function Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:r=>o.signMessage(r),async sendTransaction(r){let i={...r};r.value!=null&&(i.value=BigInt(r.value)),r.gasLimit!=null&&(i.gasLimit=BigInt(r.gasLimit)),r.gasPrice!=null&&(i.gasPrice=BigInt(r.gasPrice)),r.maxFeePerGas!=null&&(i.maxFeePerGas=BigInt(r.maxFeePerGas)),r.maxPriorityFeePerGas!=null&&(i.maxPriorityFeePerGas=BigInt(r.maxPriorityFeePerGas));try{let s=(await o.sendTransaction(i)).hash;if(!s)throw new Error("sendTransaction: no hash in response");return {hash:s}}catch(n){let s=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||s.includes("BigInt")||s.includes("bigint")){let c={...r};r.value!=null&&(c.value=`0x${BigInt(r.value).toString(16)}`),r.gasLimit!=null&&(c.gasLimit=`0x${BigInt(r.gasLimit).toString(16)}`),r.gasPrice!=null&&(c.gasPrice=`0x${BigInt(r.gasPrice).toString(16)}`),r.maxFeePerGas!=null&&(c.maxFeePerGas=`0x${BigInt(r.maxFeePerGas).toString(16)}`),r.maxPriorityFeePerGas!=null&&(c.maxPriorityFeePerGas=`0x${BigInt(r.maxPriorityFeePerGas).toString(16)}`);let l=(await o.sendTransaction(c)).hash;if(!l)throw new Error("sendTransaction: no hash in response");return {hash:l}}throw n}},signTransaction:typeof e.signTransaction=="function"?r=>t.signTransaction(r):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(r){return t.signTypedData(r.domain,r.types,r.message)}}:typeof t._signTypedData=="function"?{async signTypedData(r){return t._signTypedData(r.domain,r.types,r.message)}}:{}}}function z(o){return ut(o)?he(o):mt(o)?Ve(o):o}function qe(o){let e=chunkE6HWUEQ7_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 fe={};function yt(o){if(!fe[o]){let e=chunkE6HWUEQ7_js.e(o);fe[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),r=yt(e),i=await o.getAddress();return viem.createWalletClient({account:i,chain:r,transport:viem.custom({request:async s=>{if(s.method==="eth_accounts")return [i];if(s.method==="eth_sendTransaction"){let l=s.params?.[0]??{},{hash:a}=await o.sendTransaction({to:l.to,data:l.data,value:l.value!=null?BigInt(l.value):void 0,gasLimit:l.gas!=null?BigInt(l.gas):void 0,gasPrice:l.gasPrice!=null?BigInt(l.gasPrice):void 0,maxFeePerGas:l.maxFeePerGas!=null?BigInt(l.maxFeePerGas):void 0,maxPriorityFeePerGas:l.maxPriorityFeePerGas!=null?BigInt(l.maxPriorityFeePerGas):void 0});return a}if(s.method==="eth_signTypedData_v4"||s.method==="eth_signTypedData"){if(!o.signTypedData){let f=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(f.error)throw new Error(f.error.message);return f.result}let l=s.params?.[1];if(typeof l!="string")throw new Error("Invalid eth_signTypedData_v4 params");let a=JSON.parse(l),{EIP712Domain:d,...u}=a.types;return await o.signTypedData({domain:a.domain,types:u,primaryType:a.primaryType,message:a.message})}let g=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:s.method,params:s.params??[]})})).json();if(g.error)throw new Error(g.error.message);return g.result}})})}var j=class{constructor(e){this._normalizedSigner=null;this._getAccessTokenQueue=[];this._isGettingAccessToken=false;let t={isTestnet:false,isBetaMode:false,...e};this.validateConfig(t),this.config=t,(this.config.walletClient||this.config.signer)&&this.auth({walletClient:this.config.walletClient,signer:this.config.signer,getAccessToken:this.config.getAccessToken});}clear(){this.accessToken=void 0,this.accessTokenExpiry=void 0,this._normalizedSigner=null,this.config={...this.config,signer:void 0,walletClient:void 0,getAccessToken:void 0};}hasSigner(){return !!(this.config.getWalletClient?.()||this.config.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let r=(await this.config.walletClient.getAddresses())[0];if(r)return r}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new p("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.getWalletClient){let i=0;for(;i<1e4;){let n=this.config.getWalletClient();if(n)return n;await new Promise(s=>setTimeout(s,200)),i+=200;}throw new p("INVALID_SIGNER","WalletClient not available after chain switch")}if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new p("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?z(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:r,chainId:i}=e;if(t){if(!$e.includes(i))throw new p("INVALID_CHAIN_ID",`chainId ${i} is not in the range of TESTNET_CHAIN_IDS`)}else if(r){if(!Ue.includes(i))throw new p("INVALID_CHAIN_ID",`chainId ${i} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(i))throw new p("INVALID_CHAIN_ID",`chainId ${i} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,r)=>{this._getAccessTokenQueue.push({resolve:t,reject:r,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return chunkE6HWUEQ7_js.fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let r=3600;if(t.expireAt){let i=Math.floor(Date.now()/1e3);r=t.expireAt-i,r<=0&&(chunkE6HWUEQ7_js.fa("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return chunkE6HWUEQ7_js.fa("\u274C Received empty accessToken"),null}catch(t){return chunkE6HWUEQ7_js.ga("\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,r){this.configManager=e,this.utils=t,this.api=r;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){return (await this.api.getKlineData({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getKlineLatestBar({interval:e,...t}){this.configManager.getConfig();return (await this.api.getKlineLatestBar({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getTickerList(e){return (await this.api.getTickerData(e)).data}async searchMarketAuth(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:r})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:r})).data}async addFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:r})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let r=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:r})).data}async getBaseDetail(e){return (await this.api.getBaseDetail(e)).data}async getMarketDetail(e){return (await this.api.getMarketDetail(e)).data}async getPoolSymbolAll(){return (await this.api.getPoolSymbolAll()).data}async getPoolFundingFeeInfo({poolId:e,chainId:t,marketPrice:r}){let i=await chunkE6HWUEQ7_js.Z(t);try{return {code:0,data:await i.read.getPoolInfo([e,r])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,r,i,n){this.configManager=e,this.logger=t,this.utils=r,this.account=i,this.api=n;}async listPositions(e,t){let r=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:r??"",address:e,positionId:t})).data}}catch(i){return this.logger.error("Error fetching positions:",i),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:r,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:r,quoteToken:i,chainId:n,address:s}){this.configManager.getConfig();try{let g=await this.utils.getOraclePrice(e,n);if(!g)throw new Error("Failed to get price data");let l={poolId:e,oracleType:g.oracleType,publishTime:g.publishTime,oracleUpdateData:g?.vaa??"0"},a=!1;Number(r)>0&&(a=await this.utils.needsApproval(s,n,i,r,chunkE6HWUEQ7_js.R(n).TRADING_ROUTER));let d=BigInt(0),u=BigInt(r)>0?BigInt(r):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:s}),f=m.code===0?m.data??0n:0n,b=BigInt(0);f<u&&(b=u-f,d=b);let A={token:i,amount:d.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let Ce=await chunkE6HWUEQ7_js.U(n);if(a){let P=await this.utils.approveAuthorization({chainId:n,quoteAddress:i,amount:viem.maxUint256.toString(),spenderAddress:chunkE6HWUEQ7_js.R(n).TRADING_ROUTER});if(P.code!==0)throw new Error(P.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[l],A,t,r],{value:BigInt(g?.value??"1"),gas:BigInt(1e7)*chunkE6HWUEQ7_js.c[n]/100n});return await chunkE6HWUEQ7_js.f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(g){return {code:-1,message:g.message}}}};var bt={IOC:0},R=bt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},pi={NONE:0,GTE:1,LTE:2},v={INCREASE:0,DECREASE:1},di={LONG:0,SHORT:1},ui={IOC:0},mi={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,r,i,n){this.configManager=e,this.logger=t,this.utils=r,this.account=i,this.api=n;}async createIncreaseOrder(e,t){try{let r=BigInt(e.collateralAmount)+BigInt(t),i=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=i.code===0?i.data??0n:0n,s=BigInt(0),c=r-n;c>BigInt(0)&&(s=c);let g={token:e.executionFeeToken,amount:s.toString()},l={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:v.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},a=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkE6HWUEQ7_js.R(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");if(a){let b=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkE6HWUEQ7_js.R(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await chunkE6HWUEQ7_js.U(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...l,positionId:e.positionId});let b=await d.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...g},l]);u=await d.write.placeOrderWithPosition([e.positionId.toString(),{...g},l],{gasLimit:b*chunkE6HWUEQ7_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:l,depositData:g});let A=await d.estimateGas.placeOrderWithSalt(["1",{...g},l]);u=await d.write.placeOrderWithSalt(["1",{...g},l],{gasLimit:A*chunkE6HWUEQ7_js.c[e.chainId]/100n});}let m=await chunkE6HWUEQ7_js.f(e.chainId).waitForTransactionReceipt({hash:u});return {code:0,message:"create increase order success",data:{success:!0,transactionHash:u,blockNumber:m?.blockNumber,gasUsed:m?.gasUsed?.toString(),status:m?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:m}}}catch(r){return this.logger.error("Error placing order:",r),{code:-1,message:r?.message}}}async closeAllPositions(e,t){try{let r={token:"0x0000000000000000000000000000000000000000",amount:"0"},i=t.map(a=>a.positionId.toString()),n=t.map(a=>({user:a.address,poolId:a.poolId,orderType:a.orderType,triggerType:a.triggerType,operation:v.DECREASE,direction:a.direction,collateralAmount:a.collateralAmount,size:a.size,price:a.price,timeInForce:R,postOnly:a.postOnly,slippagePct:a.slippagePct,leverage:a.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",r,i,n),!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let s=await chunkE6HWUEQ7_js.U(e),c=await s.estimateGas.placeOrdersWithPosition([r,i,n]),g=await s.write.placeOrdersWithPosition([r,i,n],{gasLimit:c*chunkE6HWUEQ7_js.c[e]/100n}),l=await chunkE6HWUEQ7_js.f(e).waitForTransactionReceipt({hash:g});return {code:0,message:"close all positions success",transactionHash:g,blockNumber:l?.blockNumber,gasUsed:l?.gasUsed?.toString(),status:l?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:l}}catch(r){return {code:-1,message:r?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:v.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},r=BigInt(e.collateralAmount),i=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=i.code===0?i.data??0n:0n,s=BigInt(0),c=r-n;c>BigInt(0)&&(s=c);let g={token:e.executionFeeToken,amount:s.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let l=await chunkE6HWUEQ7_js.U(e.chainId),a;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,g,{data:t}]);let m=await l.estimateGas.placeOrderWithPosition([e.positionId.toString(),g,t]);a=await l.write.placeOrderWithPosition([e.positionId.toString(),g,t],{gasLimit:m*chunkE6HWUEQ7_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,g,{data:t}]);let f=await l.estimateGas.placeOrderWithSalt(["1",g,t]);a=await l.write.placeOrderWithSalt(["1",g,t],{gasLimit:f*chunkE6HWUEQ7_js.c[e.chainId]/100n});}let d=await chunkE6HWUEQ7_js.f(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkE6HWUEQ7_js.U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let g=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:v.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:Y.STOP,triggerType:e.slTriggerType,operation:v.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}],l={token:"0x0000000000000000000000000000000000000000",amount:"0"},a;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([l,[e.positionId.toString(),e.positionId.toString()],g]);a=await t.write.placeOrdersWithPosition([l,[e.positionId.toString(),e.positionId.toString()],g],{gasLimit:m*chunkE6HWUEQ7_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",g);let m=1,f=await t.estimateGas.placeOrdersWithSalt([l,[m.toString(),m.toString()],g]);a=await t.write.placeOrdersWithSalt([l,[m.toString(),m.toString()],g],{gasLimit:f*chunkE6HWUEQ7_js.c[e.chainId]/100n});}let d=await chunkE6HWUEQ7_js.f(e.chainId).waitForTransactionReceipt({hash:a});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:a,blockNumber:d?.blockNumber,gasUsed:d?.gasUsed?.toString(),status:d?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:d}}}let r={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:v.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},i={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",r);let g=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),i,r]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),i,r],{gasLimit:g*chunkE6HWUEQ7_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",r);let g=1,l=await t.estimateGas.placeOrderWithSalt([g.toString(),i,r]);n=await t.write.placeOrderWithSalt([g.toString(),i,r],{gasLimit:l*chunkE6HWUEQ7_js.c[e.chainId]/100n});}let s=await chunkE6HWUEQ7_js.f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:s?.blockNumber,gasUsed:s?.gasUsed?.toString(),status:s?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:s}}}catch(r){return {code:-1,message:r?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let i=await(await chunkE6HWUEQ7_js.U(t)).write.cancelOrders([e]);return await chunkE6HWUEQ7_js.f(t).waitForTransactionReceipt({hash:i}),{code:0,message:"cancel all orders success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let i=await(await chunkE6HWUEQ7_js.U(t)).write.cancelOrder([e]);return await chunkE6HWUEQ7_js.f(t).waitForTransactionReceipt({hash:i}),{code:0,message:"cancel order success"}}catch(r){return {code:-1,message:r?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let i=await(await chunkE6HWUEQ7_js.U(t)).write.cancelOrders([e]);return await chunkE6HWUEQ7_js.f(t).waitForTransactionReceipt({hash:i}),{code:0,message:"Orders canceled success"}}catch(r){return this.logger.error("Error canceling orders:",r),{code:-1,message:r?.message}}}async updateOrderTpSl(e,t,r,i,n,s){let c=await this.utils.getNetworkFee(n,r),g={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:s?e.tpSize:"0",tpPrice:s?e.tpPrice:"0",slSize:s?e.slSize:"0",slPrice:s?e.slPrice:"0"}},l={token:t,amount:c.toString()};if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let a=await chunkE6HWUEQ7_js.U(r);this.logger.info("updateOrderTpSl params",g);try{if(await this.utils.needsApproval(i,r,e.executionFeeToken,c.toString(),chunkE6HWUEQ7_js.R(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkE6HWUEQ7_js.R(r).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let u=await a.estimateGas.updateOrder([l,g]),m=await a.write.updateOrder([l,g],{gasLimit:u*chunkE6HWUEQ7_js.c[r]/100n}),f=await chunkE6HWUEQ7_js.f(r).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",f),{code:0,data:f,message:"update order success"}}catch(d){return this.logger.error("Error updating order:",d),{code:-1,message:"Failed to update order"}}}async getOrders(e){let t=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getOrders(t??"",e)).data}}catch(r){return this.logger.error("Error fetching orders:",r),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:r,...e,address:t})).data}}};var Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,r,i){try{if(!r||typeof r=="string"&&!r.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=i??chunkE6HWUEQ7_js.R(t).Account,c=await chunkE6HWUEQ7_js.T(t,r).read.allowance([e,n]);return {code:0,data:String(c)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await chunkE6HWUEQ7_js.ka(n)}}async needsApproval(e,t,r,i,n){try{let c=(await this.getApproveQuoteAmount(e,t,r,n)).data,g=BigInt(c),l=BigInt(i);return g<l}catch(s){return this.logger.error("Error checking approval needs:",s),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:r,spenderAddress:i}){try{let n=await chunkE6HWUEQ7_js.V(e,t),s=r??viem.maxUint256,c=i??chunkE6HWUEQ7_js.R(e).Account,g=await this.getGasPriceByRatio(),l=await n.write.approve([c,s],{gasPrice:g});return await chunkE6HWUEQ7_js.f(e).waitForTransactionReceipt({hash:l}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,r,i){let s=this.configManager.getConfig().brokerAddress;try{let c=chunkE6HWUEQ7_js.X(r,s),g=i??await this.configManager.getSignerAddress(r),l=await c.read.getUserFeeRate([g,e,t]);return {code:0,data:{takerFeeRate:l[0].toString(),makerFeeRate:l[1].toString(),baseTakerFeeRate:l[2].toString(),baseMakerFeeRate:l[3].toString()}}}catch(c){return this.logger.error("Error getting user trading fee rate:",c),{code:-1,message:c?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkE6HWUEQ7_js.Y(t,0)).read.getExecutionFee([e])).toString()}catch(r){return this.logger.error("Error getting network fee:",r),"0"}}async getOraclePrice(e,t){try{let r=await chunkE6HWUEQ7_js.ua(t,e);if(!r)throw new Error("Failed to get price data");return r}catch(r){throw this.logger.error("Error getting oracle price:",r),r}}async buildUpdatePriceParams(e,t){let r=await this.getOraclePrice(e,t);if(!r)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:r.vaa,publishTime:r.publishTime,oracleType:r.oracleType,value:r.value,price:r.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new p("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof p)return e.message;let r=await chunkE6HWUEQ7_js.ka(e);return r?r.error:JSON.stringify(e)}catch(r){return r?.message??r?.toString()??t}}async checkSeamlessGas(e,t,r){let n=await(await chunkE6HWUEQ7_js.Y(t,0)).read.getForwardFeeByToken([r]),c=await chunkE6HWUEQ7_js.T(t,r).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(c)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:r}){try{return {code:0,data:await(await chunkE6HWUEQ7_js.Z(e,0)).read.getPoolInfo([t,r])}}catch(i){return this.logger.error("Error getting pool info:",i),{code:-1,message:i?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof p)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let r=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);r&&r[1]&&(t=r[1]);}if(t){let r=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(r){let i=Object.keys(chunkE6HWUEQ7_js.ia).find(n=>n.toLowerCase()===r);if(i)return chunkE6HWUEQ7_js.ia[i]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkE6HWUEQ7_js.qa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,r=chunkE6HWUEQ7_js.d[t];return chunkE6HWUEQ7_js.pa(e,r?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,r,i){this.configManager=e,this.logger=t,this.utils=r,this.client=i;}async withRetry(e,t=3,r=300){let i;for(let n=0;n<t;n++)try{return await e()}catch(s){i=s,n<t-1&&await new Promise(c=>setTimeout(c,r));}throw i}async getTradeFlow(e,t){let r=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:r,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:r}){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Invalid signer");let i=chunkE6HWUEQ7_js.T(e,r),n=await this.configManager.getSignerAddress(e);return {code:0,data:await i.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,r,i,n){try{let c=await(await chunkE6HWUEQ7_js._(n)).write.updateAndWithdraw([e,t,r,i]);return {code:0,data:await chunkE6HWUEQ7_js.f(n).waitForTransactionReceipt({hash:c})}}catch(s){return {code:-1,message:s.message}}}async deposit({amount:e,tokenAddress:t,chainId:r}){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"",n=chunkE6HWUEQ7_js.R(r);try{if(await this.utils.needsApproval(i,r,t,e,n.Account)){let a=await this.utils.approveAuthorization({chainId:r,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:n.Account});if(a.code!==0)throw new Error(a.message)}let g=await(await chunkE6HWUEQ7_js._(r)).write.deposit([i,t,e]);return {code:0,data:await chunkE6HWUEQ7_js.f(r).waitForTransactionReceipt({hash:g})}}catch(s){return {code:-1,message:s.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:r}){try{let i=await this.getAccountInfo(t,r,e);if(i.code!==0)throw new p("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,r),s=i.data,c=BigInt(s?.quoteProfit??0),g=BigInt(s?.freeMargin??0),l=BigInt(s?.lockedMargin??0),a=n?.code===0?n.data:null,d=a?.status===1?BigInt(a?.lockedMargin??0):0n;return {code:0,data:g+c-l-d}}catch(i){return {code:-1,message:i.message}}}async getAccountInfo(e,t,r){let i=await chunkE6HWUEQ7_js.Z(e);try{return {code:0,data:await i.read.getAccountInfo([r,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let r=this.configManager.getConfig(),i=chunkE6HWUEQ7_js.X(e,r.brokerAddress),s=await chunkE6HWUEQ7_js.f(e).getBlock({blockTag:"latest"}),c=Number(s?.timestamp??BigInt(Ie__default.default().unix()))+300;try{let g=await i.read.userFeeData([t]),l;try{l=await this.withRetry(()=>i.read.userNonces([t]));}catch{l=0n;}return {code:0,data:{nonce:l.toString(),deadline:c,...g}}}catch(g){return {code:-1,message:g.message}}}async getAccountVipInfoByBackend(e,t,r,i){let n=await this.configManager.getAccessToken()??"";try{let s=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:r,nonce:i});if(s.code!==9200)throw new p("REQUEST_FAILED",s.msg??"Failed to get account vip info");return {code:0,data:s.data}}catch(s){return {code:-1,message:s.message}}}async setUserFeeData(e,t,r,i,n){let s=this.configManager.getConfig();if(r<Ie__default.default().unix())throw new p("REQUEST_FAILED","Invalid deadline, please try again");try{let c=await chunkE6HWUEQ7_js.W(t,s.brokerAddress),g={user:e,nonce:i.nonce,deadline:r,feeData:{tier:i.tier,referrer:i.referrer||viem.zeroAddress,totalReferralRebatePct:i.totalReferralRebatePct,referrerRebatePct:i.referrerRebatePct,expiry:i.expiry},signature:n},l=await c.read.userNonces([e]);if(parseInt(l.toString())+1!==parseInt(i.nonce.toString()))throw new p("REQUEST_FAILED","Invalid nonce, please try again");let a=await c.write.setUserFeeData([g]);return {code:0,data:await chunkE6HWUEQ7_js.f(t).waitForTransactionReceipt({hash:a})}}catch(c){return {code:-1,message:c.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function St(o,e){return o[e].map(r=>Qe(e,r)).join("&")}function kt(o){let e=o||{};return Object.keys(e).filter(r=>typeof e[r]<"u").map(r=>Array.isArray(e[r])?St(e,r):Ct(e,r)).join("&")}function ye(o){let e=kt(o);return e?`?${e}`:""}var re=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",r=await this.configManager.getSignerAddress(e.chainId);if(!r)throw new p("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:r}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:r=false,...i}={}){let n=r?await this.buildAuthParams():{};return chunkE6HWUEQ7_js.n.get(this.buildRequestPath(e),t,lodashEs.merge(n,i))}async post(e,t,{auth:r=false,...i}={}){let n=r?await this.buildAuthParams():{};return chunkE6HWUEQ7_js.n.post(this.buildRequestPath(e),t,lodashEs.merge(n,i))}async put(e,t,{auth:r=false,...i}={}){let n=r?await this.buildAuthParams():{};return chunkE6HWUEQ7_js.n.put(this.buildRequestPath(e),t,lodashEs.merge(n,i))}async delete(e,{auth:t=false,...r}={}){let i=t?await this.buildAuthParams():{};return chunkE6HWUEQ7_js.n.delete(this.buildRequestPath(e),lodashEs.merge(i,r))}};var ie=class extends re{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkE6HWUEQ7_js.n.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkE6HWUEQ7_js.n.post(`${this.getHost()}/v2/agent/forwarder/tx-v2`,e,{headers:{"myx-chain-id":t.toString()}})}async getOraclePrice(e,t=[]){if(t.length)return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/quote/price/oracles`,{chainId:e,poolIds:t.join(",")});throw new Error("Invalid pool id")}async getPoolDetail(e,t){return await chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${ye({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...r}){return await chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,r){return await chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,r){return await chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${r}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:r,limit:i,interval:n}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:i,interval:n})}async getKlineLatestBar(e){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async addFavoritesBatch(e){return this.post("/openapi/gateway/scan/market/add-favorites-batch",e,{auth:true})}async removeFavorite({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:i,nonce:n}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:r,deadline:i,nonce:n},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getAppealList(e){return this.get("/openapi/gateway/scan/dispute/list",e,{auth:true})}async getAppealDetail(e){return this.get("/openapi/gateway/scan/dispute/details",e,{auth:true})}async uploadAppealEvidence(e){return this.get("/openapi/gateway/scan/dispute/upload/evidence",e,{auth:true})}async getAppealReconsiderationList(e){return this.get("/openapi/gateway/scan/dispute/appeal/list",e,{auth:true})}async getAppealReconsiderationDetail(e){return this.get("/openapi/gateway/scan/dispute/appeal/details",e,{auth:true})}async getAppealReimbursementList(e){return this.get("/openapi/gateway/scan/reimbursement/list",e,{auth:true})}async getAppealNodeVoteList(e){return this.get("/openapi/gateway/scan/node/vote-list",e)}async getAppealNodeVoteDetails(e){return this.get("/openapi/gateway/scan/node/vote-details",e)}async getIsVoteNode(e){return this.get("/openapi/gateway/scan/node/vote-node-check",e)}async postVoteSignature(e){return this.get("/openapi/gateway/scan/node/vote",e,{auth:true})}async getPedingVoteCount(){return this.get("/openapi/gateway/scan/node/pending-vote-total",{},{auth:true})}async getMyAppealCount(){return this.get("/openapi/gateway/scan/processing-total",{},{auth:true})}async getWarmholeSign(e){return this.get("/openapi/gateway/scan/get-warmhole-sign",e,{auth:true})}async getDisputeTotalCount(){return this.get("/openapi/gateway/scan/dispute/dispute-total",{},{auth:true})}async getAppealTotalCount(){return this.get("/openapi/gateway/scan/dispute/appeal-total",{},{auth:true})}async getReimbursementTotalCount(){return this.get("/openapi/gateway/scan/dispute/reimbursement-total",{},{auth:true})}async getCurrentEpoch({address:e,accessToken:t,broker:r}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:r},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:i}){return chunkE6HWUEQ7_js.n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:r,myx_openapi_access_token:i}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,vt="0x55d398326f99059ff775485246999027b3197955";function xt(o){let e=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),r=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:r}}async function Mt(o,e,t,r,i,n,s,c){let g=chunkE6HWUEQ7_js.T(e,t),l=await Je(g),[a]=await o.getAddresses();if(!a)throw new p("INVALID_SIGNER","No account for signPermit");let d={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:r,spender:i,value:n,nonce:s,deadline:c},m=await o.signTypedData({account:a,domain:{...l,chainId:l.chainId},types:d,primaryType:"Permit",message:u});return xt(m)}var ne=class{constructor(e,t,r,i,n){this.configManager=e,this.logger=t,this.utils=r,this.account=i,this.api=n;}async onCheckRelayer(e,t,r,i,n){let c=await(await chunkE6HWUEQ7_js.$(r)).read.isUserRelayerEnabled([e,t]),l=await(await chunkE6HWUEQ7_js.Y(r)).read.getForwardFeeByToken([i]),a=BigInt(l)*BigInt(Xe);n=n??a.toString();let d=await this.utils.needsApproval(e,r,i,n,chunkE6HWUEQ7_js.R(r).TRADING_ROUTER);return c&&!d}async getContractAbiAndAddressByFunctionName(e,t){let r=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],i=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return r.includes(e)?{abi:chunkE6HWUEQ7_js.S,address:chunkE6HWUEQ7_js.R(t).TRADING_ROUTER}:n.includes(e)?{abi:chunkE6HWUEQ7_js.m,address:chunkE6HWUEQ7_js.R(t).Account}:i.includes(e)?{abi:chunkE6HWUEQ7_js.j,address:this.configManager.getConfig().brokerAddress}:{abi:chunkE6HWUEQ7_js.S,address:chunkE6HWUEQ7_js.R(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let i=await chunkE6HWUEQ7_js.i(t),n=chunkE6HWUEQ7_js.R(t),[s]=await i.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let c=chunkE6HWUEQ7_js.T(t,r);try{let g=await c.read.nonces([s]),l=await Mt(i,t,r,s,n.TRADING_ROUTER,viem.maxUint256,g,e);return [{token:r,owner:s,spender:n.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:l.v,r:l.r,s:l.s}]}catch(g){if(chunkE6HWUEQ7_js.ja(g))throw g;let l=g instanceof Error?g.message:String(g);throw new p("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${l}`)}}async getForwardEip712Domain(e){let r=await(await chunkE6HWUEQ7_js.$(e)).read.eip712Domain();return {name:r[1],version:r[2],chainId:r[3],verifyingContract:r[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:r,forwardFeeToken:i,functionName:n,orderParams:s,value:c="0",gas:g="800000"}){let l=await(await chunkE6HWUEQ7_js.$(e)).read.nonces([t]),a=Ie__default.default().add(60,"minute").unix(),d=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),f=viem.encodeFunctionData({abi:u,functionName:n,args:s}),b=await r({domain:d,functionHash:f,to:m,nonce:l.toString(),deadline:a}),A=await this.api.forwarderTxApi({from:t,to:m,value:c??"0",gas:g,nonce:l.toString(),data:f,deadline:a,signature:b,forwardFeeToken:i},e);if(A.data?.txHash){for(let P=0;P<5;P++)try{if((await this.api.fetchForwarderGetApi({requestId:A.data.requestId})).data?.status===9)return {code:0};P<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Se){this.logger.error("Poll transaction from chain error:",Se),P<4&&await new Promise(ce=>setTimeout(ce,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async forwarderTx({from:e,to:t,value:r,gas:i,deadline:n,data:s,nonce:c,forwardFeeToken:g},l){let a=await this.getForwardEip712Domain(l),d=await chunkE6HWUEQ7_js.i(l),[u]=await d.getAddresses();if(!u)throw new p("INVALID_SIGNER","Missing signer for forwarderTx");let m=await d.signTypedData({account:u,domain:a,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(r??"0"),gas:BigInt(i),nonce:BigInt(c),deadline:BigInt(n),data:s}});return await this.api.forwarderTxApi({from:e,to:t,value:r,gas:i,nonce:c,data:s,deadline:n,signature:m,forwardFeeToken:g},l)}async approveBalance(e,t,r){if(!this.configManager.hasSigner())throw new p("INVALID_SIGNER","Signer is required for permit");let i=await chunkE6HWUEQ7_js.V(e,t),n=chunkE6HWUEQ7_js.R(e);return await i.write?.approve([n.TRADING_ROUTER,r])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:i}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(r):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:r,address:n,tokenAddress:i})).data,b=await(await chunkE6HWUEQ7_js.Y(r)).read.getForwardFeeByToken([i]),A=BigInt(b)*BigInt(Xe);if(A>0&&A>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new p("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:r,forwardFeeToken:i});let s=Ie__default.default().add(60,"minute").unix(),c=[];if(e)try{i===vt?(await this.approveBalance(r,i,viem.maxUint256.toString()))?.hash&&(c=[]):c=await this.getUSDPermitParams(s,r,i);}catch(u){if(chunkE6HWUEQ7_js.ja(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};this.logger.warn("Failed to get USD permit params, proceeding without permit:",u),c=[];}let g=await chunkE6HWUEQ7_js.$(r,1),l=await(await chunkE6HWUEQ7_js.$(r)).read.nonces([n]),a=viem.encodeFunctionData({abi:chunkE6HWUEQ7_js.k,functionName:"permitAndApproveForwarder",args:[t,e,c]}),d;try{d=await this.forwarderTx({from:n,to:g.address,value:"0",gas:"800000",nonce:l.toString(),data:a,deadline:s,forwardFeeToken:i},r);}catch(u){if(chunkE6HWUEQ7_js.ja(u))return {code:-1,data:null,message:"User Rejected"};if(u?.name==="AccountNotFoundError")return {code:-1,data:null,message:"Wallet not connected"};throw u}if(d.data?.txHash){for(let f=0;f<5;f++)try{if((await this.api.fetchForwarderGetApi({requestId:d.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};f<4&&await new Promise(A=>setTimeout(A,1e3));}catch(b){this.logger.error("Poll transaction from chain error:",b),f<4&&await new Promise(A=>setTimeout(A,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getApproveBalance({chainId:e,forwardFeeToken:t,address:r}){try{let i=chunkE6HWUEQ7_js.R(e).TRADING_ROUTER,s=await chunkE6HWUEQ7_js.T(e,t).read.allowance([r,i]);return {code:0,data:String(s)}}catch(i){return {code:-1,message:i?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkE6HWUEQ7_js.$(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:r,functionName:i,data:n,seamlessAddress:s}){if(!e||!viem.isAddress(e))throw new p("PARAM_ERROR","address (master) is missing or invalid");if(!s||!viem.isAddress(s))throw new p("PARAM_ERROR","seamlessAddress is missing or invalid");if(!r||!viem.isAddress(r))throw new p("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))throw new p("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,r))throw new p("INSUFFICIENT_BALANCE","Insufficient relay fee");let g=await chunkE6HWUEQ7_js.$(t),l,{abi:a,address:d}=await this.getContractAbiAndAddressByFunctionName(i,t);try{l=viem.encodeFunctionData({abi:a,functionName:i,args:n});}catch(m){throw new p("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(i)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await g.read.nonces([s]);return {from:s,to:d,value:"0",gas:"800000",deadline:Ie__default.default().add(60,"minute").unix(),data:l,nonce:u.toString(),forwardFeeToken:r}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkE6HWUEQ7_js.b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return chunkE6HWUEQ7_js.R(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkE6HWUEQ7_js.X(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 chunkE6HWUEQ7_js.ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkE6HWUEQ7_js.aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let r=t==="DisputeFiled"?"caseId":"appealCaseId";for(let i of e.logs)try{let n=viem.decodeEventLog({abi:chunkE6HWUEQ7_js.l,data:i.data,topics:i.topics});if(n.eventName===t&&n.args&&r in n.args)return n.args[r]}catch{continue}return null}async submitAppeal(e,t,r){let i=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(i,this.config.chainId,t,r,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let s=await this.getDisputeCourtContract(),c=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),g=BigInt(c[0].value.toString()||"1"),l=await s.estimateGas.fileDispute([c,e,t],{value:g}),a=await this.client.utils.getGasLimitByRatio(l),d=await this.client.utils.getGasPriceByRatio(),u=await s.write.fileDispute([c,e,t],{value:g,gasLimit:a,gasPrice:d}),m=await chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),f=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(f==null)throw new p("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:f}}async voteForAppeal({caseId:e,validator:t,isFor:r,deadline:i,v:n,r:s,s:c}){let g=await this.getDisputeCourtContract(),l=await g.estimateGas.vote([e,t,r?1:0,i,n,s,c]),a=await this.client.utils.getGasLimitByRatio(l),d=await this.client.utils.getGasPriceByRatio(),u=await g.write.vote([e,t,r?1:0,i,n,s,c],{gasLimit:a,gasPrice:d});return await chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),r=await t.estimateGas.claimBond([e]),i=await this.client.utils.getGasLimitByRatio(r),n=await this.client.utils.getGasPriceByRatio(),s=await t.write.claimBond([e],{gasLimit:i,gasPrice:n});return chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:s})}async claimReimbursement(e,t,r,i){let n=await this.getReimbursementContract(),s=await n.estimateGas.claimReimbursement([e,t,r,i]),c=await this.client.utils.getGasLimitByRatio(s),g=await this.client.utils.getGasPriceByRatio(),l=await n.write.claimReimbursement([e,t,r,i],{gasLimit:c,gasPrice:g});return chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:l})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e){let t=await this.getDisputeCourtContract(),r=await this.client.utils.getGasPriceByRatio(),i=await this.client.utils.getGasLimitByRatio(await t.estimateGas.fileDisputeFromStaker([e])),n=await t.write.fileDisputeFromStaker([e],{gasLimit:i,gasPrice:r}),s=await chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:n}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new p("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,r){let i=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",s=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,r,s)){let f=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:s});if(f.code!==0)throw new p("TRANSACTION_FAILED",f.message)}let g=await i.estimateGas.appeal([e]),l=await this.client.utils.getGasLimitByRatio(g),a=await this.client.utils.getGasPriceByRatio(),d=await i.write.appeal([e],{gasLimit:l,gasPrice:a}),u=await chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:d}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new p("TRANSACTION_FAILED","AppealFiledLog not found");return {tx:u,appealCaseId:m,caseId:e}}async getAppealList(e){return this.client.api.getAppealList(e)}async getAppealDetail(e){return this.client.api.getAppealDetail(e)}async uploadAppealEvidence(e){return this.client.api.uploadAppealEvidence(e)}async getAppealReconsiderationList(e){return this.client.api.getAppealReconsiderationList(e)}async getAppealReconsiderationDetail(e){return this.client.api.getAppealReconsiderationDetail(e)}async getAppealReimbursementList(e){return this.client.api.getAppealReimbursementList(e)}async getAppealNodeVoteList(e){return this.client.api.getAppealNodeVoteList(e)}async getAppealNodeVoteDetail(e){return this.client.api.getAppealNodeVoteDetails(e)}async getIsVoteNode(e){return this.client.api.getIsVoteNode(e)}async postVoteSignature(e){return this.client.api.postVoteSignature(e)}async getPedingVoteCount(){return this.client.api.getPedingVoteCount()}async getMyAppealCount(){return this.client.api.getMyAppealCount()}async getWarmholeSign(e){return this.client.api.getWarmholeSign(e)}async getDisputeTotalCount(){return this.client.api.getDisputeTotalCount()}async getAppealTotalCount(){return this.client.api.getAppealTotalCount()}async getReimbursementTotalCount(){return this.client.api.getReimbursementTotalCount()}async getAppealStatus(e,t,r){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:r,accessToken:await this.configManager.getAccessToken()??""})}};var ae=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),r=await chunkE6HWUEQ7_js.W(this.config.chainId,t.brokerAddress),i=await r.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(i),s=await this.client.utils.getGasPriceByRatio(),c=await r.write.claimRebate([e],{gasPrice:s,gasLimit:n});return chunkE6HWUEQ7_js.f(this.config.chainId).waitForTransactionReceipt({hash:c})}};var Dt=(a=>(a[a.UnderReview=1]="UnderReview",a[a.InitialVote=2]="InitialVote",a[a.PublicNotice=3]="PublicNotice",a[a.UnderReconsideration=4]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=6]="Failed",a[a.PlatformRuling=7]="PlatformRuling",a[a.PlatformRevoked=8]="PlatformRevoked",a[a.SettlementVoting=10]="SettlementVoting",a[a.SettlementFailed=11]="SettlementFailed",a))(Dt||{}),Ot=(a=>(a[a.InitialVoting=1]="InitialVoting",a[a.PublicNotice=2]="PublicNotice",a[a.UnderReconsideration=3]="UnderReconsideration",a[a.Won=5]="Won",a[a.Failed=4]="Failed",a[a.PlatformRuling=6]="PlatformRuling",a[a.PlatformRevoked=7]="PlatformRevoked",a[a.ReconsiderationVoting=8]="ReconsiderationVoting",a[a.AppealRevert=9]="AppealRevert",a[a.NotAppealFailed=10]="NotAppealFailed",a))(Ot||{}),Lt=(i=>(i[i.UnderReview=1]="UnderReview",i[i.PublicNotice=2]="PublicNotice",i[i.UnderReconsideration=3]="UnderReconsideration",i[i.Completed=4]="Completed",i))(Lt||{}),Ft=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Ft||{}),_t=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(_t||{}),Nt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Nt||{}),Bt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Bt||{}),Gt=(r=>(r[r.Appeal=1]="Appeal",r[r.Reconsideration=2]="Reconsideration",r[r.Settlement=3]="Settlement",r))(Gt||{}),Wt=(r=>(r[r.NoVote=0]="NoVote",r[r.Supported=1]="Supported",r[r.Rejected=2]="Rejected",r))(Wt||{}),$t=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))($t||{}),Ut=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))(Ut||{});var Te=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new chunkE6HWUEQ7_js.ha({logLevel:e.logLevel});let t=chunkE6HWUEQ7_js.P.getInstance();chunkE6HWUEQ7_js.h()?.hasSigner()||(t.setConfigManager(this.configManager),chunkE6HWUEQ7_js.g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new ie(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(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 X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new K(this.configManager,this.logger),this.appeal=new se(this,this.configManager),this.referrals=new ae(this);}auth(e){this.configManager.auth(e),chunkE6HWUEQ7_js.P.getInstance().setConfigManager(this.configManager),chunkE6HWUEQ7_js.g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Yn="1.0.23-beta.2";
2
+ Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.oa}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.na}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.D}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.A}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.o}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.C}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.F}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.r}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ha}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.u}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.p}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.s}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.P}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.x}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.q}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.B}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.w}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.v}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.t}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.E}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.y}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.z}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.sa}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ya}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ra}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.qa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.pa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.wa}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ma}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.la}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.M}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.H}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.N}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.O}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.I}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.J}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.G}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.K}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ua}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ta}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.da}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.L}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.va}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.i}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.Q}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.Aa}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.xa}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.Ba}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.za}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ga}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ea}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.fa}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkE6HWUEQ7_js.ca}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=Nt;exports.AppealNodeStateEnum=Wt;exports.AppealNodeVotedStateEnum=Bt;exports.AppealReconsiderationType=Ot;exports.AppealStage=Lt;exports.AppealStatus=Ut;exports.AppealType=Dt;exports.Direction=di;exports.IsVoteNodeEnum=$t;exports.MyxClient=Te;exports.NodeTypeEnum=Ft;exports.OperationType=v;exports.OrderStatus=mi;exports.OrderType=Y;exports.SDK_VERSION=Yn;exports.TimeInForce=ui;exports.TriggerType=pi;exports.VoteTypeEnum=_t;exports.fromViemWalletClient=he;exports.normalizeSigner=z;