Ensure the security of your smart contracts

Investigating Balance Integrity in Aave Markets

Author: Artem Ustinov, Dmitry Zakharov
Security researchers at MixBytes
The BGD Labs team approached us with the issue they encountered during the Aave update from v3 to v3.1. This article explains the problem in detail, describes how we were trying to find the source of the issue, and describes the results of the research. TLDR: Funds are Safu:)
The Importance of Maintaining an Invariant for Stability
A key aspect of any stable DeFi pool is ensuring that depositors can access their funds whenever they choose, regardless of market conditions. This is achieved by maintaining an invariant — a mathematical condition that guarantees sufficient liquidity is always available. If this condition fails, the pool might not have enough balance to return funds to depositors, undermining the protocol's reliability.

In Aave markets, the presence of borrowing and debt mechanisms means that pools inherently cannot immediately fulfill all withdrawal requests. However, assuming that debts can be incentivized for repayment or liquidation, a critical invariant can be established: the sum of all deposited tokens, along with the interest they have accrued, minus the borrowed tokens and their accrued debt, must not exceed the actual balance of underlying tokens in the market. This condition ensures that debts and liquidity interest remain harmonized, preventing scenarios where repaid debt falls short of the tokens owed to depositors.

Mathematically, this invariant is expressed through the virtual balance formula, representing the minimum amount of underlying tokens required for the market to function correctly:
Bv = ( Sa + T ) • Ia – ( Sv • Iv + Ss • Is ) ,
where:

( S_a ) is the total supply of aToken shares.
( T ) is the treasury's share, accrued but not included in ( S_a ).
( I_a ) is the liquidity interest index.
( S_v ) and ( S_s ) are the total supplies of variable and stable debt tokens, respectively.
( I_v ) and ( I_s ) are the cumulative interest indexes on variable and stable debts, respectively.
This formula ensures that the virtual balance ( B_v ) does not exceed the actual token balance ( B_u ):
Bu ≥ Bv
In healthy markets, this invariant is preserved by ensuring that the linearly increasing liquidity interest remains within the bounds of the exponentially increasing debt interest.
Identifying the Imbalance Issue
During an upgrade from version 3.0 to 3.1, a concerning issue was identified by BGD Labs team: even a certain small deviation was expected in the invariant, in some specific cases this deviation was slightly higher than expected. In some cases, the virtual balance deviated significantly, resulting in a substantial delta between the expected and actual balances:
BΔ = Bv – Bu
Even though the deviation wasn't huge and couldn't affect the users in any way, its magnitude clearly wasn't caused by dust accumulation. It was crucial to determine the reason that caused such deviation to ensure that the overall system stability. To determine the root cause, a comprehensive analysis of historical transactions was undertaken.
Investigating the Cause: Analysis of Transactions
The BGD Labs team shared their vision of possible root causes of the invariant deviation. Different assumptions were made about what might have gone wrong in the past. For example, there were markets with very high historical interest rates, implementation updates, or even updated accruedToTreasury logic. They pointed out that there is a market with a deviation in the invariant, and assets from this market haven't been borrowed. We decided to start from this specific market to simplify the investigation. This simplification reduced the variables in the virtual balance formula, narrowing down possible causes. A notable case was the aArbAave market. Preliminary analysis revealed that a seemingly routine flash loan transaction had caused the delta to spike by 5*10^7.

Initial reviews of the flash loan logic did not reveal any obvious errors. While minor rounding errors could account for slight increases in delta, they could not explain the significant spike observed. To isolate the problematic transactions, a binary search method was applied, revealing that the last significant delta increase occurred over a year prior, suggesting an issue in an older implementation. A review of the relevant update following the last transaction revealed the origin of the issue.

By examining the code differences in FlashLoanLogic.sol between the affected versions, it was discovered that the calculation of the reserve.liquidityIndex during flash loan operations did not account for the accruedToTreasury variable. This variable represents the treasury's share of the accrued interest, which is not included in the total supply of aTokens but still accumulates interest over time.

Specifically, the function cumulativeToLiquidityIndex, responsible for adjusting the liquidityIndex based on the premium collected from flash loans, was using the totalSupply of aTokens without adding the accruedToTreasury. As a result, the premium was effectively being distributed over a smaller number of tokens than it should have been, causing the liquidityIndex to increase more than appropriate.

This miscalculation led to an overestimation of the virtual balance Bv, pushing it beyond the actual balance Bu.
After implementation update, no further significant delta increases (beyond a few wei) were observed in subsequent transactions, confirming that this error was indeed the root cause for this market.
Continuing the Investigation: Other Affected Markets
Despite resolving the issue related to flash loans, similar problems were found in markets where borrowing was enabled. These markets exhibited significant delta changes without recent updates to the codebase, suggesting a different underlying cause.

The delta over time in these markets was not consistently increasing or decreasing, complicating the analysis. To identify the problematic transactions, an adjusted search method was used, focusing on delta-over-time visualizations.



The analysis revealed that in each affected market, a specific transaction led to a sudden and significant increase in the delta. These transactions varied: they included borrowing, supplying, and withdrawing operation, but they all occurred without any recent changes to the market's implementation.

Further investigation showed that prior to each of these transactions, the reserveFactor parameter had been modified. The reserveFactor determines the portion of interest from borrowers that is allocated to the protocol's treasury rather than to depositors.

When the reserveFactor is increased, the treasury's share of the interest grows, but unless the rates and indexes are recalculated immediately, the system does not account for this change correctly. Specifically, the liquidityRate, which influences the growth of the liquidityIndex, should be adjusted to reflect the new reserveFactor. If this recalculation does not occur, the liquidityIndex continues to grow at the previous rate, while the treasury starts receiving a larger share of the interest. This mismatch leads to an overestimation of the virtual balance ( B_v ), again violating the invariant.
An example of this issue can be illustrated as follows:

  • Before the change: The reserveFactor is set at 10%. Borrowers' interest payments are split, with 90% going to depositors and 10% to the treasury.
  • After increasing the reserveFactor to 20%: The treasury should now receive 20% of the interest payments. However, if the liquidityRate is not recalculated, the system continues to allocate interest based on the old 90% rate instead of 80%, causing discrepancies in how interest is distributed.
An update, addressing this issue, was made to the PoolConfigurator implementation also before the problem detected. This update ensures that whenever the reserveFactor is modified, the rates and indexes are recalculated immediately, aligning the interest distribution with the new settings.
After confirming that the delta inflation was caused by these two issues: the flash loan calculation error and the reserveFactor adjustment oversight, and that both had been resolved, the investigation concluded.
Lessons Learned and Future Considerations
The investigation into the balance integrity issues within Aave markets highlights several important considerations for maintaining stability in decentralized finance systems:

  1. Comprehensive Issue Resolution: Addressing problems in live systems requires more than implementing code fixes; it also involves mitigating any potential issues that may have already occurred. In this case, the code was updated to correct the miscalculations before the problem was fully identified. However, the existing imbalance in the virtual balance remained unaddressed. If actions had been taken immediately to adjust the delta after implementing the fixes, the need for extensive historical data analysis might have been minimized. This emphasizes the importance of not only correcting the code but also actively resolving any residual effects to ensure the system returns to a stable state.
  2. Continuous Monitoring of Critical Invariants: Regular monitoring of essential invariants is crucial for early detection of issues. In this scenario, the significant deviations in the delta went unnoticed for an extended period, allowing the imbalance to persist. Implementing robust monitoring tools to track critical invariants can help identify discrepancies as they arise, enabling timely interventions that prevent potential disruptions to normal operations.
  3. Historical Context Awareness: When an unknown issue is identified, understanding its origin is vital. Investigating when the problem began and collecting comprehensive data, including reviewing past implementation updates and parameter changes, provides valuable insights into the root cause. This approach ensures that solutions are accurate and effective, addressing not just the symptoms but the underlying factors contributing to the issue.
Conclusion
The analysis of the invariant breach in Aave markets underscores the complexities involved in maintaining stable DeFi protocols. By identifying and understanding the factors that led to the imbalance, measures have been implemented to enhance the system's stability. Moving forward, proactive monitoring and thorough issue resolution will be essential in ensuring the continued reliability and robustness of decentralized financial platforms.
Who is MixBytes?
MixBytes is a team of expert blockchain auditors and security researchers specializing in providing comprehensive smart contract audits and technical advisory services for EVM-compatible and Substrate-based projects. Join us on Twitter to stay up-to-date with the latest industry trends and insights.
Disclaimer
The information contained in this Website is for educational and informational purposes only and shall not be understood or construed as financial or investment advice.
Other posts