-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathderivws-accounts.service.ts
More file actions
279 lines (245 loc) · 10 KB
/
Copy pathderivws-accounts.service.ts
File metadata and controls
279 lines (245 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { isProduction } from '@/components/shared';
import brandConfig from '../../brand.config.json';
/**
* Account information from derivatives/accounts endpoint
*/
export interface DerivAccount {
account_id: string;
balance: string;
currency: string;
group: string;
status: string;
account_type: 'demo' | 'real';
}
/**
* Response from derivatives/accounts endpoint
*/
interface AccountsResponse {
data: DerivAccount[];
}
/**
* OTP response data (nested JSON string)
*/
interface OTPResponseData {
url: string;
}
/**
* Response from options/accounts/{accountId}/otp endpoint
*/
interface OTPResponse {
data: OTPResponseData;
// JSON string containing OTPResponseData
}
/**
* Service for handling DerivWS account operations and WebSocket URL retrieval
*
* This service manages:
* - Fetching account list from derivatives/accounts endpoint
* - Storing accounts in sessionStorage
* - Fetching OTP and WebSocket URL for specific accounts
* - Managing default account selection
* - Singleton pattern to prevent duplicate API calls
* - Promise caching to handle concurrent requests
*/
export class DerivWSAccountsService {
// Singleton instance for promise caching
private static accountsFetchPromise: Promise<DerivAccount[]> | null = null;
private static otpFetchPromises: Map<string, Promise<string>> = new Map();
/**
* Gets the DerivWS base URL based on environment
* @returns DerivWS base URL (e.g., "https://api.derivws.com/trading/v1/")
*/
private static getDerivWSBaseURL(): string {
const environment = isProduction() ? 'production' : 'staging';
return brandConfig.platform.derivws.url[environment];
}
/**
* Clears all cached promises (useful for testing or forced refresh)
*/
static clearCache(): void {
this.accountsFetchPromise = null;
this.otpFetchPromises.clear();
}
/**
* Stores accounts list in sessionStorage
* @param accounts Array of DerivAccount objects
*/
static storeAccounts(accounts: DerivAccount[]): void {
sessionStorage.setItem('deriv_accounts', JSON.stringify(accounts));
}
/**
* Retrieves accounts list from sessionStorage
* @returns Array of DerivAccount objects or null if not found
*/
static getStoredAccounts(): DerivAccount[] | null {
try {
const accountsStr = sessionStorage.getItem('deriv_accounts');
if (!accountsStr) {
return null;
}
return JSON.parse(accountsStr) as DerivAccount[];
} catch (error) {
console.error('[DerivWS] Error parsing stored accounts:', error);
return null;
}
}
/**
* Gets the default account (first account from the list)
* @returns DerivAccount object or null if no accounts available
*/
static getDefaultAccount(): DerivAccount | null {
const accounts = this.getStoredAccounts();
if (!accounts || accounts.length === 0) {
return null;
}
return accounts[0];
}
/**
* Clears stored accounts from sessionStorage
*/
static clearStoredAccounts(): void {
sessionStorage.removeItem('deriv_accounts');
}
/**
* Fetches accounts list from derivatives/accounts endpoint with singleton pattern
* Prevents duplicate API calls by caching the promise
* @param accessToken Bearer token from OAuth authentication
* @returns Promise with array of DerivAccount objects
*/
static async fetchAccountsList(accessToken: string): Promise<DerivAccount[]> {
// If there's already a fetch in progress, return that promise
if (this.accountsFetchPromise) {
return this.accountsFetchPromise;
}
// Create new fetch promise and cache it
this.accountsFetchPromise = (async () => {
try {
const baseURL = this.getDerivWSBaseURL();
const OptionsDir = brandConfig.platform.derivws.directories.options;
const endpoint = `${baseURL}${OptionsDir}accounts`;
const response = await fetch(endpoint, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch accounts: ${response.status} ${response.statusText}`);
}
const data: AccountsResponse = await response.json();
// Extract accounts array from nested data structure
const accounts = data?.data || [];
if (accounts.length === 0) {
console.warn('[DerivWS] No accounts found in response');
}
// Store accounts in sessionStorage for future use
this.storeAccounts(accounts);
return accounts;
} catch (error) {
console.error('[DerivWS] Error fetching accounts:', error);
// Clear the cached promise on error so retry is possible
this.accountsFetchPromise = null;
throw error;
} finally {
// Clear the promise after completion (success or failure)
// This allows fresh fetches on subsequent calls
setTimeout(() => {
this.accountsFetchPromise = null;
}, 100);
}
})();
return this.accountsFetchPromise;
}
/**
* Fetches OTP and WebSocket URL for a specific account with singleton pattern
* Prevents duplicate OTP calls for the same account by caching the promise
* @param accessToken Bearer token from OAuth authentication
* @param accountId Account ID to get OTP for
* @returns Promise with WebSocket URL
*/
static async fetchOTPWebSocketURL(accessToken: string, accountId: string): Promise<string> {
// Create a unique key for this account's OTP request
const cacheKey = `${accountId}`;
// If there's already a fetch in progress for this account, return that promise
if (this.otpFetchPromises.has(cacheKey)) {
return this.otpFetchPromises.get(cacheKey)!;
}
// Create new fetch promise and cache it
const otpPromise = (async () => {
try {
const baseURL = this.getDerivWSBaseURL();
const optionsDir = brandConfig.platform.derivws.directories.options;
const endpoint = `${baseURL}${optionsDir}accounts/${accountId}/otp`;
const response = await fetch(endpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch OTP: ${response.status} ${response.statusText}`);
}
const otpResponse: OTPResponse = await response.json();
// Parse the nested JSON string
const websocketURL = otpResponse.data.url;
if (!websocketURL) {
throw new Error('WebSocket URL not found in OTP response');
}
return websocketURL;
} catch (error) {
console.error('[DerivWS] Error fetching OTP:', error);
// Clear the cached promise on error so retry is possible
this.otpFetchPromises.delete(cacheKey);
throw error;
} finally {
// Clear the promise after completion (success or failure)
// This allows fresh OTP fetches on subsequent calls
setTimeout(() => {
this.otpFetchPromises.delete(cacheKey);
}, 100);
}
})();
this.otpFetchPromises.set(cacheKey, otpPromise);
return otpPromise;
}
/**
* Complete flow to get authenticated WebSocket URL with optimized caching
* 1. Check if accounts are already in sessionStorage (skip fetch on refresh)
* 2. If not in storage, fetch accounts list
* 3. Store accounts in sessionStorage
* 4. Get default account (first from list)
* 5. Fetch OTP and WebSocket URL for that account (always fresh OTP)
*
* @param accessToken Bearer token from OAuth authentication
* @returns Promise with WebSocket URL
*/
static async getAuthenticatedWebSocketURL(accessToken: string): Promise<string> {
try {
let accounts: DerivAccount[] | null = null;
// Step 1: Check if accounts are already stored (optimization for refresh)
const storedAccounts = this.getStoredAccounts();
if (storedAccounts && storedAccounts.length > 0) {
accounts = storedAccounts;
} else {
// Step 2: Fetch accounts list if not in storage
accounts = await this.fetchAccountsList(accessToken);
if (!accounts || accounts.length === 0) {
throw new Error('No accounts available');
}
}
// Step 3: Resolve which account to connect as.
// On an account switch the caller has already written the new loginid to
// localStorage before triggering a WebSocket regeneration, so we honour
// that selection here instead of always falling back to accounts[0].
const activeLoginId = localStorage.getItem('active_loginid');
const targetAccount =
(activeLoginId && accounts.find(a => a.account_id === activeLoginId)) || accounts[0];
// Step 4: Fetch OTP and WebSocket URL for the resolved account (always fresh OTP)
const websocketURL = await this.fetchOTPWebSocketURL(accessToken, targetAccount.account_id);
return websocketURL;
} catch (error) {
console.error('[DerivWS] Error in authenticated WebSocket URL flow:', error);
throw error;
}
}
}