Skip to content

Commit

Permalink
tgrade-valset: Emitting information about rewards distribution contra…
Browse files Browse the repository at this point in the history
…ct on contract instantiation
  • Loading branch information
hashedone committed Oct 5, 2021
1 parent c7dd818 commit addb42f
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 9 deletions.
30 changes: 30 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions contracts/tgrade-valset/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/proto/*
!src/proto/.gitkeep
4 changes: 4 additions & 0 deletions contracts/tgrade-valset/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ backtraces = ["cosmwasm-std/backtraces"]
# use library feature to disable all instantiate/execute/query exports
library = []

[build-dependencies]
protobuf-codegen-pure = "2"

[dependencies]
cw0 = { version = "=0.10.0-soon3" }
cw2 = { version = "=0.10.0-soon3" }
Expand All @@ -35,6 +38,7 @@ tg-utils = { version = "0.4.0", path = "../../packages/utils" }
schemars = "0.8"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.21" }
protobuf = { version = "2", features = ["with-bytes"] }

[dev-dependencies]
cosmwasm-schema = { version = "1.0.0-soon" }
Expand Down
8 changes: 8 additions & 0 deletions contracts/tgrade-valset/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fn main() {
protobuf_codegen_pure::Codegen::new()
.out_dir("src/proto")
.inputs(&["proto/instantiate_reply.proto"])
.include("proto")
.run()
.expect("Protobuf codegen failed.");
}
9 changes: 9 additions & 0 deletions contracts/tgrade-valset/proto/instantiate_reply.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
syntax = "proto3";

// MsgInstantiateContractResponse defines the Msg/InstantiateContract response type.
message MsgInstantiateContractResponse {
// ContractAddress is the bech32 address of the new contract instance.
string contract_address = 1;
// Data contains base64-encoded bytes to returned from the contract
bytes data = 2;
}
57 changes: 48 additions & 9 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, MessageInfo, Order,
StdError, StdResult, Timestamp, WasmMsg,
entry_point, to_binary, Addr, Binary, BlockInfo, Deps, DepsMut, Env, Event, MessageInfo, Order,
Reply, StdError, StdResult, SubMsg, Timestamp, WasmMsg,
};

use cw0::maybe_addr;
Expand All @@ -25,16 +25,20 @@ use crate::msg::{
ListActiveValidatorsResponse, ListValidatorResponse, OperatorResponse, QueryMsg,
RewardsInstantiateMsg, ValidatorMetadata, ValidatorResponse,
};
use crate::proto::MsgInstantiateContractResponse;
use crate::rewards::{distribute_to_validators, pay_block_rewards};
use crate::state::{
operators, Config, EpochInfo, OperatorInfo, ValidatorInfo, CONFIG, EPOCH, JAIL, VALIDATORS,
};
use protobuf::Message;
use tg_utils::ADMIN;

// version info for migration info
const CONTRACT_NAME: &str = "crates.io:tgrade-valset";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

const REWARDS_INIT_REPLY_ID: u64 = 1;

/// We use this custom message everywhere
pub type Response = cosmwasm_std::Response<TgradeMsg>;

Expand Down Expand Up @@ -102,13 +106,16 @@ pub fn instantiate(
token,
};

let resp = Response::new().add_message(WasmMsg::Instantiate {
admin: Some(env.contract.address.clone().to_string()),
code_id: msg.rewards_code_id,
msg: to_binary(&rewards_init)?,
funds: vec![],
label: format!("rewards_distribution_{}", env.contract.address),
});
let resp = Response::new().add_submessage(SubMsg::reply_on_success(
WasmMsg::Instantiate {
admin: Some(env.contract.address.clone().to_string()),
code_id: msg.rewards_code_id,
msg: to_binary(&rewards_init)?,
funds: vec![],
label: format!("rewards_distribution_{}", env.contract.address),
},
REWARDS_INIT_REPLY_ID,
));

Ok(resp)
}
Expand Down Expand Up @@ -558,6 +565,38 @@ fn calculate_diff(cur_vals: Vec<ValidatorInfo>, old_vals: Vec<ValidatorInfo>) ->
ValidatorDiff { diffs }
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg.id {
REWARDS_INIT_REPLY_ID => rewards_instantiate_reply(deps, msg),
_ => Err(ContractError::UnrecognisedReply(msg.id)),
}
}

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

let resp = Response::new()
.add_attribute("action", "tgrade-valset_instantiation")
.add_attribute("rewards_contract", res.get_contract_address());

Ok(resp)
}

#[cfg(test)]
mod test {
use cw_multi_test::{next_block, AppBuilder, BasicApp, Executor};
Expand Down
9 changes: 9 additions & 0 deletions contracts/tgrade-valset/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ pub enum ContractError {

#[error("No distribution contract")]
NoDistributionContract {},

#[error("Failure response from submsg: {0}")]
SubmsgFailure(String),

#[error("Invalid reply from submessage {id}, {err}")]
ReplyParseFailure { id: u64, err: String },

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

impl From<Ed25519PubkeyConversionError> for ContractError {
Expand Down
1 change: 1 addition & 0 deletions contracts/tgrade-valset/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod contract;
pub mod error;
pub mod msg;
mod proto;
mod rewards;
pub mod state;
mod test_helpers;
Expand Down
3 changes: 3 additions & 0 deletions contracts/tgrade-valset/src/proto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod instantiate_reply;

pub use instantiate_reply::MsgInstantiateContractResponse;
Empty file.

0 comments on commit addb42f

Please sign in to comment.