@myx-trade/sdk 1.0.23-beta.2 → 1.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-4GGDHY7G.mjs → chunk-JLLMVLV6.mjs} +1 -1
- package/dist/{chunk-E6HWUEQ7.js → chunk-MD34TEJK.js} +1 -1
- package/dist/{index-Btw0KF7k.d.mts → index-BySXgyu2.d.mts} +1 -1
- package/dist/{index-Btw0KF7k.d.ts → index-BySXgyu2.d.ts} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/lp.d.mts +1 -1
- package/dist/lp.d.ts +1 -1
- package/dist/lp.js +1 -1
- package/dist/lp.mjs +1 -1
- package/package.json +1 -1
|
@@ -679,7 +679,7 @@ declare const withdrawableLpAmount: (params: {
|
|
|
679
679
|
}) => Promise<any>;
|
|
680
680
|
declare const withdraw: (params: WithdrawParams) => Promise<viem.TransactionReceipt>;
|
|
681
681
|
|
|
682
|
-
declare const transfer: (chainId: ChainId, fromPoolId: string, toPoolId: string, amount: number) => Promise<viem.TransactionReceipt | null>;
|
|
682
|
+
declare const transfer: (chainId: ChainId, fromPoolId: string, toPoolId: string, amount: number | string) => Promise<viem.TransactionReceipt | null>;
|
|
683
683
|
|
|
684
684
|
declare const getRewards: (params: RewardsParams) => Promise<any>;
|
|
685
685
|
|
|
@@ -679,7 +679,7 @@ declare const withdrawableLpAmount: (params: {
|
|
|
679
679
|
}) => Promise<any>;
|
|
680
680
|
declare const withdraw: (params: WithdrawParams) => Promise<viem.TransactionReceipt>;
|
|
681
681
|
|
|
682
|
-
declare const transfer: (chainId: ChainId, fromPoolId: string, toPoolId: string, amount: number) => Promise<viem.TransactionReceipt | null>;
|
|
682
|
+
declare const transfer: (chainId: ChainId, fromPoolId: string, toPoolId: string, amount: number | string) => Promise<viem.TransactionReceipt | null>;
|
|
683
683
|
|
|
684
684
|
declare const getRewards: (params: RewardsParams) => Promise<any>;
|
|
685
685
|
|
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-
|
|
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-
|
|
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-BySXgyu2.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-BySXgyu2.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-
|
|
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-
|
|
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-BySXgyu2.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-BySXgyu2.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 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
|
|
1
|
+
'use strict';var chunkMD34TEJK_js=require('./chunk-MD34TEJK.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 chunkMD34TEJK_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=chunkMD34TEJK_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=chunkMD34TEJK_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 chunkMD34TEJK_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&&(chunkMD34TEJK_js.fa("Received expired token, using default expiry"),r=3600);}return this.setAccessToken(t.accessToken,r),t.accessToken}else return chunkMD34TEJK_js.fa("\u274C Received empty accessToken"),null}catch(t){return chunkMD34TEJK_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 chunkMD34TEJK_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,chunkMD34TEJK_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 chunkMD34TEJK_js.U(n);if(a){let P=await this.utils.approveAuthorization({chainId:n,quoteAddress:i,amount:viem.maxUint256.toString(),spenderAddress:chunkMD34TEJK_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)*chunkMD34TEJK_js.c[n]/100n});return await chunkMD34TEJK_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,chunkMD34TEJK_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:chunkMD34TEJK_js.R(e.chainId).TRADING_ROUTER});if(b.code!==0)throw new Error(b.message)}let d=await chunkMD34TEJK_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*chunkMD34TEJK_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*chunkMD34TEJK_js.c[e.chainId]/100n});}let m=await chunkMD34TEJK_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 chunkMD34TEJK_js.U(e),c=await s.estimateGas.placeOrdersWithPosition([r,i,n]),g=await s.write.placeOrdersWithPosition([r,i,n],{gasLimit:c*chunkMD34TEJK_js.c[e]/100n}),l=await chunkMD34TEJK_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 chunkMD34TEJK_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*chunkMD34TEJK_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*chunkMD34TEJK_js.c[e.chainId]/100n});}let d=await chunkMD34TEJK_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 chunkMD34TEJK_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*chunkMD34TEJK_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*chunkMD34TEJK_js.c[e.chainId]/100n});}let d=await chunkMD34TEJK_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*chunkMD34TEJK_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*chunkMD34TEJK_js.c[e.chainId]/100n});}let s=await chunkMD34TEJK_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 chunkMD34TEJK_js.U(t)).write.cancelOrders([e]);return await chunkMD34TEJK_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 chunkMD34TEJK_js.U(t)).write.cancelOrder([e]);return await chunkMD34TEJK_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 chunkMD34TEJK_js.U(t)).write.cancelOrders([e]);return await chunkMD34TEJK_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 chunkMD34TEJK_js.U(r);this.logger.info("updateOrderTpSl params",g);try{if(await this.utils.needsApproval(i,r,e.executionFeeToken,c.toString(),chunkMD34TEJK_js.R(r).TRADING_ROUTER)){let b=await this.utils.approveAuthorization({chainId:r,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkMD34TEJK_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*chunkMD34TEJK_js.c[r]/100n}),f=await chunkMD34TEJK_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??chunkMD34TEJK_js.R(t).Account,c=await chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.V(e,t),s=r??viem.maxUint256,c=i??chunkMD34TEJK_js.R(e).Account,g=await this.getGasPriceByRatio(),l=await n.write.approve([c,s],{gasPrice:g});return await chunkMD34TEJK_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=chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.Y(t,0)).read.getForwardFeeByToken([r]),c=await chunkMD34TEJK_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 chunkMD34TEJK_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(chunkMD34TEJK_js.ia).find(n=>n.toLowerCase()===r);if(i)return chunkMD34TEJK_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 chunkMD34TEJK_js.qa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,r=chunkMD34TEJK_js.d[t];return chunkMD34TEJK_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=chunkMD34TEJK_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 chunkMD34TEJK_js._(n)).write.updateAndWithdraw([e,t,r,i]);return {code:0,data:await chunkMD34TEJK_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=chunkMD34TEJK_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 chunkMD34TEJK_js._(r)).write.deposit([i,t,e]);return {code:0,data:await chunkMD34TEJK_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 chunkMD34TEJK_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=chunkMD34TEJK_js.X(e,r.brokerAddress),s=await chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,r,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkMD34TEJK_js.n.get(`${this.getHost()}/v2/agent/forwarder/get${ye(e)}`)}async getPoolList(){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:r,limit:i,interval:n})}async getKlineLatestBar(e){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkMD34TEJK_js.n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...r}){return chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...r}){return chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...r}){return chunkMD34TEJK_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 chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,r,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkMD34TEJK_js.n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:r,deadline:i,nonce:n}){return chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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=chunkMD34TEJK_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 chunkMD34TEJK_js.$(r)).read.isUserRelayerEnabled([e,t]),l=await(await chunkMD34TEJK_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,chunkMD34TEJK_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:chunkMD34TEJK_js.S,address:chunkMD34TEJK_js.R(t).TRADING_ROUTER}:n.includes(e)?{abi:chunkMD34TEJK_js.m,address:chunkMD34TEJK_js.R(t).Account}:i.includes(e)?{abi:chunkMD34TEJK_js.j,address:this.configManager.getConfig().brokerAddress}:{abi:chunkMD34TEJK_js.S,address:chunkMD34TEJK_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 chunkMD34TEJK_js.i(t),n=chunkMD34TEJK_js.R(t),[s]=await i.getAddresses();if(!s)throw new p("INVALID_SIGNER","No account");let c=chunkMD34TEJK_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(chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.V(e,t),n=chunkMD34TEJK_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 chunkMD34TEJK_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(chunkMD34TEJK_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 chunkMD34TEJK_js.$(r,1),l=await(await chunkMD34TEJK_js.$(r)).read.nonces([n]),a=viem.encodeFunctionData({abi:chunkMD34TEJK_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(chunkMD34TEJK_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=chunkMD34TEJK_js.R(e).TRADING_ROUTER,s=await chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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||!chunkMD34TEJK_js.b(t))throw new p("INVALID_CHAIN_ID","Invalid chain id");return chunkMD34TEJK_js.R(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new p("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkMD34TEJK_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 chunkMD34TEJK_js.ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkMD34TEJK_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:chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_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 chunkMD34TEJK_js.ha({logLevel:e.logLevel});let t=chunkMD34TEJK_js.P.getInstance();chunkMD34TEJK_js.h()?.hasSigner()||(t.setConfigManager(this.configManager),chunkMD34TEJK_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),chunkMD34TEJK_js.P.getInstance().setConfigManager(this.configManager),chunkMD34TEJK_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";
|
|
2
|
+
Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkMD34TEJK_js.oa}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkMD34TEJK_js.na}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkMD34TEJK_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.D}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.A}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkMD34TEJK_js.o}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.C}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkMD34TEJK_js.F}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.r}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkMD34TEJK_js.ha}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkMD34TEJK_js.u}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkMD34TEJK_js.p}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkMD34TEJK_js.s}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkMD34TEJK_js.P}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.x}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkMD34TEJK_js.q}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.B}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.w}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.v}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.t}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.E}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.y}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkMD34TEJK_js.z}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkMD34TEJK_js.sa}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkMD34TEJK_js.ya}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkMD34TEJK_js.ra}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkMD34TEJK_js.qa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkMD34TEJK_js.pa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkMD34TEJK_js.wa}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkMD34TEJK_js.ma}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkMD34TEJK_js.la}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkMD34TEJK_js.M}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkMD34TEJK_js.H}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkMD34TEJK_js.N}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkMD34TEJK_js.O}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkMD34TEJK_js.I}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkMD34TEJK_js.J}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkMD34TEJK_js.G}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkMD34TEJK_js.K}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkMD34TEJK_js.ua}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkMD34TEJK_js.ta}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkMD34TEJK_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkMD34TEJK_js.da}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkMD34TEJK_js.L}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkMD34TEJK_js.va}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkMD34TEJK_js.i}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkMD34TEJK_js.Q}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkMD34TEJK_js.Aa}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkMD34TEJK_js.xa}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkMD34TEJK_js.Ba}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkMD34TEJK_js.za}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkMD34TEJK_js.ga}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkMD34TEJK_js.ea}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkMD34TEJK_js.fa}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkMD34TEJK_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkMD34TEJK_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;
|