Skip to content

Commit

Permalink
tgrade-valset: Instantiated rewards contract stored in config (and it…
Browse files Browse the repository at this point in the history
… is also queryable as config part)
  • Loading branch information
hashedone committed Oct 5, 2021
1 parent addb42f commit 52de51d
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 36 deletions.
9 changes: 3 additions & 6 deletions contracts/tgrade-valset/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ the message:
```json
{
"admin": "tgrade_valset_addr",
"token": "epoch_reward_denom"
"token": "epoch_reward_denom",
"members": []
}
```

Expand All @@ -94,7 +95,7 @@ emitted with `wasm` event:
}
```

Additionaly the rewards contract address can be queried at any time using
Additionally the rewards contract address can be queried at any time using
`rewards_distribution_contract {}` query.

At every epoch end, rewards would be send to rewards distribution contract
Expand Down Expand Up @@ -266,10 +267,6 @@ pub enum QueryMsg {
/// we recalculated endblock right now.
/// Also returns ListActiveValidatorsResponse
SimulateActiveValidators {},

/// Returns address of rewards distribution contract. Returns
/// `ContractResp`
RewardsDistributionContract {},
}
```

Expand Down
47 changes: 34 additions & 13 deletions contracts/tgrade-valset/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::collections::BTreeSet;
use std::convert::TryInto;

use cosmwasm_std::{
entry_point, to_binary, Addr, Binary, BlockInfo, Deps, DepsMut, Env, Event, MessageInfo, Order,
Reply, StdError, StdResult, SubMsg, Timestamp, WasmMsg,
entry_point, to_binary, Addr, Binary, BlockInfo, Deps, DepsMut, Env, MessageInfo, Order, Reply,
StdError, StdResult, SubMsg, Timestamp, WasmMsg,
};

use cw0::maybe_addr;
Expand Down Expand Up @@ -73,6 +73,8 @@ pub fn instantiate(
.distribution_contract
.map(|addr| deps.api.addr_validate(&addr))
.transpose()?,
// Will be overwritten in reply for rewards contract instantiation
rewards_contract: Addr::unchecked(""),
};
CONFIG.save(deps.storage, &cfg)?;

Expand Down Expand Up @@ -104,6 +106,7 @@ pub fn instantiate(
let rewards_init = RewardsInstantiateMsg {
admin: env.contract.address.clone(),
token,
members: vec![],
};

let resp = Response::new().add_submessage(SubMsg::reply_on_success(
Expand Down Expand Up @@ -276,7 +279,6 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> Result<Binary, ContractErro
QueryMsg::SimulateActiveValidators {} => {
Ok(to_binary(&simulate_active_validators(deps, env)?)?)
}
QueryMsg::RewardsDistributionContract {} => todo!(),
}
}

Expand Down Expand Up @@ -574,22 +576,29 @@ pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractE
}

pub fn rewards_instantiate_reply(deps: DepsMut, msg: Reply) -> Result<Response, ContractError> {
let id = msg.id;
let res: MsgInstantiateContractResponse = Message::parse_from_bytes(
msg.result
.into_result()
.map_err(ContractError::SubmsgFailure)?
.data
.ok_or_else(|| ContractError::ReplyParseFailure {
id: msg.id,
id,
err: "Missing reply data".to_owned(),
})?
.as_slice(),
)
.map_err(|err| ContractError::ReplyParseFailure {
id: msg.id,
id,
err: err.to_string(),
})?;

let addr = deps.api.addr_validate(res.get_contract_address())?;
CONFIG.update(deps.storage, |mut config| -> StdResult<_> {
config.rewards_contract = addr;
Ok(config)
})?;

let resp = Response::new()
.add_attribute("action", "tgrade-valset_instantiation")
.add_attribute("rewards_contract", res.get_contract_address());
Expand Down Expand Up @@ -645,9 +654,10 @@ mod test {
stake: Addr,
max_validators: u32,
min_weight: u64,
rewards_code_id: u64,
) -> Addr {
let valset_id = app.store_code(contract_valset());
let msg = init_msg(stake, max_validators, min_weight);
let msg = init_msg(stake, max_validators, min_weight, rewards_code_id);
app.instantiate_contract(
valset_id,
Addr::unchecked(GROUP_OWNER),
Expand Down Expand Up @@ -676,7 +686,12 @@ mod test {
}

// registers first PREREGISTER_MEMBERS members and PREREGISTER_NONMEMBERS non-members with pubkeys
fn init_msg(group_addr: Addr, max_validators: u32, min_weight: u64) -> InstantiateMsg {
fn init_msg(
group_addr: Addr,
max_validators: u32,
min_weight: u64,
rewards_code_id: u64,
) -> InstantiateMsg {
let members = addrs(PREREGISTER_MEMBERS)
.into_iter()
.map(|s| valid_operator(&s));
Expand All @@ -697,18 +712,19 @@ mod test {
auto_unjail: false,
validators_reward_ratio: Decimal::one(),
distribution_contract: None,
rewards_code_id: 0,
rewards_code_id,
}
}

#[test]
fn init_and_query_state() {
let mut app = AppBuilder::new_custom().build(|_, _, _| ());

let engagement_id = app.store_code(contract_engagement());
// make a simple group
let group_addr = instantiate_group(&mut app, 36);
// make a valset that references it (this does init)
let valset_addr = instantiate_valset(&mut app, group_addr.clone(), 10, 5);
let valset_addr = instantiate_valset(&mut app, group_addr.clone(), 10, 5, engagement_id);

// check config
let cfg: ConfigResponse = app
Expand All @@ -727,6 +743,7 @@ mod test {
auto_unjail: false,
validators_reward_ratio: Decimal::one(),
distribution_contract: None,
rewards_contract: cfg.rewards_contract.clone(),
}
);

Expand Down Expand Up @@ -779,10 +796,11 @@ mod test {
fn simulate_validators() {
let mut app = AppBuilder::new_custom().build(|_, _, _| ());

let engagement_id = app.store_code(contract_engagement());
// make a simple group
let group_addr = instantiate_group(&mut app, 36);
// make a valset that references it (this does init)
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5);
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5, engagement_id);

// what do we expect?
// 1..24 have pubkeys registered, we take the top 10 (14..24)
Expand Down Expand Up @@ -814,10 +832,11 @@ mod test {
fn update_metadata_works() {
let mut app = AppBuilder::new_custom().build(|_, _, _| ());

let engagement_id = app.store_code(contract_engagement());
// make a simple group
let group_addr = instantiate_group(&mut app, 36);
// make a valset that references it (this does init)
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5);
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5, engagement_id);

// get my initial metadata
let operator = addrs(3).pop().unwrap();
Expand Down Expand Up @@ -873,10 +892,11 @@ mod test {
fn validator_list() {
let mut app = AppBuilder::new_custom().build(|_, _, _| ());

let engagement_id = app.store_code(contract_engagement());
// make a simple group
let group_addr = instantiate_group(&mut app, 36);
// make a valset that references it (this does init)
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5);
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5, engagement_id);

// List validator keys
// First come the non-members
Expand Down Expand Up @@ -994,10 +1014,11 @@ mod test {
fn end_block_run() {
let mut app = AppBuilder::new_custom().build(|_, _, _| ());

let engagement_id = app.store_code(contract_engagement());
// make a simple group
let group_addr = instantiate_group(&mut app, 36);
// make a valset that references it (this does init)
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5);
let valset_addr = instantiate_valset(&mut app, group_addr, 10, 5, engagement_id);

// what do we expect?
// end_block hasn't run yet, so empty list
Expand Down
2 changes: 1 addition & 1 deletion contracts/tgrade-valset/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub enum ContractError {
#[error("Invalid reply from submessage {id}, {err}")]
ReplyParseFailure { id: u64, err: String },

#[error("Unrecognised reply id: {}")]
#[error("Unrecognised reply id: {0}")]
UnrecognisedReply(u64),
}

Expand Down
11 changes: 1 addition & 10 deletions contracts/tgrade-valset/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,6 @@ pub enum QueryMsg {
/// we recalculated endblock right now.
/// Also returns ListActiveValidatorsResponse
SimulateActiveValidators {},

/// Returns address of rewards distribution contract. Returns
/// `ContractResp`
RewardsDistributionContract {},
}

pub type ConfigResponse = Config;
Expand Down Expand Up @@ -295,12 +291,6 @@ pub struct ListActiveValidatorsResponse {
pub validators: Vec<ValidatorInfo>,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct ContractResp {
contract: Addr,
}

/// Messages send by this contract to external contract
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
Expand All @@ -315,6 +305,7 @@ pub enum DistributionMsg {
pub struct RewardsInstantiateMsg {
pub admin: Addr,
pub token: String,
pub members: Vec<Member>,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
Expand Down
1 change: 1 addition & 0 deletions contracts/tgrade-valset/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ mod test {
auto_unjail: false,
validators_reward_ratio: Decimal::one(),
distribution_contract: None,
rewards_contract: Addr::unchecked(""),
};
CONFIG.save(deps.storage, &cfg).unwrap();
}
Expand Down
3 changes: 3 additions & 0 deletions contracts/tgrade-valset/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ pub struct Config {
/// distribute funds send with this message.
/// If no account is provided, `validators_reward_ratio` has to be `1`.
pub distribution_contract: Option<Addr>,

/// Address of contract for rewards distribution.
pub rewards_contract: Addr,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
Expand Down
6 changes: 4 additions & 2 deletions contracts/tgrade-valset/src/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ pub fn contract_valset() -> Box<dyn Contract<TgradeMsg>> {
crate::contract::instantiate,
crate::contract::query,
)
.with_sudo(crate::contract::sudo);
.with_sudo(crate::contract::sudo)
.with_reply(crate::contract::reply);

Box::new(contract)
}

Expand Down Expand Up @@ -325,7 +327,7 @@ impl SuiteBuilder {
distribution_contract: distribution_contract
.as_ref()
.map(|addr| addr.to_string()),
rewards_code_id: 0,
rewards_code_id: engagement_id,
},
&[],
"valset",
Expand Down
20 changes: 16 additions & 4 deletions contracts/tgrade-valset/src/test_valset_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::msg::{
ValidatorResponse,
};
use crate::state::ValidatorInfo;
use crate::test_helpers::{addrs, contract_valset, valid_operator};
use crate::test_helpers::{addrs, contract_engagement, contract_valset, valid_operator};

const EPOCH_LENGTH: u64 = 100;

Expand Down Expand Up @@ -54,8 +54,14 @@ pub fn instantiate_valset(
max_validators: u32,
min_weight: u64,
) -> Addr {
let engagement_id = app.store_code(contract_engagement());
let valset_id = app.store_code(contract_valset());
let msg = init_msg(&stake.to_string(), max_validators, min_weight);
let msg = init_msg(
&stake.to_string(),
max_validators,
min_weight,
engagement_id,
);
app.instantiate_contract(
valset_id,
Addr::unchecked(STAKE_OWNER),
Expand Down Expand Up @@ -91,7 +97,12 @@ fn instantiate_stake(app: &mut BasicApp<TgradeMsg>) -> Addr {
}

// registers first PREREGISTER_MEMBERS members with pubkeys
fn init_msg(stake_addr: &str, max_validators: u32, min_weight: u64) -> InstantiateMsg {
fn init_msg(
stake_addr: &str,
max_validators: u32,
min_weight: u64,
rewards_code_id: u64,
) -> InstantiateMsg {
let members = addrs(PREREGISTER_MEMBERS)
.into_iter()
.map(|s| valid_operator(&s))
Expand All @@ -109,7 +120,7 @@ fn init_msg(stake_addr: &str, max_validators: u32, min_weight: u64) -> Instantia
auto_unjail: false,
validators_reward_ratio: Decimal::one(),
distribution_contract: None,
rewards_code_id: 0,
rewards_code_id,
}
}

Expand Down Expand Up @@ -163,6 +174,7 @@ fn init_and_query_state() {
auto_unjail: false,
validators_reward_ratio: Decimal::one(),
distribution_contract: None,
rewards_contract: cfg.rewards_contract.clone(),
}
);

Expand Down

0 comments on commit 52de51d

Please sign in to comment.