Skip to content

Commit

Permalink
distribute rewards after partial intervals instead of waiting for ent…
Browse files Browse the repository at this point in the history
…ire interval to finish, so that VP change doesn't delay distribution
  • Loading branch information
NoahSaso committed Oct 23, 2024
1 parent c05a6c8 commit 56b204c
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 21 deletions.
10 changes: 9 additions & 1 deletion contracts/distribution/dao-rewards-distributor/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use cosmwasm_std::{DivideByZeroError, OverflowError, StdError};
use cosmwasm_std::{
CheckedFromRatioError, CheckedMultiplyFractionError, DivideByZeroError, OverflowError, StdError,
};
use cw_utils::PaymentError;
use thiserror::Error;

Expand All @@ -19,6 +21,12 @@ pub enum ContractError {
#[error(transparent)]
DivideByZero(#[from] DivideByZeroError),

#[error(transparent)]
CheckedFromRatio(#[from] CheckedFromRatioError),

#[error(transparent)]
CheckedMultiplyFraction(#[from] CheckedMultiplyFractionError),

#[error(transparent)]
Payment(#[from] PaymentError),

Expand Down
16 changes: 8 additions & 8 deletions contracts/distribution/dao-rewards-distributor/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cosmwasm_std::{
coins, to_json_binary, Addr, BankMsg, BlockInfo, CosmosMsg, Deps, DepsMut, StdError, StdResult,
Uint128, Uint256, WasmMsg,
coins, to_json_binary, Addr, BankMsg, BlockInfo, CosmosMsg, Decimal, Deps, DepsMut, StdError,
StdResult, Uint128, Uint256, WasmMsg,
};
use cw20::{Denom, Expiration};
use cw_utils::Duration;
Expand Down Expand Up @@ -117,9 +117,9 @@ pub trait DurationExt {
/// Returns true if the duration is 0 blocks or 0 seconds.
fn is_zero(&self) -> bool;

/// Perform checked integer division between two durations, erroring if the
/// units do not match or denominator is 0.
fn checked_div(&self, denominator: &Self) -> Result<Uint128, ContractError>;
/// Returns the ratio between the two durations (numerator / denominator) as
/// a Decimal, erroring if the units do not match.
fn ratio(&self, denominator: &Self) -> Result<Decimal, ContractError>;
}

impl DurationExt for Duration {
Expand All @@ -130,13 +130,13 @@ impl DurationExt for Duration {
}
}

fn checked_div(&self, denominator: &Self) -> Result<Uint128, ContractError> {
fn ratio(&self, denominator: &Self) -> Result<Decimal, ContractError> {
match (self, denominator) {
(Duration::Height(numerator), Duration::Height(denominator)) => {
Ok(Uint128::from(*numerator).checked_div(Uint128::from(*denominator))?)
Ok(Decimal::checked_from_ratio(*numerator, *denominator)?)
}
(Duration::Time(numerator), Duration::Time(denominator)) => {
Ok(Uint128::from(*numerator).checked_div(Uint128::from(*denominator))?)
Ok(Decimal::checked_from_ratio(*numerator, *denominator)?)
}
_ => Err(ContractError::Std(StdError::generic_err(format!(
"incompatible durations: got numerator {:?} and denominator {:?}",
Expand Down
16 changes: 6 additions & 10 deletions contracts/distribution/dao-rewards-distributor/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,13 @@ pub fn get_active_total_earned_puvp(
if total_power.is_zero() {
Ok(curr)
} else {
// count intervals of the rewards emission that have passed
// since the last update which need to be distributed
// count (partial) intervals of the rewards emission that have
// passed since the last update which need to be distributed
let complete_distribution_periods =
new_reward_distribution_duration.checked_div(&duration)?;

// It is impossible for this to overflow as total rewards can
// never exceed max value of Uint128 as total tokens in
// existence cannot exceed Uint128 (because the bank module Coin
// type uses Uint128).
let new_rewards_distributed = amount
.full_mul(complete_distribution_periods)
new_reward_distribution_duration.ratio(&duration)?;

let new_rewards_distributed = Uint256::from(amount)
.checked_mul_floor(complete_distribution_periods)?
.checked_mul(scale_factor())?;

// the new rewards per unit voting power that have been
Expand Down
4 changes: 2 additions & 2 deletions contracts/distribution/dao-rewards-distributor/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,9 @@ impl DistributionState {

// count total intervals of the rewards emission that will pass
// based on the start and end times.
let complete_distribution_periods = epoch_duration.checked_div(&duration)?;
let complete_distribution_periods = epoch_duration.ratio(&duration)?;

Ok(amount.checked_mul(complete_distribution_periods)?)
Ok(amount.checked_mul_floor(complete_distribution_periods)?)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2659,6 +2659,43 @@ fn test_large_stake_before_claim() {
suite.claim_rewards(MEMBER3, 1);
}

#[test]
fn test_stake_during_interval() {
let mut suite = SuiteBuilder::base(super::suite::DaoType::Native)
.with_rewards_config(RewardsConfig {
amount: 100,
denom: UncheckedDenom::Native(GOV_DENOM.to_string()),
duration: Duration::Height(100),
destination: None,
continuous: true,
})
.build();

suite.assert_amount(100);
suite.assert_ends_at(Expiration::AtHeight(100_000_000));
suite.assert_duration(100);

// after half the duration, half the rewards (50) should be distributed.
suite.skip_blocks(50);

// MEMBER1 has 50% voting power, so should receive 50% of the rewards.
suite.assert_pending_rewards(MEMBER1, 1, 25);

// change voting power before the next distribution interval. MEMBER1 now
// has 80% voting power, an increase from 50%.
suite.mint_native(coin(300, GOV_DENOM), MEMBER1);
suite.stake_native_tokens(MEMBER1, 300);

// after the rest of the initial duration, they should earn rewards at the
// increased rate (50 more tokens, and they own 80% of them). 25 + 40 = 65
suite.skip_blocks(50);
suite.assert_pending_rewards(MEMBER1, 1, 65);

// after 50 more blocks from VP change, there are 40 more rewards.
suite.skip_blocks(50);
suite.assert_pending_rewards(MEMBER1, 1, 105);
}

#[test]
fn test_fund_latest_native() {
let mut suite = SuiteBuilder::base(super::suite::DaoType::Native).build();
Expand Down

0 comments on commit 56b204c

Please sign in to comment.