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
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
100 changes: 88 additions & 12 deletions backend/src/modules/blockchain/oracle.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,38 @@ import { HttpService } from '@nestjs/axios';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { firstValueFrom } from 'rxjs';
import axios, { AxiosError } from 'axios';
import { ConfigService } from '@nestjs/config';

export interface PriceData {
[symbol: string]: {
usd: number;
};
}

export interface OracleConfig {
coingeckoApiUrl: string;
cacheTtlMs: number;
fallbackPrices: Record<string, number>;
}

@Injectable()
export class OracleService {
private readonly logger = new Logger(OracleService.name);
private readonly COINGECKO_API_URL = 'https://api.coingecko.com/api/v3';
private readonly CACHE_TTL = 300000; // 5 minutes in milliseconds

// Fallback prices in case API fails
private readonly FALLBACK_PRICES: Record<string, number> = {
stellar: 0.12, // XLM fallback price
aqua: 0.25, // AQUA fallback price
'usd-coin': 1.0, // USDC fallback
};

constructor(
private readonly httpService: HttpService,
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
private readonly configService: ConfigService,
) {}

/**
Expand Down Expand Up @@ -124,6 +140,7 @@ export class OracleService {

/**
* Get cached price for an asset or fetch fresh price if not cached
* Uses both HttpService (NestJS axios) and direct axios for fallback
* @param assetId CoinGecko asset ID
* @returns Price in USD
*/
Expand All @@ -139,21 +156,57 @@ export class OracleService {

try {
this.logger.debug(`Fetching fresh price for: ${assetId}`);
const response = await firstValueFrom(
this.httpService.get<PriceData>(
`${this.COINGECKO_API_URL}/simple/price`,
{
params: {
ids: assetId,
vs_currencies: 'usd',
},
},
),
);

const price = response.data[assetId]?.usd;
// Try HttpService first (NestJS axios)
let price: number | undefined;

try {
const response = await firstValueFrom(
this.httpService.get<PriceData>(
`${this.COINGECKO_API_URL}/simple/price`,
{
params: {
ids: assetId,
vs_currencies: 'usd',
},
},
),
);
price = response.data[assetId]?.usd;
} catch (httpError) {
this.logger.warn(
`HttpService failed for ${assetId}, trying direct axios: ${(httpError as Error).message}`,
);

// Fallback to direct axios call
try {
const axiosResponse = await axios.get<PriceData>(
`${this.COINGECKO_API_URL}/simple/price`,
{
params: {
ids: assetId,
vs_currencies: 'usd',
},
timeout: 5000,
},
);
price = axiosResponse.data[assetId]?.usd;
} catch (axiosError) {
this.logger.error(
`Direct axios also failed for ${assetId}: ${(axiosError as Error).message}`,
);
}
}

if (price === undefined) {
// Use fallback price
const fallbackPrice = this.FALLBACK_PRICES[assetId];
if (fallbackPrice !== undefined) {
this.logger.warn(
`Using fallback price for ${assetId}: ${fallbackPrice}`,
);
return fallbackPrice;
}
this.logger.warn(`Price not found for asset: ${assetId}`);
return 0;
}
Expand All @@ -167,7 +220,30 @@ export class OracleService {
`Failed to fetch price for asset ${assetId}: ${(error as Error).message}`,
error,
);

// Return fallback price if available
const fallbackPrice = this.FALLBACK_PRICES[assetId];
if (fallbackPrice !== undefined) {
return fallbackPrice;
}
return 0;
}
}

/**
* Get all supported asset prices in a single batch call
* Optimized for fetching multiple prices at once to reduce API calls
* @returns Map of asset IDs to USD prices
*/
async getAllPrices(): Promise<Map<string, number>> {
const assetIds = ['stellar', 'aqua', 'usd-coin'];
const prices = new Map<string, number>();

for (const assetId of assetIds) {
const price = await this.getCachedPrice(assetId);
prices.set(assetId, price);
}

return prices;
}
}
25 changes: 20 additions & 5 deletions backend/src/modules/governance/dto/proposal-list-item.dto.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ProposalCategory, ProposalStatus } from '../entities/governance-proposal.entity';
import {
ProposalCategory,
ProposalStatus,
} from '../entities/governance-proposal.entity';

export class ProposalTimelineDto {
@ApiProperty({ description: 'Proposal start boundary as UNIX block number', nullable: true })
@ApiProperty({
description: 'Proposal start boundary as UNIX block number',
nullable: true,
})
startTime: number | null;

@ApiProperty({ description: 'Proposal end boundary as UNIX block number', nullable: true })
@ApiProperty({
description: 'Proposal end boundary as UNIX block number',
nullable: true,
})
endTime: number | null;
}

Expand All @@ -31,10 +40,16 @@ export class ProposalListItemDto {
@ApiPropertyOptional()
proposer: string | null;

@ApiProperty({ description: 'Percentage of votes cast FOR (0–100)', example: 62.5 })
@ApiProperty({
description: 'Percentage of votes cast FOR (0–100)',
example: 62.5,
})
forPercent: number;

@ApiProperty({ description: 'Percentage of votes cast AGAINST (0–100)', example: 37.5 })
@ApiProperty({
description: 'Percentage of votes cast AGAINST (0–100)',
example: 37.5,
})
againstPercent: number;

@ApiProperty({ type: () => ProposalTimelineDto })
Expand Down
Loading
Loading