feat(protection): implement insurance fund system#411
Merged
DevMuhdishaq merged 1 commit intoJun 22, 2026
Conversation
Add multi-tier insurance funds with liquidation shortfall coverage, real-time health monitoring with 20% reserve alerts, fee-based replenishment, and a complete transaction audit trail.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
This PR adds a complete Insurance Fund System to
SwapTrade-Backend, providing a multi-layered safety mechanism that automatically covers liquidation shortfalls, monitors fund health in real time, distributes trading-fee contributions, and maintains a full audit trail for all insurance-related transactions.Related Issue
Closes #380
Changes
🛡️ Protection Domain (
src/protection/)[ADD]
src/protection/entities/insurance-fund-tier.entity.tsAdded
InsuranceFundTierentity supporting LOW, MEDIUM, HIGH, and CRITICAL risk tiers.Each tier defines
minReserve,maxExposure, andfeeContributionPct.[ADD]
src/protection/entities/insurance-fund.entity.tsAdded
InsuranceFundentity to track balance, target reserve, health percent, and health status per tier/asset pair.[ADD]
src/protection/entities/insurance-transaction.entity.tsAdded
InsuranceTransactionentity for a complete audit trail.Supports
DEPOSIT,PAYOUT,FEE_CONTRIBUTION, andREPLENISHMENTtransaction types.Records
balanceBefore,balanceAfter,referenceId,userId, and metadata.[ADD]
src/protection/entities/liquidation-event.entity.tsAdded
LiquidationEvententity to track liquidation shortfall coverage and cascade prevention outcomes.⚙️ Core Services
[ADD]
src/protection/services/insurance-fund.service.tsCore insurance fund ledger: initialize multi-tier funds, record transactions, replenish, and fee contributions.
Seeds four default tiers (LOW → CRITICAL) on initialization.
[ADD]
src/protection/services/liquidation-protection.service.tsAutomated liquidation shortfall coverage with cascade prevention.
Iterates tiers in priority order (LOW → CRITICAL) to cover shortfalls.
Emits
LiquidationShortfallEventandInsurancePayoutEventon coverage.[ADD]
src/protection/services/fund-health.service.tsReal-time fund health monitoring with dashboard metrics.
Triggers
FundHealthAlertEventwhen reserves drop below 20% threshold.Resolves health status: HEALTHY, WARNING, CRITICAL, DEPLETED.
[ADD]
src/protection/services/insurance-fee-contribution.service.tsReplenishes insurance funds from trading fees based on tier
feeContributionPct.Integrated via
ProtectionListenerontrade.executedevents.🌐 REST API Surface
[ADD]
src/protection/insurance-fund.controller.tsPOST /protection/insurance/initialize— seed multi-tier fundsGET /protection/insurance/funds— list all fundsGET /protection/insurance/funds/:id— get fund detailsGET /protection/insurance/tiers— list risk tiersGET /protection/insurance/health/dashboard— fund health dashboardGET /protection/insurance/health/alerts— active alerts (< 20%)GET /protection/insurance/health/funds/:id— per-fund health metricsPOST /protection/insurance/replenish— manual fund replenishmentPOST /protection/insurance/cover-shortfall— inject insurance for liquidation shortfallPOST /protection/insurance/contribute-fees— add trading fees to fundGET /protection/insurance/transactions— audit trail[ADD]
src/protection/protection.module.tsDedicated NestJS module for the Protection domain.
Exported all insurance services for reuse by trading/order modules.
[ADD]
src/protection/listeners/protection.listener.tsEvent listener for
trade.executed(auto fee contribution),liquidation.shortfall, andfund.health.alert.[MODIFY]
src/app.module.tsRegistered
ProtectionModuleand new insurance entities in TypeORM.🗄️ Database
src/database/migrations/1727516400003-CreateInsuranceFundTables.tsinsurance_fund_tiers,insurance_funds,insurance_transactions, andliquidation_eventstables.🔐 Permissions & Configuration
[MODIFY]
src/identity/permissions/constants/permissions.tsAdded
insurance.read,insurance.write, andinsurance.adminpermissions.[MODIFY]
src/config/config.schema.tsAdded
FEATURE_INSURANCE_ENABLED,INSURANCE_MIN_RESERVE_PCT, andINSURANCE_FEE_CONTRIBUTION_PCT.[MODIFY]
src/infrastructure/events/domain.events.tsAdded
LiquidationShortfallEvent,InsurancePayoutEvent, andFundHealthAlertEvent.🧪 Tests
[ADD]
src/protection/services/fund-health.service.spec.tsUnit tests for health percent calculation, status resolution, and 20% alert threshold.
[ADD]
src/protection/services/insurance-fund.service.spec.tsUnit tests for transaction recording, fee contributions, and payouts.
[ADD]
src/protection/services/liquidation-protection.service.spec.tsUnit tests for full and partial shortfall coverage with cascade prevention.
[ADD]
src/protection/insurance-fund.integration.spec.tsFull lifecycle integration test: initialize → fee contribution → cover shortfall → health dashboard → replenish → audit trail → health alert.
Verification Results