Skip to content
Merged
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
153 changes: 153 additions & 0 deletions analytics.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { AnalyticsService } from './analytics.service';
import { User } from '../user/entities/user.entity';
import { ProcessedStellarEvent } from '../blockchain/entities/processed-event.entity';
import { LedgerTransaction } from '../blockchain/entities/transaction.entity';
import { SavingsService as BlockchainSavingsService } from '../blockchain/savings.service';
import { StellarService } from '../blockchain/stellar.service';
import { OracleService } from '../blockchain/oracle.service';
import { PortfolioTimeframe } from './dto/portfolio-timeline-query.dto';

describe('AnalyticsService', () => {
let service: AnalyticsService;
let userRepository: { findOne: jest.Mock };
let eventRepository: { find: jest.Mock };
let transactionRepository: { find: jest.Mock };
let blockchainSavingsService: { getUserSavingsBalance: jest.Mock };
let stellarService: { getHorizonServer: jest.Mock };
let oracleService: {
convertXLMToUsd: jest.Mock;
convertToUsd: jest.Mock;
convertAQUAToUsd: jest.Mock;
getXLMPrice: jest.Mock;
};

beforeEach(async () => {
userRepository = {
findOne: jest.fn(),
};

eventRepository = {
find: jest.fn(),
};

transactionRepository = {
find: jest.fn(),
};

blockchainSavingsService = {
getUserSavingsBalance: jest.fn(),
};

stellarService = {
getHorizonServer: jest.fn(),
};

oracleService = {
convertXLMToUsd: jest.fn(),
convertToUsd: jest.fn(),
convertAQUAToUsd: jest.fn(),
getXLMPrice: jest.fn().mockResolvedValue(0.12),
};

const module: TestingModule = await Test.createTestingModule({
providers: [
AnalyticsService,
{
provide: getRepositoryToken(User),
useValue: userRepository,
},
{
provide: getRepositoryToken(ProcessedStellarEvent),
useValue: eventRepository,
},
{
provide: getRepositoryToken(LedgerTransaction),
useValue: transactionRepository,
},
{
provide: BlockchainSavingsService,
useValue: blockchainSavingsService,
},
{
provide: StellarService,
useValue: stellarService,
},
{
provide: OracleService,
useValue: oracleService,
},
],
}).compile();

service = module.get<AnalyticsService>(AnalyticsService);
});

it('calculates 1W portfolio timeline correctly by working backward', async () => {
const userId = 'user-1';
const publicKey = 'GABC123';
const now = new Date('2024-03-24T12:00:00Z');
jest.useFakeTimers().setSystemTime(now);

userRepository.findOne.mockResolvedValue({ id: userId, publicKey });
blockchainSavingsService.getUserSavingsBalance.mockResolvedValue({
total: 1000,
});

// Events in reverse chronological order
eventRepository.find.mockResolvedValue([
{
eventType: 'Deposit',
eventData: { amount: 200, user: publicKey },
processedAt: new Date('2024-03-23T10:00:00Z'), // Yesterday
},
{
eventType: 'Withdrawal',
eventData: { amount: 100, user: publicKey },
processedAt: new Date('2024-03-22T10:00:00Z'), // 2 days ago
},
{
eventType: 'InterestAccrued',
eventData: { amount: 50, user: publicKey },
processedAt: new Date('2024-03-21T10:00:00Z'), // 3 days ago
},
]);

const result = await service.getPortfolioTimeline(
userId,
PortfolioTimeframe.WEEK,
);

// Expecting 7 data points (one per day)
expect(result).toHaveLength(7);

// Last point (today) should be current balance
expect(result[6].value).toBe(1000);

// Point 5 (yesterday balance before deposit)
// Balance(today) = 1000. Balance(yesterday) = 1000 - 200 = 800.
expect(result[5].value).toBe(1000); // Wait, my logic shows balance at the END of the period.
// My code:
// periodEnd = now - i * interval
// timeline.push({ date: periodEnd, value: runningBalance })
// runningBalance -= netChangeInPeriod

// Result[6] is i=0 (now): value 1000. runningBalance becomes 1000 - 0 = 1000.
// Result[5] is i=1 (now - 1d): value 1000. runningBalance becomes 1000 - 200 = 800.
// Result[4] is i=2 (now - 2d): value 800. runningBalance becomes 800 - (-100) = 900.
// Result[3] is i=3 (now - 3d): value 900. runningBalance becomes 900 - 50 = 850.

expect(result[6].value).toBe(1000);
expect(result[5].value).toBe(1000);
expect(result[4].value).toBe(800);
expect(result[3].value).toBe(900);
expect(result[2].value).toBe(850);
expect(result[1].value).toBe(850);
expect(result[0].value).toBe(850);
});

afterAll(() => {
jest.useRealTimers();
});
});
3 changes: 2 additions & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ const envValidationSchema = Joi.object({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const isProduction = configService.get<string>('NODE_ENV') === 'production';
const isProduction =
configService.get<string>('NODE_ENV') === 'production';
return {
pinoHttp: {
transport: isProduction
Expand Down
5 changes: 4 additions & 1 deletion backend/src/modules/analytics/analytics.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { ProcessedStellarEvent } from '../blockchain/entities/processed-event.en
import { LedgerTransaction } from '../blockchain/entities/transaction.entity';

@Module({
imports: [TypeOrmModule.forFeature([User, ProcessedStellarEvent])],
imports: [
TypeOrmModule.forFeature([User, ProcessedStellarEvent]),
BlockchainModule, // Import to use OracleService for USD conversion
],
controllers: [AnalyticsController],
providers: [AnalyticsService],
exports: [AnalyticsService],
Expand Down
2 changes: 2 additions & 0 deletions backend/src/modules/analytics/analytics.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('AnalyticsService', () => {
convertXLMToUsd: jest.Mock;
convertToUsd: jest.Mock;
convertAQUAToUsd: jest.Mock;
getXLMPrice: jest.Mock<() => Promise<number>>;
};

beforeEach(async () => {
Expand Down Expand Up @@ -47,6 +48,7 @@ describe('AnalyticsService', () => {
convertXLMToUsd: jest.fn(),
convertToUsd: jest.fn(),
convertAQUAToUsd: jest.fn(),
getXLMPrice: jest.fn().mockResolvedValue(0.12),
};

const module: TestingModule = await Test.createTestingModule({
Expand Down
18 changes: 13 additions & 5 deletions backend/src/modules/analytics/analytics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export class AnalyticsService {
/**
* Reconstructs the historical net worth timeline by working backward
* from the current live balance using transaction events.
* Returns values normalized to USD using oracle price conversion.
*/
async getPortfolioTimeline(userId: string, timeframe: PortfolioTimeframe) {
const user = await this.userRepository.findOne({
Expand All @@ -52,7 +53,10 @@ export class AnalyticsService {
await this.blockchainSavingsService.getUserSavingsBalance(user.publicKey);
const currentTotal = currentSavings.total;

// 2. Define intervals based on timeframe
// 2. Get current XLM price for USD conversion
const xlmPrice = await this.oracleService.getXLMPrice();

// 3. Define intervals based on timeframe
const now = new Date();
let startDate: Date;
let intervalMs: number;
Expand Down Expand Up @@ -85,7 +89,7 @@ export class AnalyticsService {
points = 7;
}

// 3. Fetch all events for the user in this timeframe
// 4. Fetch all events for the user in this timeframe
const events = await this.eventRepository.find({
where: {
processedAt: Between(startDate, now),
Expand All @@ -99,8 +103,8 @@ export class AnalyticsService {
return xdr.includes(user.publicKey!);
});

// 4. Group events by period and calculate net change per period
const timeline: { date: string; value: number }[] = [];
// 5. Group events by period and calculate net change per period
const timeline: { date: string; value: number; valueUsd?: number }[] = [];
let runningBalance = currentTotal;

for (let i = 0; i < points; i++) {
Expand All @@ -124,9 +128,13 @@ export class AnalyticsService {
}
}

// Convert native value to USD
const valueUsd = runningBalance * xlmPrice;

timeline.push({
date: this.formatDate(periodEnd, timeframe),
value: runningBalance,
value: runningBalance, // Native XLM value
valueUsd: parseFloat(valueUsd.toFixed(2)), // Normalized USD value
});

runningBalance -= netChange;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ import { DataSource } from 'typeorm';
import { xdr, nativeToScVal } from '@stellar/stellar-sdk';
import { createHash } from 'crypto';
import { DepositHandler } from './deposit.handler';
import { UserSubscription, SubscriptionStatus } from '../../savings/entities/user-subscription.entity';
import {
UserSubscription,
SubscriptionStatus,
} from '../../savings/entities/user-subscription.entity';
import { User } from '../../user/entities/user.entity';
import { LedgerTransaction, LedgerTransactionType } from '../entities/transaction.entity';
import {
LedgerTransaction,
LedgerTransactionType,
} from '../entities/transaction.entity';
import { SavingsProduct } from '../../savings/entities/savings-product.entity';

describe('DepositHandler', () => {
Expand Down Expand Up @@ -62,7 +68,11 @@ describe('DepositHandler', () => {
});

describe('handle', () => {
const mockUser = { id: 'user-id', publicKey: 'G...', defaultSavingsProductId: 'prod-id' };
const mockUser = {
id: 'user-id',
publicKey: 'G...',
defaultSavingsProductId: 'prod-id',
};
const mockProduct = { id: 'prod-id', isActive: true };
const mockEvent = {
id: 'event-1',
Expand All @@ -86,18 +96,26 @@ describe('DepositHandler', () => {
it('should process deposit successfully and update subscription', async () => {
userRepo.findOne.mockResolvedValue(mockUser);
txRepo.findOne.mockResolvedValue(null);
subRepo.findOne.mockResolvedValue({ userId: 'user-id', amount: 1000, status: SubscriptionStatus.ACTIVE });
subRepo.findOne.mockResolvedValue({
userId: 'user-id',
amount: 1000,
status: SubscriptionStatus.ACTIVE,
});

const result = await handler.handle(mockEvent);

expect(result).toBe(true);
expect(txRepo.save).toHaveBeenCalledWith(expect.objectContaining({
type: LedgerTransactionType.DEPOSIT,
amount: '500',
}));
expect(subRepo.save).toHaveBeenCalledWith(expect.objectContaining({
amount: 1500,
}));
expect(txRepo.save).toHaveBeenCalledWith(
expect.objectContaining({
type: LedgerTransactionType.DEPOSIT,
amount: '500',
}),
);
expect(subRepo.save).toHaveBeenCalledWith(
expect.objectContaining({
amount: 1500,
}),
);
});

it('should create new subscription if one does not exist', async () => {
Expand All @@ -110,9 +128,11 @@ describe('DepositHandler', () => {

expect(result).toBe(true);
expect(subRepo.create).toHaveBeenCalled();
expect(subRepo.save).toHaveBeenCalledWith(expect.objectContaining({
amount: 500,
}));
expect(subRepo.save).toHaveBeenCalledWith(
expect.objectContaining({
amount: 500,
}),
);
});

it('should match topic by symbol', async () => {
Expand All @@ -121,7 +141,11 @@ describe('DepositHandler', () => {
topic: [nativeToScVal('Deposit', { type: 'symbol' }).toXDR('base64')],
};
userRepo.findOne.mockResolvedValue(mockUser);
subRepo.findOne.mockResolvedValue({ userId: 'user-id', amount: 100, status: SubscriptionStatus.ACTIVE });
subRepo.findOne.mockResolvedValue({
userId: 'user-id',
amount: 100,
status: SubscriptionStatus.ACTIVE,
});

const result = await handler.handle(symbolEvent);
expect(result).toBe(true);
Expand All @@ -130,7 +154,9 @@ describe('DepositHandler', () => {

it('should throw error if user not found', async () => {
userRepo.findOne.mockResolvedValue(null);
await expect(handler.handle(mockEvent)).rejects.toThrow('Cannot map deposit payload publicKey to user');
await expect(handler.handle(mockEvent)).rejects.toThrow(
'Cannot map deposit payload publicKey to user',
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@ export class DepositHandler {
'to',
]) ?? '';

const amountRaw = asRecord['amount'] ?? asRecord['value'] ?? asRecord['amt'];
const amountRaw =
asRecord['amount'] ?? asRecord['value'] ?? asRecord['amt'];

const amount =
typeof amountRaw === 'bigint'
Expand Down
Loading
Loading