@@ -9,6 +9,7 @@ module aave_pool::pool_logic {
99
1010 use aave_config::reserve_config;
1111 use aave_config::reserve_config::ReserveConfigurationMap ;
12+ use aave_config::error_config;
1213 use aave_math::math_utils;
1314 use aave_math::wad_ray_math;
1415 use aave_pool::default_reserve_interest_rate_strategy;
@@ -418,21 +419,30 @@ module aave_pool::pool_logic {
418419 ) {
419420 if (reserve_cache.reserve_factor == 0 ) { return };
420421
421- //calculate the total variable debt at moment of the last interaction
422- let prev_total_variable_debt =
423- wad_ray_math::ray_mul (
424- reserve_cache.curr_scaled_variable_debt,
425- reserve_cache.curr_variable_borrow_index
426- );
422+ // Defensive check: ensure next_index >= curr_index to prevent underflow
423+ // This is guaranteed by interest accumulation (next_index always grows or stays equal)
424+ assert !(
425+ reserve_cache.next_variable_borrow_index
426+ >= reserve_cache.curr_variable_borrow_index,
427+ error_config::get_eoverflow ()
428+ );
427429
428- //calculate the new total variable debt after accumulation of the interest on the index
429- let curr_total_variable_debt =
430- wad_ray_math::ray_mul (
430+ // Calculate index delta: the difference between next and current borrow index
431+ // This represents the interest accrued since the last update
432+ let index_delta =
433+ reserve_cache.next_variable_borrow_index
434+ - reserve_cache.curr_variable_borrow_index;
435+
436+ // Calculate the debt accrued more precisely by multiplying scaled debt by index delta
437+ // This avoids double rounding errors and is mathematically equivalent to:
438+ // scaled_debt * next_index - scaled_debt * curr_index
439+ // Using ray_mul_down for conservative rounding (favor protocol)
440+ let total_debt_accrued =
441+ wad_ray_math::ray_mul_down (
431442 reserve_cache.curr_scaled_variable_debt,
432- reserve_cache.next_variable_borrow_index
443+ index_delta
433444 );
434445
435- let total_debt_accrued = curr_total_variable_debt - prev_total_variable_debt;
436446 let amount_to_mint =
437447 math_utils::percent_mul (total_debt_accrued, reserve_cache.reserve_factor);
438448
0 commit comments