forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoinmarketcap.test.js
More file actions
308 lines (254 loc) · 9.65 KB
/
Copy pathcoinmarketcap.test.js
File metadata and controls
308 lines (254 loc) · 9.65 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
'use strict';
const mockGet = jest.fn();
const mockAxiosCreate = jest.fn(() => ({ get: mockGet }));
const mockLogger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
};
const mockUsdcIssuer = 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335AX2OBFLDTQLNUEHRGPTM6RIA';
jest.mock('axios', () => ({
create: mockAxiosCreate,
}));
jest.mock('../src/config', () => ({
stellar: {
usdcIssuer: mockUsdcIssuer,
},
coinmarketcap: {
apiKey: 'cmc-test-key',
baseUrl: 'https://pro-api.coinmarketcap.test/v1',
assetIssuerMap: {
XLM: { symbol: 'XLM' },
[`USDC:${mockUsdcIssuer}`]: { id: 3408 },
},
},
priceSources: {
circuitCooldownMs: 900000,
circuitReminderIntervalMs: 300000,
},
}));
jest.mock('../src/logger', () => mockLogger);
function quoteResponse(symbol, price) {
return {
data: {
data: {
[symbol]: {
quote: {
USD: { price },
},
},
},
},
};
}
function loadSource() {
jest.resetModules();
mockGet.mockReset();
mockAxiosCreate.mockClear();
mockAxiosCreate.mockReturnValue({ get: mockGet });
mockLogger.warn.mockClear();
mockLogger.debug.mockClear();
mockLogger.error.mockClear();
return require('../src/services/sources/coinmarketcap');
}
describe('CoinMarketCap source', () => {
test('returns USD price on supported XLM response', async () => {
const coinmarketcap = loadSource();
mockGet.mockResolvedValueOnce(quoteResponse('XLM', 0.1234));
const price = await coinmarketcap.fetchPrice('XLM');
expect(price).toBe(0.1234);
expect(mockAxiosCreate).toHaveBeenCalledWith({
baseURL: 'https://pro-api.coinmarketcap.test/v1',
headers: {
Accept: 'application/json',
'X-CMC_PRO_API_KEY': 'cmc-test-key',
},
timeout: 10000,
});
expect(mockGet).toHaveBeenCalledWith('/cryptocurrency/quotes/latest', {
params: {
symbol: 'XLM',
convert: 'USD',
},
});
});
test('returns null for unsupported asset symbols without calling CMC', async () => {
const coinmarketcap = loadSource();
const price = await coinmarketcap.fetchPrice('DOGE');
expect(price).toBeNull();
expect(mockGet).not.toHaveBeenCalled();
expect(mockLogger.debug).toHaveBeenCalledWith(
'Asset not supported by CoinMarketCap',
expect.objectContaining({ assetCode: 'DOGE' })
);
});
test('returns USDC price only for the configured Stellar issuer', async () => {
const coinmarketcap = loadSource();
mockGet.mockResolvedValueOnce(quoteResponse('3408', 1.0003));
const price = await coinmarketcap.fetchPrice('USDC', mockUsdcIssuer);
expect(price).toBe(1.0003);
expect(mockGet).toHaveBeenCalledWith('/cryptocurrency/quotes/latest', {
params: {
id: 3408,
convert: 'USD',
},
});
});
test('returns null for USDC with an unknown Stellar issuer', async () => {
const coinmarketcap = loadSource();
const wrongIssuer = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
const price = await coinmarketcap.fetchPrice('USDC', wrongIssuer);
expect(price).toBeNull();
expect(mockGet).not.toHaveBeenCalled();
expect(mockLogger.debug).toHaveBeenCalledWith(
'Issuer not supported by CoinMarketCap',
{ assetCode: 'USDC', issuer: wrongIssuer }
);
});
test('throws non-retryable HTTP 401 errors for invalid API keys', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
expect(authError.nonRetryable).toBe(true);
expect(mockLogger.warn).toHaveBeenCalledWith(
'CoinMarketCap authentication failed',
{ assetCode: 'XLM' }
);
});
test('returns null and logs retry_after on HTTP 429 rate limits', async () => {
const coinmarketcap = loadSource();
const rateLimitError = new Error('too many requests');
rateLimitError.response = {
status: 429,
headers: { 'retry-after': '60' },
};
mockGet.mockRejectedValueOnce(rateLimitError);
const price = await coinmarketcap.fetchPrice('XLM');
expect(price).toBeNull();
expect(mockLogger.warn).toHaveBeenCalledWith(
'CoinMarketCap rate limit hit',
{ assetCode: 'XLM', retry_after: '60' }
);
});
test('returns null when CMC omits quote data for a mapped symbol', async () => {
const coinmarketcap = loadSource();
mockGet.mockResolvedValueOnce({ data: { data: { XLM: {} } } });
await expect(coinmarketcap.fetchPrice('XLM')).resolves.toBeNull();
});
describe('circuit breaker (#95)', () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
});
afterEach(() => {
jest.useRealTimers();
});
test('opens the circuit on a 401 and skips the HTTP request on the next fetch', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
expect(coinmarketcap.getCircuitState()).toEqual({
source: 'coinmarketcap',
open: true,
openUntil: new Date('2026-01-01T00:15:00.000Z').toISOString(),
last_success_at: null,
});
mockGet.mockClear();
const price = await coinmarketcap.fetchPrice('XLM');
expect(price).toBeNull();
expect(mockGet).not.toHaveBeenCalled();
});
test('retries the source after the cooldown window elapses', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
jest.advanceTimersByTime(900001);
mockGet.mockClear();
mockGet.mockResolvedValueOnce(quoteResponse('XLM', 0.15));
const price = await coinmarketcap.fetchPrice('XLM');
expect(mockGet).toHaveBeenCalledTimes(1);
expect(price).toBe(0.15);
});
test('a successful retry closes the circuit', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
jest.advanceTimersByTime(900001);
mockGet.mockResolvedValueOnce(quoteResponse('XLM', 0.15));
await coinmarketcap.fetchPrice('XLM');
expect(coinmarketcap.getCircuitState()).toEqual({
source: 'coinmarketcap',
open: false,
openUntil: null,
last_success_at: '2026-01-01T00:15:00.001Z',
});
});
test('a fresh 401 after cooldown re-opens the circuit with a new window', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
jest.advanceTimersByTime(900001);
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
expect(coinmarketcap.getCircuitState().open).toBe(true);
expect(mockLogger.error).toHaveBeenCalledTimes(2);
});
test('the first 401 logs distinctly at error level; repeated skips while open do not', async () => {
const coinmarketcap = loadSource();
const authError = new Error('unauthorized');
authError.response = { status: 401 };
mockGet.mockRejectedValueOnce(authError);
await expect(coinmarketcap.fetchPrice('XLM')).rejects.toThrow('unauthorized');
expect(mockLogger.error).toHaveBeenCalledTimes(1);
expect(mockLogger.error).toHaveBeenCalledWith(
'Price source permanently misconfigured',
expect.objectContaining({ source: 'coinmarketcap' })
);
await coinmarketcap.fetchPrice('XLM');
await coinmarketcap.fetchPrice('XLM');
expect(mockLogger.error).toHaveBeenCalledTimes(1);
});
test('429s are unaffected by the circuit breaker', async () => {
const coinmarketcap = loadSource();
const rateLimitError = new Error('too many requests');
rateLimitError.response = { status: 429 };
mockGet.mockRejectedValue(rateLimitError);
await coinmarketcap.fetchPrice('XLM');
const price = await coinmarketcap.fetchPrice('XLM');
expect(price).toBeNull();
expect(mockGet).toHaveBeenCalledTimes(2);
expect(coinmarketcap.getCircuitState().open).toBe(false);
});
});
describe('isSupported', () => {
test('is true for an asset with no issuer required (XLM)', () => {
const coinmarketcap = loadSource();
expect(coinmarketcap.isSupported('XLM')).toBe(true);
});
test('is true for a configured asset:issuer pair (USDC)', () => {
const coinmarketcap = loadSource();
expect(coinmarketcap.isSupported('USDC', mockUsdcIssuer)).toBe(true);
});
test('is false for an issuer not present in assetIssuerMap', () => {
const coinmarketcap = loadSource();
expect(coinmarketcap.isSupported('USDC', 'GSOMEOTHERISSUER')).toBe(
false,
);
});
test('is false for an asset with no mapping at all', () => {
const coinmarketcap = loadSource();
expect(coinmarketcap.isSupported('SOME_UNKNOWN_ASSET')).toBe(false);
});
});
});