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
60 changes: 60 additions & 0 deletions backend/src/migrations/1795000000000-CreateProductApySnapshots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { MigrationInterface, QueryRunner, Table, TableIndex } from 'typeorm';

export class CreateProductApySnapshots1795000000000
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'product_apy_snapshots',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
isGenerated: true,
generationStrategy: 'uuid',
},
{ name: 'productId', type: 'uuid' },
{
name: 'apy',
type: 'decimal',
precision: 5,
scale: 2,
},
{
name: 'tvlAmount',
type: 'decimal',
precision: 14,
scale: 2,
default: 0,
},
{
name: 'activeSubscribers',
type: 'int',
default: 0,
},
{ name: 'snapshotDate', type: 'date' },
{ name: 'createdAt', type: 'timestamp', default: 'now()' },
],
}),
true,
);

await queryRunner.createIndex(
'product_apy_snapshots',
new TableIndex({
name: 'IDX_apy_snapshots_product_date',
columnNames: ['productId', 'snapshotDate'],
}),
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropIndex(
'product_apy_snapshots',
'IDX_apy_snapshots_product_date',
);
await queryRunner.dropTable('product_apy_snapshots');
}
}
124 changes: 124 additions & 0 deletions backend/src/modules/savings/dto/product-metrics.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional } from 'class-validator';

export enum MetricsGranularity {
DAILY = 'daily',
WEEKLY = 'weekly',
MONTHLY = 'monthly',
}

export class ProductMetricsQueryDto {
@ApiPropertyOptional({
enum: MetricsGranularity,
default: MetricsGranularity.DAILY,
description: 'Granularity of historical chart data',
})
@IsEnum(MetricsGranularity)
@IsOptional()
granularity?: MetricsGranularity = MetricsGranularity.DAILY;
}

export class ApyDataPointDto {
@ApiProperty({ example: '2026-03-01', description: 'Date of the data point' })
date: string;

@ApiProperty({ example: 4.5, description: 'APY at this point (%)' })
apy: number;
}

export class TvlDataPointDto {
@ApiProperty({ example: '2026-03-01', description: 'Date of the data point' })
date: string;

@ApiProperty({ example: 125000, description: 'TVL at this point' })
tvl: number;
}

export class RiskMetricsDto {
@ApiProperty({
example: 1.42,
description: 'Sharpe ratio (risk-adjusted return)',
})
sharpeRatio: number;

@ApiProperty({
example: 0.85,
description: 'Standard deviation of APY over the period (%)',
})
apyVolatility: number;

@ApiProperty({ example: 4.5, description: 'Maximum APY observed (%)' })
maxApy: number;

@ApiProperty({ example: 3.8, description: 'Minimum APY observed (%)' })
minApy: number;

@ApiProperty({ example: 4.2, description: 'Average APY over the period (%)' })
avgApy: number;
}

export class SimilarProductDto {
@ApiProperty({ description: 'Product UUID' })
id: string;

@ApiProperty({ description: 'Product name' })
name: string;

@ApiProperty({ description: 'Current APY (%)' })
apy: number;

@ApiProperty({ description: 'Current TVL' })
tvl: number;

@ApiProperty({ description: 'Risk level' })
riskLevel: string;
}

export class ProductMetricsDto {
@ApiProperty({ description: 'Product UUID' })
productId: string;

@ApiProperty({ description: 'Product name' })
productName: string;

@ApiProperty({ description: 'Current APY (%)' })
currentApy: number;

@ApiProperty({ description: 'Current TVL' })
currentTvl: number;

@ApiProperty({ description: 'Total active subscribers' })
totalSubscribers: number;

@ApiProperty({
description: 'User retention rate (active / total ever subscribed, 0-100)',
example: 78.5,
})
retentionRate: number;

@ApiProperty({
type: [ApyDataPointDto],
description: 'Historical APY chart data',
})
apyHistory: ApyDataPointDto[];

@ApiProperty({
type: [TvlDataPointDto],
description: 'TVL growth over time',
})
tvlHistory: TvlDataPointDto[];

@ApiProperty({ type: RiskMetricsDto, description: 'Risk-adjusted metrics' })
riskMetrics: RiskMetricsDto;

@ApiProperty({
type: [SimilarProductDto],
description: 'Similar products for comparison',
})
similarProducts: SimilarProductDto[];

@ApiPropertyOptional({
description: 'ISO timestamp when this response was cached',
})
cachedAt?: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
ManyToOne,
JoinColumn,
Index,
} from 'typeorm';
import { SavingsProduct } from './savings-product.entity';

@Entity('product_apy_snapshots')
@Index('IDX_apy_snapshots_product_date', ['productId', 'snapshotDate'])
export class ProductApySnapshot {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
productId: string;

/** APY at the time of snapshot (%) */
@Column('decimal', { precision: 5, scale: 2 })
apy: number;

/** Total Value Locked at snapshot time */
@Column('decimal', { precision: 14, scale: 2, default: 0 })
tvlAmount: number;

/** Number of active subscribers at snapshot time */
@Column('int', { default: 0 })
activeSubscribers: number;

@Column({ type: 'date' })
snapshotDate: Date;

@CreateDateColumn()
createdAt: Date;

@ManyToOne(() => SavingsProduct, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'productId' })
product: SavingsProduct;
}
38 changes: 38 additions & 0 deletions backend/src/modules/savings/savings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ import { CreateGoalDto } from './dto/create-goal.dto';
import { UpdateGoalDto } from './dto/update-goal.dto';
import { SavingsProductDto } from './dto/savings-product.dto';
import { ProductDetailsDto } from './dto/product-details.dto';
import {
MetricsGranularity,
ProductMetricsDto,
ProductMetricsQueryDto,
} from './dto/product-metrics.dto';
import { RecommendationResponseDto } from './dto/recommendation-response.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
Expand Down Expand Up @@ -129,6 +134,39 @@ export class SavingsController {
};
}

@Get('products/:id/metrics')
@UseInterceptors(CacheInterceptor)
@CacheTTL(3600000)
@ApiOperation({
summary: 'Get performance metrics for a savings product',
description:
'Returns historical APY, TVL trends, user retention, risk-adjusted returns (Sharpe ratio), and similar product comparisons. Cached for 1 hour.',
})
@ApiParam({
name: 'id',
type: 'string',
format: 'uuid',
description: 'Product UUID',
})
@ApiQuery({
name: 'granularity',
required: false,
enum: MetricsGranularity,
description: 'Chart data granularity (daily, weekly, monthly)',
})
@ApiResponse({
status: 200,
description: 'Product performance metrics',
type: ProductMetricsDto,
})
@ApiResponse({ status: 404, description: 'Product not found' })
async getProductMetrics(
@Param('id') id: string,
@Query() query: ProductMetricsQueryDto,
): Promise<ProductMetricsDto> {
return this.savingsService.getProductMetrics(id, query.granularity);
}

@Post('subscribe')
@UseGuards(JwtAuthGuard)
@HttpCode(HttpStatus.CREATED)
Expand Down
2 changes: 2 additions & 0 deletions backend/src/modules/savings/savings.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { RecommendationService } from './services/recommendation.service';
import { SavingsProduct } from './entities/savings-product.entity';
import { UserSubscription } from './entities/user-subscription.entity';
import { SavingsGoal } from './entities/savings-goal.entity';
import { ProductApySnapshot } from './entities/product-apy-snapshot.entity';
import { WithdrawalRequest } from './entities/withdrawal-request.entity';
import { Transaction } from '../transactions/entities/transaction.entity';
import { User } from '../user/entities/user.entity';
Expand All @@ -26,6 +27,7 @@ import { ExperimentsService } from './experiments.service';
SavingsProduct,
UserSubscription,
SavingsGoal,
ProductApySnapshot,
WithdrawalRequest,
Transaction,
User,
Expand Down
Loading