Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/mixnet contract further adjustments #928

Merged
merged 18 commits into from
Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions common/client-libs/validator-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::nymd::{
error::NymdError, CosmWasmClient, NymdClient, QueryNymdClient, SigningNymdClient,
};
#[cfg(feature = "nymd-client")]
use mixnet_contract::ContractSettingsParams;
use mixnet_contract::ContractStateParams;

use crate::{validator_api, ValidatorClientError};
use coconut_interface::{BlindSignRequestBody, BlindedSignatureResponse, VerificationKeyResponse};
Expand Down Expand Up @@ -167,9 +167,7 @@ impl<C> Client<C> {
Ok(self.validator_api.get_gateways().await?)
}

pub async fn get_contract_settings(
&self,
) -> Result<ContractSettingsParams, ValidatorClientError>
pub async fn get_contract_settings(&self) -> Result<ContractStateParams, ValidatorClientError>
where
C: CosmWasmClient + Sync,
{
Expand Down
24 changes: 12 additions & 12 deletions common/client-libs/validator-client/src/nymd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ use cosmrs::rpc::endpoint::broadcast;
use cosmrs::rpc::{Error as TendermintRpcError, HttpClientUrl};
use cosmwasm_std::{Coin, Uint128};
use mixnet_contract::{
ContractSettingsParams, Delegation, ExecuteMsg, Gateway, GatewayOwnershipResponse, IdentityKey,
LayerDistribution, MixNode, MixOwnershipResponse, MixnetContractVersion,
MixnodeRewardingStatusResponse, PagedAllDelegationsResponse, PagedDelegatorDelegationsResponse,
PagedGatewayResponse, PagedMixDelegationsResponse, PagedMixnodeResponse, QueryMsg,
RewardingIntervalResponse,
ContractStateParams, Delegation, ExecuteMsg, Gateway, GatewayBond, GatewayOwnershipResponse,
IdentityKey, LayerDistribution, MixNode, MixNodeBond, MixOwnershipResponse,
MixnetContractVersion, MixnodeRewardingStatusResponse, PagedAllDelegationsResponse,
PagedDelegatorDelegationsResponse, PagedGatewayResponse, PagedMixDelegationsResponse,
PagedMixnodeResponse, QueryMsg, RewardingIntervalResponse,
};
use serde::Serialize;
use std::collections::HashMap;
Expand Down Expand Up @@ -208,7 +208,7 @@ impl<C> NymdClient<C> {
self.client.get_balance(address, self.denom()?).await
}

pub async fn get_contract_settings(&self) -> Result<ContractSettingsParams, NymdError>
pub async fn get_contract_settings(&self) -> Result<ContractStateParams, NymdError>
where
C: CosmWasmClient + Sync,
{
Expand Down Expand Up @@ -308,7 +308,7 @@ impl<C> NymdClient<C> {
}

/// Checks whether there is a bonded mixnode associated with the provided client's address
pub async fn owns_mixnode(&self, address: &AccountId) -> Result<bool, NymdError>
pub async fn owns_mixnode(&self, address: &AccountId) -> Result<Option<MixNodeBond>, NymdError>
where
C: CosmWasmClient + Sync,
{
Expand All @@ -319,11 +319,11 @@ impl<C> NymdClient<C> {
.client
.query_contract_smart(self.contract_address()?, &request)
.await?;
Ok(response.has_node)
Ok(response.mixnode)
}

/// Checks whether there is a bonded gateway associated with the provided client's address
pub async fn owns_gateway(&self, address: &AccountId) -> Result<bool, NymdError>
pub async fn owns_gateway(&self, address: &AccountId) -> Result<Option<GatewayBond>, NymdError>
where
C: CosmWasmClient + Sync,
{
Expand All @@ -334,7 +334,7 @@ impl<C> NymdClient<C> {
.client
.query_contract_smart(self.contract_address()?, &request)
.await?;
Ok(response.has_gateway)
Ok(response.gateway)
}

pub async fn get_mixnodes_paged(
Expand Down Expand Up @@ -717,14 +717,14 @@ impl<C> NymdClient<C> {

pub async fn update_contract_settings(
&self,
new_params: ContractSettingsParams,
new_params: ContractStateParams,
) -> Result<ExecuteResult, NymdError>
where
C: SigningCosmWasmClient + Sync,
{
let fee = self.get_fee(Operation::UpdateStateParams);

let req = ExecuteMsg::UpdateContractSettings(new_params);
let req = ExecuteMsg::UpdateContractStateParams(new_params);
self.client
.execute(
self.address(),
Expand Down
3 changes: 3 additions & 0 deletions common/mixnet-contract/src/delegation.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0

// due to code generated by JsonSchema
#![allow(clippy::field_reassign_with_default)]

Expand Down
2 changes: 1 addition & 1 deletion common/mixnet-contract/src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl PagedGatewayResponse {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct GatewayOwnershipResponse {
pub address: Addr,
pub has_gateway: bool,
pub gateway: Option<GatewayBond>,
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion common/mixnet-contract/src/mixnode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ impl PagedMixnodeResponse {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct MixOwnershipResponse {
pub address: Addr,
pub has_node: bool,
pub mixnode: Option<MixNodeBond>,
}

#[cfg(test)]
Expand Down
10 changes: 6 additions & 4 deletions common/mixnet-contract/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
// SPDX-License-Identifier: Apache-2.0

use crate::mixnode::NodeRewardParams;
use crate::ContractSettingsParams;
use crate::ContractStateParams;
use crate::{Gateway, IdentityKey, MixNode};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {}
pub struct InstantiateMsg {
pub rewarding_validator_address: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
Expand All @@ -21,7 +23,7 @@ pub enum ExecuteMsg {
gateway: Gateway,
},
UnbondGateway {},
UpdateContractSettings(ContractSettingsParams),
UpdateContractStateParams(ContractStateParams),

DelegateToMixnode {
mix_identity: IdentityKey,
Expand All @@ -41,7 +43,7 @@ pub enum ExecuteMsg {
rewarding_interval_nonce: u32,
},

RewardMixnodeV2 {
RewardMixnode {
identity: IdentityKey,
// percentage value in range 0-100
params: NodeRewardParams,
Expand Down
4 changes: 2 additions & 2 deletions common/mixnet-contract/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct RewardingIntervalResponse {
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct ContractSettingsParams {
pub struct ContractStateParams {
// so currently epoch_length is being unused and validator API performs rewarding
// based on its own epoch length config value. I guess that's fine for time being
// however, in the future, the contract constant should be controlling it instead.
Expand All @@ -52,7 +52,7 @@ pub struct ContractSettingsParams {
pub mixnode_active_set_size: u32,
}

impl Display for ContractSettingsParams {
impl Display for ContractStateParams {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Contract state parameters: [ ")?;
write!(f, "minimum mixnode bond: {}; ", self.minimum_mixnode_bond)?;
Expand Down
2 changes: 0 additions & 2 deletions contracts/mixnet/examples/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ extern crate mixnet_contract;

use cosmwasm_schema::{export_schema, remove_schemas, schema_for};
use mixnet_contract::{ExecuteMsg, InstantiateMsg, MixNodeBond, QueryMsg};
use mixnet_contracts::mixnet_contract_settings::models::ContractSettings;
use std::env::current_dir;
use std::fs::create_dir_all;

Expand All @@ -18,6 +17,5 @@ fn main() {
export_schema(&schema_for!(InstantiateMsg), &out_dir);
export_schema(&schema_for!(ExecuteMsg), &out_dir);
export_schema(&schema_for!(QueryMsg), &out_dir);
export_schema(&schema_for!(ContractSettings), &out_dir);
export_schema(&schema_for!(MixNodeBond), &out_dir);
}
39 changes: 23 additions & 16 deletions contracts/mixnet/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::delegations::queries::query_mixnode_delegations_paged;
use crate::error::ContractError;
use crate::gateways::queries::query_gateways_paged;
use crate::gateways::queries::query_owns_gateway;
use crate::mixnet_contract_settings::models::ContractSettings;
use crate::mixnet_contract_settings::models::ContractState;
use crate::mixnet_contract_settings::queries::query_rewarding_interval;
use crate::mixnet_contract_settings::queries::{
query_contract_settings_params, query_contract_version,
Expand All @@ -20,12 +20,10 @@ use crate::mixnodes::layer_queries::query_layer_distribution;
use crate::rewards::queries::query_reward_pool;
use crate::rewards::queries::{query_circulating_supply, query_rewarding_status};
use crate::rewards::storage as rewards_storage;
use config::defaults::REWARDING_VALIDATOR_ADDRESS;
use cosmwasm_std::{
entry_point, to_binary, Addr, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response, Uint128,
};
use mixnet_contract::{ContractSettingsParams, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use std::u128;
use mixnet_contract::{ContractStateParams, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};

/// Constant specifying minimum of coin required to bond a gateway
pub const INITIAL_GATEWAY_BOND: Uint128 = Uint128::new(100_000_000);
Expand All @@ -41,13 +39,19 @@ pub const EPOCH_REWARD_PERCENT: u8 = 2; // Used to calculate epoch reward pool
pub const DEFAULT_SYBIL_RESISTANCE_PERCENT: u8 = 30;

// We'll be assuming a few more things, profit margin and cost function. Since we don't have reliable package measurement, we'll be using uptime. We'll also set the value of 1 Nym to 1 $, to be able to translate epoch costs to Nyms. We'll also assume a cost of 40$ per epoch(month), converting that to Nym at our 1$ rate translates to 40_000_000 uNyms
// question to @durch: where do we need it (if at all)?
#[allow(dead_code)]
pub const DEFAULT_COST_PER_EPOCH: u32 = 40_000_000;

fn default_initial_state(owner: Addr, env: Env) -> ContractSettings {
ContractSettings {
fn default_initial_state(
owner: Addr,
rewarding_validator_address: Addr,
env: Env,
) -> ContractState {
ContractState {
owner,
rewarding_validator_address: Addr::unchecked(REWARDING_VALIDATOR_ADDRESS), // we trust our hardcoded value
params: ContractSettingsParams {
rewarding_validator_address,
params: ContractStateParams {
minimum_mixnode_bond: INITIAL_MIXNODE_BOND,
minimum_gateway_bond: INITIAL_GATEWAY_BOND,
mixnode_rewarded_set_size: INITIAL_MIXNODE_REWARDED_SET_SIZE,
Expand All @@ -69,11 +73,12 @@ pub fn instantiate(
deps: DepsMut,
env: Env,
info: MessageInfo,
_msg: InstantiateMsg,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let state = default_initial_state(info.sender, env);
let rewarding_validator_address = deps.api.addr_validate(&msg.rewarding_validator_address)?;
let state = default_initial_state(info.sender, rewarding_validator_address, env);

mixnet_params_storage::CONTRACT_SETTINGS.save(deps.storage, &state)?;
mixnet_params_storage::CONTRACT_STATE.save(deps.storage, &state)?;
mixnet_params_storage::LAYERS.save(deps.storage, &Default::default())?;
rewards_storage::REWARD_POOL.save(deps.storage, &Uint128::new(INITIAL_REWARD_POOL))?;

Expand Down Expand Up @@ -101,16 +106,16 @@ pub fn execute(
ExecuteMsg::UnbondGateway {} => {
crate::gateways::transactions::try_remove_gateway(deps, info)
}
ExecuteMsg::UpdateContractSettings(params) => {
ExecuteMsg::UpdateContractStateParams(params) => {
crate::mixnet_contract_settings::transactions::try_update_contract_settings(
deps, info, params,
)
}
ExecuteMsg::RewardMixnodeV2 {
ExecuteMsg::RewardMixnode {
identity,
params,
rewarding_interval_nonce,
} => crate::rewards::transactions::try_reward_mixnode_v2(
} => crate::rewards::transactions::try_reward_mixnode(
deps,
env,
info,
Expand Down Expand Up @@ -146,7 +151,7 @@ pub fn execute(
ExecuteMsg::RewardNextMixDelegators {
mix_identity,
rewarding_interval_nonce,
} => crate::rewards::transactions::try_reward_next_mixnode_delegators_v2(
} => crate::rewards::transactions::try_reward_next_mixnode_delegators(
deps,
info,
mix_identity,
Expand Down Expand Up @@ -260,7 +265,9 @@ pub mod tests {
fn initialize_contract() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg {};
let msg = InstantiateMsg {
rewarding_validator_address: config::defaults::REWARDING_VALIDATOR_ADDRESS.to_string(),
};
let info = mock_info("creator", &[]);

let res = instantiate(deps.as_mut(), env.clone(), info, msg).unwrap();
Expand Down
3 changes: 3 additions & 0 deletions contracts/mixnet/src/delegations/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,9 @@ pub(crate) mod tests {

assert_eq!(1, page2.delegations.len());

// save another one
test_helpers::save_dummy_delegation(&mut deps.storage, "400", &delegation_owner);

let start_after = String::from("2");
let page2 = query_delegator_delegations_paged(
deps.as_ref(),
Expand Down
Loading