Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions backend/src/services/stellar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<number | null> {
const { analyticsService } = await import('./analyticsService.js')
return analyticsService.getChangeForWindow(portfolioId, DAY_MS, DAY_CHANGE_WINDOW_MS)
}

private roundAmount(amount: number): number {
Expand Down
76 changes: 76 additions & 0 deletions backend/src/test/dayChange.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading