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
3 changes: 3 additions & 0 deletions harvest-finance/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import { VaultReservation } from './vaults/entities/vault-reservation.entity';
import { Session } from './database/entities/session.entity';
import { SecurityEvent } from './database/entities/security-event.entity';
import { CreateVaultApyHistory1700000000017 } from './database/migrations/1700000000017-CreateVaultApyHistory';
import { AddVaultFees1700000000019 } from './database/migrations/1700000000019-AddVaultFees';
import { AddRefreshTokenRotation1700000000022 } from './database/migrations/1700000000022-AddRefreshTokenRotation';
import { DomainEventsModule } from './domain-events';
import { DomainEventHandlersModule } from './common/events';
Expand Down Expand Up @@ -163,7 +164,9 @@ import { CreateCustodialWallets1700000000021 } from './database/migrations/17000
CreateVaultReservations1700000000018,
AddDepositorConcentrationThreshold1700000000022,
CreateVaultApyHistory1700000000017,
AddVaultFees1700000000019,
CreateCustodialWallets1700000000021,
AddRefreshTokenRotation1700000000022,
],
synchronize: false,
migrationsRun: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export enum DepositEventType {
CONFIRMED = 'CONFIRMED',
FAILED = 'FAILED',
REFUNDED = 'REFUNDED',
FEE_COLLECTED = 'FEE_COLLECTED',
}

/**
Expand Down
13 changes: 13 additions & 0 deletions harvest-finance/backend/src/database/entities/vault.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,19 @@ export class Vault {
@Column({ name: 'stellar_account_address', length: 56, nullable: true, default: null })
stellarAccountAddress: string | null;

@Column({ name: 'entry_fee_bps', type: 'int', default: 0 })
entryFeeBps: number;

@Column({ name: 'exit_fee_bps', type: 'int', default: 0 })
exitFeeBps: number;

@Column({ name: 'performance_fee_bps', type: 'int', default: 0 })
performanceFeeBps: number;

/** Wallet address where collected fees are sent */
@Column({ name: 'fee_address', type: 'text', nullable: true })
feeAddress: string | null;

@CreateDateColumn({ name: 'created_at' })
createdAt: Date;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddVaultFees1700000000019 implements MigrationInterface {
name = 'AddVaultFees1700000000019';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "vaults" ADD COLUMN IF NOT EXISTS "entry_fee_bps" integer NOT NULL DEFAULT 0`);
await queryRunner.query(`ALTER TABLE "vaults" ADD COLUMN IF NOT EXISTS "exit_fee_bps" integer NOT NULL DEFAULT 0`);
await queryRunner.query(`ALTER TABLE "vaults" ADD COLUMN IF NOT EXISTS "performance_fee_bps" integer NOT NULL DEFAULT 0`);
await queryRunner.query(`ALTER TABLE "vaults" ADD COLUMN IF NOT EXISTS "fee_address" text`);

// Extend deposit_events event type enum to support fee collection entries
await queryRunner.query(`ALTER TYPE "deposit_events_event_type_enum" ADD VALUE IF NOT EXISTS 'FEE_COLLECTED'`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "vaults" DROP COLUMN IF EXISTS "entry_fee_bps"`);
await queryRunner.query(`ALTER TABLE "vaults" DROP COLUMN IF EXISTS "exit_fee_bps"`);
await queryRunner.query(`ALTER TABLE "vaults" DROP COLUMN IF EXISTS "performance_fee_bps"`);
await queryRunner.query(`ALTER TABLE "vaults" DROP COLUMN IF EXISTS "fee_address"`);
// Note: removing an enum value requires recreating the type; left intentionally for safety
}
}
28 changes: 28 additions & 0 deletions harvest-finance/backend/src/vaults/dto/update-vault-fees.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsInt, IsOptional, IsString, Min } from 'class-validator';

export class UpdateVaultFeesDto {
@ApiProperty({ example: 50, description: 'Entry fee in basis points (50 bps = 0.5%)' })
@IsInt()
@Min(0)
entryFeeBps: number;

@ApiProperty({ example: 50, description: 'Exit fee in basis points (50 bps = 0.5%)' })
@IsInt()
@Min(0)
exitFeeBps: number;

@ApiProperty({ example: 1000, description: 'Performance fee in basis points (1000 bps = 10%)' })
@IsInt()
@Min(0)
performanceFeeBps: number;

@ApiProperty({
example: 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
description: 'Wallet address where fees are transferred',
required: false,
})
@IsOptional()
@IsString()
feeAddress?: string;
}
18 changes: 18 additions & 0 deletions harvest-finance/backend/src/vaults/dto/vault-response.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ export class VaultResponseDto {
description: 'Last update date',
})
updatedAt: Date;

@ApiProperty({ example: 50, description: 'Entry fee in basis points' })
entryFeeBps: number;

@ApiProperty({ example: 50, description: 'Exit fee in basis points' })
exitFeeBps: number;

@ApiProperty({ example: 1000, description: 'Performance fee in basis points' })
performanceFeeBps: number;

@ApiProperty({ example: 'GXXX...', description: 'Fee recipient address', required: false, nullable: true })
feeAddress: string | null;
}

export class DepositResponseDto {
Expand Down Expand Up @@ -235,6 +247,12 @@ export class DepositVaultResponseDto {
description: "User's total deposits across all vaults",
})
userTotalDeposits: number;

@ApiProperty({ example: 5.0, description: 'Fee amount deducted' })
feeAmount: number;

@ApiProperty({ example: 995.0, description: 'Net amount credited after fee deduction' })
netAmount: number;
}

export class BatchDepositResponseDto {
Expand Down
56 changes: 56 additions & 0 deletions harvest-finance/backend/src/vaults/fees.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { BadRequestException, Injectable } from '@nestjs/common';

// Platform-wide maximums (configurable via env; hard-coded fallbacks)
const MAX_ENTRY_FEE_BPS = parseInt(process.env.MAX_ENTRY_FEE_BPS ?? '500', 10); // 5%
const MAX_EXIT_FEE_BPS = parseInt(process.env.MAX_EXIT_FEE_BPS ?? '500', 10); // 5%
const MAX_PERFORMANCE_FEE_BPS = parseInt(process.env.MAX_PERFORMANCE_FEE_BPS ?? '3000', 10); // 30%

export interface FeeBreakdown {
grossAmount: number;
feeAmount: number;
netAmount: number;
feeBps: number;
}

@Injectable()
export class FeesService {
validateFees(entryFeeBps: number, exitFeeBps: number, performanceFeeBps: number): void {
if (entryFeeBps < 0 || entryFeeBps > MAX_ENTRY_FEE_BPS) {
throw new BadRequestException(
`Entry fee must be between 0 and ${MAX_ENTRY_FEE_BPS} bps (${MAX_ENTRY_FEE_BPS / 100}%)`,
);
}
if (exitFeeBps < 0 || exitFeeBps > MAX_EXIT_FEE_BPS) {
throw new BadRequestException(
`Exit fee must be between 0 and ${MAX_EXIT_FEE_BPS} bps (${MAX_EXIT_FEE_BPS / 100}%)`,
);
}
if (performanceFeeBps < 0 || performanceFeeBps > MAX_PERFORMANCE_FEE_BPS) {
throw new BadRequestException(
`Performance fee must be between 0 and ${MAX_PERFORMANCE_FEE_BPS} bps (${MAX_PERFORMANCE_FEE_BPS / 100}%)`,
);
}
}

calculateFee(grossAmount: number, feeBps: number): FeeBreakdown {
const feeAmount = Math.round(grossAmount * feeBps) / 10000;
return {
grossAmount,
feeAmount,
netAmount: grossAmount - feeAmount,
feeBps,
};
}

get platformMaxEntryFeeBps(): number {
return MAX_ENTRY_FEE_BPS;
}

get platformMaxExitFeeBps(): number {
return MAX_EXIT_FEE_BPS;
}

get platformMaxPerformanceFeeBps(): number {
return MAX_PERFORMANCE_FEE_BPS;
}
}
21 changes: 20 additions & 1 deletion harvest-finance/backend/src/vaults/vaults.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Post,
Get,
Delete,
Patch,
Param,
Body,
Query,
Expand Down Expand Up @@ -31,6 +32,7 @@ import { BatchDepositDto } from './dto/batch-deposit.dto';
import { CloneVaultDto } from './dto/clone-vault.dto';
import { CreateReservationDto } from './dto/create-reservation.dto';
import { ReservationResponseDto } from './dto/reservation-response.dto';
import { UpdateVaultFeesDto } from './dto/update-vault-fees.dto';
import {
BatchDepositResponseDto,
DepositVaultResponseDto,
Expand Down Expand Up @@ -393,9 +395,26 @@ export class VaultsController {
);
}

@Post(':vaultId/request-approval')
@Patch(':vaultId/fees')
@Throttle({ default: { limit: 10, ttl: 60000 } })
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Configure entry, exit, and performance fees for a vault' })
@ApiParam({ name: 'vaultId', description: 'Vault ID (UUID)' })
@ApiBody({ type: UpdateVaultFeesDto })
@ApiResponse({ status: 200, description: 'Fee configuration updated', type: VaultResponseDto })
@ApiResponse({ status: 400, description: 'Fee values exceed platform maximums' })
@ApiResponse({ status: 401, description: 'Unauthorized - Only vault owner can configure fees' })
@ApiResponse({ status: 404, description: 'Vault not found' })
async updateVaultFees(
@Param('vaultId') vaultId: string,
@Body() dto: UpdateVaultFeesDto,
@Request() req: any,
): Promise<VaultResponseDto> {
return this.vaultsService.updateVaultFees(vaultId, req.user.id, dto);
}

@Post(':vaultId/request-approval') @Throttle({ default: { limit: 10, ttl: 60000 } })
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Request approval from another user for vault operations' })
@ApiParam({
name: 'vaultId',
Expand Down
6 changes: 6 additions & 0 deletions harvest-finance/backend/src/vaults/vaults.integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { VaultsService } from './vaults.service';
import { FeesService } from './fees.service';
import { WithdrawalQueueService } from './withdrawal-queue.service';
import { ExternalPaymentEventType } from './dto/external-payment-notification.dto';
import { PaymentReceivedEvent, DepositCompletedEvent, WithdrawalConfirmedEvent, DomainEventNames } from '../domain-events';
Expand Down Expand Up @@ -210,6 +211,11 @@ describe('VaultsService — Yield Strategy Integration', () => {
{ provide: DepositEventService, useValue: mockDepositEventService },
{ provide: WithdrawalQueueService, useValue: { processQueue: jest.fn().mockResolvedValue(undefined) } },
{ provide: EventEmitter2, useValue: mockEventEmitter },
FeesService,
{
provide: WithdrawalQueueService,
useValue: { processWithdrawalQueue: jest.fn().mockResolvedValue(undefined), enqueueWithdrawal: jest.fn().mockResolvedValue(undefined) },
},
],
}).compile();

Expand Down
53 changes: 17 additions & 36 deletions harvest-finance/backend/src/vaults/vaults.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CqrsModule } from '@nestjs/cqrs';
import { TypeOrmModule } from '@nestjs/typeorm';
import { VaultsController } from './vaults.controller';
import { VaultsService } from './vaults.service';
import { FeesService } from './fees.service';
import { CommandHandlers } from './cqrs/commands/handlers';
import { QueryHandlers } from './cqrs/queries/handlers';
import { EventHandlers } from './cqrs/events/handlers';
Expand All @@ -16,6 +17,7 @@ import { VaultApyHistory } from '../database/entities/vault-apy-history.entity';
import { InsuranceClaim } from '../database/entities/insurance-claim.entity';
import { DepositEventService } from './deposit-event.service';
import { WithdrawalConfirmedHandler } from './events/withdrawal-confirmed.handler';
import { WithdrawalQueueService } from './withdrawal-queue.service';
import { StellarModule } from '../stellar/stellar.module';
import { VaultAccountMonitorService } from './vault-account-monitor.service';
import { InsuranceFundService } from './insurance-fund.service';
Expand All @@ -24,54 +26,33 @@ import { AuthModule } from '../auth/auth.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { CommonModule } from '../common/common.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { CommonModule } from '../common/common.module';
import { VaultsController } from './vaults.controller';
import { VaultsService } from './vaults.service';
import { DepositEventService } from './deposit-event.service';
import { Vault, Deposit, DepositEvent, Withdrawal, VaultReservation, VaultApyHistory, InsuranceClaim } from './entities'; // Adjust entity path if necessary

// Keep both sets of imported files to prevent regressions
import { WithdrawalConfirmedHandler } from './events/withdrawal-confirmed.handler';
import { StellarModule } from '../stellar/stellar.module';
import { VaultAccountMonitorService } from './vault-account-monitor.service';
import { WithdrawalQueueService } from './withdrawal-queue.service';
import { InsuranceFundController } from './insurance-fund.controller';
import { InsuranceFundService } from './insurance-fund.service';
import { AnalyticsModule } from '../analytics/analytics.module';

@Module({
imports: [
TypeOrmModule.forFeature([Vault, Deposit, DepositEvent, Withdrawal, VaultReservation, VaultApyHistory, InsuranceClaim]),
CqrsModule,
AuthModule,
NotificationsModule,
RealtimeModule,
CommonModule,
StellarModule,
AnalyticsModule,
],
controllers: [
VaultsController,
InsuranceFundController
],
controllers: [VaultsController, InsuranceFundController],
providers: [
VaultsService,
DepositEventService,
WithdrawalConfirmedHandler,
VaultAccountMonitorService,
WithdrawalQueueService,
InsuranceFundService
VaultsService,
FeesService,
DepositEventService,
WithdrawalConfirmedHandler,
WithdrawalQueueService,
VaultAccountMonitorService,
InsuranceFundService,
VaultReadRepository,
...CommandHandlers,
...QueryHandlers,
...EventHandlers,
],
exports: [
VaultsService,
DepositEventService,
WithdrawalQueueService,
InsuranceFundService
],
})
export class VaultsModule {}
exports: [VaultsService, DepositEventService, WithdrawalQueueService, InsuranceFundService],
})
export class VaultsModule {}
8 changes: 7 additions & 1 deletion harvest-finance/backend/src/vaults/vaults.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { VaultsService } from './vaults.service';
import { FeesService } from './fees.service';
import { WithdrawalQueueService } from './withdrawal-queue.service';
import { Vault, VaultStatus, VaultType } from '../database/entities/vault.entity';
import { Deposit, DepositStatus } from '../database/entities/deposit.entity';
import { VaultApyHistory } from '../database/entities/vault-apy-history.entity';
Expand Down Expand Up @@ -193,7 +195,11 @@ describe('VaultsService', () => {
{ provide: ContractCacheService, useValue: mockContractCache },
{ provide: InputSanitizerService, useValue: mockSanitizer },
{ provide: DepositEventService, useValue: mockDepositEventService },
{ provide: WithdrawalQueueService, useValue: {} },
FeesService,
{
provide: WithdrawalQueueService,
useValue: { processWithdrawalQueue: jest.fn().mockResolvedValue(undefined), enqueueWithdrawal: jest.fn().mockResolvedValue(undefined) },
},
],
}).compile();

Expand Down
Loading