Skip to content

Commit 6f0b567

Browse files
authored
Merge pull request #81 from aave/mike/improve/treasury-accrual-rounding
Mike/improve/treasury accrual rounding
2 parents 8ef5286 + aec7d1e commit 6f0b567

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

aave-core/sources/aave-pool/pool_logic.move

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)