@bluefin-exchange/pro-sdk 0.1.61 → 0.2.0-pre-release.1

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.
Files changed (210) hide show
  1. package/dist/{example.js → cjs/example.js} +3 -0
  2. package/dist/cjs/example.js.map +1 -0
  3. package/dist/{index.js → cjs/index.js} +1 -0
  4. package/dist/cjs/index.js.map +1 -0
  5. package/dist/{src → cjs/src}/api.js +75 -1
  6. package/dist/cjs/src/api.js.map +1 -0
  7. package/dist/{src → cjs/src}/base.js +5 -1
  8. package/dist/cjs/src/base.js.map +1 -0
  9. package/dist/{src → cjs/src}/common.js +1 -0
  10. package/dist/cjs/src/common.js.map +1 -0
  11. package/dist/{src → cjs/src}/configuration.js +1 -0
  12. package/dist/cjs/src/configuration.js.map +1 -0
  13. package/dist/{src → cjs/src}/index.js +1 -0
  14. package/dist/cjs/src/index.js.map +1 -0
  15. package/dist/{src → cjs/src}/request-signer.js +11 -0
  16. package/dist/cjs/src/request-signer.js.map +1 -0
  17. package/dist/{src → cjs/src}/sdk.js +47 -4
  18. package/dist/cjs/src/sdk.js.map +1 -0
  19. package/dist/{src → cjs/src}/utils.js +1 -0
  20. package/dist/cjs/src/utils.js.map +1 -0
  21. package/dist/{src → cjs/src}/websocket.js +1 -0
  22. package/dist/cjs/src/websocket.js.map +1 -0
  23. package/dist/esm/example.js +218 -0
  24. package/dist/esm/example.js.map +1 -0
  25. package/dist/esm/index.js +18 -0
  26. package/dist/esm/index.js.map +1 -0
  27. package/dist/esm/src/api.js +4318 -0
  28. package/dist/esm/src/api.js.map +1 -0
  29. package/dist/esm/src/base.js +69 -0
  30. package/dist/esm/src/base.js.map +1 -0
  31. package/dist/esm/src/common.js +162 -0
  32. package/dist/esm/src/common.js.map +1 -0
  33. package/dist/esm/src/configuration.js +45 -0
  34. package/dist/esm/src/configuration.js.map +1 -0
  35. package/dist/esm/src/index.js +23 -0
  36. package/dist/esm/src/index.js.map +1 -0
  37. package/dist/esm/src/request-signer.js +231 -0
  38. package/dist/esm/src/request-signer.js.map +1 -0
  39. package/dist/esm/src/sdk.js +786 -0
  40. package/dist/esm/src/sdk.js.map +1 -0
  41. package/dist/esm/src/utils.js +10 -0
  42. package/dist/esm/src/utils.js.map +1 -0
  43. package/dist/esm/src/websocket.js +159 -0
  44. package/dist/esm/src/websocket.js.map +1 -0
  45. package/dist/types/example.d.ts +2 -0
  46. package/dist/types/example.d.ts.map +1 -0
  47. package/dist/types/index.d.ts +2 -0
  48. package/dist/types/index.d.ts.map +1 -0
  49. package/dist/{src → types/src}/api.d.ts +126 -47
  50. package/dist/types/src/api.d.ts.map +1 -0
  51. package/dist/{src → types/src}/base.d.ts +1 -0
  52. package/dist/types/src/base.d.ts.map +1 -0
  53. package/dist/{src → types/src}/common.d.ts +1 -0
  54. package/dist/types/src/common.d.ts.map +1 -0
  55. package/dist/{src → types/src}/configuration.d.ts +1 -0
  56. package/dist/types/src/configuration.d.ts.map +1 -0
  57. package/dist/{src → types/src}/index.d.ts +1 -0
  58. package/dist/types/src/index.d.ts.map +1 -0
  59. package/dist/{src → types/src}/request-signer.d.ts +6 -1
  60. package/dist/types/src/request-signer.d.ts.map +1 -0
  61. package/dist/{src → types/src}/sdk.d.ts +12 -1
  62. package/dist/types/src/sdk.d.ts.map +1 -0
  63. package/dist/{src → types/src}/utils.d.ts +1 -0
  64. package/dist/types/src/utils.d.ts.map +1 -0
  65. package/dist/{src → types/src}/websocket.d.ts +1 -0
  66. package/dist/types/src/websocket.d.ts.map +1 -0
  67. package/package.json +21 -7
  68. package/dist/example.d.ts +0 -1
  69. package/dist/index.d.ts +0 -1
  70. package/example.ts +0 -323
  71. package/index.ts +0 -1
  72. package/openapitools.json +0 -24
  73. package/src/.openapi-generator/FILES +0 -128
  74. package/src/.openapi-generator/VERSION +0 -1
  75. package/src/.openapi-generator-ignore +0 -28
  76. package/src/README.md +0 -46
  77. package/src/api.ts +0 -8918
  78. package/src/base.ts +0 -86
  79. package/src/common.ts +0 -150
  80. package/src/configuration.ts +0 -115
  81. package/src/docs/Account.md +0 -64
  82. package/src/docs/AccountAggregatedTradeUpdate.md +0 -21
  83. package/src/docs/AccountAuthorizationRequest.md +0 -24
  84. package/src/docs/AccountAuthorizationRequestSignedFields.md +0 -28
  85. package/src/docs/AccountCommandFailureUpdate.md +0 -29
  86. package/src/docs/AccountDataApi.md +0 -374
  87. package/src/docs/AccountDataStream.md +0 -21
  88. package/src/docs/AccountEventReason.md +0 -25
  89. package/src/docs/AccountEventType.md +0 -21
  90. package/src/docs/AccountFundingRateHistory.md +0 -20
  91. package/src/docs/AccountFundingRateHistoryData.md +0 -30
  92. package/src/docs/AccountMarketPreference.md +0 -22
  93. package/src/docs/AccountOrderUpdate.md +0 -71
  94. package/src/docs/AccountPositionLeverageUpdateRequest.md +0 -22
  95. package/src/docs/AccountPositionLeverageUpdateRequestSignedFields.md +0 -30
  96. package/src/docs/AccountPositionUpdate.md +0 -47
  97. package/src/docs/AccountPreference.md +0 -24
  98. package/src/docs/AccountStreamMessage.md +0 -25
  99. package/src/docs/AccountStreamMessagePayload.md +0 -153
  100. package/src/docs/AccountSubscriptionMessage.md +0 -25
  101. package/src/docs/AccountTradeUpdate.md +0 -21
  102. package/src/docs/AccountTransactionUpdate.md +0 -31
  103. package/src/docs/AccountUpdate.md +0 -61
  104. package/src/docs/ActiveOrderUpdate.md +0 -65
  105. package/src/docs/AdjustIsolatedMarginRequest.md +0 -22
  106. package/src/docs/AdjustIsolatedMarginRequestSignedFields.md +0 -32
  107. package/src/docs/AdjustMarginOperation.md +0 -11
  108. package/src/docs/AffiliateIntervalOverview.md +0 -56
  109. package/src/docs/AffiliateLeaderDashboard.md +0 -38
  110. package/src/docs/AffiliateMetadata.md +0 -36
  111. package/src/docs/AffiliateMetadataFees.md +0 -31
  112. package/src/docs/AffiliateOnboardResponse.md +0 -22
  113. package/src/docs/AffiliateOverview.md +0 -46
  114. package/src/docs/AffiliateSummary.md +0 -30
  115. package/src/docs/Asset.md +0 -29
  116. package/src/docs/AssetConfig.md +0 -28
  117. package/src/docs/AuthApi.md +0 -243
  118. package/src/docs/AuthorizedWallet.md +0 -24
  119. package/src/docs/CampaignMetadata.md +0 -28
  120. package/src/docs/CampaignRewards.md +0 -18
  121. package/src/docs/CancelOrdersRequest.md +0 -23
  122. package/src/docs/CancelOrdersResponse.md +0 -21
  123. package/src/docs/CandlePriceType.md +0 -14
  124. package/src/docs/CandlestickUpdate.md +0 -41
  125. package/src/docs/CommandFailureReasonCode.md +0 -24
  126. package/src/docs/ContractsConfig.md +0 -31
  127. package/src/docs/CreateOrderRequest.md +0 -36
  128. package/src/docs/CreateOrderRequestSignedFields.md +0 -40
  129. package/src/docs/CreateOrderResponse.md +0 -20
  130. package/src/docs/EpochConfigs.md +0 -34
  131. package/src/docs/EpochConfigsResponse.md +0 -24
  132. package/src/docs/EpochMetadata.md +0 -30
  133. package/src/docs/Error.md +0 -22
  134. package/src/docs/ExchangeApi.md +0 -473
  135. package/src/docs/ExchangeInfoResponse.md +0 -30
  136. package/src/docs/FailedCommandType.md +0 -12
  137. package/src/docs/FeeConfigs.md +0 -33
  138. package/src/docs/FundingRateEntry.md +0 -24
  139. package/src/docs/GetAffiliateIntervalOverview200Response.md +0 -26
  140. package/src/docs/GetAffiliateLeaderDashboard200Response.md +0 -26
  141. package/src/docs/GetAffiliateOverview200Response.md +0 -26
  142. package/src/docs/IntervalMetadata.md +0 -28
  143. package/src/docs/IntervalRewards.md +0 -30
  144. package/src/docs/KlineInterval.md +0 -36
  145. package/src/docs/LoginRequest.md +0 -25
  146. package/src/docs/LoginResponse.md +0 -26
  147. package/src/docs/MarginType.md +0 -13
  148. package/src/docs/MarkPriceUpdate.md +0 -26
  149. package/src/docs/Market.md +0 -82
  150. package/src/docs/MarketDataStreamName.md +0 -142
  151. package/src/docs/MarketEventType.md +0 -25
  152. package/src/docs/MarketPriceUpdate.md +0 -26
  153. package/src/docs/MarketStatus.md +0 -16
  154. package/src/docs/MarketStreamMessage.md +0 -23
  155. package/src/docs/MarketStreamMessagePayload.md +0 -123
  156. package/src/docs/MarketSubscriptionMessage.md +0 -23
  157. package/src/docs/MarketSubscriptionStreams.md +0 -23
  158. package/src/docs/OnboardAffiliateRequest.md +0 -26
  159. package/src/docs/OnboardAffiliateRequestSocialUserNames.md +0 -27
  160. package/src/docs/OnboardRefereeRequest.md +0 -20
  161. package/src/docs/OpenOrderResponse.md +0 -64
  162. package/src/docs/Operators.md +0 -28
  163. package/src/docs/OraclePriceUpdate.md +0 -26
  164. package/src/docs/OrderCancelReason.md +0 -65
  165. package/src/docs/OrderCancellationFailureReason.md +0 -19
  166. package/src/docs/OrderCancellationUpdate.md +0 -35
  167. package/src/docs/OrderSide.md +0 -13
  168. package/src/docs/OrderStatus.md +0 -25
  169. package/src/docs/OrderTimeInForce.md +0 -15
  170. package/src/docs/OrderType.md +0 -29
  171. package/src/docs/OrderbookDepthResponse.md +0 -38
  172. package/src/docs/OrderbookDiffDepthUpdate.md +0 -30
  173. package/src/docs/OrderbookPartialDepthUpdate.md +0 -30
  174. package/src/docs/Position.md +0 -52
  175. package/src/docs/PositionSide.md +0 -13
  176. package/src/docs/RecentTradesUpdates.md +0 -20
  177. package/src/docs/RefereeOnboardResponse.md +0 -20
  178. package/src/docs/RefreshTokenRequest.md +0 -20
  179. package/src/docs/RefreshTokenResponse.md +0 -26
  180. package/src/docs/RewardsApi.md +0 -859
  181. package/src/docs/RewardsSummary.md +0 -26
  182. package/src/docs/SelfTradePreventionType.md +0 -15
  183. package/src/docs/StatsEntry.md +0 -26
  184. package/src/docs/StatsInterval.md +0 -14
  185. package/src/docs/StatsResponse.md +0 -20
  186. package/src/docs/StreamsApi.md +0 -126
  187. package/src/docs/SubscriptionResponseMessage.md +0 -23
  188. package/src/docs/SubscriptionType.md +0 -11
  189. package/src/docs/TickerAllUpdate.md +0 -20
  190. package/src/docs/TickerResponse.md +0 -82
  191. package/src/docs/TickerUpdate.md +0 -83
  192. package/src/docs/Trade.md +0 -54
  193. package/src/docs/TradeApi.md +0 -589
  194. package/src/docs/TradeSide.md +0 -13
  195. package/src/docs/TradeType.md +0 -15
  196. package/src/docs/TradingFees.md +0 -24
  197. package/src/docs/Transaction.md +0 -34
  198. package/src/docs/TransactionType.md +0 -25
  199. package/src/docs/UpdateAccountPreferenceRequest.md +0 -24
  200. package/src/docs/UpdateAffiliateFeeConfigRequest.md +0 -20
  201. package/src/docs/UserCampaignRewards.md +0 -48
  202. package/src/docs/WithdrawRequest.md +0 -22
  203. package/src/docs/WithdrawRequestSignedFields.md +0 -30
  204. package/src/git_push.sh +0 -57
  205. package/src/index.ts +0 -6
  206. package/src/request-signer.ts +0 -405
  207. package/src/sdk.ts +0 -982
  208. package/src/utils.ts +0 -6
  209. package/src/websocket.ts +0 -165
  210. package/tsconfig.json +0 -23
@@ -0,0 +1,786 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BluefinProSdk = void 0;
13
+ const api_1 = require("./api");
14
+ const configuration_1 = require("./configuration");
15
+ const ws_1 = require("ws");
16
+ const v3_1 = require("@firefly-exchange/library-sui/v3");
17
+ const library_sui_1 = require("@firefly-exchange/library-sui");
18
+ const bcs_1 = require("@mysten/bcs");
19
+ const environmentConfig = {
20
+ mainnet: {
21
+ authHost: 'https://auth.api.sui-prod.bluefin.io',
22
+ apiHost: 'https://api.sui-prod.bluefin.io',
23
+ tradeHost: 'https://trade.api.sui-prod.bluefin.io',
24
+ marketWsHost: 'wss://stream.api.sui-prod.bluefin.io/ws/market',
25
+ accountWsHost: 'wss://stream.api.sui-prod.bluefin.io/ws/account',
26
+ },
27
+ testnet: {
28
+ authHost: 'https://auth.api.sui-staging.bluefin.io',
29
+ apiHost: 'https://api.sui-staging.bluefin.io',
30
+ tradeHost: 'https://trade.api.sui-staging.bluefin.io',
31
+ marketWsHost: 'wss://stream.api.sui-staging.bluefin.io/ws/market',
32
+ accountWsHost: 'wss://stream.api.sui-staging.bluefin.io/ws/account',
33
+ },
34
+ devnet: {
35
+ authHost: 'https://auth.api.sui-dev.bluefin.io',
36
+ apiHost: 'https://api.sui-dev.bluefin.io',
37
+ tradeHost: 'https://trade.api.sui-dev.bluefin.io',
38
+ marketWsHost: 'wss://stream.api.sui-dev.bluefin.io/ws/market',
39
+ accountWsHost: 'wss://stream.api.sui-dev.bluefin.io/ws/account',
40
+ },
41
+ };
42
+ var Services;
43
+ (function (Services) {
44
+ Services[Services["Account"] = 0] = "Account";
45
+ Services[Services["Exchange"] = 1] = "Exchange";
46
+ Services[Services["Rewards"] = 2] = "Rewards";
47
+ Services[Services["Trade"] = 3] = "Trade";
48
+ Services[Services["Auth"] = 4] = "Auth";
49
+ Services[Services["MarketWebsocket"] = 5] = "MarketWebsocket";
50
+ Services[Services["AccountWebsocket"] = 6] = "AccountWebsocket";
51
+ })(Services || (Services = {}));
52
+ class BluefinProSdk {
53
+ constructor(bfSigner, environment = 'mainnet', suiClient, opts) {
54
+ var _a, _b, _c, _d, _e, _f;
55
+ this.bfSigner = bfSigner;
56
+ this.environment = environment;
57
+ this.suiClient = suiClient;
58
+ this.configs = {};
59
+ /**
60
+ * @description
61
+ * build gasless transaction payload bytes
62
+ * @param tx transcation block
63
+ * @returns string
64
+ * */
65
+ this.buildGaslessTxPayloadBytes = (txb) => __awaiter(this, void 0, void 0, function* () {
66
+ try {
67
+ return yield library_sui_1.SuiBlocks.buildGaslessTxPayloadBytes(txb, this.suiClient);
68
+ }
69
+ catch (error) {
70
+ throw new Error(error instanceof Error ? error.message : 'Build gasless tx payload bytes failed');
71
+ }
72
+ });
73
+ this.currentAccountAddress = opts === null || opts === void 0 ? void 0 : opts.currentAccountAddress;
74
+ this.isConnected = false;
75
+ this.updateTokenTimeout = null;
76
+ this.contractsConfig = undefined;
77
+ this.tokenResponse = null;
78
+ this.tokenSetAtSeconds = null;
79
+ this.disableLoginPromptOnLogout = (_a = opts === null || opts === void 0 ? void 0 : opts.disableLoginPromptOnLogout) !== null && _a !== void 0 ? _a : false;
80
+ this.onLogout = opts === null || opts === void 0 ? void 0 : opts.onLogout;
81
+ this.onAccessTokenUpdate = opts === null || opts === void 0 ? void 0 : opts.onAccessTokenUpdate;
82
+ this.isRefreshing = false;
83
+ this.refreshPromise = null;
84
+ this.visibilityChangeHandler = undefined;
85
+ this.onlineHandler = undefined;
86
+ this.offlineHandler = undefined;
87
+ // Initialize time offset based on provided currentTimeMs
88
+ if ((opts === null || opts === void 0 ? void 0 : opts.currentTimeMs) !== undefined) {
89
+ this.timeOffsetMs = opts.currentTimeMs - Date.now();
90
+ }
91
+ else {
92
+ this.timeOffsetMs = 0;
93
+ }
94
+ if ((opts === null || opts === void 0 ? void 0 : opts.refreshToken) && (opts === null || opts === void 0 ? void 0 : opts.refreshTokenValidForSeconds)) {
95
+ this.tokenResponse = {
96
+ accessToken: '',
97
+ accessTokenValidForSeconds: 0,
98
+ refreshToken: opts.refreshToken,
99
+ refreshTokenValidForSeconds: opts.refreshTokenValidForSeconds,
100
+ };
101
+ // Set timestamp when refresh token was provided
102
+ this.tokenSetAtSeconds = Date.now() / 1000;
103
+ }
104
+ const defaultConfig = environmentConfig[this.environment];
105
+ const basePaths = {
106
+ authHost: (_b = opts === null || opts === void 0 ? void 0 : opts.authHost) !== null && _b !== void 0 ? _b : defaultConfig.authHost,
107
+ apiHost: (_c = opts === null || opts === void 0 ? void 0 : opts.apiHost) !== null && _c !== void 0 ? _c : defaultConfig.apiHost,
108
+ tradeHost: (_d = opts === null || opts === void 0 ? void 0 : opts.tradeHost) !== null && _d !== void 0 ? _d : defaultConfig.tradeHost,
109
+ marketWsHost: (_e = opts === null || opts === void 0 ? void 0 : opts.marketWsHost) !== null && _e !== void 0 ? _e : defaultConfig.marketWsHost,
110
+ accountWsHost: (_f = opts === null || opts === void 0 ? void 0 : opts.accountWsHost) !== null && _f !== void 0 ? _f : defaultConfig.accountWsHost,
111
+ };
112
+ const authApiConfig = new configuration_1.Configuration({
113
+ basePath: basePaths.authHost,
114
+ });
115
+ this.configs[Services.Auth] = authApiConfig;
116
+ this.authApi = new api_1.AuthApi(authApiConfig);
117
+ const exchangeApiConfig = new configuration_1.Configuration({
118
+ basePath: basePaths.apiHost,
119
+ });
120
+ this.configs[Services.Exchange] = exchangeApiConfig;
121
+ this.exchangeDataApi = new api_1.ExchangeApi(exchangeApiConfig);
122
+ const rewardsApiConfig = new configuration_1.Configuration({
123
+ basePath: basePaths.apiHost,
124
+ });
125
+ this.configs[Services.Rewards] = rewardsApiConfig;
126
+ this.rewardsDataApi = new api_1.RewardsApi(rewardsApiConfig);
127
+ const accountDataApiConfig = new configuration_1.Configuration({
128
+ basePath: basePaths.apiHost,
129
+ });
130
+ this.configs[Services.Account] = accountDataApiConfig;
131
+ this.accountDataApi = new api_1.AccountDataApi(accountDataApiConfig);
132
+ const tradeApiConfig = new configuration_1.Configuration({
133
+ basePath: basePaths.tradeHost,
134
+ });
135
+ this.configs[Services.Trade] = tradeApiConfig;
136
+ this.tradeApi = new api_1.TradeApi(tradeApiConfig);
137
+ const marketWsConfig = new configuration_1.Configuration({
138
+ basePath: basePaths.marketWsHost,
139
+ });
140
+ this.configs[Services.MarketWebsocket] = marketWsConfig;
141
+ const accountWsConfig = new configuration_1.Configuration({
142
+ basePath: basePaths.accountWsHost,
143
+ });
144
+ this.configs[Services.AccountWebsocket] = accountWsConfig;
145
+ }
146
+ createWallet() {
147
+ const wallet = library_sui_1.Ed25519Keypair.generate();
148
+ const signerKey = wallet.getSecretKey();
149
+ const keyPair = (0, library_sui_1.decodeSuiPrivateKey)(signerKey);
150
+ const publicAddress = wallet.toSuiAddress();
151
+ return {
152
+ privateKey: (0, bcs_1.toHex)(keyPair.secretKey),
153
+ publicAddress,
154
+ };
155
+ }
156
+ getTokenResponse() {
157
+ return this.tokenResponse;
158
+ }
159
+ generateSalt() {
160
+ return (Date.now() + Math.floor(Math.random() * 1000000)).toString();
161
+ }
162
+ getCurrentTimeMs() {
163
+ return Date.now() + this.timeOffsetMs;
164
+ }
165
+ updateCurrentTimeMs(currentTimeMs) {
166
+ this.timeOffsetMs = currentTimeMs - Date.now();
167
+ }
168
+ isRefreshTokenValid() {
169
+ var _a;
170
+ if (!((_a = this.tokenResponse) === null || _a === void 0 ? void 0 : _a.refreshToken) || !this.tokenSetAtSeconds) {
171
+ return false;
172
+ }
173
+ const currentTimeSeconds = Date.now() / 1000;
174
+ const refreshTokenExpiryTime = this.tokenSetAtSeconds + this.tokenResponse.refreshTokenValidForSeconds;
175
+ // Add 60 second buffer to prevent using token right at expiry
176
+ return currentTimeSeconds < refreshTokenExpiryTime - 60;
177
+ }
178
+ isAccessTokenExpired() {
179
+ var _a;
180
+ if (!((_a = this.tokenResponse) === null || _a === void 0 ? void 0 : _a.accessToken) || !this.tokenSetAtSeconds) {
181
+ return true;
182
+ }
183
+ const currentTimeSeconds = Date.now() / 1000;
184
+ const tokenLifetimeSeconds = this.tokenResponse.accessTokenValidForSeconds;
185
+ const refreshAtLifetimePercentage = BluefinProSdk.TOKEN_REFRESH_THRESHOLD_PERCENTAGE;
186
+ const refreshAtSeconds = this.tokenSetAtSeconds +
187
+ tokenLifetimeSeconds * refreshAtLifetimePercentage;
188
+ // Token is considered "expired" if we've passed the 80% lifetime mark
189
+ return currentTimeSeconds >= refreshAtSeconds;
190
+ }
191
+ initializeTxBuilder() {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ var _a, _b, _c, _d, _e, _f, _g, _h;
194
+ this.txBuilder = new v3_1.TxBuilder({
195
+ AdminCap: '',
196
+ ExternalDataStore: ((_a = this.contractsConfig) === null || _a === void 0 ? void 0 : _a.edsId) || '',
197
+ InternalDataStore: ((_b = this.contractsConfig) === null || _b === void 0 ? void 0 : _b.idsId) || '',
198
+ Operators: {
199
+ admin: ((_c = this.contractsConfig) === null || _c === void 0 ? void 0 : _c.operators.admin) || '',
200
+ fee: ((_d = this.contractsConfig) === null || _d === void 0 ? void 0 : _d.operators.fee) || '',
201
+ funding: ((_e = this.contractsConfig) === null || _e === void 0 ? void 0 : _e.operators.funding) || '',
202
+ pruning: '',
203
+ sequencer: ((_f = this.contractsConfig) === null || _f === void 0 ? void 0 : _f.operators.sequencer) || '',
204
+ },
205
+ Package: ((_g = this.contractsConfig) === null || _g === void 0 ? void 0 : _g.currentContractAddress) || '',
206
+ Perpetuals: {},
207
+ SupportedAssets: ((_h = this.assets) === null || _h === void 0 ? void 0 : _h.reduce((agg, x) => {
208
+ agg[x.symbol] = Object.assign(Object.assign({}, x), { coinType: x.assetType });
209
+ return agg;
210
+ }, {})) || {},
211
+ TreasuryCap: '',
212
+ UpgradeCap: '',
213
+ });
214
+ });
215
+ }
216
+ initialize(options) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ this.initializeOptions = options;
219
+ yield this.setContractsConfig();
220
+ yield this.initializeTxBuilder();
221
+ yield this.loginAndUpdateToken();
222
+ this.setupVisibilityChangeListener();
223
+ this.setupNetworkChangeListener();
224
+ });
225
+ }
226
+ setContractsConfig() {
227
+ return __awaiter(this, void 0, void 0, function* () {
228
+ const response = yield this.exchangeDataApi.getExchangeInfo();
229
+ this.contractsConfig = response.data.contractsConfig;
230
+ this.contractsConfig.currentContractAddress = '0x3b985440fbf1624ec97932fce729a27c5fbea74a1d1781cee3f64fcb22c9cfef';
231
+ this.assets = response.data.assets;
232
+ });
233
+ }
234
+ loginAndUpdateToken() {
235
+ return __awaiter(this, void 0, void 0, function* () {
236
+ var _a;
237
+ yield this.login();
238
+ // Safety check - if login failed or logout was called, tokenResponse might be null
239
+ if (!this.tokenResponse) {
240
+ throw new Error('Login failed - no token response available');
241
+ }
242
+ this.isConnected = true;
243
+ this.configs[Services.Account].accessToken =
244
+ this.tokenResponse.accessToken;
245
+ this.configs[Services.Trade].accessToken = this.tokenResponse.accessToken;
246
+ this.configs[Services.Rewards].accessToken =
247
+ this.tokenResponse.accessToken;
248
+ // Notify about token refresh
249
+ (_a = this.onAccessTokenUpdate) === null || _a === void 0 ? void 0 : _a.call(this, this.tokenResponse.accessToken);
250
+ // Schedule the next token refresh
251
+ this.scheduleTokenRefresh();
252
+ });
253
+ }
254
+ scheduleTokenRefresh() {
255
+ // Clear any existing timeout
256
+ if (this.updateTokenTimeout) {
257
+ clearTimeout(this.updateTokenTimeout);
258
+ this.updateTokenTimeout = null;
259
+ }
260
+ if (!this.isConnected ||
261
+ !this.tokenResponse ||
262
+ !this.tokenSetAtSeconds) {
263
+ return;
264
+ }
265
+ // Calculate when to refresh: at 80% of token lifetime (or 20% before expiry)
266
+ const currentTimeSeconds = Date.now() / 1000;
267
+ const tokenLifetimeSeconds = this.tokenResponse.accessTokenValidForSeconds;
268
+ const refreshAtLifetimePercentage = BluefinProSdk.TOKEN_REFRESH_THRESHOLD_PERCENTAGE;
269
+ const refreshAtSeconds = this.tokenSetAtSeconds +
270
+ tokenLifetimeSeconds * refreshAtLifetimePercentage;
271
+ const millisecondsUntilRefresh = (refreshAtSeconds - currentTimeSeconds) * 1000;
272
+ const delayMs = Math.max(millisecondsUntilRefresh, 0);
273
+ console.log(`Scheduling token refresh in ${Math.round(delayMs / 1000)} seconds`);
274
+ this.updateTokenTimeout = setTimeout(() => {
275
+ this.refreshToken(true);
276
+ }, delayMs);
277
+ }
278
+ setupVisibilityChangeListener() {
279
+ // Only set up in browser environment
280
+ if (typeof document !== 'undefined') {
281
+ this.visibilityChangeHandler = () => {
282
+ if (document.visibilityState === 'visible' && this.isConnected) {
283
+ console.log('Page became visible, checking token status');
284
+ this.handleVisible();
285
+ }
286
+ };
287
+ document.addEventListener('visibilitychange', this.visibilityChangeHandler);
288
+ }
289
+ }
290
+ setupNetworkChangeListener() {
291
+ // Only set up in browser environment
292
+ if (typeof navigator !== 'undefined' && 'onLine' in navigator) {
293
+ window.addEventListener('online', this.handleOnline);
294
+ window.addEventListener('offline', this.handleOffline);
295
+ }
296
+ }
297
+ handleVisible() {
298
+ return __awaiter(this, void 0, void 0, function* () {
299
+ if (!this.tokenResponse || !this.tokenSetAtSeconds) {
300
+ return;
301
+ }
302
+ this.refreshToken();
303
+ });
304
+ }
305
+ handleOnline() {
306
+ return __awaiter(this, void 0, void 0, function* () {
307
+ if (!this.isConnected || !this.tokenResponse || !this.tokenSetAtSeconds) {
308
+ return;
309
+ }
310
+ console.log('Network reconnected, resuming token refresh and checking token status');
311
+ this.refreshToken(true);
312
+ });
313
+ }
314
+ handleOffline() {
315
+ if (this.updateTokenTimeout) {
316
+ clearTimeout(this.updateTokenTimeout);
317
+ this.updateTokenTimeout = null;
318
+ }
319
+ }
320
+ login() {
321
+ return __awaiter(this, void 0, void 0, function* () {
322
+ var _a, _b, _c;
323
+ console.log('Logging in to get the access token');
324
+ this.tokenSetAtSeconds = Date.now() / 1000;
325
+ if (!this.currentAccountAddress) {
326
+ this.currentAccountAddress = this.bfSigner.getAddress();
327
+ }
328
+ console.log(`Logging in as ${this.currentAccountAddress}`);
329
+ // Check if we have a valid refresh token first
330
+ if (((_a = this.tokenResponse) === null || _a === void 0 ? void 0 : _a.refreshToken) && this.isRefreshTokenValid()) {
331
+ try {
332
+ console.log('Attempting to refresh token using refresh token');
333
+ const response = yield this.authApi.authTokenRefreshPut({
334
+ refreshToken: this.tokenResponse.refreshToken,
335
+ });
336
+ this.tokenResponse = response.data;
337
+ console.log('Token refreshed successfully');
338
+ return;
339
+ }
340
+ catch (e) {
341
+ console.error('Error refreshing token:', e);
342
+ // Throw the error to let the caller handle it
343
+ throw new Error(`Token refresh failed: ${e instanceof Error ? e.message : 'Unknown error'}`);
344
+ }
345
+ }
346
+ // Fallback to full login only if refresh token is not available or invalid
347
+ // This should only happen during initial login or when refresh token is truly expired
348
+ try {
349
+ const loginRequest = {
350
+ accountAddress: this.currentAccountAddress,
351
+ signedAtMillis: this.getCurrentTimeMs(),
352
+ audience: 'api',
353
+ };
354
+ const signature = yield this.bfSigner.signLoginRequest(loginRequest);
355
+ const response = yield this.authApi.authV2TokenPost(signature, loginRequest, (_b = this.initializeOptions) === null || _b === void 0 ? void 0 : _b.refreshTokenValidForSeconds, (_c = this.initializeOptions) === null || _c === void 0 ? void 0 : _c.readOnly);
356
+ this.tokenResponse = response.data;
357
+ }
358
+ catch (e) {
359
+ console.error('Full login failed:', e);
360
+ // If this fails and we're in a mode where logout should be disabled, don't logout
361
+ if (this.disableLoginPromptOnLogout) {
362
+ throw new Error(`Login failed: ${e instanceof Error ? e.message : 'Unknown error'}`);
363
+ }
364
+ // Otherwise, throw the error and let the caller decide
365
+ throw new Error(`Login failed: ${e instanceof Error ? e.message : 'Unknown error'}`);
366
+ }
367
+ });
368
+ }
369
+ getAccessToken() {
370
+ return __awaiter(this, void 0, void 0, function* () {
371
+ if (!this.tokenResponse) {
372
+ yield this.login();
373
+ }
374
+ return this.tokenResponse.accessToken;
375
+ });
376
+ }
377
+ getOpenOrders(symbol) {
378
+ return __awaiter(this, void 0, void 0, function* () {
379
+ return yield this.tradeApi.getOpenOrders(symbol);
380
+ });
381
+ }
382
+ getStandbyOrders(symbol) {
383
+ return __awaiter(this, void 0, void 0, function* () {
384
+ return yield this.tradeApi.getStandbyOrders(symbol);
385
+ });
386
+ }
387
+ updateLeverage(symbol, leverageE9) {
388
+ return __awaiter(this, void 0, void 0, function* () {
389
+ if (!this.contractsConfig) {
390
+ throw new Error('Missing contracts config');
391
+ }
392
+ const signedFields = {
393
+ accountAddress: this.currentAccountAddress,
394
+ idsId: this.contractsConfig.idsId,
395
+ symbol: symbol,
396
+ leverageE9: leverageE9,
397
+ salt: this.generateSalt(),
398
+ signedAtMillis: this.getCurrentTimeMs(),
399
+ };
400
+ const request = yield this.bfSigner.signLeverageUpdateRequest(signedFields);
401
+ return yield this.tradeApi.putLeverageUpdate({
402
+ signedFields,
403
+ signature: request,
404
+ });
405
+ });
406
+ }
407
+ createOrder(params) {
408
+ return __awaiter(this, void 0, void 0, function* () {
409
+ var _a, _b;
410
+ if (!this.contractsConfig) {
411
+ throw new Error('Missing contracts config');
412
+ }
413
+ const signedFields = {
414
+ symbol: params.symbol,
415
+ idsId: this.contractsConfig.idsId,
416
+ accountAddress: this.currentAccountAddress,
417
+ priceE9: params.priceE9,
418
+ quantityE9: params.quantityE9,
419
+ side: params.side,
420
+ leverageE9: params.leverageE9,
421
+ isIsolated: params.isIsolated,
422
+ salt: this.generateSalt(),
423
+ expiresAtMillis: params.expiresAtMillis,
424
+ signedAtMillis: this.getCurrentTimeMs(),
425
+ };
426
+ const signature = yield this.bfSigner.signOrderRequest(signedFields);
427
+ const createOrderRequest = {
428
+ signedFields,
429
+ signature,
430
+ clientOrderId: params.clientOrderId,
431
+ type: params.type,
432
+ reduceOnly: (_a = params.reduceOnly) !== null && _a !== void 0 ? _a : false,
433
+ postOnly: (_b = params.postOnly) !== null && _b !== void 0 ? _b : false,
434
+ timeInForce: params.timeInForce,
435
+ triggerPriceE9: params.triggerPriceE9,
436
+ selfTradePreventionType: params.selfTradePreventionType,
437
+ };
438
+ console.log('Creating order:', createOrderRequest);
439
+ return yield this.tradeApi.postCreateOrder(createOrderRequest);
440
+ });
441
+ }
442
+ cancelOrder(cancelOrdersRequest) {
443
+ return __awaiter(this, void 0, void 0, function* () {
444
+ return yield this.tradeApi.cancelOrders(cancelOrdersRequest);
445
+ });
446
+ }
447
+ cancelStandbyOrder(cancelOrdersRequest) {
448
+ return __awaiter(this, void 0, void 0, function* () {
449
+ return yield this.tradeApi.cancelStandbyOrders(cancelOrdersRequest);
450
+ });
451
+ }
452
+ withdraw(assetSymbol, amountE9) {
453
+ return __awaiter(this, void 0, void 0, function* () {
454
+ const exchangeInfo = yield this.exchangeDataApi.getExchangeInfo();
455
+ const asset = exchangeInfo.data.assets.find((asset) => asset.symbol === assetSymbol);
456
+ if (!asset) {
457
+ throw new Error(`Asset ${assetSymbol} not found`);
458
+ }
459
+ if (!this.contractsConfig) {
460
+ throw new Error('Missing contractsConfig');
461
+ }
462
+ const signedFields = {
463
+ assetSymbol,
464
+ edsId: this.contractsConfig.edsId,
465
+ accountAddress: this.currentAccountAddress,
466
+ amountE9,
467
+ salt: this.generateSalt(),
468
+ signedAtMillis: this.getCurrentTimeMs(),
469
+ };
470
+ const signature = yield this.bfSigner.signWithdrawRequest(signedFields);
471
+ yield this.tradeApi.postWithdraw({
472
+ signedFields,
473
+ signature,
474
+ });
475
+ console.log('Withdraw request sent:', signedFields);
476
+ });
477
+ }
478
+ authorizeAccount(accountAddress, alias) {
479
+ return __awaiter(this, void 0, void 0, function* () {
480
+ if (!this.contractsConfig) {
481
+ throw new Error('Missing contractsConfig');
482
+ }
483
+ const signedFields = {
484
+ accountAddress: this.currentAccountAddress,
485
+ idsId: this.contractsConfig.idsId,
486
+ authorizedAccountAddress: accountAddress,
487
+ salt: this.generateSalt(),
488
+ signedAtMillis: this.getCurrentTimeMs(),
489
+ };
490
+ const signature = yield this.bfSigner.signAccountAuthorizationRequest(signedFields, true);
491
+ yield this.tradeApi.putAuthorizeAccount({
492
+ signedFields,
493
+ signature,
494
+ alias,
495
+ });
496
+ console.log('Authorize account request sent:', signedFields);
497
+ });
498
+ }
499
+ deauthorizeAccount(accountAddress) {
500
+ return __awaiter(this, void 0, void 0, function* () {
501
+ if (!this.contractsConfig) {
502
+ throw new Error('Missing contractsConfig');
503
+ }
504
+ const signedFields = {
505
+ accountAddress: this.currentAccountAddress,
506
+ idsId: this.contractsConfig.idsId,
507
+ authorizedAccountAddress: accountAddress,
508
+ salt: this.generateSalt(),
509
+ signedAtMillis: this.getCurrentTimeMs(),
510
+ };
511
+ const signature = yield this.bfSigner.signAccountAuthorizationRequest(signedFields, false);
512
+ yield this.tradeApi.putDeauthorizeAccount({
513
+ signedFields,
514
+ signature,
515
+ });
516
+ console.log('Deauthorize account request sent:', signedFields);
517
+ });
518
+ }
519
+ adjustIsolatedMargin(symbol, amountE9, add) {
520
+ return __awaiter(this, void 0, void 0, function* () {
521
+ if (!this.contractsConfig) {
522
+ throw new Error('Missing contractsConfig');
523
+ }
524
+ const signedFields = {
525
+ symbol,
526
+ idsId: this.contractsConfig.idsId,
527
+ accountAddress: this.currentAccountAddress,
528
+ operation: add
529
+ ? api_1.AdjustMarginOperation.Add
530
+ : api_1.AdjustMarginOperation.Subtract,
531
+ quantityE9: amountE9,
532
+ salt: this.generateSalt(),
533
+ signedAtMillis: this.getCurrentTimeMs(),
534
+ };
535
+ const signature = yield this.bfSigner.signAdjustIsolatedMarginRequest(signedFields);
536
+ yield this.tradeApi.putAdjustIsolatedMargin({
537
+ signedFields,
538
+ signature,
539
+ });
540
+ console.log('Adjust isolated margin request sent:', signedFields);
541
+ });
542
+ }
543
+ getAccountPreferences() {
544
+ return __awaiter(this, void 0, void 0, function* () {
545
+ return yield this.accountDataApi.getAccountPreferences();
546
+ });
547
+ }
548
+ updateAccountPreferences(updateAccountPreferenceRequest) {
549
+ return __awaiter(this, void 0, void 0, function* () {
550
+ return yield this.accountDataApi.putAccountPreferences(updateAccountPreferenceRequest);
551
+ });
552
+ }
553
+ deposit(amountE9, accountAddress, args) {
554
+ return __awaiter(this, void 0, void 0, function* () {
555
+ var _a, _b, _c;
556
+ const assetSymbol = 'USDC';
557
+ const txb = new library_sui_1.TransactionBlock();
558
+ const assetType = (_b = (_a = this.assets) === null || _a === void 0 ? void 0 : _a.find((x) => x.symbol === assetSymbol)) === null || _b === void 0 ? void 0 : _b.assetType;
559
+ if (!assetType) {
560
+ throw new Error('Missing USDC asset type');
561
+ }
562
+ const [splitCoin, mergedCoin] = yield library_sui_1.CoinUtils.createCoinWithBalance(this.suiClient, txb, amountE9, assetType, this.currentAccountAddress || this.bfSigner.getAddress());
563
+ //build the tx
564
+ (_c = this.txBuilder) === null || _c === void 0 ? void 0 : _c.depositToAssetBank(assetSymbol, accountAddress ||
565
+ this.currentAccountAddress ||
566
+ this.bfSigner.getAddress(), amountE9, splitCoin, {
567
+ txBlock: txb
568
+ });
569
+ //add the transfer objects to the tx
570
+ if (mergedCoin) {
571
+ txb.transferObjects([mergedCoin], this.currentAccountAddress || this.bfSigner.getAddress());
572
+ }
573
+ if (splitCoin) {
574
+ txb.transferObjects([splitCoin], this.currentAccountAddress || this.bfSigner.getAddress());
575
+ }
576
+ if (args && args.sponsored) {
577
+ // build the gasless tx payload bytes
578
+ const gaslessTxPayloadBytes = yield this.buildGaslessTxPayloadBytes(txb);
579
+ try {
580
+ const request = {
581
+ txBytes: gaslessTxPayloadBytes,
582
+ };
583
+ // sponsor gas for the transaction
584
+ const sponsorTxApiResponse = yield this.accountDataApi.sponsorTx(request);
585
+ const txBytes = (0, bcs_1.fromBase64)(sponsorTxApiResponse.data.txBytes);
586
+ // sign the transaction with user's wallet
587
+ const userSignedTx = yield this.bfSigner.signTx(txBytes);
588
+ // execute the transaction with both user's signature and sponsor's signature
589
+ const response = yield this.bfSigner.executeSponsoredTx(userSignedTx.bytes, userSignedTx.signature, sponsorTxApiResponse.data.signature, this.suiClient);
590
+ return response;
591
+ }
592
+ catch (error) {
593
+ if (args === null || args === void 0 ? void 0 : args.fallbackToExecuteTx) {
594
+ return this.bfSigner.executeTx(txb, this.suiClient);
595
+ }
596
+ throw error;
597
+ }
598
+ }
599
+ else {
600
+ return this.bfSigner.executeTx(txb, this.suiClient);
601
+ }
602
+ });
603
+ }
604
+ refreshToken() {
605
+ return __awaiter(this, arguments, void 0, function* (force = false) {
606
+ if (!this.isConnected)
607
+ return;
608
+ // If already refreshing, wait for that operation to complete
609
+ if (this.isRefreshing) {
610
+ if (this.refreshPromise) {
611
+ yield this.refreshPromise;
612
+ }
613
+ return;
614
+ }
615
+ // Check if token needs refreshing
616
+ if (!this.isAccessTokenExpired() && !force) {
617
+ return;
618
+ }
619
+ this.isRefreshing = true;
620
+ this.refreshPromise = this.performTokenRefresh();
621
+ try {
622
+ yield this.refreshPromise;
623
+ }
624
+ finally {
625
+ this.isRefreshing = false;
626
+ this.refreshPromise = null;
627
+ }
628
+ });
629
+ }
630
+ performTokenRefresh() {
631
+ return __awaiter(this, void 0, void 0, function* () {
632
+ const maxRetries = 5;
633
+ let retryCount = 0;
634
+ let consecutiveNetworkErrors = 0;
635
+ while (retryCount < maxRetries) {
636
+ try {
637
+ console.log(`Refreshing token (attempt ${retryCount + 1}/${maxRetries})`);
638
+ // Check if refresh token is still valid
639
+ if (!this.isRefreshTokenValid()) {
640
+ console.log('Refresh token is expired or invalid, triggering logout');
641
+ this.logout();
642
+ return;
643
+ }
644
+ yield this.loginAndUpdateToken();
645
+ console.log('Token refreshed successfully');
646
+ consecutiveNetworkErrors = 0; // Reset network error counter on success
647
+ return;
648
+ }
649
+ catch (error) {
650
+ retryCount++;
651
+ console.error(`Error refreshing token (attempt ${retryCount}):`, error);
652
+ // Check if this is a network error that we should retry
653
+ const isNetworkError = error instanceof Error &&
654
+ (error.message.includes('Network Error') ||
655
+ error.message.includes('ERR_NETWORK') ||
656
+ error.message.includes('ECONNREFUSED') ||
657
+ error.message.includes('timeout') ||
658
+ error.message.includes('ERR_NETWORK_IO_SUSPENDED'));
659
+ // Check if we're currently offline (browser environment only)
660
+ const isOffline = typeof navigator !== 'undefined' &&
661
+ 'onLine' in navigator &&
662
+ !navigator.onLine;
663
+ if (isNetworkError) {
664
+ consecutiveNetworkErrors++;
665
+ }
666
+ // If we're offline, don't count this as a "real" error - just wait for network to come back
667
+ if (isOffline) {
668
+ console.log('User is offline, will retry when network comes back online');
669
+ return;
670
+ }
671
+ // If it's not a network error and login failed (tokenResponse is null), logout immediately
672
+ if (!isNetworkError && !this.tokenResponse) {
673
+ console.error('Login failed permanently, triggering logout');
674
+ this.logout();
675
+ return;
676
+ }
677
+ // If we've had too many consecutive network errors, pause refresh attempts temporarily
678
+ if (consecutiveNetworkErrors >= 10) {
679
+ // Clear any scheduled refresh
680
+ if (this.updateTokenTimeout) {
681
+ clearTimeout(this.updateTokenTimeout);
682
+ this.updateTokenTimeout = null;
683
+ }
684
+ setTimeout(() => {
685
+ console.log('Resuming token refresh attempts');
686
+ this.scheduleTokenRefresh(); // Reschedule refresh when resuming
687
+ }, 300000); // 5 minutes
688
+ return;
689
+ }
690
+ if (retryCount >= maxRetries && !isOffline) {
691
+ if (isNetworkError) {
692
+ console.warn('Max retries reached due to network errors, will retry later');
693
+ return; // Don't logout for network issues, just wait for next interval
694
+ }
695
+ else {
696
+ console.error('Max retries reached, triggering logout');
697
+ this.logout();
698
+ return;
699
+ }
700
+ }
701
+ // Exponential backoff: wait 2^retryCount seconds, but cap at 30 seconds for network errors
702
+ const baseDelay = isNetworkError ? 5000 : 2000; // Start with 5s for network errors, 2s for others
703
+ const delayMs = Math.min(baseDelay * Math.pow(2, retryCount - 1), 30000);
704
+ console.log(`Retrying in ${delayMs}ms...`);
705
+ yield new Promise((resolve) => setTimeout(resolve, delayMs));
706
+ }
707
+ }
708
+ });
709
+ }
710
+ createAccountDataStreamListener(handler) {
711
+ return __awaiter(this, void 0, void 0, function* () {
712
+ return new Promise((resolve) => {
713
+ if (!this.tokenResponse) {
714
+ throw new Error('Missing tokenResponse');
715
+ }
716
+ const ws = new ws_1.WebSocket(this.configs[Services.AccountWebsocket].basePath, {
717
+ headers: {
718
+ Authorization: `Bearer ${this.tokenResponse.accessToken}`,
719
+ },
720
+ });
721
+ ws.onmessage = (event) => __awaiter(this, void 0, void 0, function* () {
722
+ yield handler(JSON.parse(event.data));
723
+ });
724
+ ws.on('open', () => {
725
+ resolve(ws);
726
+ });
727
+ });
728
+ });
729
+ }
730
+ createMarketDataStreamListener(handler) {
731
+ return __awaiter(this, void 0, void 0, function* () {
732
+ return new Promise((resolve) => {
733
+ const ws = new ws_1.WebSocket(this.configs[Services.MarketWebsocket].basePath);
734
+ ws.onmessage = (event) => __awaiter(this, void 0, void 0, function* () {
735
+ yield handler(JSON.parse(event.data));
736
+ });
737
+ ws.on('open', () => {
738
+ resolve(ws);
739
+ });
740
+ });
741
+ });
742
+ }
743
+ logout() {
744
+ return __awaiter(this, void 0, void 0, function* () {
745
+ var _a;
746
+ console.log('Logging out');
747
+ if (this.updateTokenTimeout) {
748
+ clearTimeout(this.updateTokenTimeout);
749
+ this.updateTokenTimeout = null;
750
+ }
751
+ this.tokenResponse = null;
752
+ this.tokenSetAtSeconds = null;
753
+ this.isConnected = false;
754
+ (_a = this.onLogout) === null || _a === void 0 ? void 0 : _a.call(this);
755
+ });
756
+ }
757
+ dispose() {
758
+ return __awaiter(this, void 0, void 0, function* () {
759
+ console.log('Disposing SDK resources');
760
+ if (this.updateTokenTimeout) {
761
+ clearTimeout(this.updateTokenTimeout);
762
+ this.updateTokenTimeout = null;
763
+ }
764
+ // Clean up visibility change listener
765
+ if (this.visibilityChangeHandler && typeof document !== 'undefined') {
766
+ document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
767
+ this.visibilityChangeHandler = undefined;
768
+ }
769
+ // Clean up network change listeners
770
+ if (typeof window !== 'undefined') {
771
+ if (this.onlineHandler) {
772
+ window.removeEventListener('online', this.onlineHandler);
773
+ this.onlineHandler = undefined;
774
+ }
775
+ if (this.offlineHandler) {
776
+ window.removeEventListener('offline', this.offlineHandler);
777
+ this.offlineHandler = undefined;
778
+ }
779
+ }
780
+ this.isConnected = false;
781
+ });
782
+ }
783
+ }
784
+ exports.BluefinProSdk = BluefinProSdk;
785
+ BluefinProSdk.TOKEN_REFRESH_THRESHOLD_PERCENTAGE = 0.8;
786
+ //# sourceMappingURL=sdk.js.map