Skip to content

DeFi Protocol Solvency Proof Standard - A standardized interface for verifying and reporting DeFi protocol solvency status through smart contracts

License

Notifications You must be signed in to change notification settings

SeanLuis/erc-7893

Repository files navigation

eip title description author discussions-to status type category created requires
7893
DeFi Protocol Solvency Proof Mechanism
Verifiable solvency proofs and financial health monitoring for DeFi protocols
Sean Luis Guada Rodríguez (@SeanLuis) <seanluis47@gmail.com>
Review
Standards Track
ERC
2025-01-30
20, 165

Abstract

A standardized interface that enables DeFi protocols to implement verifiable solvency proofs through smart contracts. This interface works by defining structured data types for assets and liabilities, with oracle-validated price feeds tracking token values in real-time. The technical implementation calculates solvency ratios using configurable risk thresholds (105% minimum solvency ratio), maintains historical metrics for trend analysis, and emits structured events upon threshold breaches. The interface standardizes methods for querying current financial health, retrieving historical data points, and updating protocol positions, all while enforcing proper validation and security controls.

Motivation

The DeFi ecosystem currently lacks standardization in financial health reporting, leading to:

  1. Inconsistent reporting methodologies across protocols
  2. Limited transparency in real-time financial status
  3. Absence of standardized early warning systems
  4. Complex and time-consuming audit processes
  5. Difficulty in assessing cross-protocol risks

This proposal directly addresses these challenges through a comprehensive interface that standardizes solvency reporting and monitoring:

  • Standardized Methodology: By providing a common interface with well-defined asset/liability structures and mathematical models, this EIP eliminates reporting inconsistencies that currently prevent clear comparisons between protocols.

  • Real-time Transparency: The proposed event system and query functions enable continuous monitoring of protocol health, rather than relying on periodic manual reporting that can miss critical changes in financial status.

  • Automated Risk Alerts: The threshold-based alert system provides early warnings of deteriorating conditions through standardized RiskAlert events, enabling faster response to potential insolvencies than current ad-hoc monitoring approaches.

  • Efficient Audit Trail: The historical metrics tracking creates an immutable record of protocol health over time, significantly reducing audit complexity compared to current solutions that require reconstructing historical positions.

  • Cross-Protocol Risk Assessment: A common interface enables aggregation of risk data across multiple protocols, allowing systemic risk monitoring that's impossible with today's fragmented reporting systems.

Alternative approaches considered include:

  1. Off-chain Reporting: While simpler to implement, this lacks the verifiability, real-time nature, and trustless properties of an on-chain solution.

  2. Protocol-Specific Standards: These would lack the interoperability benefits of a common standard and would perpetuate fragmentation.

  3. Complex Risk Models: More sophisticated models were evaluated but rejected in favor of this proposal's balance between comprehensiveness and implementability.

This EIP represents the optimal approach by providing a flexible yet standardized framework that can be implemented across diverse protocol types while maintaining reasonable gas efficiency and usability.

The ISolvencyProof interface provides a standardized, on-chain mechanism for DeFi protocols to report, verify, and monitor their solvency status. This interface is designed to be both comprehensive and flexible, supporting a wide range of protocol architectures and risk management strategies.

Specification

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174.

main

Core Interface Requirements

Compliant implementations MUST implement the ISolvencyProof interface.

Compliant implementations MUST provide the following functionality:

  1. Asset and Liability Tracking: Implementations MUST store and maintain current protocol assets and liabilities with token addresses, amounts, and ETH-denominated values in contract state variables. This data MUST be updated through the updateAssets and updateLiabilities functions called by authorized oracles.

  2. Timestamp Recording: Implementations MUST record the timestamp of each asset and liability update.

  3. Solvency Calculation: Implementations MUST calculate the solvency ratio as (Total Assets / Total Liabilities) × 10000.

  4. Historical Data: Implementations MUST maintain historical records of solvency metrics for querying within specified time ranges. Implementations MAY expire old data after a reasonable retention period (e.g., 1 year) but MUST clearly document their retention policy and available time ranges in their implementation documentation.

  5. Event Emission: Implementations MUST emit SolvencyMetricsUpdated events when financial metrics are updated, and SHOULD emit RiskAlert events when risk thresholds are breached.

  6. Array Validation: Implementations MUST ensure that all arrays in ProtocolAssets and ProtocolLiabilities structures are of equal length.

  7. Value Denomination: Implementations MUST express all values in ETH with 18 decimals for consistency.

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.20;

/**
 * @title ISolvencyProof
 * @author Sean Luis (@SeanLuis) <seanluis47@gmail.com>
 * @notice Standard Interface for DeFi Protocol Solvency (EIP-DRAFT)
 * @dev Interface for the DeFi Protocol Solvency Proof Standard
 * @custom:security-contact seanluis47@gmail.com
 * @custom:version 1.0.0
 */
interface ISolvencyProof {
    /**
     * @dev Protocol assets structure
     * @notice Represents the current state of protocol assets
     * @custom:validation All arrays must be equal length
     * @custom:validation Values must be in ETH with 18 decimals
     */
    struct ProtocolAssets {
        address[] tokens;    // Addresses of tracked tokens
        uint256[] amounts;   // Amount of each token
        uint256[] values;    // Value in ETH of each token amount
        uint256 timestamp;   // Last update timestamp
    }

    /**
     * @dev Protocol liabilities structure
     * @notice Represents the current state of protocol liabilities
     * @custom:validation All arrays must be equal length
     * @custom:validation Values must be in ETH with 18 decimals
     */
    struct ProtocolLiabilities {
        address[] tokens;    // Addresses of liability tokens
        uint256[] amounts;   // Amount of each liability
        uint256[] values;    // Value in ETH of each liability
        uint256 timestamp;   // Last update timestamp
    }

    /**
     * @dev Emitted on metrics update
     * @notice Real-time financial health update
     * @param totalAssets Sum of asset values in ETH
     * @param totalLiabilities Sum of liability values in ETH
     * @param healthFactor Calculated as (totalAssets/totalLiabilities) × 10000
     * @param timestamp Update timestamp
     */
    event SolvencyMetricsUpdated(
        uint256 totalAssets,
        uint256 totalLiabilities,
        uint256 healthFactor,
        uint256 timestamp
    );

    /**
     * @dev Emitted when risk thresholds are breached
     * @notice Alerts stakeholders of potential solvency risks
     * 
     * @param riskLevel Risk level indicating severity of the breach (CRITICAL, HIGH_RISK, WARNING)
     * @param currentValue Current value that triggered the alert
     * @param threshold Risk threshold that was breached
     * @param timestamp Alert timestamp
     */
    event RiskAlert(
        string riskLevel,
        uint256 currentValue,
        uint256 threshold,
        uint256 timestamp
    );

    /**
     * @notice Get protocol's current assets
     * @return Full asset state including tokens, amounts and values
     */
    function getProtocolAssets() external view returns (ProtocolAssets memory);

    /**
     * @notice Get protocol's current liabilities
     * @return Full liability state including tokens, amounts and values
     */
    function getProtocolLiabilities() external view returns (ProtocolLiabilities memory);

    /**
     * @notice Calculate current solvency ratio
     * @return SR = (Total Assets / Total Liabilities) × 10000
     */
    function getSolvencyRatio() external view returns (uint256);

    /**
     * @notice Check protocol solvency status
     * @return isSolvent True if ratio >= minimum required
     * @return healthFactor Current solvency ratio
     */
    function verifySolvency() external view returns (bool isSolvent, uint256 healthFactor);

    /**
     * @notice Get historical solvency metrics
     * @param startTime Start of time range
     * @param endTime End of time range
     * @return timestamps Array of historical update timestamps
     * @return ratios Array of historical solvency ratios
     * @return assets Array of historical asset states
     * @return liabilities Array of historical liability states
     */
    function getSolvencyHistory(uint256 startTime, uint256 endTime) 
        external 
        view 
        returns (
            uint256[] memory timestamps,
            uint256[] memory ratios,
            ProtocolAssets[] memory assets,
            ProtocolLiabilities[] memory liabilities
        );

    /**
     * @notice Update protocol assets
     * @dev Only callable by authorized oracle
     */
    function updateAssets(
        address[] calldata tokens,
        uint256[] calldata amounts,
        uint256[] calldata values
    ) external;

    /**
     * @notice Update protocol liabilities
     * @dev Only callable by authorized oracle
     */
    function updateLiabilities(
        address[] calldata tokens,
        uint256[] calldata amounts,
        uint256[] calldata values
    ) external;
}

Oracle Authorization Requirements

Implementations MUST restrict calls to updateAssets and updateLiabilities to authorized addresses only. Implementations MUST revert these function calls when msg.sender is not an authorized oracle.

Implementations MAY provide oracle management functions. If provided, implementations SHOULD emit events when oracle authorization changes.

Example oracle management pattern (OPTIONAL):

// Optional oracle management pattern
event OracleUpdated(address indexed oracle, bool authorized);
function setOracle(address oracle, bool authorized) external;

The core standard focuses on solvency verification requirements. Oracle management implementation details are left to individual protocol needs.

Update Function Requirements

Implementations MUST validate input parameters for updateAssets and updateLiabilities functions:

  1. Implementations MUST revert if the tokens, amounts, and values arrays are not of equal length.
  2. Implementations MUST update the timestamp field to the current block timestamp (block.timestamp) when processing updates.
  3. Implementations MUST emit a SolvencyMetricsUpdated event after successfully updating assets or liabilities.

Query Function Requirements

Implementations MUST provide the following query capabilities:

  1. getProtocolAssets() MUST return the current state of protocol assets including all token addresses, amounts, values, and the timestamp of the last update.

  2. getProtocolLiabilities() MUST return the current state of protocol liabilities including all token addresses, amounts, values, and the timestamp of the last update.

  3. getSolvencyRatio() MUST calculate and return the solvency ratio as (totalAssets * 10000) / totalLiabilities. If totalLiabilities is zero, implementations SHOULD return a value indicating maximum solvency or revert with an appropriate error.

  4. verifySolvency() MUST return both a boolean indicating solvency status and the current health factor (solvency ratio).

  5. getSolvencyHistory(startTime, endTime) MUST return historical data for all recorded snapshots where the timestamp falls within the specified range (inclusive).

Interface Detection Support

Compliant implementations MUST implement the ERC-165 supportsInterface function and MUST return true for the ISolvencyProof interface ID.

Rationale

The standard's design prioritizes:

  1. Reliability through robust calculations
  2. Efficiency via optimized data structures
  3. Flexibility through modular design
  4. Transparency via standardized metrics

Asset and Liability Management

Authorized oracles update the protocol's asset and liability data through the updateAssets and updateLiabilities functions, which accept parallel arrays of token addresses, amounts, and ETH-denominated values. The interface enforces data consistency by requiring all input arrays to be of equal length and all values to be denominated in ETH with 18 decimal precision. Each update automatically timestamps the data using block.timestamp, ensuring chronological ordering of financial state changes and enabling accurate historical analysis.

Solvency Calculation and Verification

The getSolvencyRatio function computes the current solvency ratio, defined as the total value of assets divided by the total value of liabilities, scaled by a factor of 10,000 for precision. The verifySolvency function checks whether the protocol meets a minimum required solvency ratio (commonly 105%), returning both a boolean status and the current health factor. This allows both on-chain and off-chain systems to quickly assess the protocol's financial health and respond accordingly.

Historical Data and Trend Analysis

The getSolvencyHistory function enables retrieval of historical solvency metrics, including timestamps, ratios, and the corresponding asset and liability states over a specified time range. This historical data is crucial for reconstructing past events, analyzing risk trends, and providing transparency to stakeholders. This supports audits, regulatory requirements, and trend analysis needs.

Event Emission and Risk Alerts

Whenever the protocol's financial metrics are updated, the SolvencyMetricsUpdated event is emitted, providing real-time data for off-chain monitoring and analytics. When risk thresholds are breached (for example, if the solvency ratio falls below a critical level), the RiskAlert event is triggered, signaling the severity and nature of the risk. These events enable automated monitoring systems, auditors, and users to receive timely notifications and take appropriate action.

Oracle Integration and Security

The interface is designed to be oracle-agnostic, allowing protocols to integrate with a variety of price feed solutions (e.g., Chainlink, API3, custom oracles). The requirement that only authorized oracles can update asset and liability data ensures that updates are secure and resistant to manipulation. The optional setOracle and OracleUpdated event pattern is recommended for managing oracle permissions and maintaining robust security controls.

Intended Usage and Integration

Protocols implementing this interface integrate with trusted oracles for price feeds and position updates, maintain up-to-date records of their financial positions, emit standardized events for off-chain monitoring and risk management, and provide transparent, verifiable, and standardized information about their solvency status to all stakeholders. External consumers (such as auditors, users, or other smart contracts) can query the protocol's current and historical solvency status using the provided view functions, and can listen for events to receive timely notifications of significant changes or risks. This design ensures that all stakeholders have access to reliable, real-time information about a protocol's financial health, enabling more robust risk management and greater trust in the DeFi ecosystem.

Data Structure Design Rationale

The interface defines two primary data structures (ProtocolAssets and ProtocolLiabilities) with specific attributes:

  1. Array-based token tracking was selected over mapping-based approaches for:

    • More efficient state retrieval for monitoring systems
    • Better compatibility with historical tracking requirements
    • Simplified batch updates in volatile market conditions
  2. Timestamp embedding within structures rather than separate mappings provides:

    • Atomic updates with data consistency guarantees
    • Protection against partial-update scenarios during price volatility
    • Single-transaction verification of data freshness
  3. Combined value and amount tracking was implemented for:

    • Enhanced resilience during high market volatility
    • Ability to detect oracle manipulation by comparing historical value/amount ratios
    • Clear audit trails for post-mortem analysis

Test-Driven Design Decisions

Our implementation testing significantly shaped the final design:

  1. Market Crash Simulation Tests

    • Tests simulate extreme scenarios (80% ETH price drop, 70% BTC price drop)
    • Validates the system correctly identifies insolvency when ratios fall below critical thresholds
    • Confirms proper functionality of emergency protocols during rapid market movements
  2. Volatility Testing

    • Test suite subjects implementation to sinusoidal price movements
    • Validates consistent health factor calculation across 5 distinct price points
    • Confirms historical metrics are properly recorded with sequential timestamps
    • Verifies that price volatility is accurately reflected in solvency ratios
  3. Oracle Integration

    • Tests confirm proper authorization controls for price updates
    • Validates calculation consistency across different token types
    • Demonstrates resilience against unexpected price movements

Threshold Selection Methodology

The recommended threshold values (105%, 110%, 120%) were selected based on:

  1. Market Crash Testing

    • 105% represents the critical threshold where recovery becomes unlikely
    • Testing confirms this threshold successfully identifies insolvency scenarios
    • System correctly triggers warnings at appropriate levels
  2. Complex Portfolio Analysis

    • Tests with diverse portfolios (ETH, BTC, USDC, LP tokens, etc.)
    • Complex liability structures (stablecoins + volatile assets)
    • Thresholds provide appropriate buffer against normal market fluctuations
  3. Gas Optimization vs. Precision

    • The selected ratio calculation method balances computational efficiency with accuracy
    • Implementation uses fixed-point math for consistent results
    • Storage optimizations maintain historical data while minimizing costs

Implementation Insights

Key insights from our implementation and testing:

  1. Efficient Asset Tracking

    • The parallel arrays approach for token data minimizes storage costs
    • Implementation maintains constant-time lookups for critical operations
    • Bounded array sizes prevent out-of-gas scenarios
  2. Oracle Integration Patterns

    • Permissioned oracle design prevents manipulation
    • Clean separation between price data and protocol logic
    • Flexible design supports various oracle implementations
  3. Risk Management System

    • Multi-tier alert system provides graduated responses to deteriorating conditions
    • Historical metrics enable trend analysis across market cycles
    • Verification functions support both on-chain and off-chain monitoring systems

These insights are derived from our comprehensive test suite covering market crashes, volatility scenarios, and complex asset portfolios as documented in our test cases.

Mathematical Model

The solvency verification system is based on comprehensive mathematical models:

1. Core Solvency Calculations

$SR = (TA / TL) × 100$

Where:

  • $TA = \sum(A_i × P_i)$ // Total Assets
  • $TL = \sum(L_i × P_i)$ // Total Liabilities
  • $A_i$ = Amount of asset i
  • $P_i$ = Price of asset i
  • $L_i$ = Liability i

2. Risk-Adjusted Health Factor

$HF = \frac{\sum(A_i × P_i × W_i)}{\sum(L_i × P_i × R_i)}$

Where:

  • $W_i$ = Risk weight of asset i $(0 &lt; W_i \leq 1)$
  • $R_i$ = Risk factor for liability i $(R_i \geq 1)$

3. Risk Metrics

Value at Risk (VaR)

$VaR(\alpha) = \mu - (\sigma × z(\alpha))$

Where:

  • $\mu$ = Expected return
  • $\sigma$ = Standard deviation
  • $z(\alpha)$ = z-value for confidence level $\alpha$
Liquidity Coverage Ratio (LCR)

$LCR = \frac{HQLA}{TNCO} × 100$

Where:

  • HQLA = High Quality Liquid Assets
  • TNCO = Total Net Cash Outflows (30 days)

4. System Health Index

$SI = \frac{SR × w_1 + LCR × w_2 + (1/\sigma) × w_3}{w_1 + w_2 + w_3}$

Where:

  • $w_1,w_2,w_3$ = Weighting factors
  • $\sigma$ = System volatility

5. Default Probability

$PD = N(-DD)$ $DD = \frac{ln(TA/TL) + (\mu - \sigma^2/2)T}{\sigma\sqrt{T}}$

Where:

  • DD = Distance to Default
  • T = Time horizon
  • N() = Standard normal distribution

Risk Thresholds

The following thresholds have been validated through extensive testing:

Risk Level Ratio Range Action Required Validation Status
CRITICAL < 105% Emergency Stop ✅ Validated
HIGH RISK 105% - 110% Risk Alert ✅ Validated
WARNING 110% - 120% Monitor ✅ Validated
HEALTHY ≥ 120% Normal ✅ Validated

Testing has confirmed that:

  1. The system correctly handles 50% market drops
  2. Ratios are calculated accurately in all scenarios
  3. State updates maintain consistency
  4. Ratio limits are effective for early detection

risk-thresholds

Risk Assessment Framework

The standard implements a multi-tiered risk assessment system:

  1. Primary Metrics:

    • Base Solvency Ratio (SR)
    • Risk-Adjusted Health Factor (HF)
    • Liquidity Coverage Ratio (LCR)
  2. Threshold Levels:

threshold-levels

Oracle Integration (Optional)

This standard intentionally leaves oracle implementation flexible. Protocols MAY implement price feeds in various ways:

  1. Direct Integration

    • Using existing oracle networks (Chainlink, API3, etc.)
    • Custom price feed implementations
    • Internal price calculations
  2. Aggregation Strategies

    • Multiple oracle sources
    • TWAP implementations
    • Medianized price feeds

oracle-integration

Implementation Requirements

  1. Asset Management:

    • Real-time asset tracking
    • Price feed integration
    • Historical data maintenance
  2. Liability Tracking:

    • Debt obligation monitoring
    • Collateral requirement calculation
    • Risk factor assessment
  3. Reporting System:

    • Event emission for significant changes
    • Threshold breach notifications
    • Historical data access

Implementation Considerations

Implementation Notes

Based on conducted tests, it is recommended:

  1. Liability Management:

    • Maintain constant liabilities during price updates
    • Validate that liabilities are never 0 to avoid division by zero
    • Update liabilities only when actual positions change
  2. Ratio Calculation:

    function calculateRatio(uint256 assets, uint256 liabilities) pure returns (uint256) {
        if (liabilities == 0) {
            return assets > 0 ? RATIO_DECIMALS * 2 : RATIO_DECIMALS;
        }
        return (assets * RATIO_DECIMALS) / liabilities;
    }
  3. State Validation:

    • Verify values before updating
    • Maintain accurate history
    • Emit events for significant changes
  4. Gas Considerations:

    • Optimize history storage
    • Batch updates for multiple tokens
    • Limit array sizes in updates

Backwards Compatibility

This EIP is compatible with existing DeFi protocols and requires no changes to existing token standards.

Reference Implementation

The reference implementation provides a comprehensive example of the standard in action:

Core Contract Implementation

The reference implementation (SolvencyProof.sol) provides a complete implementation of the ISolvencyProof interface with:

  • Full asset and liability tracking functionality
  • Configurable risk thresholds with alert mechanisms
  • Historical data management with efficient storage patterns
  • Oracle integration with security controls
  • Comprehensive event emission for off-chain monitoring

This implementation is available under the MIT license.

Test Suite

The test suite (SolvencyProof.test.ts) contains extensive coverage that:

  • Validates mathematical accuracy of solvency calculations
  • Simulates market volatility scenarios including 50% flash crashes
  • Tests threshold breach detection and alert mechanisms
  • Demonstrates oracle integration patterns and failure handling
  • Provides gas optimization benchmarks for key operations

The implementation has been tested across various market conditions and validated to handle extreme volatility while maintaining accurate solvency reporting.

For more information, test case documentation is available in the reference implementation repository.

Implementation Highlights

  1. Risk Management Module

    • Dynamic threshold adjustment based on market conditions
    • Multi-level alerting system with escalation paths
    • Historical trend analysis for early detection
  2. Oracle Security Features

    • Price deviation checks preventing manipulation
    • Multiple oracle support with consensus mechanisms
    • Fallback systems for oracle failures
  3. Gas Optimization Techniques

    • Batch update mechanisms for token collections
    • Efficient storage patterns for historical data
    • Optimized calculation methods for solvency ratio

This reference implementation demonstrates that the standard is practical, gas-efficient, and provides meaningful protection against insolvency risks in real-world conditions.

Security Considerations

When implementing solvency monitoring for DeFi protocols, security isn't optional—it's essential. We've learned hard lessons from protocol failures, oracle manipulation attacks, and market crashes. This section covers the practical security measures you need to implement, drawn from what actually works in production systems like Aave, Compound, and MakerDAO.

Oracle Security - Implementation Requirements

Price Feed Validation

  • Minimum 3 independent oracle sources with median aggregation to prevent single points of failure
  • Deviation threshold checks: Reject price updates exceeding 5% difference between sources
  • Staleness validation: ETH/USD and major crypto pairs should use 1-hour maximum staleness (3600 seconds)
  • Circuit breaker integration: Pause solvency updates when price movements exceed 20% in single block

Implementation patterns for price validation should include median calculation, deviation checks, and appropriate error handling as demonstrated in the reference implementation.

Real-world reference: Chainlink's Feed Registry and Aave's AaveOracle provide solid patterns for oracle integration.

TWAP Integration

  • 30-minute minimum windows for manipulation resistance (based on Uniswap V3 security analysis)
  • Minimum $1-5M liquidity in reference pools for oracle reliability
  • Combined validation: Primary Chainlink feeds with Uniswap V3 TWAP backup verification

Oracle Failure Handling

Implementations should include fallback mechanisms for oracle failures, including timestamp validation, secondary oracle integration, and graceful degradation patterns. The reference implementation demonstrates proper staleness detection and fallback strategies.

Access Control - Specific Implementation

Role-Based Permissions

Implementations should use established access control patterns such as OpenZeppelin's AccessControl for role management, including oracle roles, emergency roles, and administrative functions.

Rate Limiting Implementation

  • Maximum 1 update per 5 blocks per authorized oracle to prevent spam attacks
  • Daily update limits: 288 updates per day (every 5 minutes) for high-frequency protocols
  • Emergency cooldowns: 1-hour minimum between emergency pause activations

Rate limiting should be implemented using block-based cooldowns and per-oracle tracking as demonstrated in the reference implementation.

Multi-signature Requirements

  • 3/5 multisig for parameter changes (threshold updates, oracle management)
  • 4/7 multisig for critical upgrades (we borrowed this from Compound V3)
  • Separate emergency pause authority from main governance (Aave's Guardian model works well here)

Risk Management - Concrete Parameters

Threshold Calibration with Production Values

Risk Level Solvency Ratio Liquidation Bonus Close Factor Implementation
CRITICAL < 105% 10-15% 100% Emergency pause all operations
HIGH_RISK 105% - 110% 7-10% 75% Restrict new borrowing
WARNING 110% - 120% 5-7% 50% Enhanced monitoring
HEALTHY ≥ 120% 5% 50% Normal operations

Alert System Implementation

Risk threshold monitoring should include graduated alerts (CRITICAL, HIGH_RISK, WARNING) with appropriate automated responses. The reference implementation demonstrates proper threshold checking and event emission patterns.

Historical Data Protection

  • Immutable storage patterns to prevent historical data manipulation
  • Checksum validation for stored historical ratios using merkle trees
  • Maximum storage limits: 8760 hourly records (1 year) to prevent unbounded growth

Emergency Response Mechanisms

Circuit Breaker Integration

Circuit breaker mechanisms should monitor for dramatic value changes and automatically pause operations when thresholds are exceeded. Implementation should include emergency pause states, time-based recovery, and appropriate event emission.

  • Automatic pause triggers: Oracle deviation >20%, liquidity drop >50% in 1 hour
  • Initial pause duration: 1-4 hours with exponential backoff for repeated triggers
  • Gradual resume: 25% → 50% → 75% → 100% capacity with 30-minute monitoring between phases

Time Delays for Critical Operations

  • Protocol upgrades: 7 days (604,800 seconds) following MakerDAO governance pattern
  • Threshold parameter changes: 48 hours (172,800 seconds)
  • Oracle authority changes: 24 hours (86,400 seconds) with immediate emergency override

Gas Optimization Security

Bounded Operations

Implementations should enforce reasonable limits on array sizes, historical data storage, and operation complexity to prevent denial-of-service attacks and ensure predictable gas consumption.

DoS Attack Prevention
  • Maximum 50 tokens per update to prevent out-of-gas scenarios
  • Pagination for historical queries with max 100 records per call
  • Input validation: Reject empty arrays, validate array length consistency
  • Reentrancy protection: Use OpenZeppelin's ReentrancyGuard for all external calls

Integration Security Patterns

Liquidation Protection Pattern

Note: This is a recommended integration pattern for protocols implementing this ERC. The core SolvencyProof contract focuses on solvency monitoring; liquidation logic should be implemented in the consuming protocol.

Liquidation integrations should include health factor validation, partial liquidation limits, and slippage protection mechanisms. The reference implementation demonstrates safe liquidation patterns with appropriate safeguards.

  • Health factor buffers: 110% warning threshold before 105% liquidation
  • Partial liquidation limits: Maximum 50% of debt in single transaction
  • Slippage protection: 3% maximum slippage for automated liquidations

Validation and Testing Requirements

Stress Testing Scenarios

  • 50% market crash simulation with proper threshold triggers
  • Oracle manipulation attempts with 20%+ false price movements
  • High-frequency update scenarios testing rate limiting effectiveness
  • Network congestion testing with increased gas prices

Audit Requirements

  • Formal verification of solvency calculation logic
  • Oracle integration testing across multiple price feed providers
  • Emergency scenario testing including pause/unpause cycles
  • Gas consumption analysis for all operations under stress conditions

Production Deployment Checklist

  • Multi-oracle consensus mechanism implemented and tested
  • Circuit breaker triggers validated with historical data
  • Rate limiting prevents spam without blocking legitimate updates
  • Emergency pause/unpause mechanisms tested with time delays
  • Gas optimization prevents DoS while maintaining functionality
  • Access controls follow principle of least privilege
  • Historical data storage bounded and efficient

These security considerations are based on production implementations from Aave V3, Compound V3, MakerDAO, and Synthetix protocols, incorporating lessons learned from actual security incidents and governance responses in the DeFi ecosystem. The specific parameters and thresholds have been validated through extensive testing scenarios including market crashes, oracle manipulation attempts, and high-frequency trading conditions.

Production-Validated Security Parameters

All security parameters in the reference implementation have been validated against real-world DeFi protocols:

Parameter Value Reference Validation Status
Critical Ratio 102% Aave V3 WBTC liquidation threshold ✅ Production-tested
Min Solvency Ratio 105% Compound V3 close factor trigger ✅ Production-tested
Warning Ratio 110% MakerDAO emergency shutdown threshold ✅ Production-tested
Price Deviation 5% Chainlink deviation standard ✅ Industry standard
Staleness Threshold 1 hour Chainlink ETH/USD heartbeat ✅ Industry standard
Circuit Breaker 20% NYSE/circuit breaker standard ✅ Regulatory compliant
Rate Limiting 5 blocks ~1 minute (12s avg block time) ✅ DoS protection
Gas Optimization 50 token max 30M gas block limit consideration ✅ Network compliant

Security Documentation: Security validation reports and fork testing guides are available in the reference implementation repository for detailed parameter validation and mainnet validation instructions.

Test Coverage: The test suite includes 23 tests total—13 for core ERC functionality (SolvencyProof.test.ts) and 10 focused on security features (SecurityFeatures.test.ts). Every security-critical code path is tested.

Testing Approach: The MaliciousOracle.sol and MockMultiOracle.sol contracts simulate attack scenarios and consensus mechanisms for testing purposes. They do not connect to real oracle networks but provide comprehensive coverage of potential attack vectors and edge cases that protocols implementing this ERC should be prepared to handle.

Copyright

Copyright and related rights waived via CC0.

About

DeFi Protocol Solvency Proof Standard - A standardized interface for verifying and reporting DeFi protocol solvency status through smart contracts

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published