Skip to content

Commit

Permalink
feat: change bond/unbond to not send rewards, and only send rewards w…
Browse files Browse the repository at this point in the history
…hen 'withdraw' is called
  • Loading branch information
PFC-developer committed Dec 16, 2022
1 parent 66cb81c commit f4e1af6
Show file tree
Hide file tree
Showing 15 changed files with 380 additions and 98 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ code_id*.json
.idea

# ignore compiled objects
/artifacts/
**/artifacts/
/artifacts/*-aarch64.wasm
/artifacts/checksums_intermediate.txt
#**/artifacts/
#
/*.json
/contracts/*/.env
Expand Down
3 changes: 3 additions & 0 deletions artifacts/checksums.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ee34c7b22696c3bfe41b5936c1bf3763b889dadf9d523ea715be0c096df7f35f pfc_astroport_generator.wasm
cefd0e65d1c5b1fa155066da9866a5879c0aee9619f0724198514206bb5ccf1b pfc_fee_splitter.wasm
fdff971f8dc375ebc949ea60d4f5b15167e74e8174d0e86e7e3f10c18ab1203d pfc_vault_contract.wasm
Binary file added artifacts/pfc_astroport_generator.wasm
Binary file not shown.
Binary file added artifacts/pfc_fee_splitter.wasm
Binary file not shown.
Binary file added artifacts/pfc_vault_contract.wasm
Binary file not shown.
2 changes: 1 addition & 1 deletion contracts/pfc-vault-contract/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pfc-vault-contract"
version = "0.2.5"
version = "0.2.6"
authors = ["PFC","Valkyrie Protocol"]
edition = "2021"
description = "modified by PFC. Originally A Staking contract for Valkyrie Protocol - distribute rewards to stakers"
Expand Down
121 changes: 89 additions & 32 deletions contracts/pfc-vault-contract/src/executions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::collections::HashMap;

use cosmwasm_std::{
Addr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, StdError, StdResult,
Storage, to_binary, Uint128, WasmMsg,
to_binary, Addr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, StdError,
StdResult, Storage, Uint128, WasmMsg,
};
use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg};

Expand All @@ -11,9 +11,10 @@ use pfc_vault::message_factories;
use pfc_vault::vault::TokenBalance;

use crate::states::{
ADMIN, Config, NUM_STAKED, StakerInfo, TOTAL_REWARDS, USER_CLAIM, USER_LAST_CLAIM,
UserTokenClaim,
Config, PendingClaimAmount, StakerInfo, UserTokenClaim, ADMIN, NUM_STAKED, TOTAL_REWARDS,
USER_CLAIM, USER_LAST_CLAIM, USER_PENDING_CLAIM,
};
use crate::utils::merge_claims;

pub fn bond(
deps: DepsMut,
Expand Down Expand Up @@ -43,7 +44,8 @@ pub fn bond(
)?;
// } else {
}
let msgs = do_token_claims(deps.storage, env.block.height, &sender_addr_raw)?;
// let msgs = do_token_claims_and_gen_messages(deps.storage, env.block.height, &sender_addr_raw)?;
update_token_claims(deps.storage, env.block.height, &sender_addr_raw)?;

// Increase bond_amount
let num_staked = NUM_STAKED.update(deps.storage, |num| -> StdResult<Uint128> {
Expand All @@ -52,16 +54,15 @@ pub fn bond(
staker_info.bond_amount += amount;
staker_info.save(deps.storage)?;

Ok(Response::new()
.add_attributes(vec![
("action", "bond"),
("owner", &sender_addr),
("amount_bonded", &amount.to_string()),
("amount_staked", &staker_info.bond_amount.to_string()),
// ("amount_per_stake", &amount_per_stake.to_string()),
("total_staked", &num_staked.to_string()),
])
.add_messages(msgs))
Ok(Response::new().add_attributes(vec![
("action", "bond"),
("owner", &sender_addr),
("amount_bonded", &amount.to_string()),
("amount_staked", &staker_info.bond_amount.to_string()),
// ("amount_per_stake", &amount_per_stake.to_string()),
("total_staked", &num_staked.to_string()),
]))
// .add_messages(msgs))
}

///
Expand All @@ -83,7 +84,8 @@ pub fn unbond(
)));
}

let msgs = do_token_claims(deps.storage, env.block.height, &sender_addr_raw)?;
// let msgs = do_token_claims_and_gen_messages(deps.storage, env.block.height, &sender_addr_raw)?;
update_token_claims(deps.storage, env.block.height, &sender_addr_raw)?;

// Decrease bond_amount
let num_staked = NUM_STAKED.update(deps.storage, |num| -> StdResult<Uint128> {
Expand All @@ -107,7 +109,7 @@ pub fn unbond(
msg: Default::default(),
},
))
.add_messages(msgs)
// .add_messages(msgs)
.add_attribute("owner", sender_addr_raw.to_string())
.add_attribute("amount", amount.to_string())
.add_attribute("amount_staked", &staker_info.bond_amount.to_string())
Expand Down Expand Up @@ -166,13 +168,17 @@ pub fn withdraw(deps: DepsMut, env: Env, info: MessageInfo) -> Result<Response,
let sender_addr_raw = info.sender;

let staker_info = StakerInfo::load_or_default(deps.storage, &sender_addr_raw)?;
let has_pending = USER_PENDING_CLAIM
.may_load(deps.storage, sender_addr_raw.clone())?
.unwrap_or_default();

if staker_info.bond_amount.is_zero() {
if staker_info.bond_amount.is_zero() && has_pending.is_empty() {
staker_info.delete(deps.storage);
Err(ContractError::NoneBonded {})
} else {
let num_staked = NUM_STAKED.load(deps.storage)?;
let msgs = do_token_claims(deps.storage, env.block.height, &sender_addr_raw)?;
let msgs =
do_token_claims_and_gen_messages(deps.storage, env.block.height, &sender_addr_raw)?;

Ok(Response::new()
.add_attributes(vec![
Expand Down Expand Up @@ -273,7 +279,11 @@ pub fn execute_set_new_astroport_generator(
generator_contract: Option<String>,
) -> Result<Response, ContractError> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
let astroport_generator_contract = if let Some(x) = generator_contract { Some(deps.api.addr_validate(&x)?) } else { None };
let astroport_generator_contract = if let Some(x) = generator_contract {
Some(deps.api.addr_validate(&x)?)
} else {
None
};
let mut config = Config::load(deps.storage)?;

config.new_gov_contract = astroport_generator_contract;
Expand Down Expand Up @@ -314,12 +324,27 @@ pub fn execute_accept_gov_contract(
}
}

pub(crate) fn do_token_claims(
/// calculates the amount of claims outstanding, storing it in USER_PENDING_CLAIM but not sending it
pub(crate) fn update_token_claims(
storage: &mut dyn Storage,
block_height: u64,
addr: &Addr,
) -> Result<Vec<CosmosMsg>, ContractError> {
let mut resp: Vec<CosmosMsg> = vec![];
) -> Result<(), ContractError> {
let previous = USER_PENDING_CLAIM
.may_load(storage, addr.clone())?
.unwrap_or_default();
let current = get_current_claims(storage, block_height, addr)?;
let merged = merge_claims(&previous, &current);
USER_PENDING_CLAIM.save(storage, addr.clone(), &merged)?;
Ok(())
}

pub(crate) fn get_current_claims(
storage: &mut dyn Storage,
block_height: u64,
addr: &Addr,
) -> Result<Vec<PendingClaimAmount>, ContractError> {
let mut resp: Vec<PendingClaimAmount> = vec![];
let mut new_claims: Vec<UserTokenClaim> = vec![];

let tallies = TOTAL_REWARDS
Expand Down Expand Up @@ -365,16 +390,10 @@ pub(crate) fn do_token_claims(
});

if !amt_to_send.is_zero() {
let msg = Cw20ExecuteMsg::Send {
contract: addr.to_string(),
resp.push(PendingClaimAmount {
token: token.0,
amount: amt_to_send,
msg: Default::default(),
};
resp.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: token.0.to_string(),
msg: to_binary(&msg)?,
funds: vec![],
}))
});
}
}
/*
Expand All @@ -384,6 +403,44 @@ pub(crate) fn do_token_claims(
);
*/
USER_CLAIM.save(storage, addr.clone(), &new_claims)?;
Ok(resp)
}

pub(crate) fn gen_claim_messages(
storage: &mut dyn Storage,
addr: &Addr,
clear_pending: bool,
) -> Result<Vec<CosmosMsg>, ContractError> {
let mut resp: Vec<CosmosMsg> = vec![];
if let Some(pending) = USER_PENDING_CLAIM.may_load(storage, addr.clone())? {
for claim_amount in pending {
if !claim_amount.amount.is_zero() {
let msg = Cw20ExecuteMsg::Send {
contract: addr.to_string(),
amount: claim_amount.amount,
msg: Default::default(),
};
resp.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: claim_amount.token.to_string(),
msg: to_binary(&msg)?,
funds: vec![],
}))
}
}
if clear_pending {
USER_PENDING_CLAIM.save(storage, addr.clone(), &vec![])?
}
}
Ok(resp)
}

pub(crate) fn do_token_claims_and_gen_messages(
storage: &mut dyn Storage,
block_height: u64,
addr: &Addr,
) -> Result<Vec<CosmosMsg>, ContractError> {
update_token_claims(storage, block_height, addr)?;
let resp = gen_claim_messages(storage, addr, true)?;

Ok(resp)
}
1 change: 1 addition & 0 deletions contracts/pfc-vault-contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ mod states;

#[cfg(test)]
mod tests;
mod utils;
53 changes: 46 additions & 7 deletions contracts/pfc-vault-contract/src/queries.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use cosmwasm_std::{Addr, Decimal, Deps, Env, Order, StdResult, Storage};
use pfc_vault::errors::ContractError;
use pfc_vault::vault::query_msgs::{
ConfigResponse, StakerInfoResponse, StateResponse,
};
use pfc_vault::vault::query_msgs::{ConfigResponse, StakerInfoResponse, StateResponse};
use pfc_vault::vault::TokenBalance;
use std::collections::HashMap;
use std::ops::Add;

use crate::states::{
Config, StakerInfo, UserTokenClaim, NUM_STAKED, TOTAL_REWARDS, USER_CLAIM, USER_LAST_CLAIM,
Config, PendingClaimAmount, StakerInfo, UserTokenClaim, NUM_STAKED, TOTAL_REWARDS, USER_CLAIM,
USER_LAST_CLAIM, USER_PENDING_CLAIM,
};

pub fn query_config(deps: Deps) -> Result<ConfigResponse, ContractError> {
Expand All @@ -19,7 +19,7 @@ pub fn query_config(deps: Deps) -> Result<ConfigResponse, ContractError> {
gov_contract: config.gov_contract.to_string(),
new_gov_contract: config.new_gov_contract.map(|f| f.to_string()),
change_gov_contract_by_height: config.change_gov_contract_by_height,
astroport_generator_contract: config.astroport_generator_contract.map(|f| f.to_string())
astroport_generator_contract: config.astroport_generator_contract.map(|f| f.to_string()),
};

Ok(resp)
Expand Down Expand Up @@ -47,13 +47,52 @@ pub fn query_staker_info(

let staker_info: StakerInfo = StakerInfo::load_or_default(deps.storage, &staker_raw)?;

let rewards = calc_token_claims(deps.storage, &staker_raw)?;
let pending_claim = USER_PENDING_CLAIM
.may_load(deps.storage, staker_raw.clone())?
.unwrap_or_default();

let rewards_vec = calc_token_claims(deps.storage, &staker_raw)?;
let pending = pending_claim
.into_iter()
.map(|f| {
(
f.token.clone(),
PendingClaimAmount {
amount: f.amount,
token: f.token,
},
)
})
.collect::<HashMap<Addr, PendingClaimAmount>>();
let mut rewards = rewards_vec
.into_iter()
.map(|f| {
(
f.token.clone(),
TokenBalance {
amount: f.amount,
token: f.token.clone(),
last_block_rewards_seen: f.last_block_rewards_seen,
},
)
})
.collect::<HashMap<Addr, TokenBalance>>();
for pending_tb in pending {
rewards
.entry(pending_tb.0)
.and_modify(|e| e.amount = e.amount.add(Decimal::new(pending_tb.1.amount)))
.or_insert(TokenBalance {
amount: Decimal::new(pending_tb.1.amount),
token: pending_tb.1.token.clone(),
last_block_rewards_seen: 0,
});
}
let last_claim = USER_LAST_CLAIM.may_load(deps.storage, staker_raw)?;

Ok(StakerInfoResponse {
staker,
total_staked: staker_info.bond_amount,
estimated_rewards: rewards,
estimated_rewards: rewards.into_iter().map(|f| f.1).collect(),
last_claimed: last_claim,
})
}
Expand Down
7 changes: 7 additions & 0 deletions contracts/pfc-vault-contract/src/states.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,16 @@ pub struct UserTokenClaim {
pub last_claimed_amount: Decimal,
pub token: Addr,
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
pub struct PendingClaimAmount {
pub amount: Uint128,
pub token: Addr,
}

/// Stores total token rewards PER UNIT NFT since the beginning of time, keyed by CW20 address
pub const USER_CLAIM: Map<Addr, Vec<UserTokenClaim>> = Map::new("user_claim_v1");
/// Stores total token rewards PER UNIT NFT since the beginning of time, keyed by CW20 address
pub const USER_PENDING_CLAIM: Map<Addr, Vec<PendingClaimAmount>> = Map::new("user_pending_claim_v1");

#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
pub struct Config {
Expand Down
Loading

0 comments on commit f4e1af6

Please sign in to comment.