@myx-trade/sdk 1.0.20-beta.9 → 1.0.21

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.
@@ -47,7 +47,7 @@ declare enum TriggerType$1 {
47
47
  }
48
48
  interface TpSl {
49
49
  amount: number;
50
- triggerPrice: number;
50
+ triggerPrice: number | string;
51
51
  triggerType: TriggerType$1;
52
52
  }
53
53
  interface TpSLParams {
@@ -47,7 +47,7 @@ declare enum TriggerType$1 {
47
47
  }
48
48
  interface TpSl {
49
49
  amount: number;
50
- triggerPrice: number;
50
+ triggerPrice: number | string;
51
51
  triggerType: TriggerType$1;
52
52
  }
53
53
  interface TpSLParams {
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-C2d3GtOj.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-C2d3GtOj.mjs';
1
+ import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-CbPRefJT.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-CbPRefJT.mjs';
3
3
  import * as viem from 'viem';
4
4
  import { WalletClient, Address, PublicClient, Abi } from 'viem';
5
5
  export { formatUnits, parseUnits } from 'viem';
@@ -817,6 +817,7 @@ declare class Api extends Request {
817
817
  searchMarketAuth({ accessToken, address, ...params }: SearchMarketParams & AccessTokenRequest): Promise<ApiResponse<SearchResultResponse>>;
818
818
  searchMarket({ ...params }: SearchMarketParams): Promise<ApiResponse<SearchResultResponse>>;
819
819
  addFavorite({ accessToken, address, ...params }: AddFavoriteParams & AccessTokenRequest): Promise<ApiResponse<null>>;
820
+ addFavoritesBatch(params: AddFavoritesBatchParams): Promise<ApiResponse<null>>;
820
821
  removeFavorite({ accessToken, address, ...params }: RemoveFavoriteParams & AccessTokenRequest): Promise<ApiResponse<null>>;
821
822
  getFavoritesList({ accessToken, address, ...params }: FavoritesListParams & AccessTokenRequest): Promise<ApiResponse<FavoritesListItem[]>>;
822
823
  getBaseDetail({ ...params }: GetBaseDetailParams): Promise<ApiResponse<BaseDetailResponse>>;
@@ -911,6 +912,7 @@ declare class Markets {
911
912
  * favorite
912
913
  */
913
914
  addFavorite(params: AddFavoriteParams, address: string): Promise<null>;
915
+ addFavoritesBatch(params: AddFavoritesBatchParams): Promise<null>;
914
916
  removeFavorite(params: RemoveFavoriteParams, address: string): Promise<null>;
915
917
  /**
916
918
  * base detail
@@ -1794,6 +1796,9 @@ interface AddFavoriteParams {
1794
1796
  poolId: string;
1795
1797
  chainId: ChainId;
1796
1798
  }
1799
+ interface AddFavoritesBatchParams {
1800
+ list: AddFavoriteParams[];
1801
+ }
1797
1802
  interface RemoveFavoriteParams {
1798
1803
  poolId: string;
1799
1804
  chainId: ChainId;
@@ -1878,4 +1883,4 @@ declare function normalizeSigner(signerLike: SignerLike): ISigner;
1878
1883
 
1879
1884
  declare const SDK_VERSION: string;
1880
1885
 
1881
- export { AccessTokenRequest, type AddFavoriteParams, Address$1 as Address, ApiResponse, AppealCaseTypeEnum, AppealClaimStatusEnum, type AppealDetail, type AppealListItem, AppealNodeStateEnum, type AppealNodeVoteItem, type AppealNodeVoteListItem, AppealNodeVotedStateEnum, type AppealReconsiderationDetail, type AppealReconsiderationItem, type AppealReconsiderationListItem, AppealReconsiderationType, type AppealReimbursementItem, type AppealReimbursementParams, AppealStage, AppealStatus, AppealType, type AppealUploadEvidenceParams, type AppealVoteItem, BaseDetailResponse, BaseResponse, ChainId, CloseTypeEnum, DirectionEnum, ExecTypeEnum, FavoritesListItem, type FavoritesListParams, type FavoritesTimeInterval, type FetchForwarderGetParams, type FetchForwarderGetResponse, type FetchForwarderGetResponseData, ForwarderGetStatus, type ForwarderTxParams, type GetAppealDetailParams, type GetAppealListParams, type GetAppealNodeVoteListParams, type GetAppealReconsiderationDetailParams, type GetAppealReconsiderationListParams, type GetAppealVoteNodeDetailParams, type GetBaseDetailParams, type GetHistoryOrdersParams, type GetIsVoteNodeParams, type GetKlineDataParams, type GetMarketDetailParams, type GetPoolLevelConfigParams, type GetTickerDataParams, type GetWarmholeSignParams, type GetWarmholeSignResponse, type GuardianSignatureItem, type HistoryOrderItem, HttpEnvParams, HttpKlineIntervalEnum, type ISigner, IsVoteNodeEnum, KlineDataItemType, type KlineDataResponse, type KlineResolution, type LevelConfig, type LogLevel, type LogSink, Logger, type LoggerOptions, MarketDetailResponse, MarketInfo, MxSDK, MyxClient, type MyxClientConfig, type MyxSubscriptionOptions, NodeTypeEnum, type OnKlineCallback, type OnOrderCallback, type OnPositionCallback, type OnTickersAllCallback, type OnTickersCallback, OperationEnum, OracleType, OrderItem, OrderResponse, OrderStatusEnum, OrderTypeEnum, type PaginationParams, PlaceOrderParams, type PoolLevelConfig, PoolOpenOrdersResponse, PoolResponse, type PoolSymbolAllResponse, type PositionHistoryItem, PositionResponse, PositionTpSlOrderParams, PositionType, type PostVoteResponse, type PostVoteSignatureParams, PriceResponse, type RemoveFavoriteParams, SDK_VERSION, type SearchMarketParams, SearchResultResponse, SearchSecondTypeEnum, SearchTypeEnum, type SignerLike, TickerDataItem, type TickersDataResponse, TradeFlowAccountTypeEnum, type TradeFlowItem, TradeFlowTypeEnum, TriggerTypeEnum, VoteTypeEnum, approve, bigintAmountSlipperCalculator, bigintTradingGasPriceWithRatio, bigintTradingGasToRatioCalculator, fromViemWalletClient, getAllowanceApproved, getBalanceOf, getBaseDetail, getBaseUrlByEnv, getMarketDetail, getMarketList, getOraclePrice, getPoolDetail, getPoolList, getPoolOpenOrders, getPublicClient, getSdkLogSink, getTickerData, getTokenInfo, getWalletClient, getWalletProvider, normalizeSigner, sdkError, sdkLog, sdkWarn, setConfigManagerForViem, setSdkLogSink };
1886
+ export { AccessTokenRequest, type AddFavoriteParams, type AddFavoritesBatchParams, Address$1 as Address, ApiResponse, AppealCaseTypeEnum, AppealClaimStatusEnum, type AppealDetail, type AppealListItem, AppealNodeStateEnum, type AppealNodeVoteItem, type AppealNodeVoteListItem, AppealNodeVotedStateEnum, type AppealReconsiderationDetail, type AppealReconsiderationItem, type AppealReconsiderationListItem, AppealReconsiderationType, type AppealReimbursementItem, type AppealReimbursementParams, AppealStage, AppealStatus, AppealType, type AppealUploadEvidenceParams, type AppealVoteItem, BaseDetailResponse, BaseResponse, ChainId, CloseTypeEnum, DirectionEnum, ExecTypeEnum, FavoritesListItem, type FavoritesListParams, type FavoritesTimeInterval, type FetchForwarderGetParams, type FetchForwarderGetResponse, type FetchForwarderGetResponseData, ForwarderGetStatus, type ForwarderTxParams, type GetAppealDetailParams, type GetAppealListParams, type GetAppealNodeVoteListParams, type GetAppealReconsiderationDetailParams, type GetAppealReconsiderationListParams, type GetAppealVoteNodeDetailParams, type GetBaseDetailParams, type GetHistoryOrdersParams, type GetIsVoteNodeParams, type GetKlineDataParams, type GetMarketDetailParams, type GetPoolLevelConfigParams, type GetTickerDataParams, type GetWarmholeSignParams, type GetWarmholeSignResponse, type GuardianSignatureItem, type HistoryOrderItem, HttpEnvParams, HttpKlineIntervalEnum, type ISigner, IsVoteNodeEnum, KlineDataItemType, type KlineDataResponse, type KlineResolution, type LevelConfig, type LogLevel, type LogSink, Logger, type LoggerOptions, MarketDetailResponse, MarketInfo, MxSDK, MyxClient, type MyxClientConfig, type MyxSubscriptionOptions, NodeTypeEnum, type OnKlineCallback, type OnOrderCallback, type OnPositionCallback, type OnTickersAllCallback, type OnTickersCallback, OperationEnum, OracleType, OrderItem, OrderResponse, OrderStatusEnum, OrderTypeEnum, type PaginationParams, PlaceOrderParams, type PoolLevelConfig, PoolOpenOrdersResponse, PoolResponse, type PoolSymbolAllResponse, type PositionHistoryItem, PositionResponse, PositionTpSlOrderParams, PositionType, type PostVoteResponse, type PostVoteSignatureParams, PriceResponse, type RemoveFavoriteParams, SDK_VERSION, type SearchMarketParams, SearchResultResponse, SearchSecondTypeEnum, SearchTypeEnum, type SignerLike, TickerDataItem, type TickersDataResponse, TradeFlowAccountTypeEnum, type TradeFlowItem, TradeFlowTypeEnum, TriggerTypeEnum, VoteTypeEnum, approve, bigintAmountSlipperCalculator, bigintTradingGasPriceWithRatio, bigintTradingGasToRatioCalculator, fromViemWalletClient, getAllowanceApproved, getBalanceOf, getBaseDetail, getBaseUrlByEnv, getMarketDetail, getMarketList, getOraclePrice, getPoolDetail, getPoolList, getPoolOpenOrders, getPublicClient, getSdkLogSink, getTickerData, getTokenInfo, getWalletClient, getWalletProvider, normalizeSigner, sdkError, sdkLog, sdkWarn, setConfigManagerForViem, setSdkLogSink };
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-C2d3GtOj.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-C2d3GtOj.js';
1
+ import { O as OracleType, H as HttpKlineIntervalEnum, A as AccessTokenRequest, a as ApiResponse, C as ChainId, P as PoolResponse, b as PositionResponse, c as OrderResponse, d as PoolOpenOrdersResponse, K as KlineDataItemType, T as TickerDataItem, S as SearchResultResponse, F as FavoritesListItem, B as BaseDetailResponse, M as MarketDetailResponse, e as MarketInfo, f as PositionType, g as PlaceOrderParams, h as PositionTpSlOrderParams, i as OrderItem, j as Address$1, k as ContractAddress, l as BaseResponse, m as SearchTypeEnum, n as SearchSecondTypeEnum, o as PriceResponse, p as HttpEnvParams } from './index-CbPRefJT.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-CbPRefJT.js';
3
3
  import * as viem from 'viem';
4
4
  import { WalletClient, Address, PublicClient, Abi } from 'viem';
5
5
  export { formatUnits, parseUnits } from 'viem';
@@ -817,6 +817,7 @@ declare class Api extends Request {
817
817
  searchMarketAuth({ accessToken, address, ...params }: SearchMarketParams & AccessTokenRequest): Promise<ApiResponse<SearchResultResponse>>;
818
818
  searchMarket({ ...params }: SearchMarketParams): Promise<ApiResponse<SearchResultResponse>>;
819
819
  addFavorite({ accessToken, address, ...params }: AddFavoriteParams & AccessTokenRequest): Promise<ApiResponse<null>>;
820
+ addFavoritesBatch(params: AddFavoritesBatchParams): Promise<ApiResponse<null>>;
820
821
  removeFavorite({ accessToken, address, ...params }: RemoveFavoriteParams & AccessTokenRequest): Promise<ApiResponse<null>>;
821
822
  getFavoritesList({ accessToken, address, ...params }: FavoritesListParams & AccessTokenRequest): Promise<ApiResponse<FavoritesListItem[]>>;
822
823
  getBaseDetail({ ...params }: GetBaseDetailParams): Promise<ApiResponse<BaseDetailResponse>>;
@@ -911,6 +912,7 @@ declare class Markets {
911
912
  * favorite
912
913
  */
913
914
  addFavorite(params: AddFavoriteParams, address: string): Promise<null>;
915
+ addFavoritesBatch(params: AddFavoritesBatchParams): Promise<null>;
914
916
  removeFavorite(params: RemoveFavoriteParams, address: string): Promise<null>;
915
917
  /**
916
918
  * base detail
@@ -1794,6 +1796,9 @@ interface AddFavoriteParams {
1794
1796
  poolId: string;
1795
1797
  chainId: ChainId;
1796
1798
  }
1799
+ interface AddFavoritesBatchParams {
1800
+ list: AddFavoriteParams[];
1801
+ }
1797
1802
  interface RemoveFavoriteParams {
1798
1803
  poolId: string;
1799
1804
  chainId: ChainId;
@@ -1878,4 +1883,4 @@ declare function normalizeSigner(signerLike: SignerLike): ISigner;
1878
1883
 
1879
1884
  declare const SDK_VERSION: string;
1880
1885
 
1881
- export { AccessTokenRequest, type AddFavoriteParams, Address$1 as Address, ApiResponse, AppealCaseTypeEnum, AppealClaimStatusEnum, type AppealDetail, type AppealListItem, AppealNodeStateEnum, type AppealNodeVoteItem, type AppealNodeVoteListItem, AppealNodeVotedStateEnum, type AppealReconsiderationDetail, type AppealReconsiderationItem, type AppealReconsiderationListItem, AppealReconsiderationType, type AppealReimbursementItem, type AppealReimbursementParams, AppealStage, AppealStatus, AppealType, type AppealUploadEvidenceParams, type AppealVoteItem, BaseDetailResponse, BaseResponse, ChainId, CloseTypeEnum, DirectionEnum, ExecTypeEnum, FavoritesListItem, type FavoritesListParams, type FavoritesTimeInterval, type FetchForwarderGetParams, type FetchForwarderGetResponse, type FetchForwarderGetResponseData, ForwarderGetStatus, type ForwarderTxParams, type GetAppealDetailParams, type GetAppealListParams, type GetAppealNodeVoteListParams, type GetAppealReconsiderationDetailParams, type GetAppealReconsiderationListParams, type GetAppealVoteNodeDetailParams, type GetBaseDetailParams, type GetHistoryOrdersParams, type GetIsVoteNodeParams, type GetKlineDataParams, type GetMarketDetailParams, type GetPoolLevelConfigParams, type GetTickerDataParams, type GetWarmholeSignParams, type GetWarmholeSignResponse, type GuardianSignatureItem, type HistoryOrderItem, HttpEnvParams, HttpKlineIntervalEnum, type ISigner, IsVoteNodeEnum, KlineDataItemType, type KlineDataResponse, type KlineResolution, type LevelConfig, type LogLevel, type LogSink, Logger, type LoggerOptions, MarketDetailResponse, MarketInfo, MxSDK, MyxClient, type MyxClientConfig, type MyxSubscriptionOptions, NodeTypeEnum, type OnKlineCallback, type OnOrderCallback, type OnPositionCallback, type OnTickersAllCallback, type OnTickersCallback, OperationEnum, OracleType, OrderItem, OrderResponse, OrderStatusEnum, OrderTypeEnum, type PaginationParams, PlaceOrderParams, type PoolLevelConfig, PoolOpenOrdersResponse, PoolResponse, type PoolSymbolAllResponse, type PositionHistoryItem, PositionResponse, PositionTpSlOrderParams, PositionType, type PostVoteResponse, type PostVoteSignatureParams, PriceResponse, type RemoveFavoriteParams, SDK_VERSION, type SearchMarketParams, SearchResultResponse, SearchSecondTypeEnum, SearchTypeEnum, type SignerLike, TickerDataItem, type TickersDataResponse, TradeFlowAccountTypeEnum, type TradeFlowItem, TradeFlowTypeEnum, TriggerTypeEnum, VoteTypeEnum, approve, bigintAmountSlipperCalculator, bigintTradingGasPriceWithRatio, bigintTradingGasToRatioCalculator, fromViemWalletClient, getAllowanceApproved, getBalanceOf, getBaseDetail, getBaseUrlByEnv, getMarketDetail, getMarketList, getOraclePrice, getPoolDetail, getPoolList, getPoolOpenOrders, getPublicClient, getSdkLogSink, getTickerData, getTokenInfo, getWalletClient, getWalletProvider, normalizeSigner, sdkError, sdkLog, sdkWarn, setConfigManagerForViem, setSdkLogSink };
1886
+ export { AccessTokenRequest, type AddFavoriteParams, type AddFavoritesBatchParams, Address$1 as Address, ApiResponse, AppealCaseTypeEnum, AppealClaimStatusEnum, type AppealDetail, type AppealListItem, AppealNodeStateEnum, type AppealNodeVoteItem, type AppealNodeVoteListItem, AppealNodeVotedStateEnum, type AppealReconsiderationDetail, type AppealReconsiderationItem, type AppealReconsiderationListItem, AppealReconsiderationType, type AppealReimbursementItem, type AppealReimbursementParams, AppealStage, AppealStatus, AppealType, type AppealUploadEvidenceParams, type AppealVoteItem, BaseDetailResponse, BaseResponse, ChainId, CloseTypeEnum, DirectionEnum, ExecTypeEnum, FavoritesListItem, type FavoritesListParams, type FavoritesTimeInterval, type FetchForwarderGetParams, type FetchForwarderGetResponse, type FetchForwarderGetResponseData, ForwarderGetStatus, type ForwarderTxParams, type GetAppealDetailParams, type GetAppealListParams, type GetAppealNodeVoteListParams, type GetAppealReconsiderationDetailParams, type GetAppealReconsiderationListParams, type GetAppealVoteNodeDetailParams, type GetBaseDetailParams, type GetHistoryOrdersParams, type GetIsVoteNodeParams, type GetKlineDataParams, type GetMarketDetailParams, type GetPoolLevelConfigParams, type GetTickerDataParams, type GetWarmholeSignParams, type GetWarmholeSignResponse, type GuardianSignatureItem, type HistoryOrderItem, HttpEnvParams, HttpKlineIntervalEnum, type ISigner, IsVoteNodeEnum, KlineDataItemType, type KlineDataResponse, type KlineResolution, type LevelConfig, type LogLevel, type LogSink, Logger, type LoggerOptions, MarketDetailResponse, MarketInfo, MxSDK, MyxClient, type MyxClientConfig, type MyxSubscriptionOptions, NodeTypeEnum, type OnKlineCallback, type OnOrderCallback, type OnPositionCallback, type OnTickersAllCallback, type OnTickersCallback, OperationEnum, OracleType, OrderItem, OrderResponse, OrderStatusEnum, OrderTypeEnum, type PaginationParams, PlaceOrderParams, type PoolLevelConfig, PoolOpenOrdersResponse, PoolResponse, type PoolSymbolAllResponse, type PositionHistoryItem, PositionResponse, PositionTpSlOrderParams, PositionType, type PostVoteResponse, type PostVoteSignatureParams, PriceResponse, type RemoveFavoriteParams, SDK_VERSION, type SearchMarketParams, SearchResultResponse, SearchSecondTypeEnum, SearchTypeEnum, type SignerLike, TickerDataItem, type TickersDataResponse, TradeFlowAccountTypeEnum, type TradeFlowItem, TradeFlowTypeEnum, TriggerTypeEnum, VoteTypeEnum, approve, bigintAmountSlipperCalculator, bigintTradingGasPriceWithRatio, bigintTradingGasToRatioCalculator, fromViemWalletClient, getAllowanceApproved, getBalanceOf, getBaseDetail, getBaseUrlByEnv, getMarketDetail, getMarketList, getOraclePrice, getPoolDetail, getPoolList, getPoolOpenOrders, getPublicClient, getSdkLogSink, getTickerData, getTokenInfo, getWalletClient, getWalletProvider, normalizeSigner, sdkError, sdkLog, sdkWarn, setConfigManagerForViem, setSdkLogSink };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkSY4XAFN4_js=require('./chunk-SY4XAFN4.js'),lt=require('mitt'),cryptoEs=require('crypto-es'),pt=require('reconnecting-websocket'),viem=require('viem'),Ae=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var lt__default=/*#__PURE__*/_interopDefault(lt);var pt__default=/*#__PURE__*/_interopDefault(pt);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var $=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var V=o=>{switch(o.request){case "signin":return $(o.request)}return $(JSON.stringify(o))},N=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return $(JSON.stringify({topic:e,params:t}))}},_e=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",dt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},Be=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:N({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[i,r]=t.split("_");return {...o,type:N({topic:"candle",params:{globalId:parseInt(i),resolution:r}}),globalId:parseInt(i),resolution:r}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=lt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:i,...r}=t;this.config={...Ge,...r},this.logger=new chunkSY4XAFN4_js.ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let i={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new pt__default.default(this.config.url,this.config.protocols,i),this.setupEventListeners(e,t);}catch(i){t(i);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async i=>{this.eventBus.emit("open",i),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=i=>{this.handleMessage(i);},this.ws.onclose=i=>{this.eventBus.emit("close",i),this.stopHeartbeatTimer();},this.ws.onerror=i=>{this.eventBus.emit("error",i),t(i);},this.ws.addEventListener("reconnecting",i=>{this.eventBus.emit("reconnecting",{detail:i.detail||0}),this.isFirstConnection=false;}),this.ws.addEventListener("maxreconnectattempts",()=>{this.eventBus.emit("maxreconnectattempts",void 0);}));}pong(e){this.send({request:"pong",args:e});}request(e){return new Promise((t,i)=>{let r=V(e);this.waitingRequests.has(r)?(this.waitingRequests.get(r)?.onSuccess.add(t),this.waitingRequests.get(r)?.onError.add(i)):this.waitingRequests.set(r,{onSuccess:new Set([t]),onError:new Set([i])}),this.send(e);})}subscribe(e,t){let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(!n.has(g))if(n.add(g),this.subscriptions.has(g))this.subscriptions.get(g).callbacks.add(t);else {let s={id:g,topic:a.topic,callbacks:new Set([t])};this.subscriptions.set(g,s),r.push(g),this.logger.debug(`create new subscription: ${g}`);}}),r.length>0&&this.send({request:"subv2",args:r});}unsubscribe(e,t){if(!e)return;let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(n.has(g))return;n.add(g);let s=this.subscriptions.get(g);s&&(s.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${g}`),s.callbacks.size===0&&(this.subscriptions.delete(g),r.push(g),this.logger.debug(`subscription ${g} has no callbacks, will unsubscribe`)));}),r.length>0&&this.send({request:"unsubv2",args:r});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(_e(t)){this.handleAckMessage(t);return}this.handleSubscriptionMessage(t);}catch(t){this.logger.error(`Failed to parse WebSocket message: ${t}`);}}handleAckMessage(e){let t;switch(e.type){case "signin":t=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let i=this.waitingRequests.get(t),r=e.data.code===9200;r?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),i?.onError.size&&!r&&i.onError.forEach(n=>{n(new l("REQUEST_FAILED","Request failed"));}),i?.onSuccess.size&&r&&i.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=Be(e),i=t.type,r=this.subscriptions.get(i);r&&r.callbacks.forEach(n=>{try{n(t);}catch(a){this.logger.error(`Callback Error (${i}): ${a}`);}});}resubscribeAll(){if(this.subscriptions.size===0)return;this.logger.debug("resubscribe all...");let e=Array.from(this.subscriptions.values()).map(t=>t.id);e.length>0&&(this.send({request:"subv2",args:e}),this.logger.debug(`resubscribe ${e.length} topics`));}timeoutHeartbeat(){this.stopHeartbeatTimer(),Date.now()-this.lastMessageTime>(this.config.noMessageTimeout||Ge.noMessageTimeout)&&(this.logger.debug("no message timeout"),this.subscriptions.size>0?this.reconnect():this.ws?.close()),this.heartbeatIntervalId=setTimeout(()=>{this.timeoutHeartbeat();},this.config.heartbeatInterval);}stopHeartbeatTimer(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null);}};var We=[56,59144,42161],Ue=[59141,421614,97],$e=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var z=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let i=H.MainNet;e.getConfig().isBetaMode?i=H.BetaNet:e.getConfig().isTestnet&&(i=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:i,...this.configManager.getConfig()?.socketConfig,onBeforeReSubscribe:()=>{if(this.clientAuth)return this.auth(true).then(()=>{this.logger.debug("reconnect auth success");})}});}get isConnected(){return this.wsClient.isConnected()}connect(){this.wsClient.connect();}disconnect(){this.wsClient.disconnect();}reconnect(){this.wsClient.reconnect();}subscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.subscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}unsubscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}subscribeKline(e,t,i){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}unsubscribeKline(e,t,i){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function 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 me(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let i=typeof t=="string"?t:{raw:t};return await o.signMessage({message:i})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let i=t.to;if(!i)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:i,data:t.data,value:t.value!=null?BigInt(t.value):void 0,gas:t.gasLimit!=null?BigInt(t.gasLimit):void 0,gasPrice:t.gasPrice!=null?BigInt(t.gasPrice):void 0,maxFeePerGas:t.maxFeePerGas!=null?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas!=null?BigInt(t.maxPriorityFeePerGas):void 0})}},...typeof e.signTypedData=="function"?{async signTypedData(t){return await e.signTypedData(t)}}:{}}}function Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:i=>o.signMessage(i),async sendTransaction(i){let r={...i};i.value!=null&&(r.value=BigInt(i.value)),i.gasLimit!=null&&(r.gasLimit=BigInt(i.gasLimit)),i.gasPrice!=null&&(r.gasPrice=BigInt(i.gasPrice)),i.maxFeePerGas!=null&&(r.maxFeePerGas=BigInt(i.maxFeePerGas)),i.maxPriorityFeePerGas!=null&&(r.maxPriorityFeePerGas=BigInt(i.maxPriorityFeePerGas));try{let a=(await o.sendTransaction(r)).hash;if(!a)throw new Error("sendTransaction: no hash in response");return {hash:a}}catch(n){let a=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||a.includes("BigInt")||a.includes("bigint")){let g={...i};i.value!=null&&(g.value=`0x${BigInt(i.value).toString(16)}`),i.gasLimit!=null&&(g.gasLimit=`0x${BigInt(i.gasLimit).toString(16)}`),i.gasPrice!=null&&(g.gasPrice=`0x${BigInt(i.gasPrice).toString(16)}`),i.maxFeePerGas!=null&&(g.maxFeePerGas=`0x${BigInt(i.maxFeePerGas).toString(16)}`),i.maxPriorityFeePerGas!=null&&(g.maxPriorityFeePerGas=`0x${BigInt(i.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(g)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw n}},signTransaction:typeof e.signTransaction=="function"?i=>t.signTransaction(i):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(i){return t.signTypedData(i.domain,i.types,i.message)}}:typeof t._signTypedData=="function"?{async signTypedData(i){return t._signTypedData(i.domain,i.types,i.message)}}:{}}}function K(o){return ut(o)?me(o):mt(o)?Ve(o):o}function qe(o){let e=chunkSY4XAFN4_js.e(o),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var fe={};function bt(o){if(!fe[o]){let e=chunkSY4XAFN4_js.e(o);fe[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),i=bt(e),r=await o.getAddress();return viem.createWalletClient({account:r,chain:i,transport:viem.custom({request:async a=>{if(a.method==="eth_accounts")return [r];if(a.method==="eth_sendTransaction"){let c=a.params?.[0]??{},{hash:d}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return d}if(a.method==="eth_signTypedData_v4"||a.method==="eth_signTypedData"){if(!o.signTypedData){let h=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(h.error)throw new Error(h.error.message);return h.result}let c=a.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let d=JSON.parse(c),{EIP712Domain:p,...u}=d.types;return await o.signTypedData({domain:d.domain,types:u,primaryType:d.primaryType,message:d.message})}let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(s.error)throw new Error(s.error.message);return s.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.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let i=(await this.config.walletClient.getAddresses())[0];if(i)return i}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?K(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:i,chainId:r}=e;if(t){if(!Ue.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of TESTNET_CHAIN_IDS`)}else if(i){if(!$e.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,i)=>{this._getAccessTokenQueue.push({resolve:t,reject:i,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return chunkSY4XAFN4_js.fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let i=3600;if(t.expireAt){let r=Math.floor(Date.now()/1e3);i=t.expireAt-r,i<=0&&(chunkSY4XAFN4_js.fa("Received expired token, using default expiry"),i=3600);}return this.setAccessToken(t.accessToken,i),t.accessToken}else return chunkSY4XAFN4_js.fa("\u274C Received empty accessToken"),null}catch(t){return chunkSY4XAFN4_js.ga("\u274C Failed to refresh accessToken:",t),null}}setAccessToken(e,t=3600){this.accessToken=e,this.accessTokenExpiry=Date.now()+t*1e3;}getCurrentAccessToken(){return this.accessToken}isAccessTokenValid(){return !!this.accessToken}clearAccessToken(){this.accessToken=void 0,this.accessTokenExpiry=void 0;}getConfig(){return this.config}};var Q=class{constructor(e,t,i){this.configManager=e,this.utils=t,this.api=i;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){return (await this.api.getKlineData({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getKlineLatestBar({interval:e,...t}){this.configManager.getConfig();return (await this.api.getKlineLatestBar({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getTickerList(e){return (await this.api.getTickerData(e)).data}async searchMarketAuth(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:i})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:i})).data}async addFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:i})).data}async removeFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:i})).data}async getBaseDetail(e){return (await this.api.getBaseDetail(e)).data}async getMarketDetail(e){return (await this.api.getMarketDetail(e)).data}async getPoolSymbolAll(){return (await this.api.getPoolSymbolAll()).data}async getPoolFundingFeeInfo({poolId:e,chainId:t,marketPrice:i}){let r=await chunkSY4XAFN4_js.Z(t);try{return {code:0,data:await r.read.getPoolInfo([e,i])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async listPositions(e,t){let i=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:i??"",address:e,positionId:t})).data}}catch(r){return this.logger.error("Error fetching positions:",r),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:i,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:i,quoteToken:r,chainId:n,address:a}){this.configManager.getConfig();try{let s=await this.utils.getOraclePrice(e,n);if(!s)throw new Error("Failed to get price data");let c={poolId:e,oracleType:s.oracleType,publishTime:s.publishTime,oracleUpdateData:s?.vaa??"0"},d=!1;Number(i)>0&&(d=await this.utils.needsApproval(a,n,r,i,chunkSY4XAFN4_js.R(n).TRADING_ROUTER));let p=BigInt(0),u=BigInt(i)>0?BigInt(i):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:a}),h=m.code===0?m.data??0n:0n,w=BigInt(0);h<u&&(w=u-h,p=w);let I={token:r,amount:p.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let Ce=await chunkSY4XAFN4_js.U(n);if(d){let S=await this.utils.approveAuthorization({chainId:n,quoteAddress:r,amount:viem.maxUint256.toString(),spenderAddress:chunkSY4XAFN4_js.R(n).TRADING_ROUTER});if(S.code!==0)throw new Error(S.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[c],I,t,i],{value:BigInt(s?.value??"1"),gas:BigInt(1e7)*chunkSY4XAFN4_js.c[n]/100n});return await chunkSY4XAFN4_js.f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(s){return {code:-1,message:s.message}}}};var wt={IOC:0},R=wt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},lr={NONE:0,GTE:1,LTE:2},k={INCREASE:0,DECREASE:1},pr={LONG:0,SHORT:1},ur={IOC:0},mr={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async createIncreaseOrder(e,t){try{let i=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()},c={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},d=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkSY4XAFN4_js.R(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(d){let w=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkSY4XAFN4_js.R(e.chainId).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let p=await chunkSY4XAFN4_js.U(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c,positionId:e.positionId});let w=await p.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...s},c]);u=await p.write.placeOrderWithPosition([e.positionId.toString(),{...s},c],{gasLimit:w*chunkSY4XAFN4_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c,depositData:s});let I=await p.estimateGas.placeOrderWithSalt(["1",{...s},c]);u=await p.write.placeOrderWithSalt(["1",{...s},c],{gasLimit:I*chunkSY4XAFN4_js.c[e.chainId]/100n});}let m=await chunkSY4XAFN4_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(i){return this.logger.error("Error placing order:",i),{code:-1,message:i?.message}}}async closeAllPositions(e,t){try{let i={token:"0x0000000000000000000000000000000000000000",amount:"0"},r=t.map(d=>d.positionId.toString()),n=t.map(d=>({user:d.address,poolId:d.poolId,orderType:d.orderType,triggerType:d.triggerType,operation:k.DECREASE,direction:d.direction,collateralAmount:d.collateralAmount,size:d.size,price:d.price,timeInForce:R,postOnly:d.postOnly,slippagePct:d.slippagePct,leverage:d.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",i,r,n),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await chunkSY4XAFN4_js.U(e),g=await a.estimateGas.placeOrdersWithPosition([i,r,n]),s=await a.write.placeOrdersWithPosition([i,r,n],{gasLimit:g*chunkSY4XAFN4_js.c[e]/100n}),c=await chunkSY4XAFN4_js.f(e).waitForTransactionReceipt({hash:s});return {code:0,message:"close all positions success",transactionHash:s,blockNumber:c?.blockNumber,gasUsed:c?.gasUsed?.toString(),status:c?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c}}catch(i){return {code:-1,message:i?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},i=BigInt(e.collateralAmount),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c=await chunkSY4XAFN4_js.U(e.chainId),d;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,s,{data:t}]);let m=await c.estimateGas.placeOrderWithPosition([e.positionId.toString(),s,t]);d=await c.write.placeOrderWithPosition([e.positionId.toString(),s,t],{gasLimit:m*chunkSY4XAFN4_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,s,{data:t}]);let h=await c.estimateGas.placeOrderWithSalt(["1",s,t]);d=await c.write.placeOrderWithSalt(["1",s,t],{gasLimit:h*chunkSY4XAFN4_js.c[e.chainId]/100n});}let p=await chunkSY4XAFN4_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkSY4XAFN4_js.U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let s=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:k.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:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c={token:"0x0000000000000000000000000000000000000000",amount:"0"},d;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s]);d=await t.write.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s],{gasLimit:m*chunkSY4XAFN4_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",s);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c,[m.toString(),m.toString()],s]);d=await t.write.placeOrdersWithSalt([c,[m.toString(),m.toString()],s],{gasLimit:h*chunkSY4XAFN4_js.c[e.chainId]/100n});}let p=await chunkSY4XAFN4_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}let i={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",i);let s=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,i]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),r,i],{gasLimit:s*chunkSY4XAFN4_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",i);let s=1,c=await t.estimateGas.placeOrderWithSalt([s.toString(),r,i]);n=await t.write.placeOrderWithSalt([s.toString(),r,i],{gasLimit:c*chunkSY4XAFN4_js.c[e.chainId]/100n});}let a=await chunkSY4XAFN4_js.f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:a?.blockNumber,gasUsed:a?.gasUsed?.toString(),status:a?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:a}}}catch(i){return {code:-1,message:i?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkSY4XAFN4_js.U(t)).write.cancelOrders([e]);return await chunkSY4XAFN4_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel all orders success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkSY4XAFN4_js.U(t)).write.cancelOrder([e]);return await chunkSY4XAFN4_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel order success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkSY4XAFN4_js.U(t)).write.cancelOrders([e]);return await chunkSY4XAFN4_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"Orders canceled success"}}catch(i){return this.logger.error("Error canceling orders:",i),{code:-1,message:i?.message}}}async updateOrderTpSl(e,t,i,r,n,a){let g=await this.utils.getNetworkFee(n,i),s={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:a?e.tpSize:"0",tpPrice:a?e.tpPrice:"0",slSize:a?e.slSize:"0",slPrice:a?e.slPrice:"0"}},c={token:t,amount:g.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await chunkSY4XAFN4_js.U(i);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(r,i,e.executionFeeToken,g.toString(),chunkSY4XAFN4_js.R(i).TRADING_ROUTER)){let w=await this.utils.approveAuthorization({chainId:i,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkSY4XAFN4_js.R(i).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let u=await d.estimateGas.updateOrder([c,s]),m=await d.write.updateOrder([c,s],{gasLimit:u*chunkSY4XAFN4_js.c[i]/100n}),h=await chunkSY4XAFN4_js.f(i).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(p){return this.logger.error("Error updating order:",p),{code:-1,message:"Failed to update order"}}}async getOrders(e){let t=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getOrders(t??"",e)).data}}catch(i){return this.logger.error("Error fetching orders:",i),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:i,...e,address:t})).data}}};var he={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,i,r){try{if(!i||typeof i=="string"&&!i.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=r??chunkSY4XAFN4_js.R(t).Account,g=await chunkSY4XAFN4_js.T(t,i).read.allowance([e,n]);return {code:0,data:String(g)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await chunkSY4XAFN4_js.ja(n)}}async needsApproval(e,t,i,r,n){try{let g=(await this.getApproveQuoteAmount(e,t,i,n)).data,s=BigInt(g),c=BigInt(r);return s<c}catch(a){return this.logger.error("Error checking approval needs:",a),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:i,spenderAddress:r}){try{let n=await chunkSY4XAFN4_js.V(e,t),a=i??viem.maxUint256,g=r??chunkSY4XAFN4_js.R(e).Account,s=await this.getGasPriceByRatio(),c=await n.write.approve([g,a],{gasPrice:s});return await chunkSY4XAFN4_js.f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,i,r){let a=this.configManager.getConfig().brokerAddress;try{let g=chunkSY4XAFN4_js.X(i,a),s=r??await this.configManager.getSignerAddress(i),c=await g.read.getUserFeeRate([s,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(g){return this.logger.error("Error getting user trading fee rate:",g),{code:-1,message:g?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkSY4XAFN4_js.Y(t,0)).read.getExecutionFee([e])).toString()}catch(i){return this.logger.error("Error getting network fee:",i),"0"}}async getOraclePrice(e,t){try{let i=await chunkSY4XAFN4_js.ta(t,e);if(!i)throw new Error("Failed to get price data");return i}catch(i){throw this.logger.error("Error getting oracle price:",i),i}}async buildUpdatePriceParams(e,t){let i=await this.getOraclePrice(e,t);if(!i)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:i.vaa,publishTime:i.publishTime,oracleType:i.oracleType,value:i.value,price:i.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let i=await chunkSY4XAFN4_js.ja(e);return i?i.error:JSON.stringify(e)}catch(i){return i?.message??i?.toString()??t}}async checkSeamlessGas(e,t,i){let n=await(await chunkSY4XAFN4_js.Y(t,0)).read.getForwardFeeByToken([i]),g=await chunkSY4XAFN4_js.T(t,i).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(g)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:i}){try{return {code:0,data:await(await chunkSY4XAFN4_js.Z(e,0)).read.getPoolInfo([t,i])}}catch(r){return this.logger.error("Error getting pool info:",r),{code:-1,message:r?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let i=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);i&&i[1]&&(t=i[1]);}if(t){let i=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(i){let r=Object.keys(he).find(n=>n.toLowerCase()===i);if(r)return he[r]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkSY4XAFN4_js.pa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,i=chunkSY4XAFN4_js.d[t];return chunkSY4XAFN4_js.oa(e,i?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,i,r){this.configManager=e,this.logger=t,this.utils=i,this.client=r;}async withRetry(e,t=3,i=300){let r;for(let n=0;n<t;n++)try{return await e()}catch(a){r=a,n<t-1&&await new Promise(g=>setTimeout(g,i));}throw r}async getTradeFlow(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:i,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:i}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=chunkSY4XAFN4_js.T(e,i),n=await this.configManager.getSignerAddress(e);return {code:0,data:await r.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,i,r,n){try{let g=await(await chunkSY4XAFN4_js._(n)).write.updateAndWithdraw([e,t,i,r]);return {code:0,data:await chunkSY4XAFN4_js.f(n).waitForTransactionReceipt({hash:g})}}catch(a){return {code:-1,message:a.message}}}async deposit({amount:e,tokenAddress:t,chainId:i}){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"",n=chunkSY4XAFN4_js.R(i);try{if(await this.utils.needsApproval(r,i,t,e,n.Account)){let d=await this.utils.approveAuthorization({chainId:i,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:n.Account});if(d.code!==0)throw new Error(d.message)}let s=await(await chunkSY4XAFN4_js._(i)).write.deposit([r,t,e]);return {code:0,data:await chunkSY4XAFN4_js.f(i).waitForTransactionReceipt({hash:s})}}catch(a){return {code:-1,message:a.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:i}){try{let r=await this.getAccountInfo(t,i,e);if(r.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,i),a=r.data,g=BigInt(a?.quoteProfit??0),s=BigInt(a?.freeMargin??0),c=BigInt(a?.lockedMargin??0),d=n?.code===0?n.data:null,p=d?.status===1?BigInt(d?.lockedMargin??0):0n;return {code:0,data:s+g-c-p}}catch(r){return {code:-1,message:r.message}}}async getAccountInfo(e,t,i){let r=await chunkSY4XAFN4_js.Z(e);try{return {code:0,data:await r.read.getAccountInfo([i,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let i=this.configManager.getConfig(),r=chunkSY4XAFN4_js.X(e,i.brokerAddress),a=await chunkSY4XAFN4_js.f(e).getBlock({blockTag:"latest"}),g=Number(a?.timestamp??BigInt(Ae__default.default().unix()))+300;try{let s=await r.read.userFeeData([t]),c;try{c=await this.withRetry(()=>r.read.userNonces([t]));}catch{c=0n;}return {code:0,data:{nonce:c.toString(),deadline:g,...s}}}catch(s){return {code:-1,message:s.message}}}async getAccountVipInfoByBackend(e,t,i,r){let n=await this.configManager.getAccessToken()??"";try{let a=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:i,nonce:r});if(a.code!==9200)throw new l("REQUEST_FAILED",a.msg??"Failed to get account vip info");return {code:0,data:a.data}}catch(a){return {code:-1,message:a.message}}}async setUserFeeData(e,t,i,r,n){let a=this.configManager.getConfig();if(i<Ae__default.default().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let g=await chunkSY4XAFN4_js.W(t,a.brokerAddress),s={user:e,nonce:r.nonce,deadline:i,feeData:{tier:r.tier,referrer:r.referrer||viem.zeroAddress,totalReferralRebatePct:r.totalReferralRebatePct,referrerRebatePct:r.referrerRebatePct,expiry:r.expiry},signature:n},c=await g.read.userNonces([e]);if(parseInt(c.toString())+1!==parseInt(r.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let d=await g.write.setUserFeeData([s]);return {code:0,data:await chunkSY4XAFN4_js.f(t).waitForTransactionReceipt({hash:d})}}catch(g){return {code:-1,message:g.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(i=>Qe(e,i)).join("&")}function Pt(o){let e=o||{};return Object.keys(e).filter(i=>typeof e[i]<"u").map(i=>Array.isArray(e[i])?Tt(e,i):Ct(e,i)).join("&")}function be(o){let e=Pt(o);return e?`?${e}`:""}var ie=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",i=await this.configManager.getSignerAddress(e.chainId);if(!i)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:i}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkSY4XAFN4_js.n.get(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async post(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkSY4XAFN4_js.n.post(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async put(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkSY4XAFN4_js.n.put(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async delete(e,{auth:t=false,...i}={}){let r=t?await this.buildAuthParams():{};return chunkSY4XAFN4_js.n.delete(this.buildRequestPath(e),lodashEs.merge(r,i))}};var re=class extends ie{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkSY4XAFN4_js.n.get(`${this.getHost()}/v2/agent/forwarder/get${be(e)}`)}async getPoolList(){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkSY4XAFN4_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 chunkSY4XAFN4_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 chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${be({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...i}){return await chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,i){return await chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,i){return await chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${i}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:i,limit:r,interval:n}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:i,limit:r,interval:n})}async getKlineLatestBar(e){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async removeFavorite({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:i,deadline:r,nonce:n}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:i,deadline:r,nonce:n},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getAppealList(e){return this.get("/openapi/gateway/scan/dispute/list",e,{auth:true})}async getAppealDetail(e){return this.get("/openapi/gateway/scan/dispute/details",e,{auth:true})}async uploadAppealEvidence(e){return this.get("/openapi/gateway/scan/dispute/upload/evidence",e,{auth:true})}async getAppealReconsiderationList(e){return this.get("/openapi/gateway/scan/dispute/appeal/list",e,{auth:true})}async getAppealReconsiderationDetail(e){return this.get("/openapi/gateway/scan/dispute/appeal/details",e,{auth:true})}async getAppealReimbursementList(e){return this.get("/openapi/gateway/scan/reimbursement/list",e,{auth:true})}async getAppealNodeVoteList(e){return this.get("/openapi/gateway/scan/node/vote-list",e)}async getAppealNodeVoteDetails(e){return this.get("/openapi/gateway/scan/node/vote-details",e)}async getIsVoteNode(e){return this.get("/openapi/gateway/scan/node/vote-node-check",e)}async postVoteSignature(e){return this.get("/openapi/gateway/scan/node/vote",e,{auth:true})}async getPedingVoteCount(){return this.get("/openapi/gateway/scan/node/pending-vote-total",{},{auth:true})}async getMyAppealCount(){return this.get("/openapi/gateway/scan/processing-total",{},{auth:true})}async getWarmholeSign(e){return this.get("/openapi/gateway/scan/get-warmhole-sign",e,{auth:true})}async getDisputeTotalCount(){return this.get("/openapi/gateway/scan/dispute/dispute-total",{},{auth:true})}async getAppealTotalCount(){return this.get("/openapi/gateway/scan/dispute/appeal-total",{},{auth:true})}async getReimbursementTotalCount(){return this.get("/openapi/gateway/scan/dispute/reimbursement-total",{},{auth:true})}async getCurrentEpoch({address:e,accessToken:t,broker:i}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:i},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:r}){return chunkSY4XAFN4_js.n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:i,myx_openapi_access_token:r}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,kt="0x55d398326f99059ff775485246999027b3197955";function vt(o){let e=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),i=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:i}}async function Mt(o,e,t,i,r,n,a,g){let s=chunkSY4XAFN4_js.T(e,t),c=await Je(s),[d]=await o.getAddresses();if(!d)throw new l("INVALID_SIGNER","No account for signPermit");let p={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:i,spender:r,value:n,nonce:a,deadline:g},m=await o.signTypedData({account:d,domain:{...c,chainId:c.chainId},types:p,primaryType:"Permit",message:u});return vt(m)}var ne=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async onCheckRelayer(e,t,i,r,n){let g=await(await chunkSY4XAFN4_js.$(i)).read.isUserRelayerEnabled([e,t]),c=await(await chunkSY4XAFN4_js.Y(i)).read.getForwardFeeByToken([r]),d=BigInt(c)*BigInt(Xe);n=n??d.toString();let p=await this.utils.needsApproval(e,i,r,n,chunkSY4XAFN4_js.R(i).TRADING_ROUTER);return g&&!p}async getContractAbiAndAddressByFunctionName(e,t){let i=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],r=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return i.includes(e)?{abi:chunkSY4XAFN4_js.S,address:chunkSY4XAFN4_js.R(t).TRADING_ROUTER}:n.includes(e)?{abi:chunkSY4XAFN4_js.m,address:chunkSY4XAFN4_js.R(t).Account}:r.includes(e)?{abi:chunkSY4XAFN4_js.j,address:this.configManager.getConfig().brokerAddress}:{abi:chunkSY4XAFN4_js.S,address:chunkSY4XAFN4_js.R(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkSY4XAFN4_js.i(t),n=chunkSY4XAFN4_js.R(t),[a]=await r.getAddresses();if(!a)throw new l("INVALID_SIGNER","No account");let g=chunkSY4XAFN4_js.T(t,i);try{let s=await g.read.nonces([a]),c=await Mt(r,t,i,a,n.TRADING_ROUTER,viem.maxUint256,s,e);return [{token:i,owner:a,spender:n.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch(s){if(chunkSY4XAFN4_js.ia(s))throw s;let c=s instanceof Error?s.message:String(s);throw new l("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${c}`)}}async getForwardEip712Domain(e){let i=await(await chunkSY4XAFN4_js.$(e)).read.eip712Domain();return {name:i[1],version:i[2],chainId:i[3],verifyingContract:i[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:i,forwardFeeToken:r,functionName:n,orderParams:a,value:g="0",gas:s="800000"}){let c=await(await chunkSY4XAFN4_js.$(e)).read.nonces([t]),d=Ae__default.default().add(60,"minute").unix(),p=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),h=viem.encodeFunctionData({abi:u,functionName:n,args:a}),w=await i({domain:p,functionHash:h,to:m,nonce:c.toString(),deadline:d}),I=await this.api.forwarderTxApi({from:t,to:m,value:g??"0",gas:s,nonce:c.toString(),data:h,deadline:d,signature:w,forwardFeeToken:r},e);if(I.data?.txHash){for(let S=0;S<5;S++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};S<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Te){this.logger.error("Poll transaction from chain error:",Te),S<4&&await new Promise(ce=>setTimeout(ce,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async forwarderTx({from:e,to:t,value:i,gas:r,deadline:n,data:a,nonce:g,forwardFeeToken:s},c){let d=await this.getForwardEip712Domain(c),p=await chunkSY4XAFN4_js.i(c),[u]=await p.getAddresses();if(!u)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await p.signTypedData({account:u,domain:d,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(i??"0"),gas:BigInt(r),nonce:BigInt(g),deadline:BigInt(n),data:a}});return await this.api.forwarderTxApi({from:e,to:t,value:i,gas:r,nonce:g,data:a,deadline:n,signature:m,forwardFeeToken:s},c)}async approveBalance(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkSY4XAFN4_js.V(e,t),n=chunkSY4XAFN4_js.R(e);return await r.write?.approve([n.TRADING_ROUTER,i])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:i,address:n,tokenAddress:r})).data,w=await(await chunkSY4XAFN4_js.Y(i)).read.getForwardFeeByToken([r]),I=BigInt(w)*BigInt(Xe);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r});let a=Ae__default.default().add(60,"minute").unix(),g=[];if(e)try{r===kt?(await this.approveBalance(i,r,viem.maxUint256.toString()))?.hash&&(g=[]):g=await this.getUSDPermitParams(a,i,r);}catch(u){if(chunkSY4XAFN4_js.ia(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),g=[];}let s=await chunkSY4XAFN4_js.$(i,1),c=await(await chunkSY4XAFN4_js.$(i)).read.nonces([n]),d=viem.encodeFunctionData({abi:chunkSY4XAFN4_js.k,functionName:"permitAndApproveForwarder",args:[t,e,g]}),p;try{p=await this.forwarderTx({from:n,to:s.address,value:"0",gas:"800000",nonce:c.toString(),data:d,deadline:a,forwardFeeToken:r},i);}catch(u){if(chunkSY4XAFN4_js.ia(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(p.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:p.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(w){this.logger.error("Poll transaction from chain error:",w),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getApproveBalance({chainId:e,forwardFeeToken:t,address:i}){try{let r=chunkSY4XAFN4_js.R(e).TRADING_ROUTER,a=await chunkSY4XAFN4_js.T(e,t).read.allowance([i,r]);return {code:0,data:String(a)}}catch(r){return {code:-1,message:r?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkSY4XAFN4_js.$(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:i,functionName:r,data:n,seamlessAddress:a}){if(!e||!viem.isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!a||!viem.isAddress(a))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!i||!viem.isAddress(i))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,i))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let s=await chunkSY4XAFN4_js.$(t),c,{abi:d,address:p}=await this.getContractAbiAndAddressByFunctionName(r,t);try{c=viem.encodeFunctionData({abi:d,functionName:r,args:n});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(r)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await s.read.nonces([a]);return {from:a,to:p,value:"0",gas:"800000",deadline:Ae__default.default().add(60,"minute").unix(),data:c,nonce:u.toString(),forwardFeeToken:i}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkSY4XAFN4_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkSY4XAFN4_js.R(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkSY4XAFN4_js.X(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkSY4XAFN4_js.ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkSY4XAFN4_js.aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let i=t==="DisputeFiled"?"caseId":"appealCaseId";for(let r of e.logs)try{let n=viem.decodeEventLog({abi:chunkSY4XAFN4_js.l,data:r.data,topics:r.topics});if(n.eventName===t&&n.args&&i in n.args)return n.args[i]}catch{continue}return null}async submitAppeal(e,t,i){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(r,this.config.chainId,t,i,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let a=await this.getDisputeCourtContract(),g=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),s=BigInt(g[0].value.toString()||"1"),c=await a.estimateGas.fileDispute([g,e,t],{value:s}),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.fileDispute([g,e,t],{value:s,gasLimit:d,gasPrice:p}),m=await chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:i,deadline:r,v:n,r:a,s:g}){let s=await this.getDisputeCourtContract(),c=await s.estimateGas.vote([e,t,i?1:0,r,n,a,g]),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await s.write.vote([e,t,i?1:0,r,n,a,g],{gasLimit:d,gasPrice:p});return await chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),i=await t.estimateGas.claimBond([e]),r=await this.client.utils.getGasLimitByRatio(i),n=await this.client.utils.getGasPriceByRatio(),a=await t.write.claimBond([e],{gasLimit:r,gasPrice:n});return chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:a})}async claimReimbursement(e,t,i,r){let n=await this.getReimbursementContract(),a=await n.estimateGas.claimReimbursement([e,t,i,r]),g=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),c=await n.write.claimReimbursement([e,t,i,r],{gasLimit:g,gasPrice:s});return chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,i){let r=await this.getDisputeCourtContract(),n=await this.client.utils.getGasPriceByRatio(),a=await this.client.utils.getGasLimitByRatio(await r.estimateGas.fileDisputeFromStaker([e,t,i])),g=await r.write.fileDisputeFromStaker([e,t,i],{gasLimit:a,gasPrice:n}),s=await chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:g}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,i){let r=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",a=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,i,a)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:a});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let s=await r.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),p=await r.write.appeal([e],{gasLimit:c,gasPrice:d}),u=await chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:p}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new l("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,i){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:await this.configManager.getAccessToken()??""})}};var se=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),i=await chunkSY4XAFN4_js.W(this.config.chainId,t.brokerAddress),r=await i.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(r),a=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimRebate([e],{gasPrice:a,gasLimit:n});return chunkSY4XAFN4_js.f(this.config.chainId).waitForTransactionReceipt({hash:g})}};var Dt=(s=>(s[s.UnderReview=1]="UnderReview",s[s.InitialVote=2]="InitialVote",s[s.PublicNotice=3]="PublicNotice",s[s.UnderReconsideration=4]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=6]="Failed",s[s.PlatformRuling=7]="PlatformRuling",s[s.PlatformRevoked=8]="PlatformRevoked",s))(Dt||{}),Ot=(d=>(d[d.InitialVoting=1]="InitialVoting",d[d.PublicNotice=2]="PublicNotice",d[d.UnderReconsideration=3]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=4]="Failed",d[d.PlatformRuling=6]="PlatformRuling",d[d.PlatformRevoked=7]="PlatformRevoked",d[d.ReconsiderationVoting=8]="ReconsiderationVoting",d[d.AppealRevert=9]="AppealRevert",d[d.NotAppealFailed=10]="NotAppealFailed",d))(Ot||{}),Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.PublicNotice=2]="PublicNotice",r[r.UnderReconsideration=3]="UnderReconsideration",r[r.Completed=4]="Completed",r))(Ft||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Lt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Lt||{}),_t=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(_t||{}),Bt=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(Bt||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),Wt=(i=>(i[i.NoVote=0]="NoVote",i[i.Supported=1]="Supported",i[i.Rejected=2]="Rejected",i))(Wt||{}),Ut=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Ut||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var xe=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new chunkSY4XAFN4_js.ha({logLevel:e.logLevel});let t=chunkSY4XAFN4_js.P.getInstance();chunkSY4XAFN4_js.h()?.hasSigner()||(t.setConfigManager(this.configManager),chunkSY4XAFN4_js.g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new re(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new Q(this.configManager,this.utils,this.api),this.position=new J(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new se(this);}auth(e){this.configManager.auth(e),chunkSY4XAFN4_js.P.getInstance().setConfigManager(this.configManager),chunkSY4XAFN4_js.g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Xn="1.0.20-beta.9";
2
- Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkSY4XAFN4_js.na}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ma}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkSY4XAFN4_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.D}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.A}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkSY4XAFN4_js.o}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.C}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkSY4XAFN4_js.F}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.r}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ha}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkSY4XAFN4_js.u}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkSY4XAFN4_js.p}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkSY4XAFN4_js.s}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkSY4XAFN4_js.P}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.x}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkSY4XAFN4_js.q}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.B}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.w}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.v}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.t}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.E}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.y}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkSY4XAFN4_js.z}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ra}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkSY4XAFN4_js.xa}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkSY4XAFN4_js.qa}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkSY4XAFN4_js.pa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkSY4XAFN4_js.oa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkSY4XAFN4_js.va}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkSY4XAFN4_js.la}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ka}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkSY4XAFN4_js.M}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkSY4XAFN4_js.H}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkSY4XAFN4_js.N}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkSY4XAFN4_js.O}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkSY4XAFN4_js.I}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkSY4XAFN4_js.J}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkSY4XAFN4_js.G}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkSY4XAFN4_js.K}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ta}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkSY4XAFN4_js.sa}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkSY4XAFN4_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkSY4XAFN4_js.da}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkSY4XAFN4_js.L}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ua}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkSY4XAFN4_js.i}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkSY4XAFN4_js.Q}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkSY4XAFN4_js.za}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkSY4XAFN4_js.wa}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkSY4XAFN4_js.Aa}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ya}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ga}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ea}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkSY4XAFN4_js.fa}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkSY4XAFN4_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkSY4XAFN4_js.ca}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=_t;exports.AppealNodeStateEnum=Wt;exports.AppealNodeVotedStateEnum=Bt;exports.AppealReconsiderationType=Ot;exports.AppealStage=Ft;exports.AppealStatus=$t;exports.AppealType=Dt;exports.Direction=pr;exports.IsVoteNodeEnum=Ut;exports.MyxClient=xe;exports.NodeTypeEnum=Nt;exports.OperationType=k;exports.OrderStatus=mr;exports.OrderType=Y;exports.SDK_VERSION=Xn;exports.TimeInForce=ur;exports.TriggerType=lr;exports.VoteTypeEnum=Lt;exports.fromViemWalletClient=me;exports.normalizeSigner=K;
1
+ 'use strict';var chunkUIM35W7V_js=require('./chunk-UIM35W7V.js'),lt=require('mitt'),cryptoEs=require('crypto-es'),pt=require('reconnecting-websocket'),viem=require('viem'),Ae=require('dayjs'),lodashEs=require('lodash-es');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var lt__default=/*#__PURE__*/_interopDefault(lt);var pt__default=/*#__PURE__*/_interopDefault(pt);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var $=(o,e)=>cryptoEs.MD5(o,{outputLength:32}).toString(cryptoEs.Hex);var V=o=>{switch(o.request){case "signin":return $(o.request)}return $(JSON.stringify(o))},N=o=>{let{topic:e,params:t}=o;switch(e){case "candle":return `${e}.${t.globalId}_${t.resolution}`;case "ticker":return `${e}.${t.globalId}`;case "ticker.*":case "order":case "position":return e;default:return $(JSON.stringify({topic:e,params:t}))}},Be=({type:o})=>o==="pong"||o==="signin"||o==="subv2"||o==="unsubv2"||o==="ping"||o==="pong",dt=o=>{switch(o){case "order":case "position":case "ticker.*":return o;default:let[e]=o.split(".");return e}},_e=o=>{switch(dt(o.type)){case "ticker":{let[,t=""]=o.type.split(".");return {...o,type:N({topic:"ticker",params:{globalId:parseInt(t)}}),globalId:parseInt(t)}}case "candle":{let[,t=""]=o.type.split("."),[i,r]=t.split("_");return {...o,type:N({topic:"candle",params:{globalId:parseInt(i),resolution:r}}),globalId:parseInt(i),resolution:r}}}return o};var l=class extends Error{constructor(e,t){super(t),this.name=e;}toJSON(){return {code:this.name,message:this.message}}toString(){return `[MYX-ERROR-${this.name}]: ${this.message}`}};var Ge={url:"",initialReconnectDelay:1e3,maxReconnectDelay:3e4,reconnectMultiplier:1.5,maxReconnectAttempts:10,maxEnqueuedMessages:100,requestTimeout:1e4,heartbeatInterval:1e4,heartbeatMessage:"ping",noMessageTimeout:5e3,connectionTimeout:1e4},q=class{constructor(e){this.ws=null;this.subscriptions=new Map;this.waitingRequests=new Map;this.eventBus=lt__default.default();this.heartbeatIntervalId=null;this.isFirstConnection=true;this.lastMessageTime=0;let t={...e,logLevel:e?.logLevel||"info"},{logLevel:i,...r}=t;this.config={...Ge,...r},this.logger=new chunkUIM35W7V_js.ha({logLevel:e?.logLevel}),this.logger.debug("WebSocketClient constructor",this.config);}connect(){return new Promise((e,t)=>{if(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING){e();return}try{let i={maxReconnectionDelay:this.config.maxReconnectDelay,minReconnectionDelay:this.config.initialReconnectDelay,reconnectionDelayGrowFactor:this.config.reconnectMultiplier,maxRetries:this.config.maxReconnectAttempts,maxEnqueuedMessages:this.config.maxEnqueuedMessages,connectionTimeout:this.config.connectionTimeout};this.ws=new pt__default.default(this.config.url,this.config.protocols,i),this.setupEventListeners(e,t);}catch(i){t(i);}})}async onBeforeReSubscribe(){return this.config.onBeforeReSubscribe&&await this.config.onBeforeReSubscribe(),true}setupEventListeners(e,t){this.ws&&(this.ws.onopen=async i=>{this.eventBus.emit("open",i),this.lastMessageTime=Date.now(),this.timeoutHeartbeat(),this.isFirstConnection||this.onBeforeReSubscribe().then(()=>this.resubscribeAll()),this.isFirstConnection=false,e();},this.ws.onmessage=i=>{this.handleMessage(i);},this.ws.onclose=i=>{this.eventBus.emit("close",i),this.stopHeartbeatTimer();},this.ws.onerror=i=>{this.eventBus.emit("error",i),t(i);},this.ws.addEventListener("reconnecting",i=>{this.eventBus.emit("reconnecting",{detail:i.detail||0}),this.isFirstConnection=false;}),this.ws.addEventListener("maxreconnectattempts",()=>{this.eventBus.emit("maxreconnectattempts",void 0);}));}pong(e){this.send({request:"pong",args:e});}request(e){return new Promise((t,i)=>{let r=V(e);this.waitingRequests.has(r)?(this.waitingRequests.get(r)?.onSuccess.add(t),this.waitingRequests.get(r)?.onError.add(i)):this.waitingRequests.set(r,{onSuccess:new Set([t]),onError:new Set([i])}),this.send(e);})}subscribe(e,t){let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(!n.has(g))if(n.add(g),this.subscriptions.has(g))this.subscriptions.get(g).callbacks.add(t);else {let s={id:g,topic:a.topic,callbacks:new Set([t])};this.subscriptions.set(g,s),r.push(g),this.logger.debug(`create new subscription: ${g}`);}}),r.length>0&&this.send({request:"subv2",args:r});}unsubscribe(e,t){if(!e)return;let i=Array.isArray(e)?e:[e],r=[],n=new Set;i.forEach(a=>{let g=N(a);if(n.has(g))return;n.add(g);let s=this.subscriptions.get(g);s&&(s.callbacks.delete(t),this.logger.debug(`remove callback from subscription: ${g}`),s.callbacks.size===0&&(this.subscriptions.delete(g),r.push(g),this.logger.debug(`subscription ${g} has no callbacks, will unsubscribe`)));}),r.length>0&&this.send({request:"unsubv2",args:r});}send(e){let t=typeof e=="string"?e:JSON.stringify(e);if(!this.ws)throw new l("SOCKET_NOT_CONNECTED","WebSocket is not connected");this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING&&this.reconnect(),this.ws.send(t);}disconnect(){this.stopHeartbeatTimer(),this.ws&&(this.ws.close(),this.ws=null);}reconnect(){this.ws?this.ws.readyState!==WebSocket.CONNECTING&&this.ws.reconnect():this.connect().catch(e=>{this.logger.error(e);});}isConnected(){return this.ws?.readyState===WebSocket.OPEN}on(e,t){this.eventBus.on(e,t);}off(e,t){this.eventBus.off(e,t);}handleMessage(e){try{let t=JSON.parse(e.data);if(this.lastMessageTime=Date.now(),t.type==="ping"){queueMicrotask(()=>{this.pong(t.data);});return}if(Be(t)){this.handleAckMessage(t);return}this.handleSubscriptionMessage(t);}catch(t){this.logger.error(`Failed to parse WebSocket message: ${t}`);}}handleAckMessage(e){let t;switch(e.type){case "signin":t=V({request:e.type,args:""});break;default:t=V({request:e.type,args:e.data.data});break}let i=this.waitingRequests.get(t),r=e.data.code===9200;r?this.logger.debug(`AcK Message:${e.type} received`):(this.logger.error(`Ack Message:${e.type} received`,e),this.eventBus.emit("error",e)),i?.onError.size&&!r&&i.onError.forEach(n=>{n(new l("REQUEST_FAILED","Request failed"));}),i?.onSuccess.size&&r&&i.onSuccess.forEach(n=>{n(e.data);});}handleSubscriptionMessage(e){let t=_e(e),i=t.type,r=this.subscriptions.get(i);r&&r.callbacks.forEach(n=>{try{n(t);}catch(a){this.logger.error(`Callback Error (${i}): ${a}`);}});}resubscribeAll(){if(this.subscriptions.size===0)return;this.logger.debug("resubscribe all...");let e=Array.from(this.subscriptions.values()).map(t=>t.id);e.length>0&&(this.send({request:"subv2",args:e}),this.logger.debug(`resubscribe ${e.length} topics`));}timeoutHeartbeat(){this.stopHeartbeatTimer(),Date.now()-this.lastMessageTime>(this.config.noMessageTimeout||Ge.noMessageTimeout)&&(this.logger.debug("no message timeout"),this.subscriptions.size>0?this.reconnect():this.ws?.close()),this.heartbeatIntervalId=setTimeout(()=>{this.timeoutHeartbeat();},this.config.heartbeatInterval);}stopHeartbeatTimer(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null);}};var We=[56,59144,42161],Ue=[59141,421614,97],$e=[97,421614];var H={TestNet:"wss://oapi-test.myx.cash/ws",MainNet:"wss://oapi.myx.finance/ws",BetaNet:"wss://oapi-beta.myx.finance/ws"};var z=class{constructor(e,t){this.clientAuth=false;this.prevUserAddress=null;this.configManager=e,this.logger=t;let i=H.MainNet;e.getConfig().isBetaMode?i=H.BetaNet:e.getConfig().isTestnet&&(i=H.TestNet),this.wsClient=new q({logLevel:this.configManager.getConfig()?.logLevel,url:i,...this.configManager.getConfig()?.socketConfig,onBeforeReSubscribe:()=>{if(this.clientAuth)return this.auth(true).then(()=>{this.logger.debug("reconnect auth success");})}});}get isConnected(){return this.wsClient.isConnected()}connect(){this.wsClient.connect();}disconnect(){this.wsClient.disconnect();}reconnect(){this.wsClient.reconnect();}subscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.subscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}unsubscribeTickers(e,t){let i=Array.isArray(e)?e:[e];this.wsClient.unsubscribe(i.map(r=>({topic:"ticker",params:{globalId:r}})),t);}subscribeKline(e,t,i){this.logger.debug(`subscribe kline ${e} ${t}`),this.wsClient.subscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}unsubscribeKline(e,t,i){this.logger.debug(`unsubscribe kline ${e} ${t}`),this.wsClient.unsubscribe({topic:"candle",params:{globalId:e,resolution:t}},i);}async getSdkAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getSignerAddress(e.chainId);if(!t)throw new l("INVALID_SIGNER");return {userAddress:t}}async auth(e=false){let{userAddress:t}=await this.getSdkAuthParams();if(t===this.prevUserAddress&&this.clientAuth&&!e)return Promise.resolve();this.logger.debug(`sdkaccount: ${t}`),await this.wsClient.request({request:"signin",args:`sdkaccount.${t}`}).then(()=>{this.logger.debug(`auth success ${t}`),this.clientAuth=true,this.prevUserAddress=t;});}async subscribePosition(e){this.logger.debug("subscribe position"),await this.auth(),this.wsClient.subscribe({topic:"position"},e);}unsubscribePosition(e){this.logger.debug("unsubscribe position"),this.wsClient.unsubscribe({topic:"position"},e);}async subscribeOrder(e){this.logger.debug("subscribe order"),await this.auth(),this.wsClient.subscribe({topic:"order"},e);}unsubscribeOrder(e){this.logger.debug("unsubscribe order"),this.wsClient.unsubscribe({topic:"order"},e);}on(e,t){this.wsClient.on(e,t);}off(e,t){this.wsClient.off(e,t);}};function 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 me(o){let e=o;return {async getAddress(){let[t]=await o.getAddresses();if(!t)throw new Error("WalletClient: no address");return t},async signMessage(t){let i=typeof t=="string"?t:{raw:t};return await o.signMessage({message:i})},signTransaction:t=>o.signTransaction(t),async sendTransaction(t){let i=t.to;if(!i)throw new Error("sendTransaction: to is required");return {hash:await o.sendTransaction({to:i,data:t.data,value:t.value!=null?BigInt(t.value):void 0,gas:t.gasLimit!=null?BigInt(t.gasLimit):void 0,gasPrice:t.gasPrice!=null?BigInt(t.gasPrice):void 0,maxFeePerGas:t.maxFeePerGas!=null?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas!=null?BigInt(t.maxPriorityFeePerGas):void 0})}},...typeof e.signTypedData=="function"?{async signTypedData(t){return await e.signTypedData(t)}}:{}}}function Ve(o){let e=o,t=o;return {getAddress:()=>o.getAddress(),signMessage:i=>o.signMessage(i),async sendTransaction(i){let r={...i};i.value!=null&&(r.value=BigInt(i.value)),i.gasLimit!=null&&(r.gasLimit=BigInt(i.gasLimit)),i.gasPrice!=null&&(r.gasPrice=BigInt(i.gasPrice)),i.maxFeePerGas!=null&&(r.maxFeePerGas=BigInt(i.maxFeePerGas)),i.maxPriorityFeePerGas!=null&&(r.maxPriorityFeePerGas=BigInt(i.maxPriorityFeePerGas));try{let a=(await o.sendTransaction(r)).hash;if(!a)throw new Error("sendTransaction: no hash in response");return {hash:a}}catch(n){let a=typeof n=="object"&&n!==null?String(n.message):"";if(n instanceof TypeError||a.includes("BigInt")||a.includes("bigint")){let g={...i};i.value!=null&&(g.value=`0x${BigInt(i.value).toString(16)}`),i.gasLimit!=null&&(g.gasLimit=`0x${BigInt(i.gasLimit).toString(16)}`),i.gasPrice!=null&&(g.gasPrice=`0x${BigInt(i.gasPrice).toString(16)}`),i.maxFeePerGas!=null&&(g.maxFeePerGas=`0x${BigInt(i.maxFeePerGas).toString(16)}`),i.maxPriorityFeePerGas!=null&&(g.maxPriorityFeePerGas=`0x${BigInt(i.maxPriorityFeePerGas).toString(16)}`);let c=(await o.sendTransaction(g)).hash;if(!c)throw new Error("sendTransaction: no hash in response");return {hash:c}}throw n}},signTransaction:typeof e.signTransaction=="function"?i=>t.signTransaction(i):()=>Promise.reject(new Error("signTransaction not supported by this signer")),...typeof t.signTypedData=="function"?{async signTypedData(i){return t.signTypedData(i.domain,i.types,i.message)}}:typeof t._signTypedData=="function"?{async signTypedData(i){return t._signTypedData(i.domain,i.types,i.message)}}:{}}}function K(o){return ut(o)?me(o):mt(o)?Ve(o):o}function qe(o){let e=chunkUIM35W7V_js.e(o),t=[...e.privateJsonRPCUrl?[e.privateJsonRPCUrl]:[],...Array.isArray(e.publicJsonRPCUrl)?[...e.publicJsonRPCUrl]:[]].filter(Boolean);if(t.length===0)throw new Error(`${o} has no jsonRPCUrl configured`);return t[0]}var fe={};function bt(o){if(!fe[o]){let e=chunkUIM35W7V_js.e(o);fe[o]={id:o,name:e.label||`Chain ${o}`,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[qe(o)]}}};}return fe[o]}async function He(o,e){let t=qe(e),i=bt(e),r=await o.getAddress();return viem.createWalletClient({account:r,chain:i,transport:viem.custom({request:async a=>{if(a.method==="eth_accounts")return [r];if(a.method==="eth_sendTransaction"){let c=a.params?.[0]??{},{hash:d}=await o.sendTransaction({to:c.to,data:c.data,value:c.value!=null?BigInt(c.value):void 0,gasLimit:c.gas!=null?BigInt(c.gas):void 0,gasPrice:c.gasPrice!=null?BigInt(c.gasPrice):void 0,maxFeePerGas:c.maxFeePerGas!=null?BigInt(c.maxFeePerGas):void 0,maxPriorityFeePerGas:c.maxPriorityFeePerGas!=null?BigInt(c.maxPriorityFeePerGas):void 0});return d}if(a.method==="eth_signTypedData_v4"||a.method==="eth_signTypedData"){if(!o.signTypedData){let h=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(h.error)throw new Error(h.error.message);return h.result}let c=a.params?.[1];if(typeof c!="string")throw new Error("Invalid eth_signTypedData_v4 params");let d=JSON.parse(c),{EIP712Domain:p,...u}=d.types;return await o.signTypedData({domain:d.domain,types:u,primaryType:d.primaryType,message:d.message})}let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:a.method,params:a.params??[]})})).json();if(s.error)throw new Error(s.error.message);return s.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.walletClient||this.config.signer!=null||this._normalizedSigner!=null)}async getSignerAddress(e){if(this.config.walletClient){let i=(await this.config.walletClient.getAddresses())[0];if(i)return i}if(this._normalizedSigner)return this._normalizedSigner.getAddress();throw new l("INVALID_SIGNER","Invalid signer")}async getViemWalletClient(e){if(this.config.walletClient)return this.config.walletClient;if(this._normalizedSigner)return await He(this._normalizedSigner,e);throw new l("INVALID_SIGNER","Invalid signer: call auth({ signer }) or auth({ walletClient })")}updateClientChainId(e,t){this.config={...this.config,chainId:e,brokerAddress:t};}auth(e){let t=e.signer!=null?K(e.signer):null;this.accessToken=void 0,this.accessTokenExpiry=void 0,this.config={...this.config,...e},this._normalizedSigner=t,this.validateConfig(this.config);}validateConfig(e){let{isTestnet:t,isBetaMode:i,chainId:r}=e;if(t){if(!Ue.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of TESTNET_CHAIN_IDS`)}else if(i){if(!$e.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of BETA_ENV_CHAIN_IDS`)}else if(!We.includes(r))throw new l("INVALID_CHAIN_ID",`chainId ${r} is not in the range of MAINNET_CHAIN_IDS`)}async getAccessToken(){return this.accessToken??null}async refreshAccessToken(e=false){return new Promise((t,i)=>{this._getAccessTokenQueue.push({resolve:t,reject:i,forceRefresh:e}),this._processAccessTokenQueue();})}_processAccessTokenQueue(){if(this._isGettingAccessToken)return;this._isGettingAccessToken=true;let e=this._getAccessTokenQueue.shift();e?this._refreshAccessToken(e.forceRefresh).then(e.resolve).catch(e.reject).finally(()=>{this._isGettingAccessToken=false,this._getAccessTokenQueue.length>0&&this._processAccessTokenQueue();}):this._isGettingAccessToken=false;}async _refreshAccessToken(e=false){if(!e&&this.isAccessTokenValid())return this._isGettingAccessToken=false,this.accessToken;if(!this.config.getAccessToken)return chunkUIM35W7V_js.fa("No getAccessToken method provided in config"),null;try{let t=await this.config.getAccessToken()??{accessToken:"",expireAt:0};if(t&&t.accessToken){let i=3600;if(t.expireAt){let r=Math.floor(Date.now()/1e3);i=t.expireAt-r,i<=0&&(chunkUIM35W7V_js.fa("Received expired token, using default expiry"),i=3600);}return this.setAccessToken(t.accessToken,i),t.accessToken}else return chunkUIM35W7V_js.fa("\u274C Received empty accessToken"),null}catch(t){return chunkUIM35W7V_js.ga("\u274C Failed to refresh accessToken:",t),null}}setAccessToken(e,t=3600){this.accessToken=e,this.accessTokenExpiry=Date.now()+t*1e3;}getCurrentAccessToken(){return this.accessToken}isAccessTokenValid(){return !!this.accessToken}clearAccessToken(){this.accessToken=void 0,this.accessTokenExpiry=void 0;}getConfig(){return this.config}};var Q=class{constructor(e,t,i){this.configManager=e,this.utils=t,this.api=i;}getMarkets(){return Promise.resolve([])}async getPoolLevelConfig(e,t){return (await this.api.getPoolLevelConfig({poolId:e,chainId:t})).data}async getKlineList({interval:e,...t}){return (await this.api.getKlineData({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getKlineLatestBar({interval:e,...t}){this.configManager.getConfig();return (await this.api.getKlineLatestBar({...t,interval:this.utils.transferKlineResolutionToInterval(e)})).data}async getTickerList(e){return (await this.api.getTickerData(e)).data}async searchMarketAuth(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.searchMarketAuth({address:t,...e,accessToken:i})).data}async searchMarket(e){return (await this.api.searchMarket(e)).data}async getFavoritesList(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.getFavoritesList({...e,address:t,accessToken:i})).data}async addFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.addFavorite({...e,address:t,accessToken:i})).data}async addFavoritesBatch(e){return (await this.api.addFavoritesBatch(e)).data}async removeFavorite(e,t){let i=await this.configManager.getAccessToken()??"";return (await this.api.removeFavorite({...e,address:t,accessToken:i})).data}async getBaseDetail(e){return (await this.api.getBaseDetail(e)).data}async getMarketDetail(e){return (await this.api.getMarketDetail(e)).data}async getPoolSymbolAll(){return (await this.api.getPoolSymbolAll()).data}async getPoolFundingFeeInfo({poolId:e,chainId:t,marketPrice:i}){let r=await chunkUIM35W7V_js.Z(t);try{return {code:0,data:await r.read.getPoolInfo([e,i])}}catch(n){return {code:-1,message:n.message}}}};var J=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async listPositions(e,t){let i=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getPositions({accessToken:i??"",address:e,positionId:t})).data}}catch(r){return this.logger.error("Error fetching positions:",r),{code:-1,message:"Failed to fetch positions"}}}async getPositionHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getPositionHistory({accessToken:i,...e,address:t})).data}}async adjustCollateral({poolId:e,positionId:t,adjustAmount:i,quoteToken:r,chainId:n,address:a}){this.configManager.getConfig();try{let s=await this.utils.getOraclePrice(e,n);if(!s)throw new Error("Failed to get price data");let c={poolId:e,oracleType:s.oracleType,publishTime:s.publishTime,oracleUpdateData:s?.vaa??"0"},d=!1;Number(i)>0&&(d=await this.utils.needsApproval(a,n,r,i,chunkUIM35W7V_js.R(n).TRADING_ROUTER));let p=BigInt(0),u=BigInt(i)>0?BigInt(i):0n,m=await this.account.getAvailableMarginBalance({poolId:e,chainId:n,address:a}),h=m.code===0?m.data??0n:0n,w=BigInt(0);h<u&&(w=u-h,p=w);let I={token:r,amount:p.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let Ce=await chunkUIM35W7V_js.U(n);if(d){let S=await this.utils.approveAuthorization({chainId:n,quoteAddress:r,amount:viem.maxUint256.toString(),spenderAddress:chunkUIM35W7V_js.R(n).TRADING_ROUTER});if(S.code!==0)throw new Error(S.message)}let oe=await Ce.write.updatePriceAndAdjustCollateral([[c],I,t,i],{value:BigInt(s?.value??"1"),gas:BigInt(1e7)*chunkUIM35W7V_js.c[n]/100n});return await chunkUIM35W7V_js.f(n).waitForTransactionReceipt({hash:oe}),{code:0,data:{hash:oe},message:"Adjust collateral transaction submitted"}}catch(s){return {code:-1,message:s.message}}}};var wt={IOC:0},R=wt.IOC;var Y={MARKET:0,LIMIT:1,STOP:2,CONDITIONAL:3},lr={NONE:0,GTE:1,LTE:2},k={INCREASE:0,DECREASE:1},pr={LONG:0,SHORT:1},ur={IOC:0},mr={PENDING:0,PARTIAL:1,FILLED:2,CANCELLED:3,REJECTED:4,EXPIRED:5};var X=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async createIncreaseOrder(e,t){try{let i=BigInt(e.collateralAmount)+BigInt(t),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()},c={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.INCREASE,direction:e.direction,collateralAmount:e.collateralAmount.toString(),size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly??!1,slippagePct:e.slippagePct??"0",leverage:e.leverage??0,tpSize:e.tpSize??"0",tpPrice:e.tpPrice??"0",slSize:e.slSize??"0",slPrice:e.slPrice??"0",broker:this.configManager.getConfig().brokerAddress},d=await this.utils.needsApproval(e.address,e.chainId,e.executionFeeToken,e.collateralAmount,chunkUIM35W7V_js.R(e.chainId).TRADING_ROUTER);if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");if(d){let w=await this.utils.approveAuthorization({chainId:e.chainId,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkUIM35W7V_js.R(e.chainId).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let p=await chunkUIM35W7V_js.U(e.chainId),u;if(e.positionId){this.logger.info("createIncreaseOrder nft position params--->",{...c,positionId:e.positionId});let w=await p.estimateGas.placeOrderWithPosition([e.positionId.toString(),{...s},c]);u=await p.write.placeOrderWithPosition([e.positionId.toString(),{...s},c],{gasLimit:w*chunkUIM35W7V_js.c[e.chainId]/100n});}else {this.logger.info("createIncreaseOrder salt position params--->",{positionSalt:"1",data:c,depositData:s});let I=await p.estimateGas.placeOrderWithSalt(["1",{...s},c]);u=await p.write.placeOrderWithSalt(["1",{...s},c],{gasLimit:I*chunkUIM35W7V_js.c[e.chainId]/100n});}let m=await chunkUIM35W7V_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(i){return this.logger.error("Error placing order:",i),{code:-1,message:i?.message}}}async closeAllPositions(e,t){try{let i={token:"0x0000000000000000000000000000000000000000",amount:"0"},r=t.map(d=>d.positionId.toString()),n=t.map(d=>({user:d.address,poolId:d.poolId,orderType:d.orderType,triggerType:d.triggerType,operation:k.DECREASE,direction:d.direction,collateralAmount:d.collateralAmount,size:d.size,price:d.price,timeInForce:R,postOnly:d.postOnly,slippagePct:d.slippagePct,leverage:d.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress}));if(this.logger.info("closeAllPositions params--->",i,r,n),!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let a=await chunkUIM35W7V_js.U(e),g=await a.estimateGas.placeOrdersWithPosition([i,r,n]),s=await a.write.placeOrdersWithPosition([i,r,n],{gasLimit:g*chunkUIM35W7V_js.c[e]/100n}),c=await chunkUIM35W7V_js.f(e).waitForTransactionReceipt({hash:s});return {code:0,message:"close all positions success",transactionHash:s,blockNumber:c?.blockNumber,gasUsed:c?.gasUsed?.toString(),status:c?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:c}}catch(i){return {code:-1,message:i?.message}}}async createDecreaseOrder(e){try{let t={user:e.address,poolId:e.poolId,orderType:e.orderType,triggerType:e.triggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:e.collateralAmount,size:e.size,price:e.price,timeInForce:R,postOnly:e.postOnly,slippagePct:e.slippagePct,leverage:e.leverage,tpSize:0,tpPrice:0,slSize:0,slPrice:0,broker:this.configManager.getConfig().brokerAddress},i=BigInt(e.collateralAmount),r=await this.account.getAvailableMarginBalance({poolId:e.poolId,chainId:e.chainId,address:e.address}),n=r.code===0?r.data??0n:0n,a=BigInt(0),g=i-n;g>BigInt(0)&&(a=g);let s={token:e.executionFeeToken,amount:a.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let c=await chunkUIM35W7V_js.U(e.chainId),d;if(e.positionId){this.logger.info("createDecreaseOrder nft position params--->",[e.positionId,s,{data:t}]);let m=await c.estimateGas.placeOrderWithPosition([e.positionId.toString(),s,t]);d=await c.write.placeOrderWithPosition([e.positionId.toString(),s,t],{gasLimit:m*chunkUIM35W7V_js.c[e.chainId]/100n});}else {this.logger.info("createDecreaseOrder salt position params--->",[1,s,{data:t}]);let h=await c.estimateGas.placeOrderWithSalt(["1",s,t]);d=await c.write.placeOrderWithSalt(["1",s,t],{gasLimit:h*chunkUIM35W7V_js.c[e.chainId]/100n});}let p=await chunkUIM35W7V_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}catch(t){return {code:-1,message:t?.message}}}async createPositionTpSlOrder(e){try{let t=await chunkUIM35W7V_js.U(e.chainId);try{if(e.tpSize!=="0"&&e.slSize!=="0"){let s=[{user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpTriggerType,operation:k.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:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.slSize??"0",price:e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:e.leverage,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress}],c={token:"0x0000000000000000000000000000000000000000",amount:"0"},d;if(e.positionId){let m=await t.estimateGas.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s]);d=await t.write.placeOrdersWithPosition([c,[e.positionId.toString(),e.positionId.toString()],s],{gasLimit:m*chunkUIM35W7V_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpSlOrder salt position data--->",s);let m=1,h=await t.estimateGas.placeOrdersWithSalt([c,[m.toString(),m.toString()],s]);d=await t.write.placeOrdersWithSalt([c,[m.toString(),m.toString()],s],{gasLimit:h*chunkUIM35W7V_js.c[e.chainId]/100n});}let p=await chunkUIM35W7V_js.f(e.chainId).waitForTransactionReceipt({hash:d});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:d,blockNumber:p?.blockNumber,gasUsed:p?.gasUsed?.toString(),status:p?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:p}}}let i={user:e.address,poolId:e.poolId,orderType:Y.STOP,triggerType:e.tpSize!=="0"?e.tpTriggerType:e.slTriggerType,operation:k.DECREASE,direction:e.direction,collateralAmount:"0",size:e.tpSize!=="0"?e.tpSize??"0":e.slSize??"0",price:e.tpPrice!=="0"?e.tpPrice??"0":e.slPrice??"0",timeInForce:R,postOnly:!1,slippagePct:e.slippagePct??"0",leverage:0,tpSize:"0",tpPrice:"0",slSize:"0",slPrice:"0",broker:this.configManager.getConfig().brokerAddress},r={token:"0x0000000000000000000000000000000000000000",amount:"0"},n;if(e.positionId){this.logger.info("createPositionTpOrSlOrder nft position data--->",i);let s=await t.estimateGas.placeOrderWithPosition([e.positionId.toString(),r,i]);n=await t.write.placeOrderWithPosition([e.positionId.toString(),r,i],{gasLimit:s*chunkUIM35W7V_js.c[e.chainId]/100n});}else {this.logger.info("createPositionTpOrSlOrder salt position data--->",i);let s=1,c=await t.estimateGas.placeOrderWithSalt([s.toString(),r,i]);n=await t.write.placeOrderWithSalt([s.toString(),r,i],{gasLimit:c*chunkUIM35W7V_js.c[e.chainId]/100n});}let a=await chunkUIM35W7V_js.f(e.chainId).waitForTransactionReceipt({hash:n});return {code:0,message:"create decrease order success",data:{success:!0,transactionHash:n,blockNumber:a?.blockNumber,gasUsed:a?.gasUsed?.toString(),status:a?.status==="success"?"success":"failed",confirmations:1,timestamp:Date.now(),receipt:a}}}catch(i){return {code:-1,message:i?.message}}}catch(t){return {code:-1,message:t?.message}}}async cancelAllOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkUIM35W7V_js.U(t)).write.cancelOrders([e]);return await chunkUIM35W7V_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel all orders success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrder(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkUIM35W7V_js.U(t)).write.cancelOrder([e]);return await chunkUIM35W7V_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"cancel order success"}}catch(i){return {code:-1,message:i?.message}}}async cancelOrders(e,t){try{if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=await(await chunkUIM35W7V_js.U(t)).write.cancelOrders([e]);return await chunkUIM35W7V_js.f(t).waitForTransactionReceipt({hash:r}),{code:0,message:"Orders canceled success"}}catch(i){return this.logger.error("Error canceling orders:",i),{code:-1,message:i?.message}}}async updateOrderTpSl(e,t,i,r,n,a){let g=await this.utils.getNetworkFee(n,i),s={orderId:e.orderId,size:e.size,price:e.price,broker:this.configManager.getConfig().brokerAddress,tpsl:{tpSize:a?e.tpSize:"0",tpPrice:a?e.tpPrice:"0",slSize:a?e.slSize:"0",slPrice:a?e.slPrice:"0"}},c={token:t,amount:g.toString()};if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let d=await chunkUIM35W7V_js.U(i);this.logger.info("updateOrderTpSl params",s);try{if(await this.utils.needsApproval(r,i,e.executionFeeToken,g.toString(),chunkUIM35W7V_js.R(i).TRADING_ROUTER)){let w=await this.utils.approveAuthorization({chainId:i,quoteAddress:e.executionFeeToken,amount:viem.maxUint256.toString(),spenderAddress:chunkUIM35W7V_js.R(i).TRADING_ROUTER});if(w.code!==0)throw new Error(w.message)}let u=await d.estimateGas.updateOrder([c,s]),m=await d.write.updateOrder([c,s],{gasLimit:u*chunkUIM35W7V_js.c[i]/100n}),h=await chunkUIM35W7V_js.f(i).waitForTransactionReceipt({hash:m});return this.logger.info("updateOrderTpSl receipt",h),{code:0,data:h,message:"update order success"}}catch(p){return this.logger.error("Error updating order:",p),{code:-1,message:"Failed to update order"}}}async getOrders(e){let t=await this.configManager.getAccessToken();try{return {code:0,data:(await this.api.getOrders(t??"",e)).data}}catch(i){return this.logger.error("Error fetching orders:",i),{code:-1,message:"Failed to fetch orders"}}}async getOrderHistory(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.api.getHistoryOrders({accessToken:i,...e,address:t})).data}}};var he={"0xfa52dfc0":"AccountInsufficientFreeAmount()","0xe2a1a260":"AccountInsufficientReservedAmount()","0xffd10028":"AccountInsufficientTradableAmount(uint256,uint256)","0x9996b315":"AddressEmptyCode(address)","0x4c9c8ce3":"ERC1967InvalidImplementation(address)","0xb398979f":"ERC1967NonPayable()","0xd6bda275":"FailedCall()","0xf92ee8a9":"InvalidInitialization()","0x44d3438f":"NotAddressManager()","0x3fc81f20":"NotDependencyManager()","0xd7e6bcf8":"NotInitializing()","0x507f487a":"NotProxyAdmin()","0xe03f6024":"PermissionDenied(address,address)","0x5274afe7":"SafeERC20FailedOperation(address)","0xe07c8dba":"UUPSUnauthorizedCallContext()","0xaa1d49a4":"UUPSUnsupportedProxiableUUID(bytes32)","0x24775e06":"SafeCastOverflowedUintToInt(uint256)","0xba767932":"ConvertAmountMismatch(uint256,uint256)","0xd93c0665":"EnforcedPause()","0x8dfc202b":"ExpectedPause()","0x059e2f49":"InRewindMode()","0x42301c23":"InsufficientOutputAmount()","0xcaa99aac":"MismatchExecuteFee(uint256,uint256,uint256)","0x8637dfc0":"NotInRewindMode()","0x4578ddb8":"OnlyRelayer()","0x1e4fbdf7":"OwnableInvalidOwner(address)","0x118cdaa7":"OwnableUnauthorizedAccount(address)","0x3ee5aeb5":"ReentrancyGuardReentrantCall()","0x90b8ec18":"TransferFailed()","0xbe1af266":"InternalOnly()","0x3385aa1f":"ExceedOrderSize(uint256)","0xb07e3bc4":"InsufficientCollateral(uint256,uint256)","0x613970e0":"InvalidParameter()","0x27d08510":"NotActiveBroker(address)","0xf6412b5a":"NotOrderOwner()","0x70d645e3":"NotPositionOwner()","0xe75316c6":"OrderNotExist(OrderId)","0xba01b06f":"PoolNotActive(PoolId)","0xddefae28":"AlreadyMinted()","0x64283d7b":"ERC721IncorrectOwner(address,uint256,address)","0x177e802f":"ERC721InsufficientApproval(address,uint256)","0xa9fbf51f":"ERC721InvalidApprover(address)","0x5b08ba18":"ERC721InvalidOperator(address)","0x89c62b64":"ERC721InvalidOwner(address)","0x64a0ae92":"ERC721InvalidReceiver(address)","0x73c6ac6e":"ERC721InvalidSender(address)","0x7e273289":"ERC721NonexistentToken(uint256)","0xb4762117":"ExceedMaxLeverage(PositionId)","0x29143a42":"ExceedPositionSize()","0x8ea9158f":"InvalidPosition(PositionId)","0xa5afd143":"PositionNotHealthy(PositionId,uint256)","0xba0d3752":"PositionNotInitialized(PositionId)","0xc20f35b7":"UnderflowOI()","0xf4d678b8":"InsufficientBalance()","0x6aee3c1a":"InsufficientRiskReserves()","0x2c5211c6":"InvalidAmount()","0x82cb17ef":"InvalidSplitConfig()","0xe921c36b":"AlreadyMigrated(PositionId,PositionId)","0xd34e366f":"ExceedBaseCollateral(uint256,uint256)","0xc7544914":"ExceedDebt(uint256,uint256)","0xe7aa687a":"ExceedExchangeable()","0x4b3c8f33":"ExceedMaxBaseProfit()","0xdc82bd68":"ExceedMinOutputAmount()","0xdb42144d":"InsufficientBalance(address,uint256,uint256)","0x5646203f":"InsufficientCollateral(PositionId,uint256)","0x9ac13039":"InsufficientPoolProfit()","0x14be833f":"InsufficientReturnAmount(uint256,uint256)","0x419ecd12":"MatchNotSupported()","0x4ec4fd74":"PoolFundingFeeNotPositive(int256,uint256,Direction)","0xba8f5df5":"PoolNotCompoundable(PoolId)","0xf645eedf":"ECDSAInvalidSignature()","0xfce698f7":"ECDSAInvalidSignatureLength(uint256)","0xd78bce0c":"ECDSAInvalidSignatureS(bytes32)","0x48834bee":"ExpiredFeeData()","0x56d69198":"InvalidFeeRate()","0x80577032":"NoRebateToClaim()","0x6e6b79b0":"NotBrokerSigner(address)","0xff70343d":"UnsupportedAssetClass(AssetClass)","0x185676be":"UnsupportedFeeTier(uint8)","0x60b25fe4":"BrokerAlreadyExists()","0x7eb4a674":"BrokerNotFound()","0x8c3b5bf0":"NotBrokerAdmin()","0x3733548a":"InvalidFeeTier()","0x192105d7":"InitializationFunctionReverted(address,bytes)","0x97c7f537":"ExcessiveSlippage()","0x700deaad":"InvalidADLPosition(OrderId,PositionId)","0xf64fa6a8":"InvalidOrder(OrderId)","0xd4944235":"NoADLNeeded(OrderId)","0xe079169e":"NotReachedPrice(OrderId,uint256,uint256,TriggerType)","0xc60eb335":"OnlyKeeper()","0xa8ce4432":"SafeCastOverflowedIntToUint(int256)","0x17229ec4":"NotMeetEarlyCloseCriteria(PositionId)","0x0dc149f0":"AlreadyInitialized()","0x7a5c919f":"InvalidRewindPrice()","0xc53f84e7":"PositionRemainsHealthy(PositionId)","0x1dab59cf":"InvalidOrderPair(OrderId,OrderId)","0x230e8e43":"PoolNotInPreBenchState(PoolId)","0x107dec14":"RiskCloseNotAllowed()","0x664431a8":"NotAllowedTarget(address)","0x03357c6c":"ExceedsMaximumRelayFee()","0x0d10f63b":"InconsistentParamsLength()","0x38802743":"InsufficientFeeAllowance(address,uint256,uint256)","0xd95b4ad5":"InsufficientFeeBalance(address,uint256,uint256)","0xa3972305":"MismatchedSender(address)","0xc3b80e86":"RelayerRegistered(address)","0xee0844a3":"RemoveRelayerFailed()","0xc583a8da":"IncorrectFee(uint256)","0x00bfc921":"InvalidPrice()","0x148cd0dd":"VerifyPriceFailed()","0xb12d13eb":"ETHTransferFailed()","0xa83325d4":"PoolOracleFeeCharged()","0x6b75f90d":"PoolOracleFeeNotCharged()","0x42a0e2a7":"PoolOracleFeeNotExisted()","0x8ee01e1c":"PoolOracleFeeNotSoldOut()","0x5e0a829b":"ETHTransferFailed(address,uint256)","0x4ba6536f":"GasLimitExceeded(address,uint256,uint256)","0xca1aae4b":"GasLimitNotSet(address)","0x3728b83d":"InvalidAmount(uint256)","0x3484727e":"BaseFeeNotSoldOut()","0x0251bde4":"LPNotFullyMinted()","0x1acb203e":"PositionNotEmpty()","0x2be7b24b":"UnexpectedPoolState()","0x759b3876":"UnhealthyAfterRiskTierApplied(PositionId)","0x7bd42a2e":"NotEmptyAddress()","0x6697b232":"AccessControlBadConfirmation()","0xe2517d3f":"AccessControlUnauthorizedAccount(address,bytes32)","0x7c9a1cf9":"AlreadyVoted()","0x796ea3a6":"BondNotReleased()","0x6511c20d":"BondZeroAmount()","0xf38e5973":"CaseAppealNotFinished()","0x1eaa4a59":"CaseDeadlineNotReached()","0xe6c67e3a":"CaseDeadlineReached()","0x0fc957b1":"CaseNotAccepted()","0x3ddb819d":"CaseNotExist(CaseId)","0x79eab18d":"CaseRespondentAppealed(CaseId,address)","0xa179f8c9":"ChainIdMismatch()","0x311c16d3":"DisputeNotAllowed()","0x752d88c0":"InvalidAccountNonce(address,uint256)","0xa710429d":"InvalidContractAddress()","0x8076dd8a":"InvalidFunctionSignature()","0xc37906a0":"InvalidPayloadLength(uint256,uint256)","0xdcdedda9":"InvalidPoolToken()","0x3471a3c2":"InvalidProfitAmount()","0x1d9617a0":"InvalidResponseVersion()","0x9284b197":"InvalidSourceChain()","0xb9021668":"NoChainResponse()","0xc546bca4":"NotCaseRespondent(CaseId,address)","0x84ae4a30":"NumberOfResponsesMismatch()","0x02164961":"RequestTypeMismatch()","0x4cf72652":"RiskCloseNotCompleted()","0x0819bdcd":"SignatureExpired()","0xc00ca938":"UnexpectedCaseState()","0x7935e939":"UnexpectedCaseType()","0x5e7bd6ec":"UnexpectedNumberOfResults()","0x51ee5853":"UnsupportedQueryType(uint8)","0x29ca666b":"UntrustfulVoting()","0x439cc0cd":"VerificationFailed()","0x714f5513":"VersionMismatch()","0x96b8e05b":"WrongQueryType(uint8,uint8)","0xbb6b170d":"ZeroQueries()","0xa9214540":"AlreadyClaimed(CaseId,address)","0xd4ac59c1":"InvalidAmount(CaseId,address)","0x7a6f5328":"MerkleTreeVerificationFailed(CaseId,address)","0x094a5cfe":"ReimbursementValidity(CaseId)","0x8b922563":"TreeAlreadySet()","0x7b27120a":"InDisputeMode()","0xb04111ef":"InsufficientFreeCollateral(PositionId,uint256)","0x12f1b11a":"InsufficientLockedCollateral(PositionId,uint256)","0x6dfcc650":"SafeCastOverflowedUintDowncast(uint8,uint256)","0xd24b47fb":"UserProfitFrozen()","0x1c151780":"ExceedMinOutput(uint256,uint256)","0xe1f0493d":"NotAllowedCaller(address)","0xfb8f41b2":"ERC20InsufficientAllowance(address,uint256,uint256)","0xe450d38c":"ERC20InsufficientBalance(address,uint256,uint256)","0xe602df05":"ERC20InvalidApprover(address)","0xec442f05":"ERC20InvalidReceiver(address)","0x96c6fd1e":"ERC20InvalidSender(address)","0x94280d62":"ERC20InvalidSpender(address)","0x62791302":"ERC2612ExpiredSignature(uint256)","0x4b800e46":"ERC2612InvalidSigner(address,address)","0xb3512b0c":"InvalidShortString()","0x305a27a9":"StringTooLong(string)","0xfd0f789d":"ExceedMaxPriceDeviation()","0x407b87e5":"ExchangeRateAlreadyApplied()","0x5c6c5686":"ExchangeRateAlreadyDisabled()","0x1ae17fcd":"InvalidDeviationRatio()","0x18b88897":"InvalidUpdateFee()","0xf76740e3":"PriceDeviationBelowMinimum()","0x49386283":"PriceDeviationThresholdReached()","0x19abf40e":"StalePrice()","0xe351cd13":"ExceedMaxExchangeableAmount()","0x15912a6f":"NotSupportVersion()","0xf1364a74":"ArrayEmpty()","0x15ed381d":"ExceedMaxProfit()","0x51aeee6c":"PoolNotExist(PoolId)","0x70f6c197":"InvalidQuoteTokenAddress()","0x0b8457f4":"InvalidRatioParams()","0x29dae146":"MarketAlreadyExisted()","0xf040b67a":"MarketNotExisted()","0x0e442a4a":"InvalidBaseToken()","0x24e219c7":"MarketNotExist(MarketId)","0xcc36f935":"PoolExists(PoolId)","0xe84c308d":"ExceedBaseReserved(uint256,uint256)","0x3e241751":"ExceedQuoteReserved(uint256,uint256)","0xde656889":"ExceedReservable(uint256,uint256,uint256)","0xd54d0fc4":"InsufficientLiquidity(uint256,uint256,uint256)","0x7e562a65":"InvalidDistributionAmount()","0x83c7580d":"ReservableNotEnough(uint256,uint256)","0x94eef58a":"ERC2771ForwarderExpiredRequest(uint48)","0xc845a056":"ERC2771ForwarderInvalidSigner(address,address)","0x70647f79":"ERC2771ForwarderMismatchedValue(uint256,uint256)","0xd2650cd1":"ERC2771UntrustfulTarget(address,address)","0xcf479181":"InsufficientBalance(uint256,uint256)","0x4c150d8f":"DifferentMarket(PoolId,PoolId)","0xaa98b06a":"InsufficientQuoteIn(uint256,uint256,uint256)","0x3e589bee":"InvalidLiquidityAmount()","0xaebd3617":"InvalidTpsl(uint256)","0x7fe81129":"SamePoolMigration(PoolId)","0x71c4efed":"SlippageExceeded(uint256,uint256)","0x62b9bc7b":"DesignatedTokenMismatch(address,address)","0x49465eb0":"NotForwardAllowedTarget(address)","0x301b6707":"ExecutionFeeNotCollected()","0xc6e8248a":"InsufficientSize()","0xd15b4fe2":"InvalidQuoteToken()","0xd8daec7c":"MarketNotInitialized()","0xcd4891b6":"NotInDisputeMode()","0x1ad308dc":"OrderExpired(OrderId)","0x486aa307":"PoolNotInitialized()"};var Z=class{constructor(e,t){this.configManager=e,this.logger=t;}async getApproveQuoteAmount(e,t,i,r){try{if(!i||typeof i=="string"&&!i.trim())throw new Error("getApproveQuoteAmount: tokenAddress is required (ERC20 contract address)");let n=r??chunkUIM35W7V_js.R(t).Account,g=await chunkUIM35W7V_js.T(t,i).read.allowance([e,n]);return {code:0,data:String(g)}}catch(n){throw this.logger.error("Error getting allowance:",n),typeof n=="string"?n:await chunkUIM35W7V_js.ja(n)}}async needsApproval(e,t,i,r,n){try{let g=(await this.getApproveQuoteAmount(e,t,i,n)).data,s=BigInt(g),c=BigInt(r);return s<c}catch(a){return this.logger.error("Error checking approval needs:",a),true}}async approveAuthorization({chainId:e,quoteAddress:t,amount:i,spenderAddress:r}){try{let n=await chunkUIM35W7V_js.V(e,t),a=i??viem.maxUint256,g=r??chunkUIM35W7V_js.R(e).Account,s=await this.getGasPriceByRatio(),c=await n.write.approve([g,a],{gasPrice:s});return await chunkUIM35W7V_js.f(e).waitForTransactionReceipt({hash:c}),{code:0,message:"Approval success"}}catch(n){return this.logger.error("Approval error:",n),{code:-1,message:n?.message}}}async getUserTradingFeeRate(e,t,i,r){let a=this.configManager.getConfig().brokerAddress;try{let g=chunkUIM35W7V_js.X(i,a),s=r??await this.configManager.getSignerAddress(i),c=await g.read.getUserFeeRate([s,e,t]);return {code:0,data:{takerFeeRate:c[0].toString(),makerFeeRate:c[1].toString(),baseTakerFeeRate:c[2].toString(),baseMakerFeeRate:c[3].toString()}}}catch(g){return this.logger.error("Error getting user trading fee rate:",g),{code:-1,message:g?.message??"Unknown error"}}}async getNetworkFee(e,t){try{return (await(await chunkUIM35W7V_js.Y(t,0)).read.getExecutionFee([e])).toString()}catch(i){return this.logger.error("Error getting network fee:",i),"0"}}async getOraclePrice(e,t){try{let i=await chunkUIM35W7V_js.ta(t,e);if(!i)throw new Error("Failed to get price data");return i}catch(i){throw this.logger.error("Error getting oracle price:",i),i}}async buildUpdatePriceParams(e,t){let i=await this.getOraclePrice(e,t);if(!i)throw new Error("Failed to get price data");return [{poolId:e,oracleUpdateData:i.vaa,publishTime:i.publishTime,oracleType:i.oracleType,value:i.value,price:i.price}]}transferKlineResolutionToInterval(e){switch(e){case "1m":return 1;case "5m":return 5;case "15m":return 15;case "30m":return 30;case "1h":return 60;case "4h":return 240;case "1d":return 1440;case "1w":return 10080;case "1M":return 40320;default:throw new l("PARAM_ERROR",`Invalid kline resolution: ${e}`)}}async getErrorMessage(e,t="Unknown error"){try{if(typeof e=="string")return e;if(e instanceof l)return e.message;let i=await chunkUIM35W7V_js.ja(e);return i?i.error:JSON.stringify(e)}catch(i){return i?.message??i?.toString()??t}}async checkSeamlessGas(e,t,i){let n=await(await chunkUIM35W7V_js.Y(t,0)).read.getForwardFeeByToken([i]),g=await chunkUIM35W7V_js.T(t,i).read.balanceOf([e]);return !(BigInt(n)>0n&&BigInt(g)<BigInt(n))}async getLiquidityInfo({chainId:e,poolId:t,marketPrice:i}){try{return {code:0,data:await(await chunkUIM35W7V_js.Z(e,0)).read.getPoolInfo([t,i])}}catch(r){return this.logger.error("Error getting pool info:",r),{code:-1,message:r?.message}}}formatErrorMessage(e){if(typeof e=="string")return e;if(e instanceof l)return e.message;if(e?.code==="ACTION_REJECTED"||e?.code===4001||e?.info?.error?.code===4001||typeof e?.message=="string"&&(e.message.toLowerCase().includes("user rejected")||e.message.toLowerCase().includes("denied")))return "User Rejected";let t=e?.data;if(!t&&e?.message&&typeof e.message=="string"){let i=e.message.match(/data=["'](0x[0-9a-fA-F]+)["']/i);i&&i[1]&&(t=i[1]);}if(t){let i=typeof t=="string"&&t.startsWith("0x")?t.slice(0,10).toLowerCase():null;if(i){let r=Object.keys(he).find(n=>n.toLowerCase()===i);if(r)return he[r]}}return e?.reason?e.reason:e?.message?e.message:JSON.stringify(e)}async getGasPriceByRatio(){let e=this.configManager.getConfig().chainId;return (await chunkUIM35W7V_js.pa(e)).gasPrice}async getGasLimitByRatio(e){let t=this.configManager.getConfig().chainId,i=chunkUIM35W7V_js.d[t];return chunkUIM35W7V_js.oa(e,i?.gasLimitRatio??1.3)}};var ee=class{constructor(e,t,i,r){this.configManager=e,this.logger=t,this.utils=i,this.client=r;}async withRetry(e,t=3,i=300){let r;for(let n=0;n<t;n++)try{return await e()}catch(a){r=a,n<t-1&&await new Promise(g=>setTimeout(g,i));}throw r}async getTradeFlow(e,t){let i=await this.configManager.getAccessToken()??"";return {code:0,data:(await this.client.api.getTradeFlow({accessToken:i,...e,address:t})).data}}async getWalletQuoteTokenBalance({chainId:e,address:t,tokenAddress:i}){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Invalid signer");let r=chunkUIM35W7V_js.T(e,i),n=await this.configManager.getSignerAddress(e);return {code:0,data:await r.read.balanceOf([t||n])}}async updateAndWithdraw(e,t,i,r,n){try{let g=await(await chunkUIM35W7V_js._(n)).write.updateAndWithdraw([e,t,i,r]);return {code:0,data:await chunkUIM35W7V_js.f(n).waitForTransactionReceipt({hash:g})}}catch(a){return {code:-1,message:a.message}}}async deposit({amount:e,tokenAddress:t,chainId:i}){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"",n=chunkUIM35W7V_js.R(i);try{if(await this.utils.needsApproval(r,i,t,e,n.Account)){let d=await this.utils.approveAuthorization({chainId:i,quoteAddress:t,amount:viem.maxUint256.toString(),spenderAddress:n.Account});if(d.code!==0)throw new Error(d.message)}let s=await(await chunkUIM35W7V_js._(i)).write.deposit([r,t,e]);return {code:0,data:await chunkUIM35W7V_js.f(i).waitForTransactionReceipt({hash:s})}}catch(a){return {code:-1,message:a.message}}}async getAvailableMarginBalance({poolId:e,chainId:t,address:i}){try{let r=await this.getAccountInfo(t,i,e);if(r.code!==0)throw new l("REQUEST_FAILED","Failed to get account info");let n=await this.client.appeal.getAppealStatus(e,t,i),a=r.data,g=BigInt(a?.quoteProfit??0),s=BigInt(a?.freeMargin??0),c=BigInt(a?.lockedMargin??0),d=n?.code===0?n.data:null,p=d?.status===1?BigInt(d?.lockedMargin??0):0n;return {code:0,data:s+g-c-p}}catch(r){return {code:-1,message:r.message}}}async getAccountInfo(e,t,i){let r=await chunkUIM35W7V_js.Z(e);try{return {code:0,data:await r.read.getAccountInfo([i,t])}}catch(n){return {code:-1,message:n.message}}}async getAccountVipInfo(e,t){let i=this.configManager.getConfig(),r=chunkUIM35W7V_js.X(e,i.brokerAddress),a=await chunkUIM35W7V_js.f(e).getBlock({blockTag:"latest"}),g=Number(a?.timestamp??BigInt(Ae__default.default().unix()))+300;try{let s=await r.read.userFeeData([t]),c;try{c=await this.withRetry(()=>r.read.userNonces([t]));}catch{c=0n;}return {code:0,data:{nonce:c.toString(),deadline:g,...s}}}catch(s){return {code:-1,message:s.message}}}async getAccountVipInfoByBackend(e,t,i,r){let n=await this.configManager.getAccessToken()??"";try{let a=await this.client.api.getAccountVipInfo({address:e,accessToken:n,chainId:t,deadline:i,nonce:r});if(a.code!==9200)throw new l("REQUEST_FAILED",a.msg??"Failed to get account vip info");return {code:0,data:a.data}}catch(a){return {code:-1,message:a.message}}}async setUserFeeData(e,t,i,r,n){let a=this.configManager.getConfig();if(i<Ae__default.default().unix())throw new l("REQUEST_FAILED","Invalid deadline, please try again");try{let g=await chunkUIM35W7V_js.W(t,a.brokerAddress),s={user:e,nonce:r.nonce,deadline:i,feeData:{tier:r.tier,referrer:r.referrer||viem.zeroAddress,totalReferralRebatePct:r.totalReferralRebatePct,referrerRebatePct:r.referrerRebatePct,expiry:r.expiry},signature:n},c=await g.read.userNonces([e]);if(parseInt(c.toString())+1!==parseInt(r.nonce.toString()))throw new l("REQUEST_FAILED","Invalid nonce, please try again");let d=await g.write.setUserFeeData([s]);return {code:0,data:await chunkUIM35W7V_js.f(t).waitForTransactionReceipt({hash:d})}}catch(g){return {code:-1,message:g.message}}}};function Qe(o,e){return `${encodeURIComponent(o)}=${encodeURIComponent(typeof e=="number"?e:`${e}`)}`}function Ct(o,e){return Qe(e,o[e])}function Tt(o,e){return o[e].map(i=>Qe(e,i)).join("&")}function Pt(o){let e=o||{};return Object.keys(e).filter(i=>typeof e[i]<"u").map(i=>Array.isArray(e[i])?Tt(e,i):Ct(e,i)).join("&")}function be(o){let e=Pt(o);return e?`?${e}`:""}var ie=class{constructor(e){this.configManager=e;}getHost(){let{isTestnet:e,isBetaMode:t}=this.configManager.getConfig();return t?"https://api-beta.myx.finance":e?"https://api-test.myx.cash":"https://api.myx.finance"}async buildAuthParams(){let e=this.configManager.getConfig();if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER");let t=await this.configManager.getAccessToken()??"",i=await this.configManager.getSignerAddress(e.chainId);if(!i)throw new l("INVALID_SIGNER");return {headers:{myx_openapi_access_token:t,myx_openapi_account:i}}}buildRequestPath(e){return e.startsWith("http")?e:this.getHost()+e}async get(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUIM35W7V_js.n.get(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async post(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUIM35W7V_js.n.post(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async put(e,t,{auth:i=false,...r}={}){let n=i?await this.buildAuthParams():{};return chunkUIM35W7V_js.n.put(this.buildRequestPath(e),t,lodashEs.merge(n,r))}async delete(e,{auth:t=false,...i}={}){let r=t?await this.buildAuthParams():{};return chunkUIM35W7V_js.n.delete(this.buildRequestPath(e),lodashEs.merge(r,i))}};var re=class extends ie{constructor(e,t){super(e),this.logger=t;}async getTradeFlow({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/trade/flow`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolSymbolAll(){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/pools`)}async fetchForwarderGetApi(e){return await chunkUIM35W7V_js.n.get(`${this.getHost()}/v2/agent/forwarder/get${be(e)}`)}async getPoolList(){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/list`)}async forwarderTxApi(e,t){return chunkUIM35W7V_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 chunkUIM35W7V_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 chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/info?chainId=${e}&poolId=${t}`)}async getPoolLevelConfig({poolId:e,chainId:t}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/risk/market_pool/level_config${be({poolId:e,chainId:t})}`)}async getPositions({accessToken:e,address:t,...i}){return await chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getOrders(e,t,i){return await chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/open`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getPoolOpenOrders(e,t,i){return await chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/pool-order/open?chainId=${i}`,void 0,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getKlineData({chainId:e,poolId:t,endTime:i,limit:r,interval:n}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/quote/candles`,{chainId:e,poolId:t,endTime:i,limit:r,interval:n})}async getKlineLatestBar(e){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/latest`,e)}async getTickerData({chainId:e,poolIds:t}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/quote/candle/tickers`,{chainId:e,poolIds:t.join(",")})}async getAllTickers(){return chunkUIM35W7V_js.n.get(`${this.getHost()}/v2/mx-gateway/quote/candle/all_tickers`)}async searchMarketAuth({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/ac-search`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async searchMarket({...e}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/search`,e)}async addFavorite({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/add-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async addFavoritesBatch(e){return this.post("/openapi/gateway/scan/market/add-favorites-batch",e,{auth:true})}async removeFavorite({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/cancel-favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getFavoritesList({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/favorites`,i,{headers:{myx_openapi_access_token:e,myx_openapi_account:t}})}async getBaseDetail({...e}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/base-details`,e)}async getMarketDetail({...e}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market/detail`,e)}async getHistoryOrders({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/order/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getPositionHistory({accessToken:e,address:t,...i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/position/closed`,i,{headers:{myx_openapi_account:t,myx_openapi_access_token:e}})}async getMarketList(){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/market`)}async getAccountVipInfo({address:e,accessToken:t,chainId:i,deadline:r,nonce:n}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/vip/trade_config`,{chainId:i,deadline:r,nonce:n},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getAppealList(e){return this.get("/openapi/gateway/scan/dispute/list",e,{auth:true})}async getAppealDetail(e){return this.get("/openapi/gateway/scan/dispute/details",e,{auth:true})}async uploadAppealEvidence(e){return this.get("/openapi/gateway/scan/dispute/upload/evidence",e,{auth:true})}async getAppealReconsiderationList(e){return this.get("/openapi/gateway/scan/dispute/appeal/list",e,{auth:true})}async getAppealReconsiderationDetail(e){return this.get("/openapi/gateway/scan/dispute/appeal/details",e,{auth:true})}async getAppealReimbursementList(e){return this.get("/openapi/gateway/scan/reimbursement/list",e,{auth:true})}async getAppealNodeVoteList(e){return this.get("/openapi/gateway/scan/node/vote-list",e)}async getAppealNodeVoteDetails(e){return this.get("/openapi/gateway/scan/node/vote-details",e)}async getIsVoteNode(e){return this.get("/openapi/gateway/scan/node/vote-node-check",e)}async postVoteSignature(e){return this.get("/openapi/gateway/scan/node/vote",e,{auth:true})}async getPedingVoteCount(){return this.get("/openapi/gateway/scan/node/pending-vote-total",{},{auth:true})}async getMyAppealCount(){return this.get("/openapi/gateway/scan/processing-total",{},{auth:true})}async getWarmholeSign(e){return this.get("/openapi/gateway/scan/get-warmhole-sign",e,{auth:true})}async getDisputeTotalCount(){return this.get("/openapi/gateway/scan/dispute/dispute-total",{},{auth:true})}async getAppealTotalCount(){return this.get("/openapi/gateway/scan/dispute/appeal-total",{},{auth:true})}async getReimbursementTotalCount(){return this.get("/openapi/gateway/scan/dispute/reimbursement-total",{},{auth:true})}async getCurrentEpoch({address:e,accessToken:t,broker:i}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/get-current-epoch`,{broker:i},{headers:{myx_openapi_account:e,myx_openapi_access_token:t}})}async getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:r}){return chunkUIM35W7V_js.n.get(`${this.getHost()}/openapi/gateway/scan/pool-id-dispute-state?poolId=${e}&chainId=${t}`,{},{headers:{myx_openapi_account:i,myx_openapi_access_token:r}})}};var Je=async o=>{try{let e=await o.read.eip712Domain();return {name:e[1],version:e[2],chainId:BigInt(e[3]),verifyingContract:e[4]}}catch(e){throw new Error(`Error fetching EIP712 domain: ${e}`)}};var Rt={ForwardRequest:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gas",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint48"},{name:"data",type:"bytes"}]},Xe=2,kt="0x55d398326f99059ff775485246999027b3197955";function vt(o){let e=viem.hexToBytes(o);if(e.length<65)throw new Error("Invalid signature length");let t=viem.toHex(e.slice(0,32)),i=viem.toHex(e.slice(32,64));return {v:e[64],r:t,s:i}}async function Mt(o,e,t,i,r,n,a,g){let s=chunkUIM35W7V_js.T(e,t),c=await Je(s),[d]=await o.getAddresses();if(!d)throw new l("INVALID_SIGNER","No account for signPermit");let p={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:i,spender:r,value:n,nonce:a,deadline:g},m=await o.signTypedData({account:d,domain:{...c,chainId:c.chainId},types:p,primaryType:"Permit",message:u});return vt(m)}var ne=class{constructor(e,t,i,r,n){this.configManager=e,this.logger=t,this.utils=i,this.account=r,this.api=n;}async onCheckRelayer(e,t,i,r,n){let g=await(await chunkUIM35W7V_js.$(i)).read.isUserRelayerEnabled([e,t]),c=await(await chunkUIM35W7V_js.Y(i)).read.getForwardFeeByToken([r]),d=BigInt(c)*BigInt(Xe);n=n??d.toString();let p=await this.utils.needsApproval(e,i,r,n,chunkUIM35W7V_js.R(i).TRADING_ROUTER);return g&&!p}async getContractAbiAndAddressByFunctionName(e,t){let i=["placeOrderWithSalt","placeOrderWithPosition","cancelOrders","cancelOrder","updateOrder","updatePriceAndAdjustCollateral"],r=["setUserFeeData"],n=["updateAndWithdraw","deposit"];return i.includes(e)?{abi:chunkUIM35W7V_js.S,address:chunkUIM35W7V_js.R(t).TRADING_ROUTER}:n.includes(e)?{abi:chunkUIM35W7V_js.m,address:chunkUIM35W7V_js.R(t).Account}:r.includes(e)?{abi:chunkUIM35W7V_js.j,address:this.configManager.getConfig().brokerAddress}:{abi:chunkUIM35W7V_js.S,address:chunkUIM35W7V_js.R(t).TRADING_ROUTER}}async getUSDPermitParams(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkUIM35W7V_js.i(t),n=chunkUIM35W7V_js.R(t),[a]=await r.getAddresses();if(!a)throw new l("INVALID_SIGNER","No account");let g=chunkUIM35W7V_js.T(t,i);try{let s=await g.read.nonces([a]),c=await Mt(r,t,i,a,n.TRADING_ROUTER,viem.maxUint256,s,e);return [{token:i,owner:a,spender:n.TRADING_ROUTER,value:viem.maxUint256.toString(),deadline:e.toString(),v:c.v,r:c.r,s:c.s}]}catch(s){if(chunkUIM35W7V_js.ia(s))throw s;let c=s instanceof Error?s.message:String(s);throw new l("INVALID_PRIVATE_KEY",`getUSDPermitParams failed: ${c}`)}}async getForwardEip712Domain(e){let i=await(await chunkUIM35W7V_js.$(e)).read.eip712Domain();return {name:i[1],version:i[2],chainId:i[3],verifyingContract:i[4]}}async forwardTxInFront({chainId:e,seamlessAddress:t,signFunction:i,forwardFeeToken:r,functionName:n,orderParams:a,value:g="0",gas:s="800000"}){let c=await(await chunkUIM35W7V_js.$(e)).read.nonces([t]),d=Ae__default.default().add(60,"minute").unix(),p=await this.getForwardEip712Domain(e),{abi:u,address:m}=await this.getContractAbiAndAddressByFunctionName(n,e),h=viem.encodeFunctionData({abi:u,functionName:n,args:a}),w=await i({domain:p,functionHash:h,to:m,nonce:c.toString(),deadline:d}),I=await this.api.forwarderTxApi({from:t,to:m,value:g??"0",gas:s,nonce:c.toString(),data:h,deadline:d,signature:w,forwardFeeToken:r},e);if(I.data?.txHash){for(let S=0;S<5;S++)try{if((await this.api.fetchForwarderGetApi({requestId:I.data.requestId})).data?.status===9)return {code:0};S<4&&await new Promise(ce=>setTimeout(ce,1e3));}catch(Te){this.logger.error("Poll transaction from chain error:",Te),S<4&&await new Promise(ce=>setTimeout(ce,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async forwarderTx({from:e,to:t,value:i,gas:r,deadline:n,data:a,nonce:g,forwardFeeToken:s},c){let d=await this.getForwardEip712Domain(c),p=await chunkUIM35W7V_js.i(c),[u]=await p.getAddresses();if(!u)throw new l("INVALID_SIGNER","Missing signer for forwarderTx");let m=await p.signTypedData({account:u,domain:d,types:Rt,primaryType:"ForwardRequest",message:{from:e,to:t,value:BigInt(i??"0"),gas:BigInt(r),nonce:BigInt(g),deadline:BigInt(n),data:a}});return await this.api.forwarderTxApi({from:e,to:t,value:i,gas:r,nonce:g,data:a,deadline:n,signature:m,forwardFeeToken:s},c)}async approveBalance(e,t,i){if(!this.configManager.hasSigner())throw new l("INVALID_SIGNER","Signer is required for permit");let r=await chunkUIM35W7V_js.V(e,t),n=chunkUIM35W7V_js.R(e);return await r.write?.approve([n.TRADING_ROUTER,i])}async authorizeSeamlessAccount({approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r}){let n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(i):"";if(e){let m=(await this.account.getWalletQuoteTokenBalance({chainId:i,address:n,tokenAddress:r})).data,w=await(await chunkUIM35W7V_js.Y(i)).read.getForwardFeeByToken([r]),I=BigInt(w)*BigInt(Xe);if(I>0&&I>BigInt(m))throw this.logger.debug("Insufficient wallet balance"),new l("INSUFFICIENT_BALANCE","Insufficient wallet balance")}console.log("authorizeSeamlessAccount-->",{masterAddress:n,approve:e,seamlessAddress:t,chainId:i,forwardFeeToken:r});let a=Ae__default.default().add(60,"minute").unix(),g=[];if(e)try{r===kt?(await this.approveBalance(i,r,viem.maxUint256.toString()))?.hash&&(g=[]):g=await this.getUSDPermitParams(a,i,r);}catch(u){if(chunkUIM35W7V_js.ia(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),g=[];}let s=await chunkUIM35W7V_js.$(i,1),c=await(await chunkUIM35W7V_js.$(i)).read.nonces([n]),d=viem.encodeFunctionData({abi:chunkUIM35W7V_js.k,functionName:"permitAndApproveForwarder",args:[t,e,g]}),p;try{p=await this.forwarderTx({from:n,to:s.address,value:"0",gas:"800000",nonce:c.toString(),data:d,deadline:a,forwardFeeToken:r},i);}catch(u){if(chunkUIM35W7V_js.ia(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(p.data?.txHash){for(let h=0;h<5;h++)try{if((await this.api.fetchForwarderGetApi({requestId:p.data.requestId})).data?.status===9)return {code:0,data:{seamlessAccount:t,authorized:e}};h<4&&await new Promise(I=>setTimeout(I,1e3));}catch(w){this.logger.error("Poll transaction from chain error:",w),h<4&&await new Promise(I=>setTimeout(I,1e3));}return {code:-1,data:null,message:"Transaction confirmation timeout, please check later"}}else return {code:-1,data:null,message:"Your request timed out, please try again"}}async getApproveBalance({chainId:e,forwardFeeToken:t,address:i}){try{let r=chunkUIM35W7V_js.R(e).TRADING_ROUTER,a=await chunkUIM35W7V_js.T(e,t).read.allowance([i,r]);return {code:0,data:String(a)}}catch(r){return {code:-1,message:r?.message}}}async getOriginSeamlessAccount(e,t){return {code:0,data:{masterAddress:await(await chunkUIM35W7V_js.$(t)).read.originAccount([e])}}}async formatForwarderTxParams({address:e,chainId:t,forwardFeeToken:i,functionName:r,data:n,seamlessAddress:a}){if(!e||!viem.isAddress(e))throw new l("PARAM_ERROR","address (master) is missing or invalid");if(!a||!viem.isAddress(a))throw new l("PARAM_ERROR","seamlessAddress is missing or invalid");if(!i||!viem.isAddress(i))throw new l("PARAM_ERROR","forwardFeeToken is missing or invalid");if(!Array.isArray(n))throw new l("PARAM_ERROR","data must be an array of ABI arguments for encodeFunctionData (e.g. [arg1, arg2])");if(!await this.utils.checkSeamlessGas(e,t,i))throw new l("INSUFFICIENT_BALANCE","Insufficient relay fee");let s=await chunkUIM35W7V_js.$(t),c,{abi:d,address:p}=await this.getContractAbiAndAddressByFunctionName(r,t);try{c=viem.encodeFunctionData({abi:d,functionName:r,args:n});}catch(m){throw new l("PARAM_ERROR",`encodeFunctionData failed for TradingRouter.${String(r)}: ${m.message}. Check args shape and that no address field is undefined.`)}let u=await s.read.nonces([a]);return {from:a,to:p,value:"0",gas:"800000",deadline:Ae__default.default().add(60,"minute").unix(),data:c,nonce:u.toString(),forwardFeeToken:i}}};var D=class{constructor(e){this.client=e;}getConfig(){return this.client.getConfigManager()?.getConfig()}getAddressConfig(){let t=this.getConfig()?.chainId;if(!t||!chunkUIM35W7V_js.b(t))throw new l("INVALID_CHAIN_ID","Invalid chain id");return chunkUIM35W7V_js.R(t)}getBrokerContract(){let e=this.getConfig();if(!e?.brokerAddress)throw new l("INVALID_BROKER_ADDRESS","Invalid broker address");return chunkUIM35W7V_js.X(e.chainId,e.brokerAddress)}get config(){return this.getConfig()}};var ae=class extends D{constructor(e,t){super(e),this.configManager=t;}getDisputeCourtContract(e=true){return chunkUIM35W7V_js.ba(this.config.chainId,e?1:0)}getReimbursementContract(e=true){return chunkUIM35W7V_js.aa(this.config.chainId,e?1:0)}getCaseIdFromReceiptLogs(e,t){let i=t==="DisputeFiled"?"caseId":"appealCaseId";for(let r of e.logs)try{let n=viem.decodeEventLog({abi:chunkUIM35W7V_js.l,data:r.data,topics:r.topics});if(n.eventName===t&&n.args&&i in n.args)return n.args[i]}catch{continue}return null}async submitAppeal(e,t,i){let r=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",n=await this.client.utils.needsApproval(r,this.config.chainId,t,i,this.getAddressConfig().DISPUTE_COURT);this.client.logger.debug("need-approve",n),n&&await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:this.getAddressConfig().DISPUTE_COURT});let a=await this.getDisputeCourtContract(),g=await this.client.utils.buildUpdatePriceParams(e,this.config.chainId),s=BigInt(g[0].value.toString()||"1"),c=await a.estimateGas.fileDispute([g,e,t],{value:s}),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await a.write.fileDispute([g,e,t],{value:s,gasLimit:d,gasPrice:p}),m=await chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:u}),h=this.getCaseIdFromReceiptLogs(m,"DisputeFiled");if(h==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {transaction:m,caseId:h}}async voteForAppeal({caseId:e,validator:t,isFor:i,deadline:r,v:n,r:a,s:g}){let s=await this.getDisputeCourtContract(),c=await s.estimateGas.vote([e,t,i?1:0,r,n,a,g]),d=await this.client.utils.getGasLimitByRatio(c),p=await this.client.utils.getGasPriceByRatio(),u=await s.write.vote([e,t,i?1:0,r,n,a,g],{gasLimit:d,gasPrice:p});return await chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:u})}async claimAppealMargin(e){let t=await this.getDisputeCourtContract(),i=await t.estimateGas.claimBond([e]),r=await this.client.utils.getGasLimitByRatio(i),n=await this.client.utils.getGasPriceByRatio(),a=await t.write.claimBond([e],{gasLimit:r,gasPrice:n});return chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:a})}async claimReimbursement(e,t,i,r){let n=await this.getReimbursementContract(),a=await n.estimateGas.claimReimbursement([e,t,i,r]),g=await this.client.utils.getGasLimitByRatio(a),s=await this.client.utils.getGasPriceByRatio(),c=await n.write.claimReimbursement([e,t,i,r],{gasLimit:g,gasPrice:s});return chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:c})}async getDisputeConfiguration(){return (await this.getDisputeCourtContract(false)).read.getDisputeConfiguration()}async submitAppealByVoteNode(e,t,i){let r=await this.getDisputeCourtContract(),n=await this.client.utils.getGasPriceByRatio(),a=await this.client.utils.getGasLimitByRatio(await r.estimateGas.fileDisputeFromStaker([e,t,i])),g=await r.write.fileDisputeFromStaker([e,t,i],{gasLimit:a,gasPrice:n}),s=await chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:g}),c=this.getCaseIdFromReceiptLogs(s,"DisputeFiled");if(c==null)throw new l("TRANSACTION_FAILED","DisputeFiledLog not found");return {tx:s,caseId:c}}async appealReconsideration(e,t,i){let r=await this.getDisputeCourtContract(),n=this.configManager.hasSigner()?await this.configManager.getSignerAddress(this.config.chainId):"",a=this.getAddressConfig().DISPUTE_COURT;if(await this.client.utils.needsApproval(n,this.config.chainId,t,i,a)){let h=await this.client.utils.approveAuthorization({chainId:this.config.chainId,quoteAddress:t,spenderAddress:a});if(h.code!==0)throw new l("TRANSACTION_FAILED",h.message)}let s=await r.estimateGas.appeal([e]),c=await this.client.utils.getGasLimitByRatio(s),d=await this.client.utils.getGasPriceByRatio(),p=await r.write.appeal([e],{gasLimit:c,gasPrice:d}),u=await chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:p}),m=this.getCaseIdFromReceiptLogs(u,"AppealFiled");if(m==null)throw new l("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,i){return this.client.api.getPoolAppealStatus({poolId:e,chainId:t,address:i,accessToken:await this.configManager.getAccessToken()??""})}};var se=class extends D{constructor(e){super(e);}async claimRebate(e){let t=this.getConfig(),i=await chunkUIM35W7V_js.W(this.config.chainId,t.brokerAddress),r=await i.estimateGas.claimRebate([e]),n=await this.client.utils.getGasLimitByRatio(r),a=await this.client.utils.getGasPriceByRatio(),g=await i.write.claimRebate([e],{gasPrice:a,gasLimit:n});return chunkUIM35W7V_js.f(this.config.chainId).waitForTransactionReceipt({hash:g})}};var Dt=(s=>(s[s.UnderReview=1]="UnderReview",s[s.InitialVote=2]="InitialVote",s[s.PublicNotice=3]="PublicNotice",s[s.UnderReconsideration=4]="UnderReconsideration",s[s.Won=5]="Won",s[s.Failed=6]="Failed",s[s.PlatformRuling=7]="PlatformRuling",s[s.PlatformRevoked=8]="PlatformRevoked",s))(Dt||{}),Ot=(d=>(d[d.InitialVoting=1]="InitialVoting",d[d.PublicNotice=2]="PublicNotice",d[d.UnderReconsideration=3]="UnderReconsideration",d[d.Won=5]="Won",d[d.Failed=4]="Failed",d[d.PlatformRuling=6]="PlatformRuling",d[d.PlatformRevoked=7]="PlatformRevoked",d[d.ReconsiderationVoting=8]="ReconsiderationVoting",d[d.AppealRevert=9]="AppealRevert",d[d.NotAppealFailed=10]="NotAppealFailed",d))(Ot||{}),Ft=(r=>(r[r.UnderReview=1]="UnderReview",r[r.PublicNotice=2]="PublicNotice",r[r.UnderReconsideration=3]="UnderReconsideration",r[r.Completed=4]="Completed",r))(Ft||{}),Nt=(t=>(t[t.ElectionNode=0]="ElectionNode",t[t.OfficialNode=1]="OfficialNode",t))(Nt||{}),Lt=(t=>(t[t.Reject=0]="Reject",t[t.Support=1]="Support",t))(Lt||{}),Bt=(t=>(t[t.UnClaimed=0]="UnClaimed",t[t.Claimed=1]="Claimed",t))(Bt||{}),_t=(t=>(t[t.NotVoted=0]="NotVoted",t[t.Voted=1]="Voted",t))(_t||{}),Gt=(t=>(t[t.Appeal=1]="Appeal",t[t.Reconsideration=2]="Reconsideration",t))(Gt||{}),Wt=(i=>(i[i.NoVote=0]="NoVote",i[i.Supported=1]="Supported",i[i.Rejected=2]="Rejected",i))(Wt||{}),Ut=(t=>(t[t.Yes=1]="Yes",t[t.No=0]="No",t))(Ut||{}),$t=(t=>(t[t.None=0]="None",t[t.isAppealing=1]="isAppealing",t))($t||{});var xe=class{getConfigManager(){return this.configManager}constructor(e){this.configManager=new j(e),this.logger=new chunkUIM35W7V_js.ha({logLevel:e.logLevel});let t=chunkUIM35W7V_js.P.getInstance();chunkUIM35W7V_js.h()?.hasSigner()||(t.setConfigManager(this.configManager),chunkUIM35W7V_js.g(this.configManager)),t.getMarkets().then(),this.utils=new Z(this.configManager,this.logger),this.api=new re(this.configManager,this.logger),this.account=new ee(this.configManager,this.logger,this.utils,this),this.seamless=new ne(this.configManager,this.logger,this.utils,this.account,this.api),this.markets=new Q(this.configManager,this.utils,this.api),this.position=new J(this.configManager,this.logger,this.utils,this.account,this.api),this.order=new X(this.configManager,this.logger,this.utils,this.account,this.api),this.subscription=new z(this.configManager,this.logger),this.appeal=new ae(this,this.configManager),this.referrals=new se(this);}auth(e){this.configManager.auth(e),chunkUIM35W7V_js.P.getInstance().setConfigManager(this.configManager),chunkUIM35W7V_js.g(this.configManager);}updateClientChainId(e,t){this.configManager.updateClientChainId(e,t);}close(){this.configManager.clear(),this.subscription.disconnect();}async getAccessToken(){return await this.configManager.getAccessToken()}async refreshAccessToken(e=false){return await this.configManager.refreshAccessToken(e)}};var Xn="1.0.21";
2
+ Object.defineProperty(exports,"COMMON_LP_AMOUNT_DECIMALS",{enumerable:true,get:function(){return chunkUIM35W7V_js.na}});Object.defineProperty(exports,"COMMON_PRICE_DECIMALS",{enumerable:true,get:function(){return chunkUIM35W7V_js.ma}});Object.defineProperty(exports,"ChainId",{enumerable:true,get:function(){return chunkUIM35W7V_js.a}});Object.defineProperty(exports,"CloseTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.D}});Object.defineProperty(exports,"DirectionEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.A}});Object.defineProperty(exports,"ErrorCode",{enumerable:true,get:function(){return chunkUIM35W7V_js.o}});Object.defineProperty(exports,"ExecTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.C}});Object.defineProperty(exports,"ForwarderGetStatus",{enumerable:true,get:function(){return chunkUIM35W7V_js.F}});Object.defineProperty(exports,"HttpKlineIntervalEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.r}});Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return chunkUIM35W7V_js.ha}});Object.defineProperty(exports,"MarketCapType",{enumerable:true,get:function(){return chunkUIM35W7V_js.u}});Object.defineProperty(exports,"MarketPoolState",{enumerable:true,get:function(){return chunkUIM35W7V_js.p}});Object.defineProperty(exports,"MarketType",{enumerable:true,get:function(){return chunkUIM35W7V_js.s}});Object.defineProperty(exports,"MxSDK",{enumerable:true,get:function(){return chunkUIM35W7V_js.P}});Object.defineProperty(exports,"OperationEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.x}});Object.defineProperty(exports,"OracleType",{enumerable:true,get:function(){return chunkUIM35W7V_js.q}});Object.defineProperty(exports,"OrderStatusEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.B}});Object.defineProperty(exports,"OrderTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.w}});Object.defineProperty(exports,"SearchSecondTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.v}});Object.defineProperty(exports,"SearchTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.t}});Object.defineProperty(exports,"TradeFlowAccountTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.E}});Object.defineProperty(exports,"TradeFlowTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.y}});Object.defineProperty(exports,"TriggerTypeEnum",{enumerable:true,get:function(){return chunkUIM35W7V_js.z}});Object.defineProperty(exports,"approve",{enumerable:true,get:function(){return chunkUIM35W7V_js.ra}});Object.defineProperty(exports,"base",{enumerable:true,get:function(){return chunkUIM35W7V_js.xa}});Object.defineProperty(exports,"bigintAmountSlipperCalculator",{enumerable:true,get:function(){return chunkUIM35W7V_js.qa}});Object.defineProperty(exports,"bigintTradingGasPriceWithRatio",{enumerable:true,get:function(){return chunkUIM35W7V_js.pa}});Object.defineProperty(exports,"bigintTradingGasToRatioCalculator",{enumerable:true,get:function(){return chunkUIM35W7V_js.oa}});Object.defineProperty(exports,"formatUnits",{enumerable:true,get:function(){return chunkUIM35W7V_js.va}});Object.defineProperty(exports,"getAllowanceApproved",{enumerable:true,get:function(){return chunkUIM35W7V_js.la}});Object.defineProperty(exports,"getBalanceOf",{enumerable:true,get:function(){return chunkUIM35W7V_js.ka}});Object.defineProperty(exports,"getBaseDetail",{enumerable:true,get:function(){return chunkUIM35W7V_js.M}});Object.defineProperty(exports,"getBaseUrlByEnv",{enumerable:true,get:function(){return chunkUIM35W7V_js.H}});Object.defineProperty(exports,"getMarketDetail",{enumerable:true,get:function(){return chunkUIM35W7V_js.N}});Object.defineProperty(exports,"getMarketList",{enumerable:true,get:function(){return chunkUIM35W7V_js.O}});Object.defineProperty(exports,"getOraclePrice",{enumerable:true,get:function(){return chunkUIM35W7V_js.I}});Object.defineProperty(exports,"getPoolDetail",{enumerable:true,get:function(){return chunkUIM35W7V_js.J}});Object.defineProperty(exports,"getPoolList",{enumerable:true,get:function(){return chunkUIM35W7V_js.G}});Object.defineProperty(exports,"getPoolOpenOrders",{enumerable:true,get:function(){return chunkUIM35W7V_js.K}});Object.defineProperty(exports,"getPriceData",{enumerable:true,get:function(){return chunkUIM35W7V_js.ta}});Object.defineProperty(exports,"getPricesData",{enumerable:true,get:function(){return chunkUIM35W7V_js.sa}});Object.defineProperty(exports,"getPublicClient",{enumerable:true,get:function(){return chunkUIM35W7V_js.f}});Object.defineProperty(exports,"getSdkLogSink",{enumerable:true,get:function(){return chunkUIM35W7V_js.da}});Object.defineProperty(exports,"getTickerData",{enumerable:true,get:function(){return chunkUIM35W7V_js.L}});Object.defineProperty(exports,"getTokenInfo",{enumerable:true,get:function(){return chunkUIM35W7V_js.ua}});Object.defineProperty(exports,"getWalletClient",{enumerable:true,get:function(){return chunkUIM35W7V_js.i}});Object.defineProperty(exports,"getWalletProvider",{enumerable:true,get:function(){return chunkUIM35W7V_js.Q}});Object.defineProperty(exports,"market",{enumerable:true,get:function(){return chunkUIM35W7V_js.za}});Object.defineProperty(exports,"parseUnits",{enumerable:true,get:function(){return chunkUIM35W7V_js.wa}});Object.defineProperty(exports,"pool",{enumerable:true,get:function(){return chunkUIM35W7V_js.Aa}});Object.defineProperty(exports,"quote",{enumerable:true,get:function(){return chunkUIM35W7V_js.ya}});Object.defineProperty(exports,"sdkError",{enumerable:true,get:function(){return chunkUIM35W7V_js.ga}});Object.defineProperty(exports,"sdkLog",{enumerable:true,get:function(){return chunkUIM35W7V_js.ea}});Object.defineProperty(exports,"sdkWarn",{enumerable:true,get:function(){return chunkUIM35W7V_js.fa}});Object.defineProperty(exports,"setConfigManagerForViem",{enumerable:true,get:function(){return chunkUIM35W7V_js.g}});Object.defineProperty(exports,"setSdkLogSink",{enumerable:true,get:function(){return chunkUIM35W7V_js.ca}});exports.AppealCaseTypeEnum=Gt;exports.AppealClaimStatusEnum=Bt;exports.AppealNodeStateEnum=Wt;exports.AppealNodeVotedStateEnum=_t;exports.AppealReconsiderationType=Ot;exports.AppealStage=Ft;exports.AppealStatus=$t;exports.AppealType=Dt;exports.Direction=pr;exports.IsVoteNodeEnum=Ut;exports.MyxClient=xe;exports.NodeTypeEnum=Nt;exports.OperationType=k;exports.OrderStatus=mr;exports.OrderType=Y;exports.SDK_VERSION=Xn;exports.TimeInForce=ur;exports.TriggerType=lr;exports.VoteTypeEnum=Lt;exports.fromViemWalletClient=me;exports.normalizeSigner=K;