diff --git a/backend/src/services/stellar.ts b/backend/src/services/stellar.ts index b719bc4..30f0919 100644 --- a/backend/src/services/stellar.ts +++ b/backend/src/services/stellar.ts @@ -12,6 +12,9 @@ import { import { getFeatureFlags } from '../config/featureFlags.js' import { rebalanceHistoryService, riskManagementService } from './serviceContainer.js' +const DAY_MS = 24 * 60 * 60 * 1000 +const DAY_CHANGE_WINDOW_MS = 2 * 60 * 60 * 1000 + interface StoredPortfolio { id: string userAddress: string @@ -560,25 +563,23 @@ export class StellarService { needsRebalance, lastRebalance: portfolio.lastRebalance, threshold: portfolio.threshold, - dayChange: this.calculateDayChange(allocations) + dayChange: await this.calculateDayChange(portfolioId) } } catch (error) { throw new Error(`Failed to fetch portfolio: ${error}`) } } - private calculateDayChange(allocations: Array<{ current: number }>): number { - let weightedChange = 0 - let totalWeight = 0 - - for (const allocation of allocations) { - const priceChange = Math.random() * 4 - 2 - const weight = allocation.current / 100 - weightedChange += priceChange * weight - totalWeight += weight - } - - return totalWeight > 0 ? weightedChange / totalWeight : 0 + /** + * Real 24h change from recorded analytics snapshots (#57): the snapshot + * closest to 24h ago (within a 2h window) against the latest one, the same + * calculation `calculatePerformanceMetrics` uses for `dailyChange`. + * Returns null when there isn't enough history, so the dashboard shows + * "—" instead of a made-up number. This used to be `Math.random()`. + */ + private async calculateDayChange(portfolioId: string): Promise { + const { analyticsService } = await import('./analyticsService.js') + return analyticsService.getChangeForWindow(portfolioId, DAY_MS, DAY_CHANGE_WINDOW_MS) } private roundAmount(amount: number): number { diff --git a/backend/src/test/dayChange.test.ts b/backend/src/test/dayChange.test.ts new file mode 100644 index 0000000..dbd0c02 --- /dev/null +++ b/backend/src/test/dayChange.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +// #57 — getPortfolio().dayChange must come from recorded snapshots, never +// from Math.random(), and must be null when there is no history to compare. + +const { getChangeForWindow } = vi.hoisted(() => ({ getChangeForWindow: vi.fn() })) + +vi.mock('../services/analyticsService.js', () => ({ + analyticsService: { getChangeForWindow } +})) + +vi.mock('../services/portfolioStorage.js', () => ({ + portfolioStorage: { + getPortfolio: vi.fn(async () => ({ + id: 'p1', + userAddress: 'GUSER', + allocations: { XLM: 60, USDC: 40 }, + balances: { XLM: 100, USDC: 50 }, + threshold: 5, + totalValue: 0, + createdAt: '2026-01-01T00:00:00.000Z', + lastRebalance: '2026-01-01T00:00:00.000Z' + })) + } +})) + +vi.mock('../services/reflector.js', () => ({ + ReflectorService: class { + async getCurrentPrices() { + return { XLM: { price: 0.5 }, USDC: { price: 1 } } + } + } +})) + +vi.mock('../services/serviceContainer.js', () => ({ + rebalanceHistoryService: {}, + riskManagementService: {} +})) + +import { StellarService } from '../services/stellar.js' + +describe('StellarService.getPortfolio dayChange (#57)', () => { + beforeEach(() => { + getChangeForWindow.mockReset() + }) + + it('uses the 24h snapshot change with a 2h tolerance window', async () => { + getChangeForWindow.mockResolvedValue(3.25) + const randomSpy = vi.spyOn(Math, 'random') + + const portfolio = await new StellarService().getPortfolio('p1') + + expect(portfolio.dayChange).toBe(3.25) + expect(getChangeForWindow).toHaveBeenCalledWith('p1', 24 * 60 * 60 * 1000, 2 * 60 * 60 * 1000) + expect(randomSpy).not.toHaveBeenCalled() + randomSpy.mockRestore() + }) + + it('is null when there is no snapshot history', async () => { + getChangeForWindow.mockResolvedValue(null) + + const portfolio = await new StellarService().getPortfolio('p1') + + expect(portfolio.dayChange).toBeNull() + }) + + it('is stable across calls for the same history', async () => { + getChangeForWindow.mockResolvedValue(-1.5) + const service = new StellarService() + + const first = await service.getPortfolio('p1') + const second = await service.getPortfolio('p1') + + expect(first.dayChange).toBe(second.dayChange) + }) +})