forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriceOracle.test.js
More file actions
739 lines (593 loc) · 25.9 KB
/
Copy pathpriceOracle.test.js
File metadata and controls
739 lines (593 loc) · 25.9 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
'use strict';
// Unit tests for the price oracle's core business logic: median aggregation,
// temporal anomaly detection, multi-source fan-out, and the cache hit/miss
// paths of getPrice/fetchFreshPrice/refreshAllCachedPrices.
//
// NOTE ON BEHAVIOUR: detectAnomaly compares the current aggregated price
// against the *previously cached aggregate over time* and only logs a warning.
// It does NOT exclude an outlier source from the median, and fetchFreshPrice
// ignores its return value. These tests document that actual behaviour rather
// than an assumed cross-source outlier-rejection scheme.
const mockCacheGet = jest.fn();
const mockCacheSet = jest.fn();
const mockCacheIsConnected = jest.fn();
const mockCacheGetClient = jest.fn();
const mockStellarFetch = jest.fn();
const mockCoingeckoFetch = jest.fn();
const mockCoinmarketcapFetch = jest.fn();
const mockStellarIsSupported = jest.fn();
const mockCoingeckoIsSupported = jest.fn();
const mockCoinmarketcapIsSupported = jest.fn();
const mockLogger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
};
jest.mock('../src/services/cache', () => ({
get: mockCacheGet,
set: mockCacheSet,
isConnected: mockCacheIsConnected,
getClient: mockCacheGetClient,
}));
jest.mock('../src/services/sources/stellarDex', () => ({
fetchPrice: mockStellarFetch,
isSupported: mockStellarIsSupported,
}));
jest.mock('../src/services/sources/coingecko', () => ({
fetchPrice: mockCoingeckoFetch,
isSupported: mockCoingeckoIsSupported,
}));
jest.mock('../src/services/sources/coinmarketcap', () => ({
fetchPrice: mockCoinmarketcapFetch,
isSupported: mockCoinmarketcapIsSupported,
}));
jest.mock('../src/config', () => ({
price: {
cacheTtl: 60,
refreshInterval: 30,
staleThresholdMinutes: 5,
anomalyThresholdPercent: 20,
minSources: 2,
anomalyAction: 'warn',
refreshMaxCycleMs: 90000,
circuitBreaker: {
failureThreshold: 3,
successThreshold: 1,
timeoutMs: 30000,
},
},
priceSources: {
circuitCooldownMs: 900000,
circuitReminderIntervalMs: 300000,
},
}));
jest.mock('../src/logger', () => mockLogger);
const oracle = require('../src/services/priceOracle');
beforeEach(() => {
mockCacheGet.mockReset();
mockCacheSet.mockReset();
mockCacheIsConnected.mockReset();
mockCacheGetClient.mockReset();
mockStellarFetch.mockReset();
mockCoingeckoFetch.mockReset();
mockCoinmarketcapFetch.mockReset();
mockStellarIsSupported.mockReset();
mockCoingeckoIsSupported.mockReset();
mockCoinmarketcapIsSupported.mockReset();
Object.values(mockLogger).forEach((fn) => fn.mockClear());
// Sensible defaults: cache writes succeed, cache empty unless a test says
// otherwise; every source supports every asset unless a test says
// otherwise, so existing tests that never touch isSupported keep exercising
// the breaker-wrapped fetch path exactly as before #130's fix.
mockCacheGet.mockResolvedValue(null);
mockCacheSet.mockResolvedValue(undefined);
mockStellarIsSupported.mockReturnValue(true);
mockCoingeckoIsSupported.mockReturnValue(true);
mockCoinmarketcapIsSupported.mockReturnValue(true);
// #130's tests deliberately trip breakers via repeated failures; reset
// them after every test so state never leaks into the next one.
oracle.resetCircuitBreakers();
});
describe('median', () => {
const { median } = oracle;
test('returns null for an empty array', () => {
expect(median([])).toBeNull();
});
test('returns the single value for a one-element array', () => {
expect(median([5])).toBe(5);
});
test('averages the middle two for an even-length array', () => {
expect(median([1, 3])).toBe(2);
expect(median([4, 1, 3, 2])).toBe(2.5);
});
test('returns the middle value for an odd-length array', () => {
expect(median([1, 2, 3])).toBe(2);
});
test('does not mutate the input array (sorts a copy)', () => {
const input = [3, 1, 2];
median(input);
expect(input).toEqual([3, 1, 2]);
});
test('sorts numerically, not lexicographically', () => {
// Lexicographic sort would order these as [10, 100, 9] and return 100.
expect(median([9, 10, 100])).toBe(10);
});
test('resists a single outlier print across three sources', () => {
// The median is naturally robust to one bad print even though no source
// is explicitly excluded.
expect(median([1.0, 1.01, 50])).toBe(1.01);
});
});
describe('detectAnomaly', () => {
const { detectAnomaly } = oracle;
const ASSET = 'XLM';
test('stores the price and returns anomalous: false when no history exists', async () => {
mockCacheGet.mockResolvedValueOnce(null);
const result = await detectAnomaly(0.1, ASSET, null);
expect(result).toEqual({ anomalous: false, changePercent: 0 });
expect(mockCacheSet).toHaveBeenCalledWith(
'price:history:XLM',
expect.objectContaining({ price: 0.1 }),
3600
);
});
test('treats a non-positive cached price as no history', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 0, timestamp: Date.now() });
const result = await detectAnomaly(0.1, ASSET, null);
expect(result).toEqual({ anomalous: false, changePercent: 0 });
expect(mockCacheSet).toHaveBeenCalledWith(
'price:history:XLM',
expect.objectContaining({ price: 0.1 }),
3600
);
});
test('returns anomalous: false for a change below the threshold', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 1.0, timestamp: Date.now() });
const result = await detectAnomaly(1.1, ASSET, null); // +10%, threshold 20
expect(result.anomalous).toBe(false);
expect(mockLogger.warn).not.toHaveBeenCalled();
});
test('returns anomalous: false at exactly the threshold (strict greater-than boundary)', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 1.0, timestamp: Date.now() });
const result = await detectAnomaly(1.2, ASSET, null); // exactly +20%
expect(result.anomalous).toBe(false);
expect(mockLogger.warn).not.toHaveBeenCalled();
});
test('logs a warning and returns anomalous: true just past the threshold', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 1.0, timestamp: Date.now() });
const result = await detectAnomaly(1.21, ASSET, null); // +21%
expect(result.anomalous).toBe(true);
expect(result.changePercent).toBeCloseTo(21, 0);
expect(mockLogger.warn).toHaveBeenCalledWith(
'Price anomaly detected',
expect.objectContaining({ assetCode: ASSET, previousPrice: 1.0, currentPrice: 1.21 })
);
});
test('detects anomalies symmetrically on a downward move', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 1.0, timestamp: Date.now() });
const result = await detectAnomaly(0.5, ASSET, null); // -50%
expect(result.anomalous).toBe(true);
});
test('re-stores the current price even when an anomaly fires', async () => {
mockCacheGet.mockResolvedValueOnce({ price: 1.0, timestamp: Date.now() });
await detectAnomaly(2.0, ASSET, null);
expect(mockCacheSet).toHaveBeenCalledWith(
'price:history:XLM',
expect.objectContaining({ price: 2.0 }),
3600
);
});
test('uses an issuer-scoped history key when an issuer is provided', async () => {
mockCacheGet.mockResolvedValueOnce(null);
await detectAnomaly(1.0, 'USDC', 'GISSUER');
expect(mockCacheGet).toHaveBeenCalledWith('price:history:USDC:GISSUER');
});
test('skips detection and returns false when the cache read fails', async () => {
mockCacheGet.mockRejectedValueOnce(new Error('redis down'));
const result = await detectAnomaly(1.0, ASSET, null);
expect(result).toEqual({ anomalous: false, changePercent: 0 });
expect(mockLogger.warn).toHaveBeenCalledWith(
'Cache read failed in anomaly detection, skipping',
expect.objectContaining({ error: 'redis down' })
);
expect(mockCacheSet).not.toHaveBeenCalled();
});
test('swallows a cache write failure without throwing', async () => {
mockCacheGet.mockResolvedValueOnce(null);
mockCacheSet.mockRejectedValueOnce(new Error('write failed'));
await expect(detectAnomaly(1.0, ASSET, null)).resolves.toEqual({ anomalous: false, changePercent: 0 });
expect(mockLogger.warn).toHaveBeenCalledWith(
'Cache write failed in anomaly detection',
expect.objectContaining({ error: 'write failed' })
);
});
});
describe('fetchFromAllSources', () => {
const { fetchFromAllSources } = oracle;
test('returns a result entry for every source that succeeds', async () => {
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoingeckoFetch.mockResolvedValueOnce(0.11);
mockCoinmarketcapFetch.mockResolvedValueOnce(0.12);
const results = await fetchFromAllSources('XLM', null);
expect(results).toEqual([
{ source: 'stellar_dex', price: 0.1 },
{ source: 'coingecko', price: 0.11 },
{ source: 'coinmarketcap', price: 0.12 },
]);
});
test('fetchFreshPrice aggregates successful source prices by median', async () => {
mockCacheGet.mockResolvedValue(null);
mockStellarFetch.mockResolvedValueOnce(100);
mockCoingeckoFetch.mockResolvedValueOnce(10);
mockCoinmarketcapFetch.mockResolvedValueOnce(11);
const result = await oracle.fetchFreshPrice('XLM', null);
expect(result.price_usd).toBe(11);
expect(result.quorum_met).toBe(true);
expect(result.sources_attempted).toEqual(['stellar_dex', 'coingecko', 'coinmarketcap']);
});
test('swallows a throwing source and returns the healthy ones', async () => {
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoingeckoFetch.mockRejectedValueOnce(new Error('timeout'));
mockCoinmarketcapFetch.mockResolvedValueOnce(0.12);
const results = await fetchFromAllSources('XLM', null);
expect(results).toEqual([
{ source: 'stellar_dex', price: 0.1 },
{ source: 'coinmarketcap', price: 0.12 },
]);
expect(mockLogger.warn).toHaveBeenCalledWith(
'Source fetch failed',
expect.objectContaining({ source: 'coingecko', error: 'timeout' })
);
});
test('returns an empty array when every source throws', async () => {
mockStellarFetch.mockRejectedValueOnce(new Error('a'));
mockCoingeckoFetch.mockRejectedValueOnce(new Error('b'));
mockCoinmarketcapFetch.mockRejectedValueOnce(new Error('c'));
const results = await fetchFromAllSources('XLM', null);
expect(results).toEqual([]);
});
test('ignores null and non-positive prices from sources', async () => {
mockStellarFetch.mockResolvedValueOnce(null);
mockCoingeckoFetch.mockResolvedValueOnce(0);
mockCoinmarketcapFetch.mockResolvedValueOnce(0.12);
const results = await fetchFromAllSources('XLM', null);
expect(results).toEqual([{ source: 'coinmarketcap', price: 0.12 }]);
});
test('accepts a single healthy source (no minimum-quorum rule)', async () => {
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoingeckoFetch.mockResolvedValueOnce(null);
mockCoinmarketcapFetch.mockRejectedValueOnce(new Error('down'));
const results = await fetchFromAllSources('XLM', null);
expect(results).toEqual([{ source: 'stellar_dex', price: 0.1 }]);
});
// #130: a source that doesn't support the requested asset must never
// reach the circuit breaker at all — that's a permanent, per-asset
// condition, not a signal about the source's health.
describe('unsupported-asset false-trip regression (#130)', () => {
test('skips a source entirely, never calling fetch, when it does not support the asset', async () => {
mockCoingeckoIsSupported.mockReturnValue(false);
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoinmarketcapFetch.mockResolvedValueOnce(0.12);
const results = await fetchFromAllSources('USDC', null);
expect(mockCoingeckoFetch).not.toHaveBeenCalled();
expect(results).toEqual([
{ source: 'stellar_dex', price: 0.1 },
{ source: 'coinmarketcap', price: 0.12 },
]);
});
test('many repeated lookups for an unsupported asset never trip that source open, and a supported asset keeps succeeding via it throughout', async () => {
mockCoingeckoIsSupported.mockImplementation((assetCode) => assetCode === 'XLM');
// Simulate 5 consecutive refresh-cycle lookups for an asset CoinGecko
// was never mapped for (default failureThreshold is 3 — if these
// reached the breaker, it would already be open by the 3rd).
for (let i = 0; i < 5; i += 1) {
// eslint-disable-next-line no-await-in-loop
await fetchFromAllSources('SOME_UNMAPPED_ASSET', null);
}
expect(mockCoingeckoFetch).not.toHaveBeenCalled();
expect(oracle.getCircuitStates().coingecko).toBe('closed');
// A CoinGecko-supported asset fetched right after still gets a
// CoinGecko contribution — the breaker was never touched.
mockCoingeckoFetch.mockResolvedValueOnce(0.11);
const results = await fetchFromAllSources('XLM', null);
expect(results).toContainEqual({ source: 'coingecko', price: 0.11 });
});
test('a source still trips open after failureThreshold genuine failures for an asset it supports', async () => {
mockCoingeckoIsSupported.mockReturnValue(true);
mockCoingeckoFetch.mockResolvedValue(null); // genuine "no data" every time, for a supported asset
// Default failureThreshold is 3 (no config.price.circuitBreaker override in this suite).
await fetchFromAllSources('XLM', null);
await fetchFromAllSources('XLM', null);
await fetchFromAllSources('XLM', null);
expect(oracle.getCircuitStates().coingecko).toBe('open');
// Once open, the breaker itself skips the call — fetch is not
// invoked a 4th time even though this asset is supported.
mockCoingeckoFetch.mockClear();
mockCoingeckoFetch.mockResolvedValueOnce(0.11);
await fetchFromAllSources('XLM', null);
expect(mockCoingeckoFetch).not.toHaveBeenCalled();
});
});
});
describe('getPrice', () => {
const { getPrice } = oracle;
test('returns a fresh cached price with is_stale false on a cache hit', async () => {
const fetchedAt = Date.now() - 60 * 1000; // 1 minute old, threshold 5
mockCacheGet.mockResolvedValueOnce({
price: 1.01,
source: 'coingecko',
fetchedAt,
sourcesAttempted: ['stellar_dex', 'coingecko'],
});
const result = await getPrice('USDC', 'GISSUER');
expect(result).toMatchObject({
asset_code: 'USDC',
issuer: 'GISSUER',
price_usd: 1.01,
source: 'coingecko',
is_stale: false,
stale_warning: null,
sources_attempted: ['stellar_dex', 'coingecko'],
redis_unavailable: false,
});
// Cache hit must not fan out to the sources.
expect(mockStellarFetch).not.toHaveBeenCalled();
});
test('flags is_stale and emits a warning when the cached entry is old', async () => {
const fetchedAt = Date.now() - 10 * 60 * 1000; // 10 minutes old, threshold 5
mockCacheGet.mockResolvedValueOnce({
price: 1.01,
source: 'coingecko',
fetchedAt,
sourcesAttempted: ['coingecko'],
});
const result = await getPrice('USDC', null);
expect(result.is_stale).toBe(true);
expect(result.stale_warning).toMatch(/threshold: 5 min/);
});
test('defaults sources_attempted to an empty array when absent from the cache entry', async () => {
mockCacheGet.mockResolvedValueOnce({
price: 1.01,
source: 'coingecko',
fetchedAt: Date.now(),
});
const result = await getPrice('USDC', null);
expect(result.sources_attempted).toEqual([]);
});
test('falls through to a fresh fetch and caches the result on a cache miss', async () => {
mockCacheGet.mockResolvedValueOnce(null); // miss
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoingeckoFetch.mockResolvedValueOnce(0.12);
mockCoinmarketcapFetch.mockResolvedValueOnce(0.11);
const result = await getPrice('XLM', null);
// median([0.1, 0.12, 0.11]) === 0.11
expect(result.price_usd).toBe(0.11);
expect(result.is_stale).toBe(false);
expect(result.sources_attempted).toEqual(['stellar_dex', 'coingecko', 'coinmarketcap']);
// Result is written back to the main cache key.
expect(mockCacheSet).toHaveBeenCalledWith(
'price:XLM',
expect.objectContaining({ price: 0.11, source: 'stellar_dex' }),
60
);
});
test('marks redis_unavailable and still fetches when the cache read throws', async () => {
mockCacheGet.mockRejectedValueOnce(new Error('redis down'));
mockStellarFetch.mockResolvedValueOnce(0.1);
mockCoingeckoFetch.mockResolvedValueOnce(0.1);
mockCoinmarketcapFetch.mockResolvedValueOnce(0.1);
const result = await getPrice('XLM', null);
expect(result.redis_unavailable).toBe(true);
expect(result.price_usd).toBe(0.1);
// When redis is unavailable we must not attempt to write back.
expect(mockCacheSet).not.toHaveBeenCalled();
});
});
describe('fetchFreshPrice', () => {
const { fetchFreshPrice } = oracle;
test('returns the unavailable shape when no source has data', async () => {
mockStellarFetch.mockResolvedValueOnce(null);
mockCoingeckoFetch.mockRejectedValueOnce(new Error('down'));
mockCoinmarketcapFetch.mockResolvedValueOnce(null);
const result = await fetchFreshPrice('XLM', null);
expect(result).toMatchObject({
price_usd: null,
source: 'unavailable',
is_stale: true,
stale_warning: 'No price data available from any source',
});
expect(mockCacheSet).not.toHaveBeenCalled();
});
test('runs anomaly detection against the aggregated price when redis is available', async () => {
// No price history yet -> detectAnomaly stores the aggregate and the main key.
mockCacheGet.mockResolvedValue(null);
mockStellarFetch.mockResolvedValueOnce(1.0);
mockCoingeckoFetch.mockResolvedValueOnce(1.0);
mockCoinmarketcapFetch.mockResolvedValueOnce(1.0);
await fetchFreshPrice('USDC', null);
expect(mockCacheSet).toHaveBeenCalledWith(
'price:history:USDC',
expect.objectContaining({ price: 1.0 }),
3600
);
});
test('skips anomaly detection and cache writes when redisUnavailable is true', async () => {
mockStellarFetch.mockResolvedValueOnce(1.0);
mockCoingeckoFetch.mockResolvedValueOnce(1.0);
mockCoinmarketcapFetch.mockResolvedValueOnce(1.0);
const result = await fetchFreshPrice('USDC', null, true);
expect(result.redis_unavailable).toBe(true);
expect(mockCacheSet).not.toHaveBeenCalled();
expect(mockCacheGet).not.toHaveBeenCalled();
});
test('degrades to redis_unavailable when the cache write fails', async () => {
mockCacheGet.mockResolvedValue(null);
mockCacheSet
.mockResolvedValueOnce(undefined) // detectAnomaly history write succeeds
.mockRejectedValueOnce(new Error('write failed')); // main cache write fails
mockStellarFetch.mockResolvedValueOnce(1.0);
mockCoingeckoFetch.mockResolvedValueOnce(1.0);
mockCoinmarketcapFetch.mockResolvedValueOnce(1.0);
const result = await fetchFreshPrice('USDC', null);
expect(result.price_usd).toBe(1.0);
expect(result.redis_unavailable).toBe(true);
expect(mockLogger.warn).toHaveBeenCalledWith(
'Cache write failed, continuing without caching',
expect.objectContaining({ error: 'write failed' })
);
});
});
describe('refreshAllCachedPrices', () => {
const { refreshAllCachedPrices } = oracle;
test('skips the cycle when redis is not connected', async () => {
mockCacheIsConnected.mockReturnValue(false);
const result = await refreshAllCachedPrices();
expect(result).toBeUndefined();
expect(mockCacheGetClient).not.toHaveBeenCalled();
expect(mockLogger.warn).toHaveBeenCalledWith(
'Redis unavailable, skipping scheduled price refresh cycle'
);
});
test('scans cached keys, refreshes prices, and skips history keys', async () => {
mockCacheIsConnected.mockReturnValue(true);
const redis = {
scan: jest
.fn()
// single scan pass: returns cursor '0' to terminate, with one price key and one history key
.mockResolvedValueOnce(['0', ['price:XLM', 'price:history:XLM']]),
};
mockCacheGetClient.mockReturnValue(redis);
// The refresh re-fetches fresh prices for the matched (non-history) key.
mockStellarFetch.mockResolvedValue(0.1);
mockCoingeckoFetch.mockResolvedValue(0.1);
mockCoinmarketcapFetch.mockResolvedValue(0.1);
const result = await refreshAllCachedPrices();
expect(redis.scan).toHaveBeenCalledWith('0', 'MATCH', 'price:*', 'COUNT', 100);
// Only the non-history key is refreshed.
expect(mockStellarFetch).toHaveBeenCalledWith('XLM', null);
expect(result).toEqual({ XLM: { price: 0.1, source: 'stellar_dex' } });
});
test('aborts the cycle when the redis scan throws', async () => {
mockCacheIsConnected.mockReturnValue(true);
const redis = { scan: jest.fn().mockRejectedValueOnce(new Error('scan failed')) };
mockCacheGetClient.mockReturnValue(redis);
const result = await refreshAllCachedPrices();
expect(result).toBeUndefined();
expect(mockLogger.warn).toHaveBeenCalledWith(
'Redis scan failed during price refresh, aborting cycle',
expect.objectContaining({ error: 'scan failed' })
);
});
});
// ---------------------------------------------------------------------------
// #69: single-flight dedup — concurrent callers share one in-flight promise
// ---------------------------------------------------------------------------
describe('fetchFreshPrice single-flight dedup (#69)', () => {
const { fetchFreshPrice, inFlight } = oracle;
beforeEach(() => {
// Ensure no stale in-flight entries from prior tests
inFlight.clear();
});
test('coalesces concurrent callers for the same asset:issuer', async () => {
let callCount = 0;
mockStellarFetch.mockImplementation(async () => {
callCount += 1;
// Simulate async delay
await new Promise((r) => setTimeout(r, 20));
return 0.1;
});
mockCoingeckoFetch.mockImplementation(async () => 0.1);
mockCoinmarketcapFetch.mockImplementation(async () => 0.1);
mockCacheGet.mockResolvedValue(null);
const [a, b, c] = await Promise.all([
fetchFreshPrice('XLM', null),
fetchFreshPrice('XLM', null),
fetchFreshPrice('XLM', null),
]);
// All three should get the same result object
expect(a.price_usd).toBe(0.1);
expect(b.price_usd).toBe(0.1);
expect(c.price_usd).toBe(0.1);
// Sources should have been hit only once, not three times
expect(callCount).toBe(1);
// In-flight map should be clean after completion
expect(inFlight.has('XLM:null')).toBe(false);
});
test('does not coalesce calls for different assets', async () => {
mockStellarFetch.mockImplementation(async () => {
await new Promise((r) => setTimeout(r, 10));
return 0.1;
});
mockCoingeckoFetch.mockImplementation(async () => 0.1);
mockCoinmarketcapFetch.mockImplementation(async () => 0.1);
mockCacheGet.mockResolvedValue(null);
const [a, b] = await Promise.all([
fetchFreshPrice('XLM', null),
fetchFreshPrice('USDC', null),
]);
expect(a.price_usd).toBe(0.1);
expect(b.price_usd).toBe(0.1);
// Each asset should have hit the sources independently
expect(mockStellarFetch).toHaveBeenCalledTimes(2);
});
});
// ---------------------------------------------------------------------------
// #70: quorum_met, anomalous fields, anomaly rejection
// ---------------------------------------------------------------------------
describe('fetchFreshPrice quorum and anomaly fields (#70)', () => {
const { fetchFreshPrice } = oracle;
test('includes quorum_met and anomalous in response', async () => {
mockCacheGet.mockResolvedValue(null);
mockStellarFetch.mockResolvedValueOnce(1.0);
mockCoingeckoFetch.mockResolvedValueOnce(1.0);
mockCoinmarketcapFetch.mockResolvedValueOnce(1.0);
const result = await fetchFreshPrice('XLM', null);
expect(result).toHaveProperty('quorum_met');
expect(result).toHaveProperty('anomalous');
expect(result.quorum_met).toBe(true); // 3 sources >= minSources(2)
expect(result.anomalous).toBe(false);
});
test('quorum_met is false when fewer sources than minSources respond', async () => {
mockCacheGet.mockResolvedValue(null);
mockStellarFetch.mockResolvedValueOnce(1.0);
mockCoingeckoFetch.mockResolvedValue(null);
mockCoinmarketcapFetch.mockRejectedValueOnce(new Error('down'));
const result = await fetchFreshPrice('XLM', null);
expect(result.quorum_met).toBe(false); // 1 source < minSources(2)
expect(result.price_usd).toBe(1.0);
});
test('rejects anomalous price and returns cached price when anomalyAction is reject', async () => {
// Temporarily override config for reject mode
const configMock = require('../src/config');
const originalAction = configMock.price.anomalyAction;
configMock.price.anomalyAction = 'reject';
try {
// Prior history says price was 1.0; current sources report 5.0 (+400%)
// detectAnomaly will detect this as anomalous since 400% > 20% threshold
let callCount = 0;
mockCacheGet.mockReset();
mockCacheGet.mockImplementation(async () => {
callCount += 1;
if (callCount === 1) return { price: 1.0, timestamp: Date.now() }; // detectAnomaly reads history
if (callCount === 2) return { // anomaly rejection reads cached price
price: 1.0,
source: 'coingecko',
fetchedAt: Date.now(),
};
return null;
});
// Sources report 5.0 — a +400% jump from history, well above 20% threshold
mockStellarFetch.mockResolvedValueOnce(5.0);
mockCoingeckoFetch.mockResolvedValueOnce(5.0);
mockCoinmarketcapFetch.mockResolvedValueOnce(5.0);
const result = await fetchFreshPrice('XLM', null);
expect(result.price_usd).toBe(1.0); // rejected anomalous, returned cached
expect(result.anomalous).toBe(true);
expect(result.is_stale).toBe(true);
expect(result.stale_warning).toMatch(/Anomalous price rejected/);
} finally {
configMock.price.anomalyAction = originalAction;
}
});
});