riftenlabs-indexer/src/rpc/apy/apyaggregator.rs

38 lines
1.1 KiB
Rust
Raw Normal View History

// Copyright (C) 2024 Riften Labs AS
//
// This software is licensed under the GNU Affero General Public License (AGPL), version 3.0 or later.
// A copy of the license can be found in the LICENSE file or at https://www.gnu.org/licenses/agpl-3.0.html
use anyhow::Result;
use rust_decimal::Decimal;
use super::poolperiod::PoolPeriod;
pub struct APYAggregator;
impl APYAggregator {
pub fn aggregate_apy<I>(pools: I, period_start: Option<u64>) -> Result<Decimal>
where
I: Iterator<Item = PoolPeriod>,
{
let mut weighted_apy_sum = Decimal::ZERO;
let mut total_active_time = Decimal::ZERO;
for pool in pools {
let days_active = pool.duration_days(&period_start)?;
if !days_active.is_zero() {
let (_pool_yield, apy) = pool.yield_and_apy(&period_start)?;
weighted_apy_sum += apy * days_active;
total_active_time += days_active;
}
}
if total_active_time.is_zero() {
Ok(Decimal::ZERO)
} else {
Ok(weighted_apy_sum / total_active_time)
}
}
}