From 9ca9d81de3284b3c6e22f8e900e59db4f7803d0c Mon Sep 17 00:00:00 2001 From: Christoph Otter Date: Tue, 11 Apr 2023 12:42:19 +0200 Subject: [PATCH 1/2] Fix staking reward calculation --- src/staking.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/staking.rs b/src/staking.rs index 8f0a63f1..612664c7 100644 --- a/src/staking.rs +++ b/src/staking.rs @@ -289,13 +289,12 @@ impl StakeKeeper { validator_info.stake, ); - // update validator info and delegators - if !new_rewards.is_zero() { - validator_info.last_rewards_calculation = block.time; - - // save updated validator - VALIDATOR_INFO.save(staking_storage, validator, &validator_info)?; + // update validator info + validator_info.last_rewards_calculation = block.time; + VALIDATOR_INFO.save(staking_storage, validator, &validator_info)?; + // update delegators + if !new_rewards.is_zero() { let validator_addr = api.addr_validate(&validator_obj.address)?; // update all delegators for staker in validator_info.stakers.iter() { From 62244ca8e6ae25d85669a39495cb00853800f3c4 Mon Sep 17 00:00:00 2001 From: Christoph Otter Date: Tue, 11 Apr 2023 13:17:40 +0200 Subject: [PATCH 2/2] Add test for timestamp update --- src/staking.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/staking.rs b/src/staking.rs index 612664c7..b4911c51 100644 --- a/src/staking.rs +++ b/src/staking.rs @@ -2450,5 +2450,51 @@ mod test { .unwrap(); assert_eq!(balance.amount.u128(), 55); } + + #[test] + fn rewards_initial_wait() { + let (mut test_env, validator) = + TestEnv::wrap(setup_test_env(Decimal::percent(10), Decimal::zero())); + let delegator = Addr::unchecked("delegator"); + + // init balance + test_env + .router + .bank + .init_balance(&mut test_env.store, &delegator, vec![coin(100, "TOKEN")]) + .unwrap(); + + // wait a year before staking + const YEAR: u64 = 60 * 60 * 24 * 365; + test_env.block.time = test_env.block.time.plus_seconds(YEAR); + + // delegate some tokens + execute_stake( + &mut test_env, + delegator.clone(), + StakingMsg::Delegate { + validator: validator.to_string(), + amount: coin(100, "TOKEN"), + }, + ) + .unwrap(); + + // wait another year + test_env.block.time = test_env.block.time.plus_seconds(YEAR); + + // query rewards + let response: DelegationResponse = query_stake( + &test_env, + StakingQuery::Delegation { + delegator: delegator.to_string(), + validator: validator.to_string(), + }, + ) + .unwrap(); + assert_eq!( + response.delegation.unwrap().accumulated_rewards, + vec![coin(10, "TOKEN")] // 10% of 100 + ); + } } }