Skip to content

feat: implement treasury protection policies module#203

Merged
mijinummi merged 2 commits into
MD-Creative-Production:mainfrom
jotel-dev:Create-Treasury-Protection-Policies
Jul 19, 2026
Merged

feat: implement treasury protection policies module#203
mijinummi merged 2 commits into
MD-Creative-Production:mainfrom
jotel-dev:Create-Treasury-Protection-Policies

Conversation

@jotel-dev

@jotel-dev jotel-dev commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Core Overview
Problem Statement The Sentinel platform currently lacks automated treasury protection policies, creating significant security risks for organizations managing high-value on-chain assets. Treasury wallets often contain an organization's most valuable funds and require stricter monitoring than regular wallets. Without configurable treasury protection:

Unauthorized high-value transfers may go unnoticed until after execution
Unexpected treasury depletion cannot be detected in real-time
Transfers to unapproved recipient addresses lack automated blocking
Large withdrawals outside business hours cannot be monitored
Excessive transaction frequency may indicate compromised accounts
Security teams lack consistent enforcement of treasury controls
Incident response is delayed due to missing contextual alerts
Proposed Solution This PR implements a comprehensive treasury protection policy engine under treasury/policies that:

Provides configurable security rules for monitoring treasury wallets and high-value assets
Continuously evaluates treasury-related activity against configured policies
Generates alerts whenever a policy violation is detected
Supports 12 different policy types for comprehensive coverage
Maintains violation history for audit and compliance reporting
Provides impact-based severity classification for alert prioritization
Closes #144

Technical Implementation Details

  1. Policy Management (TreasuryPolicyService)
    Implements full CRUD operations for treasury protection policies:

Policy Creation: Validates policy configuration before activation with type-specific rules
Policy Updates: Supports threshold modifications and status changes without redeployment
Policy Deletion: Soft deletion with audit trail preservation
Audit Logging: Records all administrative actions (create, update, delete, activate/deactivate)
Multi-Wallet Support: Allows multiple policies per wallet with independent configurations
Version Tracking: Maintains policy version history for compliance requirements
2. Policy Validation (TreasuryPolicyValidator)
Validates policy configurations with type-specific rules:

Address Validation: Ensures wallet addresses follow Ethereum address format
Threshold Validation: Validates numeric thresholds are positive values
Type-Specific Rules: Enforces policy-type specific requirements (e.g., BusinessHoursOnly requires time zone, UnauthorizedDestination requires approved addresses)
Threshold Config Validation: Validates time windows, risk scores, and other configuration parameters
3. Policy Evaluation Engine (TreasuryPolicyEngine)
Evaluates transactions against active policies with 12 supported policy types:

MaxTransactionAmount: Blocks transactions exceeding configured amount
DailyTransferLimit: Enforces daily transfer quotas with configurable time windows
HourlyTransferLimit: Monitors hourly transfer velocity
MaxTransactionCount: Limits transaction frequency within time windows
BalancePercentageTransfer: Alerts on transfers exceeding percentage of treasury balance
UnauthorizedDestination: Blocks transfers to non-approved addresses
LargeBalanceDecrease: Detects significant balance drops
HighFrequencyTransfers: Identifies suspicious transfer velocity patterns
FirstTimeRecipient: Alerts on transactions to new recipients
BusinessHoursOnly: Restricts transfers to configured business hours
MinBalanceThreshold: Alerts when balance falls below minimum threshold
4. Automated Scheduling (TreasuryPolicyScheduler)
Provides configurable, resilient monitoring cycles:

Configurable Intervals: Default 60-second polling with per-chain override capability
Multi-Chain Support: Independent monitoring for each configured chain
Graceful Error Handling: Continues monitoring remaining chains if individual requests fail
Lifecycle Management: Clean start/stop with running state tracking
Alert Processing: Processes unsent alerts in batches for reliable delivery
5. Alert Generation (alert-generator.util)
Generates contextual alerts with severity-based formatting:

Severity Mapping: Maps policy severity to emoji indicators (Critical: , High: , Medium: , Low: )
Contextual Messages: Includes wallet address, chain ID, transaction hash, violated rule, threshold, and observed value
Recommended Actions: Provides actionable guidance for each violation type
Flexible Metadata: Supports additional context data for custom integrations
Database Schema Changes
Three new entities with TypeORM decorators:

TreasuryPolicyEntity (treasury_policies)

Stores policy configuration with status, thresholds, and notification preferences
Indexed on walletAddress + chainId, status, policyType, chainId
Tracks policy version, creator/updater metadata, and business hours configuration
Supports flexible threshold configuration via JSON storage
PolicyViolationEntity (policy_violations)

Stores detected violations with full context and severity
Indexed on policyId, walletAddress + chainId, transactionHash, status, severity, createdAt
Tracks violation lifecycle (Active → Acknowledged → Resolved/False Positive)
Persists transaction details, balance changes, and recommended actions
Supports alert delivery tracking with timestamps
PolicyAuditLogEntity (policy_audit_logs)

Stores administrative action history for compliance auditing
Indexed on policyId, action, performedBy, createdAt
Records before/after state for all policy modifications
Captures IP address, user agent, and reason for audit trail
Quality Assurance & Testing Matrix
Code Quality Verification
Type Safety: Full TypeScript coverage with strict type definitions
Code Style: Follows existing codebase patterns (service/repository/entity separation)
Linting: Compatible with existing ESLint configuration
Architecture: Aligns with existing module structure
Functional Validation Requirements
Component | Test Scenario | Expected Behavior Policy Management | Create policy with invalid address | Validation error returned Policy Management | Create policy without required fields | Validation error with specific field names Policy Management | Update policy threshold | Audit log entry created with previous/new state Policy Evaluation | Transaction exceeds max amount | Violation recorded with Critical severity Policy Evaluation | Transfer to unauthorized address | Violation recorded with Critical severity Policy Evaluation | Transfer within business hours | No violation generated Policy Evaluation | First-time recipient detected | Violation with Medium severity Scheduler | Service start/stop | Clean lifecycle management Scheduler | Chain request failure | Continues monitoring other chains Alert Generation | Critical severity violation | Alert with emoji and recommended action

Deployment & Migration Strategy
Pre-Deployment Requirements
Ensure TypeORM entities are registered in the data source configuration
Configure treasury policy parameters (chain IDs, wallet addresses, polling intervals)
Set up database indexes for optimal query performance
Configure notification channels for alert delivery
Database Actions
Run TypeORM migration to create treasury_policies, policy_violations, and policy_audit_logs tables
Existing tables are not modified - zero breaking changes
New indexes are non-blocking and can be created on live databases
Configuration
// Example configuration for treasury policy monitoring const treasuryConfig: TreasuryPolicyConfig[] = [ { chainId: 1, walletAddress: '0x...', pollIntervalMs: 60000, enabled: true, networkName: 'Ethereum Mainnet' } ];

Rollback Plan
Remove treasury policy module initialization from application bootstrap
Drop new tables if persistence cleanup is required
No impact on existing governance or detection functionality
Monitoring Integration
The service integrates seamlessly with existing repository patterns and notification infrastructure, requiring no changes to current monitoring or alerting systems.

closes #144

- Add enums for policy types, statuses, severities, and threshold types
- Create entities for treasury policies, violations, and audit logs
- Implement DTOs for policy and violation operations
- Add interfaces for policy evaluation and configuration
- Implement treasury policy repository with CRUD operations
- Add policy validator for configuration validation
- Implement policy evaluation engine with 12 policy types
- Create treasury policy service for policy management
- Add scheduler for continuous policy monitoring
- Implement alert generation utilities
- Add helper utilities for address and time operations
- Apply prettier auto-formatting
- Fix unused parameter warnings by prefixing with underscore
@mijinummi
mijinummi merged commit de0c907 into MD-Creative-Production:main Jul 19, 2026
12 checks passed
@mijinummi

Copy link
Copy Markdown
Collaborator

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🏦 Create Treasury Protection Policies

2 participants