ERC-7893 - DeFi Protocol Solvency Proof Mechanism

Created 2025-01-30
Status Draft
Category ERC
Type Standards Track
Authors
  • Sean Luis Guada Rodríguez (@SeanLuis) <seanluis47 at gmail.com>

Requires

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:

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.

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 Interfaces

The standard defines a comprehensive interface for solvency verification. Key features include:

  1. Asset and Liability Management
  2. Protocol assets tracking
  3. Protocol liabilities tracking
  4. Real-time value updates
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.20;

/**
 * @title ISolvencyProof
 * @author Sean Luis ([@SeanLuis](https://github.com/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;
}

Optional Oracle Management

While not part of the core standard, implementations should consider including oracle management:

// Recommended but not required
event OracleUpdated(address indexed oracle, bool authorized);
function setOracle(address oracle, bool authorized) external;

This provides: - Flexible price feed management - Security controls - Update authorization

The core standard focuses on solvency verification, leaving oracle management implementation details to individual protocols.

How the Interface Works

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.

Asset and Liability Management

Authorized oracles are responsible for updating the protocol's asset and liability data using the updateAssets and updateLiabilities functions. These updates include the list of tokens, their respective amounts, and their current values denominated in ETH. Each update is timestamped, ensuring that all solvency calculations and historical records are based on the most recent and accurate data available. The interface enforces that all arrays provided must be of equal length, and values must be denominated in ETH with 18 decimals for consistency and comparability.

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 the minimum required solvency ratio (e.g., 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

To support audits, regulatory requirements, 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.

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. If a risk threshold is 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). Only authorized oracles can update asset and liability data, ensuring 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 are expected to: - 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. - 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.

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

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:
  2. More efficient state retrieval for monitoring systems
  3. Better compatibility with historical tracking requirements
  4. Simplified batch updates in volatile market conditions

  5. Timestamp embedding within structures rather than separate mappings provides:

  6. Atomic updates with data consistency guarantees
  7. Protection against partial-update scenarios during price volatility
  8. Single-transaction verification of data freshness

  9. Combined value and amount tracking was implemented for:

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

Test-Driven Design Decisions

Our implementation testing significantly shaped the final design:

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

  5. Volatility Testing

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

  10. Oracle Integration

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

Threshold Selection Methodology

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

  1. Market Crash Testing
  2. 105% represents the critical threshold where recovery becomes unlikely
  3. Testing confirms this threshold successfully identifies insolvency scenarios
  4. System correctly triggers warnings at appropriate levels

  5. Complex Portfolio Analysis

  6. Tests with diverse portfolios (ETH, BTC, USDC, LP tokens, etc.)
  7. Complex liability structures (stablecoins + volatile assets)
  8. Thresholds provide appropriate buffer against normal market fluctuations

  9. Gas Optimization vs. Precision

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

Implementation Insights

Key insights from our implementation and testing:

  1. Efficient Asset Tracking
  2. The parallel arrays approach for token data minimizes storage costs
  3. Implementation maintains constant-time lookups for critical operations
  4. Bounded array sizes prevent out-of-gas scenarios

  5. Oracle Integration Patterns

  6. Permissioned oracle design prevents manipulation
  7. Clean separation between price data and protocol logic
  8. Flexible design supports various oracle implementations

  9. Risk Management System

  10. Multi-tier alert system provides graduated responses to deteriorating conditions
  11. Historical metrics enable trend analysis across market cycles
  12. 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:

2. Risk-Adjusted Health Factor

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

Where:

3. Risk Metrics

Value at Risk (VaR)

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

Where:

Liquidity Coverage Ratio (LCR)

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

Where:

4. System Health Index

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

Where:

5. Default Probability

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

Where:

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:
  2. Base Solvency Ratio (SR)
  3. Risk-Adjusted Health Factor (HF)
  4. Liquidity Coverage Ratio (LCR)

  5. 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
  2. Using existing oracle networks (Chainlink, API3, etc.)
  3. Custom price feed implementations
  4. Internal price calculations

  5. Aggregation Strategies

  6. Multiple oracle sources
  7. TWAP implementations
  8. Medianized price feeds

oracle-integration

Implementation Requirements

  1. Asset Management:
  2. Real-time asset tracking
  3. Price feed integration
  4. Historical data maintenance

  5. Liability Tracking:

  6. Debt obligation monitoring
  7. Collateral requirement calculation
  8. Risk factor assessment

  9. Reporting System:

  10. Event emission for significant changes
  11. Threshold breach notifications
  12. Historical data access

Implementation Considerations

Implementation Notes

Based on conducted tests, it is recommended:

  1. Liability Management:
  2. Maintain constant liabilities during price updates
  3. Validate that liabilities are never 0 to avoid division by zero
  4. Update liabilities only when actual positions change

  5. Ratio Calculation:

solidity 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; }

  1. State Validation:
  2. Verify values before updating
  3. Maintain accurate history
  4. Emit events for significant changes

  5. Gas Considerations:

  6. Optimize history storage
  7. Batch updates for multiple tokens
  8. Limit array sizes in updates

For more details please visit: Solvency Proof Implementation

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

SolvencyProof.sol provides a complete implementation of the ISolvencyProof interface with:

This implementation is under license: MIT

Test Suite

SolvencyProof.test.ts contains an extensive test suite that:

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

For more information please visit: Test Case Documentation

Implementation Highlights

  1. Risk Management Module
  2. Dynamic threshold adjustment based on market conditions
  3. Multi-level alerting system with escalation paths
  4. Historical trend analysis for early detection

  5. Oracle Security Features

  6. Price deviation checks preventing manipulation
  7. Multiple oracle support with consensus mechanisms
  8. Fallback systems for oracle failures

  9. Gas Optimization Techniques

  10. Batch update mechanisms for token collections
  11. Efficient storage patterns for historical data
  12. 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

Key security considerations include:

  1. Oracle Security:
  2. Multiple price feed sources
  3. Manipulation resistance
  4. Fallback mechanisms

  5. Access Control:

  6. Authorized updaters
  7. Rate limiting

  8. Risk Management:

  9. Threshold calibration
  10. Alert system reliability

Copyright

Copyright and related rights waived via CC0.