Skip to content

Commit

Permalink
staking contracts completed
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhishek-1857 committed Jan 26, 2024
1 parent 6adfa04 commit ac0d95f
Show file tree
Hide file tree
Showing 29 changed files with 730 additions and 762 deletions.
483 changes: 212 additions & 271 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 11 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -142,16 +142,23 @@ voting-v1 = { package = "dao-voting", version = "0.1.0" }
# cosmwasm-storage = { version = "1.1.11", package = "secret-cosmwasm-storage", default-features = false }
secret-utils = { path="./packages/utils/"}
# cosmwasm-std = { version = "1.1.11", package = "secret-cosmwasm-std", default-features = false }
secret-toolkit = { git = "https://github.com/scrtlabs/secret-toolkit", tag = "v0.8.0",features = ["viewing-key","permit"] }
secret-toolkit = { version = "0.10.0", default-features = false, features = [
"utils",
"serialization",
"viewing-key",
"permit",
"storage",
"snip20"
] }
secret-storage-plus = { path = "./packages/storage-plus/"}
secret-cw-controllers = { path = "./packages/controllers/"}
secret-cw2 = { path="./packages/cw2/" }
secret-multi-test = {path = "./packages/multi-test/"}

cosmwasm-std = { git = "https://github.com/scrtlabs/cosmwasm", tag = "v1.1.9-secret" }
cosmwasm-storage = { git = "https://github.com/scrtlabs/cosmwasm", tag = "v1.1.9-secret" }
cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.1.10" }
cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.1.10" }
schemars = { version = "0.8.11" }
serde = { version = "1.0" }
thiserror = { version = "1.0" }
cosmwasm-schema = "1.0.0"
cosmwasm-schema = { git = "https://github.com/scrtlabs/cosmwasm/", branch = "secret" }
snip20-reference-impl ={ path = "./snip20-reference-impl/"}
67 changes: 55 additions & 12 deletions contracts/staking/snip20-stake-external-rewards/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
use crate::msg::{
ExecuteMsg, InfoResponse, InstantiateMsg, MigrateMsg, PendingRewardsResponse, QueryMsg,
ExecuteMsg, InfoResponse, InstantiateMsg, PendingRewardsResponse, QueryMsg,
ReceiveMsg,
};
use crate::state::{
Config, Denom, RewardConfig, CONFIG, LAST_UPDATE_BLOCK, PENDING_REWARDS, REWARD_CONFIG,
REWARD_PER_TOKEN, USER_REWARD_PER_TOKEN,
REWARD_PER_TOKEN, SNIP20_STAKING_VIEWING_KEY, USER_REWARD_PER_TOKEN,
};
use crate::ContractError;
use crate::ContractError::{
InvalidFunds, InvalidSnip20, NoRewardsClaimable, RewardPeriodNotFinished,
};
use crate::{snip20_stake_msg, ContractError};
use secret_toolkit::utils::HandleCallback;
const EXECUTE_SNIP20_STAKE_VIEWING_KEY_ID: u64 = 0;
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;

use crate::msg::Snip20ReceiveMsg;
use crate::state::Denom::Snip20;
use cosmwasm_std::{
from_binary, to_binary, Addr, BankMsg, Binary, Coin, CosmosMsg, Deps, DepsMut, Empty, Env,
MessageInfo, Response, StdError, StdResult, Uint128, Uint256, WasmMsg,
MessageInfo, Reply, Response, StdError, StdResult, SubMsg, SubMsgResult, Uint128, Uint256,
WasmMsg,
};
use dao_hooks::stake::StakeChangedHookMsg;
use secret_cw2::{get_contract_version, set_contract_version, ContractVersion};
use secret_cw2::set_contract_version;
use std::cmp::min;
use std::convert::TryInto;

Expand All @@ -30,7 +33,7 @@ const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response<Empty>, ContractError> {
Expand Down Expand Up @@ -69,6 +72,20 @@ pub fn instantiate(
};
REWARD_CONFIG.save(deps.storage, &reward_config)?;

// Create Snip20 Stake viewing key
let gen_viewing_key_msg = snip20_stake_msg::ExecuteMsg::CreateViewingKey {
entropy: "entropy".to_string(),
};

let submsg = SubMsg::reply_on_success(
gen_viewing_key_msg.to_cosmos_msg(
msg.staking_contract_code_hash.clone(),
msg.staking_contract.clone().to_string(),
None,
)?,
EXECUTE_SNIP20_STAKE_VIEWING_KEY_ID,
);

Ok(Response::new()
.add_attribute("owner", msg.owner.unwrap_or_else(|| "None".to_string()))
.add_attribute("staking_contract", config.staking_contract)
Expand All @@ -81,7 +98,8 @@ pub fn instantiate(
)
.add_attribute("reward_rate", reward_config.reward_rate)
.add_attribute("period_finish", reward_config.period_finish.to_string())
.add_attribute("reward_duration", reward_config.reward_duration.to_string()))
.add_attribute("reward_duration", reward_config.reward_duration.to_string())
.add_submessage(submsg).set_data(to_binary(&env.contract.code_hash)?))
}

// #[cfg_attr(not(feature = "library"), entry_point)]
Expand Down Expand Up @@ -257,7 +275,12 @@ pub fn execute_claim(
}
PENDING_REWARDS.save(deps.storage, info.sender.clone(), &Uint128::zero())?;
let config = CONFIG.load(deps.storage)?;
let transfer_msg = get_transfer_msg(info.sender, rewards, config.reward_token, config.reward_token_code_hash)?;
let transfer_msg = get_transfer_msg(
info.sender,
rewards,
config.reward_token,
config.reward_token_code_hash,
)?;
Ok(Response::new()
.add_message(transfer_msg)
.add_attribute("action", "claim")
Expand Down Expand Up @@ -364,14 +387,15 @@ pub fn get_reward_per_token(

pub fn get_rewards_earned(
deps: Deps,
_env: &Env,
env: &Env,
addr: &Addr,
reward_per_token: Uint256,
staking_contract: &Addr,
) -> StdResult<Uint128> {
let config = CONFIG.load(deps.storage)?;
let staked_balance = Uint256::from(get_staked_balance(
deps,
env,
staking_contract,
config.staking_contract_code_hash,
addr,
Expand Down Expand Up @@ -406,18 +430,21 @@ fn get_total_staked(
// Need to add submsg functionality
fn get_staked_balance(
deps: Deps,
contract_addr: &Addr,
env: &Env,
contract_address: &Addr,
staking_contract_code_hash: String,
addr: &Addr,
) -> StdResult<Uint128> {
let key = SNIP20_STAKING_VIEWING_KEY.load(deps.storage)?;
let msg = snip20_stake::msg::QueryMsg::StakedBalanceAtHeight {
contract_address:Some(env.contract.address.to_string()),
address: addr.into(),
height: None,
key: "key".into(),
key,
};
let resp: snip20_stake::msg::StakedBalanceAtHeightResponse =
deps.querier
.query_wasm_smart(staking_contract_code_hash, contract_addr, &msg)?;
.query_wasm_smart(staking_contract_code_hash, contract_address.to_string(), &msg)?;
Ok(resp.balance)
}

Expand Down Expand Up @@ -501,6 +528,22 @@ pub fn query_pending_rewards(
})
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg.id {
EXECUTE_SNIP20_STAKE_VIEWING_KEY_ID => match msg.result {
SubMsgResult::Ok(res) => {
let data: snip20_stake::msg::CreateViewingKeyResponse =
from_binary(&res.data.unwrap())?;
SNIP20_STAKING_VIEWING_KEY.save(deps.storage, &data.key)?;
Ok(Response::new().add_attribute("action", "create_snip20_stake_viewing_key"))
}
SubMsgResult::Err(_) => Err(ContractError::Snip20StakeExecuteError {}),
},
_ => Err(ContractError::UnknownReplyId { id: msg.id }),
}
}

// #[cfg(test)]
// mod tests {
// use std::borrow::BorrowMut;
Expand Down
4 changes: 4 additions & 0 deletions contracts/staking/snip20-stake-external-rewards/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub enum ContractError {
ZeroRewardDuration {},
#[error("can not migrate. current version is up to date")]
AlreadyMigrated {},
#[error("Error executing staking contract")]
Snip20StakeExecuteError {},
#[error("Got a submessage reply with unknown id: {id}")]
UnknownReplyId { id: u64 },
}

#[derive(Error, Debug, PartialEq)]
Expand Down
2 changes: 1 addition & 1 deletion contracts/staking/snip20-stake-external-rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
pub mod contract;
mod error;
pub mod msg;
pub mod snip20_stake_msg;
pub mod state;

pub use crate::error::ContractError;
9 changes: 6 additions & 3 deletions contracts/staking/snip20-stake-external-rewards/src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use cosmwasm_schema::{cw_serde, QueryResponses};
use crate::state::{Config, Denom, RewardConfig};
use cosmwasm_schema::QueryResponses;
use cosmwasm_std::{Addr, Binary, Uint128};
use dao_hooks::stake::StakeChangedHookMsg;
use serde::{Deserialize, Serialize};
use schemars::JsonSchema;
use crate::state::{Config, Denom, RewardConfig};
use serde::{Deserialize, Serialize};

pub use secret_cw_controllers::ClaimsResponse;
// so that consumers don't need a cw_ownable dependency to consume
Expand Down Expand Up @@ -35,6 +35,7 @@ pub struct Snip20ReceiveMsg {

#[cw_ownable_execute]
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
StakeChangeHook(StakeChangedHookMsg),
Claim {},
Expand All @@ -44,6 +45,7 @@ pub enum ExecuteMsg {
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum MigrateMsg {
/// Migrates from version 0.2.6 to 2.0.0. The significant changes
/// being the addition of a two-step ownership transfer using
Expand All @@ -58,6 +60,7 @@ pub enum ReceiveMsg {
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug, QueryResponses)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
#[returns(InfoResponse)]
Info {},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use schemars::JsonSchema;
use secret_toolkit::utils::{HandleCallback, InitCallback};
use secret_utils::Duration;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct InstantiateMsg {
// Owner can update all configs including changing the owner. This will generally be a DAO.
pub owner: Option<String>,
pub token_address: String,
pub token_code_hash: Option<String>,
pub unstaking_duration: Option<Duration>,
}

impl InitCallback for InstantiateMsg {
const BLOCK_SIZE: usize = 256;
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
CreateViewingKey { entropy: String },
}

impl HandleCallback for ExecuteMsg {
const BLOCK_SIZE: usize = 256;
}
5 changes: 3 additions & 2 deletions contracts/staking/snip20-stake-external-rewards/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Uint128, Uint256};
use schemars::JsonSchema;
use secret_storage_plus::{Item, Map};
use serde::{Deserialize, Serialize};
use schemars::JsonSchema;

#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)]
pub enum Denom {
Expand Down Expand Up @@ -36,3 +35,5 @@ pub const LAST_UPDATE_BLOCK: Item<u64> = Item::new("last_update_block");
pub const PENDING_REWARDS: Map<Addr, Uint128> = Map::new("pending_rewards");

pub const USER_REWARD_PER_TOKEN: Map<Addr, Uint256> = Map::new("user_reward_per_token");

pub const SNIP20_STAKING_VIEWING_KEY: Item<String> = Item::new("snip20_staking_viewing_key");
2 changes: 2 additions & 0 deletions contracts/staking/snip20-stake-reward-distributor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ library = []
[dependencies]
cosmwasm-std = { workspace = true }
cosmwasm-schema = { workspace = true }
serde={workspace=true}
cw20 = { workspace = true }
cw20-base = { workspace = true, features = ["library"] }
snip20-stake = { workspace = true, features = ["library"]}
Expand All @@ -33,6 +34,7 @@ secret-storage-plus = { workspace = true, default-features = false }
secret-cw-controllers = { workspace = true }
secret-cw2 = { workspace = true }
snip20-reference-impl ={ workspace=true }
schemars={ workspace=true }

[dev-dependencies]
secret-multi-test = { workspace = true }
Loading

0 comments on commit ac0d95f

Please sign in to comment.