Feature/terminology update (#941)

* Corrected used bond/pledge terminology

* ibid for the wallet and explorer

* [ci skip] Generate TS types

Co-authored-by: jstuczyn <jstuczyn@users.noreply.github.com>
This commit is contained in:
Jędrzej Stuczyński
2021-12-06 16:30:55 +00:00
committed by GitHub
parent db111490b6
commit 5aa1c29409
33 changed files with 317 additions and 303 deletions
@@ -617,7 +617,7 @@ impl<C> NymdClient<C> {
pub async fn bond_mixnode(
&self,
mixnode: MixNode,
bond: Coin,
pledge: Coin,
) -> Result<ExecuteResult, NymdError>
where
C: SigningCosmWasmClient + Sync,
@@ -632,7 +632,7 @@ impl<C> NymdClient<C> {
&req,
fee,
"Bonding mixnode from rust!",
vec![cosmwasm_coin_to_cosmos_coin(bond)],
vec![cosmwasm_coin_to_cosmos_coin(pledge)],
)
.await
}
@@ -642,7 +642,7 @@ impl<C> NymdClient<C> {
&self,
mixnode: MixNode,
owner: String,
bond: Coin,
pledge: Coin,
) -> Result<ExecuteResult, NymdError>
where
C: SigningCosmWasmClient + Sync,
@@ -660,7 +660,7 @@ impl<C> NymdClient<C> {
&req,
fee,
"Bonding mixnode on behalf from rust!",
vec![cosmwasm_coin_to_cosmos_coin(bond)],
vec![cosmwasm_coin_to_cosmos_coin(pledge)],
)
.await
}
@@ -683,7 +683,7 @@ impl<C> NymdClient<C> {
mix_node: bond.mix_node,
owner: bond.owner.to_string(),
},
vec![cosmwasm_coin_to_cosmos_coin(bond.bond_amount)],
vec![cosmwasm_coin_to_cosmos_coin(bond.pledge_amount)],
)
})
.collect();
@@ -887,7 +887,7 @@ impl<C> NymdClient<C> {
pub async fn bond_gateway(
&self,
gateway: Gateway,
bond: Coin,
pledge: Coin,
) -> Result<ExecuteResult, NymdError>
where
C: SigningCosmWasmClient + Sync,
@@ -902,7 +902,7 @@ impl<C> NymdClient<C> {
&req,
fee,
"Bonding gateway from rust!",
vec![cosmwasm_coin_to_cosmos_coin(bond)],
vec![cosmwasm_coin_to_cosmos_coin(pledge)],
)
.await
}
@@ -912,7 +912,7 @@ impl<C> NymdClient<C> {
&self,
gateway: Gateway,
owner: String,
bond: Coin,
pledge: Coin,
) -> Result<ExecuteResult, NymdError>
where
C: SigningCosmWasmClient + Sync,
@@ -927,7 +927,7 @@ impl<C> NymdClient<C> {
&req,
fee,
"Bonding gateway on behalf from rust!",
vec![cosmwasm_coin_to_cosmos_coin(bond)],
vec![cosmwasm_coin_to_cosmos_coin(pledge)],
)
.await
}
@@ -950,7 +950,7 @@ impl<C> NymdClient<C> {
gateway: bond.gateway,
owner: bond.owner.to_string(),
},
vec![cosmwasm_coin_to_cosmos_coin(bond.bond_amount)],
vec![cosmwasm_coin_to_cosmos_coin(bond.pledge_amount)],
)
})
.collect();
+21 -18
View File
@@ -23,7 +23,7 @@ pub struct Gateway {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct GatewayBond {
pub bond_amount: Coin,
pub pledge_amount: Coin,
pub owner: Addr,
pub block_height: u64,
pub gateway: Gateway,
@@ -32,14 +32,14 @@ pub struct GatewayBond {
impl GatewayBond {
pub fn new(
bond_amount: Coin,
pledge_amount: Coin,
owner: Addr,
block_height: u64,
gateway: Gateway,
proxy: Option<Addr>,
) -> Self {
GatewayBond {
bond_amount,
pledge_amount,
owner,
block_height,
gateway,
@@ -51,8 +51,8 @@ impl GatewayBond {
&self.gateway.identity_key
}
pub fn bond_amount(&self) -> Coin {
self.bond_amount.clone()
pub fn pledge_amount(&self) -> Coin {
self.pledge_amount.clone()
}
pub fn owner(&self) -> &Addr {
@@ -67,17 +67,17 @@ impl GatewayBond {
impl PartialOrd for GatewayBond {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// first remove invalid cases
if self.bond_amount.denom != other.bond_amount.denom {
if self.pledge_amount.denom != other.pledge_amount.denom {
return None;
}
// try to order by total bond
let bond_cmp = self
.bond_amount
// try to order by total pledge
let pledge_cmp = self
.pledge_amount
.amount
.partial_cmp(&other.bond_amount.amount)?;
if bond_cmp != Ordering::Equal {
return Some(bond_cmp);
.partial_cmp(&other.pledge_amount.amount)?;
if pledge_cmp != Ordering::Equal {
return Some(pledge_cmp);
}
// then check block height
@@ -102,7 +102,10 @@ impl Display for GatewayBond {
write!(
f,
"amount: {} {}, owner: {}, identity: {}",
self.bond_amount.amount, self.bond_amount.denom, self.owner, self.gateway.identity_key
self.pledge_amount.amount,
self.pledge_amount.denom,
self.owner,
self.gateway.identity_key
)
}
}
@@ -158,7 +161,7 @@ mod tests {
let _0foos = Coin::new(0, "foo");
let gate1 = GatewayBond {
bond_amount: _150foos.clone(),
pledge_amount: _150foos.clone(),
owner: Addr::unchecked("foo1"),
block_height: 100,
gateway: gateway_fixture(),
@@ -166,7 +169,7 @@ mod tests {
};
let gate2 = GatewayBond {
bond_amount: _150foos,
pledge_amount: _150foos,
owner: Addr::unchecked("foo2"),
block_height: 120,
gateway: gateway_fixture(),
@@ -174,7 +177,7 @@ mod tests {
};
let gate3 = GatewayBond {
bond_amount: _50foos,
pledge_amount: _50foos,
owner: Addr::unchecked("foo3"),
block_height: 120,
gateway: gateway_fixture(),
@@ -182,7 +185,7 @@ mod tests {
};
let gate4 = GatewayBond {
bond_amount: _140foos,
pledge_amount: _140foos,
owner: Addr::unchecked("foo4"),
block_height: 120,
gateway: gateway_fixture(),
@@ -190,7 +193,7 @@ mod tests {
};
let gate5 = GatewayBond {
bond_amount: _0foos,
pledge_amount: _0foos,
owner: Addr::unchecked("foo5"),
block_height: 120,
gateway: gateway_fixture(),
+39 -36
View File
@@ -229,7 +229,7 @@ impl NodeRewardResult {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct MixNodeBond {
pub bond_amount: Coin,
pub pledge_amount: Coin,
pub total_delegation: Coin,
pub owner: Addr,
pub layer: Layer,
@@ -241,7 +241,7 @@ pub struct MixNodeBond {
impl MixNodeBond {
pub fn new(
bond_amount: Coin,
pledge_amount: Coin,
owner: Addr,
layer: Layer,
block_height: u64,
@@ -250,8 +250,8 @@ impl MixNodeBond {
proxy: Option<Addr>,
) -> Self {
MixNodeBond {
total_delegation: coin(0, &bond_amount.denom),
bond_amount,
total_delegation: coin(0, &pledge_amount.denom),
pledge_amount,
owner,
layer,
block_height,
@@ -270,8 +270,8 @@ impl MixNodeBond {
&self.mix_node.identity_key
}
pub fn bond_amount(&self) -> Coin {
self.bond_amount.clone()
pub fn pledge_amount(&self) -> Coin {
self.pledge_amount.clone()
}
pub fn owner(&self) -> &Addr {
@@ -283,10 +283,10 @@ impl MixNodeBond {
}
pub fn total_stake(&self) -> Option<u128> {
if self.bond_amount.denom != self.total_delegation.denom {
if self.pledge_amount.denom != self.total_delegation.denom {
None
} else {
Some(self.bond_amount.amount.u128() + self.total_delegation.amount.u128())
Some(self.pledge_amount.amount.u128() + self.total_delegation.amount.u128())
}
}
@@ -294,27 +294,27 @@ impl MixNodeBond {
self.total_delegation.clone()
}
pub fn bond_to_circulating_supply(&self, circulating_supply: u128) -> U128 {
U128::from_num(self.bond_amount().amount.u128()) / U128::from_num(circulating_supply)
pub fn pledge_to_circulating_supply(&self, circulating_supply: u128) -> U128 {
U128::from_num(self.pledge_amount().amount.u128()) / U128::from_num(circulating_supply)
}
pub fn total_stake_to_circulating_supply(&self, circulating_supply: u128) -> U128 {
U128::from_num(self.bond_amount().amount.u128() + self.total_delegation().amount.u128())
pub fn total_bond_to_circulating_supply(&self, circulating_supply: u128) -> U128 {
U128::from_num(self.pledge_amount().amount.u128() + self.total_delegation().amount.u128())
/ U128::from_num(circulating_supply)
}
pub fn lambda(&self, params: &NodeRewardParams) -> U128 {
// Ratio of a bond to the token circulating supply
let bond_to_circulating_supply_ratio =
self.bond_to_circulating_supply(params.circulating_supply());
bond_to_circulating_supply_ratio.min(params.one_over_k())
let pledge_to_circulating_supply_ratio =
self.pledge_to_circulating_supply(params.circulating_supply());
pledge_to_circulating_supply_ratio.min(params.one_over_k())
}
pub fn sigma(&self, params: &NodeRewardParams) -> U128 {
// Ratio of a delegation to the the token circulating supply
let total_stake_to_circulating_supply_ratio =
self.total_stake_to_circulating_supply(params.circulating_supply());
total_stake_to_circulating_supply_ratio.min(params.one_over_k())
let total_bond_to_circulating_supply_ratio =
self.total_bond_to_circulating_supply(params.circulating_supply());
total_bond_to_circulating_supply_ratio.min(params.one_over_k())
}
pub fn reward(&self, params: &NodeRewardParams) -> NodeRewardResult {
@@ -370,9 +370,9 @@ impl MixNodeBond {
}
pub fn sigma_ratio(&self, params: &NodeRewardParams) -> U128 {
if self.total_stake_to_circulating_supply(params.circulating_supply()) < params.one_over_k()
if self.total_bond_to_circulating_supply(params.circulating_supply()) < params.one_over_k()
{
self.total_stake_to_circulating_supply(params.circulating_supply())
self.total_bond_to_circulating_supply(params.circulating_supply())
} else {
params.one_over_k()
}
@@ -387,33 +387,33 @@ impl MixNodeBond {
impl PartialOrd for MixNodeBond {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// first remove invalid cases
if self.bond_amount.denom != self.total_delegation.denom {
if self.pledge_amount.denom != self.total_delegation.denom {
return None;
}
if other.bond_amount.denom != other.total_delegation.denom {
if other.pledge_amount.denom != other.total_delegation.denom {
return None;
}
if self.bond_amount.denom != other.bond_amount.denom {
if self.pledge_amount.denom != other.pledge_amount.denom {
return None;
}
// try to order by total bond + delegation
let total_cmp = (self.bond_amount.amount + self.total_delegation.amount)
.partial_cmp(&(self.bond_amount.amount + self.total_delegation.amount))?;
let total_cmp = (self.pledge_amount.amount + self.total_delegation.amount)
.partial_cmp(&(self.pledge_amount.amount + self.total_delegation.amount))?;
if total_cmp != Ordering::Equal {
return Some(total_cmp);
}
// then if those are equal, prefer higher bond over delegation
let bond_cmp = self
.bond_amount
let pledge_cmp = self
.pledge_amount
.amount
.partial_cmp(&other.bond_amount.amount)?;
if bond_cmp != Ordering::Equal {
return Some(bond_cmp);
.partial_cmp(&other.pledge_amount.amount)?;
if pledge_cmp != Ordering::Equal {
return Some(pledge_cmp);
}
// then look at delegation (I'm not sure we can get here, but better safe than sorry)
@@ -452,7 +452,10 @@ impl Display for MixNodeBond {
write!(
f,
"amount: {} {}, owner: {}, identity: {}",
self.bond_amount.amount, self.bond_amount.denom, self.owner, self.mix_node.identity_key
self.pledge_amount.amount,
self.pledge_amount.denom,
self.owner,
self.mix_node.identity_key
)
}
}
@@ -507,7 +510,7 @@ mod tests {
let _0foos = Coin::new(0, "foo");
let mix1 = MixNodeBond {
bond_amount: _150foos.clone(),
pledge_amount: _150foos.clone(),
total_delegation: _50foos.clone(),
owner: Addr::unchecked("foo1"),
layer: Layer::One,
@@ -518,7 +521,7 @@ mod tests {
};
let mix2 = MixNodeBond {
bond_amount: _150foos.clone(),
pledge_amount: _150foos.clone(),
total_delegation: _50foos.clone(),
owner: Addr::unchecked("foo2"),
layer: Layer::One,
@@ -529,7 +532,7 @@ mod tests {
};
let mix3 = MixNodeBond {
bond_amount: _50foos,
pledge_amount: _50foos,
total_delegation: _150foos.clone(),
owner: Addr::unchecked("foo3"),
layer: Layer::One,
@@ -540,7 +543,7 @@ mod tests {
};
let mix4 = MixNodeBond {
bond_amount: _150foos.clone(),
pledge_amount: _150foos.clone(),
total_delegation: _0foos.clone(),
owner: Addr::unchecked("foo4"),
layer: Layer::One,
@@ -551,7 +554,7 @@ mod tests {
};
let mix5 = MixNodeBond {
bond_amount: _0foos,
pledge_amount: _0foos,
total_delegation: _150foos,
owner: Addr::unchecked("foo5"),
layer: Layer::One,
+12 -4
View File
@@ -40,8 +40,8 @@ pub struct ContractStateParams {
// 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.
// pub epoch_length: u32, // length of a rewarding epoch/interval, expressed in hours
pub minimum_mixnode_bond: Uint128, // minimum amount a mixnode must bond to get into the system
pub minimum_gateway_bond: Uint128, // minimum amount a gateway must bond to get into the system
pub minimum_mixnode_pledge: Uint128, // minimum amount a mixnode must pledge to get into the system
pub minimum_gateway_pledge: Uint128, // minimum amount a gateway must pledge to get into the system
// number of mixnode that are going to get rewarded during current rewarding interval (k_m)
// based on overall demand for private bandwidth-
@@ -55,8 +55,16 @@ pub struct ContractStateParams {
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)?;
write!(f, "minimum gateway bond: {}; ", self.minimum_gateway_bond)?;
write!(
f,
"minimum mixnode pledge: {}; ",
self.minimum_mixnode_pledge
)?;
write!(
f,
"minimum gateway pledge: {}; ",
self.minimum_gateway_pledge
)?;
write!(
f,
"mixnode rewarded set size: {}",
+1 -1
View File
@@ -125,7 +125,7 @@ impl<'a> TryFrom<&'a GatewayBond> for Node {
Ok(Node {
owner: bond.owner.as_str().to_owned(),
stake: bond.bond_amount.amount.into(),
stake: bond.pledge_amount.amount.into(),
location: bond.gateway.location.clone(),
host,
mix_host,
+1 -1
View File
@@ -117,7 +117,7 @@ impl<'a> TryFrom<&'a MixNodeBond> for Node {
Ok(Node {
owner: bond.owner.as_str().to_owned(),
stake: bond.bond_amount.amount.into(),
stake: bond.pledge_amount.amount.into(),
delegation: bond.total_delegation.amount.into(),
host,
mix_host,
+4 -4
View File
@@ -26,10 +26,10 @@ use cosmwasm_std::{
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);
pub const INITIAL_GATEWAY_PLEDGE: Uint128 = Uint128::new(100_000_000);
/// Constant specifying minimum of coin required to bond a mixnode
pub const INITIAL_MIXNODE_BOND: Uint128 = Uint128::new(100_000_000);
pub const INITIAL_MIXNODE_PLEDGE: Uint128 = Uint128::new(100_000_000);
pub const INITIAL_MIXNODE_REWARDED_SET_SIZE: u32 = 200;
pub const INITIAL_MIXNODE_ACTIVE_SET_SIZE: u32 = 100;
@@ -52,8 +52,8 @@ fn default_initial_state(
owner,
rewarding_validator_address,
params: ContractStateParams {
minimum_mixnode_bond: INITIAL_MIXNODE_BOND,
minimum_gateway_bond: INITIAL_GATEWAY_BOND,
minimum_mixnode_pledge: INITIAL_MIXNODE_PLEDGE,
minimum_gateway_pledge: INITIAL_GATEWAY_PLEDGE,
mixnode_rewarded_set_size: INITIAL_MIXNODE_REWARDED_SET_SIZE,
mixnode_active_set_size: INITIAL_MIXNODE_ACTIVE_SET_SIZE,
},
+7 -7
View File
@@ -46,12 +46,12 @@ mod tests {
use mixnet_contract::{Gateway, IdentityKeyRef};
// currently this is only used in tests but may become useful later on
pub(crate) fn read_gateway_bond_amount(
pub(crate) fn read_gateway_pledge_amount(
storage: &dyn Storage,
identity: IdentityKeyRef,
) -> StdResult<cosmwasm_std::Uint128> {
let node = storage::gateways().load(storage, identity)?;
Ok(node.bond_amount.amount)
Ok(node.pledge_amount.amount)
}
#[test]
@@ -79,14 +79,14 @@ mod tests {
let node_identity: IdentityKey = "nodeidentity".into();
// produces an error if target gateway doesn't exist
let res = read_gateway_bond_amount(&mock_storage, &node_identity);
let res = read_gateway_pledge_amount(&mock_storage, &node_identity);
assert!(res.is_err());
// returns appropriate value otherwise
let bond_value = 1000;
let pledge_amount = 1000;
let gateway_bond = GatewayBond {
bond_amount: coin(bond_value, DENOM),
pledge_amount: coin(pledge_amount, DENOM),
owner: node_owner.clone(),
block_height: 12_345,
gateway: Gateway {
@@ -101,8 +101,8 @@ mod tests {
.unwrap();
assert_eq!(
Uint128::new(bond_value),
read_gateway_bond_amount(&mock_storage, &node_identity).unwrap()
Uint128::new(pledge_amount),
read_gateway_pledge_amount(&mock_storage, &node_identity).unwrap()
);
}
}
+39 -39
View File
@@ -18,14 +18,14 @@ pub fn try_add_gateway(
info: MessageInfo,
gateway: Gateway,
) -> Result<Response, ContractError> {
// check if the bond contains any funds of the appropriate denomination
let minimum_bond = mixnet_params_storage::CONTRACT_STATE
// check if the pledge contains any funds of the appropriate denomination
let minimum_pledge = mixnet_params_storage::CONTRACT_STATE
.load(deps.storage)?
.params
.minimum_mixnode_bond;
let bond = validate_gateway_bond(info.funds, minimum_bond)?;
.minimum_mixnode_pledge;
let pledge = validate_gateway_pledge(info.funds, minimum_pledge)?;
_try_add_gateway(deps, env, gateway, bond, info.sender.as_str(), None)
_try_add_gateway(deps, env, gateway, pledge, info.sender.as_str(), None)
}
pub fn try_add_gateway_on_behalf(
@@ -35,22 +35,22 @@ pub fn try_add_gateway_on_behalf(
gateway: Gateway,
owner: String,
) -> Result<Response, ContractError> {
// check if the bond contains any funds of the appropriate denomination
let minimum_bond = mixnet_params_storage::CONTRACT_STATE
// check if the pledge contains any funds of the appropriate denomination
let minimum_pledge = mixnet_params_storage::CONTRACT_STATE
.load(deps.storage)?
.params
.minimum_mixnode_bond;
let bond = validate_gateway_bond(info.funds, minimum_bond)?;
.minimum_mixnode_pledge;
let pledge = validate_gateway_pledge(info.funds, minimum_pledge)?;
let proxy = info.sender;
_try_add_gateway(deps, env, gateway, bond, &owner, Some(proxy))
_try_add_gateway(deps, env, gateway, pledge, &owner, Some(proxy))
}
pub(crate) fn _try_add_gateway(
deps: DepsMut,
env: Env,
gateway: Gateway,
bond: Coin,
pledge: Coin,
owner: &str,
proxy: Option<Addr>,
) -> Result<Response, ContractError> {
@@ -70,7 +70,7 @@ pub(crate) fn _try_add_gateway(
}
}
let bond = GatewayBond::new(bond, owner, env.block.height, gateway, proxy);
let bond = GatewayBond::new(pledge, owner, env.block.height, gateway, proxy);
storage::gateways().save(deps.storage, bond.identity(), &bond)?;
mixnet_params_storage::increment_layer_count(deps.storage, Layer::Gateway)?;
@@ -119,7 +119,7 @@ pub(crate) fn _try_remove_gateway(
// send bonded funds back to the bond owner
let return_tokens = BankMsg::Send {
to_address: proxy.as_ref().unwrap_or(&owner).to_string(),
amount: vec![gateway_bond.bond_amount()],
amount: vec![gateway_bond.pledge_amount()],
};
// remove the bond
@@ -137,7 +137,7 @@ pub(crate) fn _try_remove_gateway(
if let Some(proxy) = &proxy {
let msg = VestingContractExecuteMsg::TrackUnbondGateway {
owner: owner.as_str().to_string(),
amount: gateway_bond.bond_amount,
amount: gateway_bond.pledge_amount,
};
let track_unbond_message = wasm_execute(proxy, &msg, coins(0, DENOM))?;
@@ -147,42 +147,42 @@ pub(crate) fn _try_remove_gateway(
Ok(response)
}
fn validate_gateway_bond(
mut bond: Vec<Coin>,
minimum_bond: Uint128,
fn validate_gateway_pledge(
mut pledge: Vec<Coin>,
minimum_pledge: Uint128,
) -> Result<Coin, ContractError> {
// check if anything was put as bond
if bond.is_empty() {
if pledge.is_empty() {
return Err(ContractError::NoBondFound);
}
if bond.len() > 1 {
if pledge.len() > 1 {
return Err(ContractError::MultipleDenoms);
}
// check that the denomination is correct
if bond[0].denom != DENOM {
if pledge[0].denom != DENOM {
return Err(ContractError::WrongDenom {});
}
// check that we have at least 100 coins in our bond
if bond[0].amount < minimum_bond {
// check that we have at least 100 coins in our pledge
if pledge[0].amount < minimum_pledge {
return Err(ContractError::InsufficientGatewayBond {
received: bond[0].amount.into(),
minimum: minimum_bond.into(),
received: pledge[0].amount.into(),
minimum: minimum_pledge.into(),
});
}
Ok(bond.pop().unwrap())
Ok(pledge.pop().unwrap())
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::contract::{execute, query, INITIAL_GATEWAY_BOND};
use crate::contract::{execute, query, INITIAL_GATEWAY_PLEDGE};
use crate::error::ContractError;
use crate::gateways::transactions::try_add_gateway;
use crate::gateways::transactions::validate_gateway_bond;
use crate::gateways::transactions::validate_gateway_pledge;
use crate::support::tests::test_helpers;
use config::defaults::DENOM;
use cosmwasm_std::attr;
@@ -198,7 +198,7 @@ pub mod tests {
let mut deps = test_helpers::init_contract();
// if we fail validation (by say not sending enough funds
let insufficient_bond = Into::<u128>::into(INITIAL_GATEWAY_BOND) - 1;
let insufficient_bond = Into::<u128>::into(INITIAL_GATEWAY_PLEDGE) - 1;
let info = mock_info("anyone", &coins(insufficient_bond, DENOM));
let msg = ExecuteMsg::BondGateway {
gateway: test_helpers::gateway_fixture(),
@@ -210,7 +210,7 @@ pub mod tests {
result,
Err(ContractError::InsufficientGatewayBond {
received: insufficient_bond,
minimum: INITIAL_GATEWAY_BOND.into(),
minimum: INITIAL_GATEWAY_PLEDGE.into(),
})
);
@@ -481,7 +481,7 @@ pub mod tests {
"gateway_bond",
format!(
"amount: {} {}, owner: fred, identity: fredsgateway",
INITIAL_GATEWAY_BOND, DENOM
INITIAL_GATEWAY_PLEDGE, DENOM
),
),
];
@@ -568,36 +568,36 @@ pub mod tests {
#[test]
fn validating_gateway_bond() {
// you must send SOME funds
let result = validate_gateway_bond(Vec::new(), INITIAL_GATEWAY_BOND);
let result = validate_gateway_pledge(Vec::new(), INITIAL_GATEWAY_PLEDGE);
assert_eq!(result, Err(ContractError::NoBondFound));
// you must send at least 100 coins...
let mut bond = test_helpers::good_gateway_bond();
bond[0].amount = INITIAL_GATEWAY_BOND.checked_sub(Uint128::new(1)).unwrap();
let result = validate_gateway_bond(bond.clone(), INITIAL_GATEWAY_BOND);
bond[0].amount = INITIAL_GATEWAY_PLEDGE.checked_sub(Uint128::new(1)).unwrap();
let result = validate_gateway_pledge(bond.clone(), INITIAL_GATEWAY_PLEDGE);
assert_eq!(
result,
Err(ContractError::InsufficientGatewayBond {
received: Into::<u128>::into(INITIAL_GATEWAY_BOND) - 1,
minimum: INITIAL_GATEWAY_BOND.into(),
received: Into::<u128>::into(INITIAL_GATEWAY_PLEDGE) - 1,
minimum: INITIAL_GATEWAY_PLEDGE.into(),
})
);
// more than that is still fine
let mut bond = test_helpers::good_gateway_bond();
bond[0].amount = INITIAL_GATEWAY_BOND + Uint128::new(1);
let result = validate_gateway_bond(bond.clone(), INITIAL_GATEWAY_BOND);
bond[0].amount = INITIAL_GATEWAY_PLEDGE + Uint128::new(1);
let result = validate_gateway_pledge(bond.clone(), INITIAL_GATEWAY_PLEDGE);
assert!(result.is_ok());
// it must be sent in the defined denom!
let mut bond = test_helpers::good_gateway_bond();
bond[0].denom = "baddenom".to_string();
let result = validate_gateway_bond(bond.clone(), INITIAL_GATEWAY_BOND);
let result = validate_gateway_pledge(bond.clone(), INITIAL_GATEWAY_PLEDGE);
assert_eq!(result, Err(ContractError::WrongDenom {}));
let mut bond = test_helpers::good_gateway_bond();
bond[0].denom = "foomp".to_string();
let result = validate_gateway_bond(bond.clone(), INITIAL_GATEWAY_BOND);
let result = validate_gateway_pledge(bond.clone(), INITIAL_GATEWAY_PLEDGE);
assert_eq!(result, Err(ContractError::WrongDenom {}));
}
}
@@ -51,8 +51,8 @@ pub(crate) mod tests {
owner: Addr::unchecked("someowner"),
rewarding_validator_address: Addr::unchecked("monitor"),
params: ContractStateParams {
minimum_mixnode_bond: 123u128.into(),
minimum_gateway_bond: 456u128.into(),
minimum_mixnode_pledge: 123u128.into(),
minimum_gateway_pledge: 456u128.into(),
mixnode_rewarded_set_size: 1000,
mixnode_active_set_size: 500,
},
@@ -43,7 +43,7 @@ pub(crate) fn try_update_contract_settings(
#[cfg(test)]
pub mod tests {
use super::*;
use crate::contract::{INITIAL_GATEWAY_BOND, INITIAL_MIXNODE_BOND};
use crate::contract::{INITIAL_GATEWAY_PLEDGE, INITIAL_MIXNODE_PLEDGE};
use crate::error::ContractError;
use crate::mixnet_contract_settings::transactions::try_update_contract_settings;
use crate::support::tests::test_helpers;
@@ -56,8 +56,8 @@ pub mod tests {
let mut deps = test_helpers::init_contract();
let new_params = ContractStateParams {
minimum_mixnode_bond: INITIAL_MIXNODE_BOND,
minimum_gateway_bond: INITIAL_GATEWAY_BOND,
minimum_mixnode_pledge: INITIAL_MIXNODE_PLEDGE,
minimum_gateway_pledge: INITIAL_GATEWAY_PLEDGE,
mixnode_rewarded_set_size: 100,
mixnode_active_set_size: 50,
};
+13 -13
View File
@@ -44,7 +44,7 @@ pub(crate) fn mixnodes<'a>(
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub(crate) struct StoredMixnodeBond {
pub bond_amount: Coin,
pub pledge_amount: Coin,
pub owner: Addr,
pub layer: Layer,
pub block_height: u64,
@@ -55,7 +55,7 @@ pub(crate) struct StoredMixnodeBond {
impl StoredMixnodeBond {
pub(crate) fn new(
bond_amount: Coin,
pledge_amount: Coin,
owner: Addr,
layer: Layer,
block_height: u64,
@@ -64,7 +64,7 @@ impl StoredMixnodeBond {
proxy: Option<Addr>,
) -> Self {
StoredMixnodeBond {
bond_amount,
pledge_amount,
owner,
layer,
block_height,
@@ -77,10 +77,10 @@ impl StoredMixnodeBond {
pub(crate) fn attach_delegation(self, total_delegation: Uint128) -> MixNodeBond {
MixNodeBond {
total_delegation: Coin {
denom: self.bond_amount.denom.clone(),
denom: self.pledge_amount.denom.clone(),
amount: total_delegation,
},
bond_amount: self.bond_amount,
pledge_amount: self.pledge_amount,
owner: self.owner,
layer: self.layer,
block_height: self.block_height,
@@ -94,8 +94,8 @@ impl StoredMixnodeBond {
&self.mix_node.identity_key
}
pub(crate) fn bond_amount(&self) -> Coin {
self.bond_amount.clone()
pub(crate) fn pledge_amount(&self) -> Coin {
self.pledge_amount.clone()
}
}
@@ -104,7 +104,7 @@ impl Display for StoredMixnodeBond {
write!(
f,
"amount: {}, owner: {}, identity: {}",
self.bond_amount, self.owner, self.mix_node.identity_key
self.pledge_amount, self.owner, self.mix_node.identity_key
)
}
}
@@ -119,7 +119,7 @@ pub(crate) fn read_full_mixnode_bond(
Some(stored_bond) => {
let total_delegation = TOTAL_DELEGATION.may_load(storage, mix_identity)?;
Ok(Some(MixNodeBond {
bond_amount: stored_bond.bond_amount,
pledge_amount: stored_bond.pledge_amount,
total_delegation: Coin {
denom: DENOM.to_owned(),
amount: total_delegation.unwrap_or_default(),
@@ -172,22 +172,22 @@ mod tests {
assert!(res.is_none());
// returns appropriate value otherwise
let bond_value = 1000000000;
let pledge_value = 1000000000;
let mixnode = MixNode {
identity_key: node_identity.clone(),
..test_helpers::mix_node_fixture()
};
let info = mock_info(node_owner.as_str(), &vec![coin(bond_value, DENOM)]);
let info = mock_info(node_owner.as_str(), &vec![coin(pledge_value, DENOM)]);
try_add_mixnode(deps.as_mut(), mock_env(), info, mixnode).unwrap();
assert_eq!(
Uint128::new(bond_value),
Uint128::new(pledge_value),
storage::read_full_mixnode_bond(deps.as_ref().storage, node_identity.as_str())
.unwrap()
.unwrap()
.bond_amount
.pledge_amount
.amount
);
}
+39 -39
View File
@@ -20,14 +20,14 @@ pub fn try_add_mixnode(
info: MessageInfo,
mix_node: MixNode,
) -> Result<Response, ContractError> {
// check if the bond contains any funds of the appropriate denomination
let minimum_bond = mixnet_params_storage::CONTRACT_STATE
// check if the pledge contains any funds of the appropriate denomination
let minimum_pledge = mixnet_params_storage::CONTRACT_STATE
.load(deps.storage)?
.params
.minimum_mixnode_bond;
let bond = validate_mixnode_bond(info.funds, minimum_bond)?;
.minimum_mixnode_pledge;
let pledge = validate_mixnode_pledge(info.funds, minimum_pledge)?;
_try_add_mixnode(deps, env, mix_node, bond, info.sender.as_str(), None)
_try_add_mixnode(deps, env, mix_node, pledge, info.sender.as_str(), None)
}
pub fn try_add_mixnode_on_behalf(
@@ -37,22 +37,22 @@ pub fn try_add_mixnode_on_behalf(
mix_node: MixNode,
owner: String,
) -> Result<Response, ContractError> {
// check if the bond contains any funds of the appropriate denomination
let minimum_bond = mixnet_params_storage::CONTRACT_STATE
// check if the pledge contains any funds of the appropriate denomination
let minimum_pledge = mixnet_params_storage::CONTRACT_STATE
.load(deps.storage)?
.params
.minimum_mixnode_bond;
let bond = validate_mixnode_bond(info.funds, minimum_bond)?;
.minimum_mixnode_pledge;
let pledge = validate_mixnode_pledge(info.funds, minimum_pledge)?;
let proxy = info.sender;
_try_add_mixnode(deps, env, mix_node, bond, &owner, Some(proxy))
_try_add_mixnode(deps, env, mix_node, pledge, &owner, Some(proxy))
}
fn _try_add_mixnode(
deps: DepsMut,
env: Env,
mix_node: MixNode,
bond_amount: Coin,
pledge_amount: Coin,
owner: &str,
proxy: Option<Addr>,
) -> Result<Response, ContractError> {
@@ -75,7 +75,7 @@ fn _try_add_mixnode(
let layer = layer_distribution.choose_with_fewest();
let stored_bond = StoredMixnodeBond::new(
bond_amount,
pledge_amount,
owner,
layer,
env.block.height,
@@ -143,7 +143,7 @@ pub(crate) fn _try_remove_mixnode(
// send bonded funds back to the bond owner
let return_tokens = BankMsg::Send {
to_address: proxy.as_ref().unwrap_or(&owner).to_string(),
amount: vec![mixnode_bond.bond_amount()],
amount: vec![mixnode_bond.pledge_amount()],
};
// remove the bond
@@ -160,7 +160,7 @@ pub(crate) fn _try_remove_mixnode(
if let Some(proxy) = &proxy {
let msg = VestingContractExecuteMsg::TrackUnbondMixnode {
owner: owner.as_str().to_string(),
amount: mixnode_bond.bond_amount,
amount: mixnode_bond.pledge_amount,
};
let track_unbond_message = wasm_execute(proxy, &msg, coins(0, DENOM))?;
@@ -170,42 +170,42 @@ pub(crate) fn _try_remove_mixnode(
Ok(response)
}
fn validate_mixnode_bond(
mut bond: Vec<Coin>,
minimum_bond: Uint128,
fn validate_mixnode_pledge(
mut pledge: Vec<Coin>,
minimum_pledge: Uint128,
) -> Result<Coin, ContractError> {
// check if anything was put as bond
if bond.is_empty() {
if pledge.is_empty() {
return Err(ContractError::NoBondFound);
}
if bond.len() > 1 {
if pledge.len() > 1 {
return Err(ContractError::MultipleDenoms);
}
// check that the denomination is correct
if bond[0].denom != DENOM {
if pledge[0].denom != DENOM {
return Err(ContractError::WrongDenom {});
}
// check that we have at least MIXNODE_BOND coins in our bond
if bond[0].amount < minimum_bond {
// check that we have at least MIXNODE_BOND coins in our pledge
if pledge[0].amount < minimum_pledge {
return Err(ContractError::InsufficientMixNodeBond {
received: bond[0].amount.into(),
minimum: minimum_bond.into(),
received: pledge[0].amount.into(),
minimum: minimum_pledge.into(),
});
}
Ok(bond.pop().unwrap())
Ok(pledge.pop().unwrap())
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::contract::{execute, query, INITIAL_MIXNODE_BOND};
use crate::contract::{execute, query, INITIAL_MIXNODE_PLEDGE};
use crate::error::ContractError;
use crate::mixnodes::transactions::try_add_mixnode;
use crate::mixnodes::transactions::validate_mixnode_bond;
use crate::mixnodes::transactions::validate_mixnode_pledge;
use crate::support::tests::test_helpers;
use config::defaults::DENOM;
use cosmwasm_std::attr;
@@ -222,7 +222,7 @@ pub mod tests {
let mut deps = test_helpers::init_contract();
// if we don't send enough funds
let insufficient_bond = Into::<u128>::into(INITIAL_MIXNODE_BOND) - 1;
let insufficient_bond = Into::<u128>::into(INITIAL_MIXNODE_PLEDGE) - 1;
let info = mock_info("anyone", &coins(insufficient_bond, DENOM));
let msg = ExecuteMsg::BondMixnode {
mix_node: MixNode {
@@ -237,7 +237,7 @@ pub mod tests {
result,
Err(ContractError::InsufficientMixNodeBond {
received: insufficient_bond,
minimum: INITIAL_MIXNODE_BOND.into(),
minimum: INITIAL_MIXNODE_PLEDGE.into(),
})
);
@@ -537,7 +537,7 @@ pub mod tests {
"mixnode_bond",
format!(
"amount: {}{}, owner: fred, identity: fredsmixnode",
INITIAL_MIXNODE_BOND, DENOM
INITIAL_MIXNODE_PLEDGE, DENOM
),
),
];
@@ -624,36 +624,36 @@ pub mod tests {
#[test]
fn validating_mixnode_bond() {
// you must send SOME funds
let result = validate_mixnode_bond(Vec::new(), INITIAL_MIXNODE_BOND);
let result = validate_mixnode_pledge(Vec::new(), INITIAL_MIXNODE_PLEDGE);
assert_eq!(result, Err(ContractError::NoBondFound));
// you must send at least 100 coins...
let mut bond = test_helpers::good_mixnode_bond();
bond[0].amount = INITIAL_MIXNODE_BOND.checked_sub(Uint128::new(1)).unwrap();
let result = validate_mixnode_bond(bond.clone(), INITIAL_MIXNODE_BOND);
bond[0].amount = INITIAL_MIXNODE_PLEDGE.checked_sub(Uint128::new(1)).unwrap();
let result = validate_mixnode_pledge(bond.clone(), INITIAL_MIXNODE_PLEDGE);
assert_eq!(
result,
Err(ContractError::InsufficientMixNodeBond {
received: Into::<u128>::into(INITIAL_MIXNODE_BOND) - 1,
minimum: INITIAL_MIXNODE_BOND.into(),
received: Into::<u128>::into(INITIAL_MIXNODE_PLEDGE) - 1,
minimum: INITIAL_MIXNODE_PLEDGE.into(),
})
);
// more than that is still fine
let mut bond = test_helpers::good_mixnode_bond();
bond[0].amount = INITIAL_MIXNODE_BOND + Uint128::new(1);
let result = validate_mixnode_bond(bond.clone(), INITIAL_MIXNODE_BOND);
bond[0].amount = INITIAL_MIXNODE_PLEDGE + Uint128::new(1);
let result = validate_mixnode_pledge(bond.clone(), INITIAL_MIXNODE_PLEDGE);
assert!(result.is_ok());
// it must be sent in the defined denom!
let mut bond = test_helpers::good_mixnode_bond();
bond[0].denom = "baddenom".to_string();
let result = validate_mixnode_bond(bond.clone(), INITIAL_MIXNODE_BOND);
let result = validate_mixnode_pledge(bond.clone(), INITIAL_MIXNODE_PLEDGE);
assert_eq!(result, Err(ContractError::WrongDenom {}));
let mut bond = test_helpers::good_mixnode_bond();
bond[0].denom = "foomp".to_string();
let result = validate_mixnode_bond(bond.clone(), INITIAL_MIXNODE_BOND);
let result = validate_mixnode_pledge(bond.clone(), INITIAL_MIXNODE_PLEDGE);
assert_eq!(result, Err(ContractError::WrongDenom {}));
}
+2 -2
View File
@@ -20,7 +20,7 @@ pub(crate) fn update_post_rewarding_storage(
return Ok(());
}
// update bond
// update pledge
if operator_reward > Uint128::zero() {
mixnodes_storage::mixnodes().update(storage, mix_identity, |current_bond| {
match current_bond {
@@ -28,7 +28,7 @@ pub(crate) fn update_post_rewarding_storage(
identity: mix_identity.to_string(),
}),
Some(mut mixnode_bond) => {
mixnode_bond.bond_amount.amount += operator_reward;
mixnode_bond.pledge_amount.amount += operator_reward;
Ok(mixnode_bond)
}
}
+9 -9
View File
@@ -948,7 +948,7 @@ pub mod tests {
let initial_bond = 10000_000000;
let initial_delegation = 20000_000000;
let mixnode_bond = StoredMixnodeBond {
bond_amount: coin(initial_bond, DENOM),
pledge_amount: coin(initial_bond, DENOM),
owner: node_owner.clone(),
layer: Layer::One,
block_height: env.block.height,
@@ -1003,7 +1003,7 @@ pub mod tests {
assert_eq!(
initial_bond,
test_helpers::read_mixnode_bond_amount(deps.as_ref().storage, &node_identity)
test_helpers::read_mixnode_pledge_amount(deps.as_ref().storage, &node_identity)
.unwrap()
.u128()
);
@@ -1040,7 +1040,7 @@ pub mod tests {
try_finish_mixnode_rewarding(deps.as_mut(), info, 2).unwrap();
assert!(
test_helpers::read_mixnode_bond_amount(deps.as_ref().storage, &node_identity)
test_helpers::read_mixnode_pledge_amount(deps.as_ref().storage, &node_identity)
.unwrap()
.u128()
> initial_bond
@@ -1064,8 +1064,8 @@ pub mod tests {
// reward happens now, both for node owner and delegators
env.block.height += storage::MINIMUM_BLOCK_AGE_FOR_REWARDING - 1;
let bond_before_rewarding =
test_helpers::read_mixnode_bond_amount(deps.as_ref().storage, &node_identity)
let pledge_before_rewarding =
test_helpers::read_mixnode_pledge_amount(deps.as_ref().storage, &node_identity)
.unwrap()
.u128();
@@ -1083,10 +1083,10 @@ pub mod tests {
try_finish_mixnode_rewarding(deps.as_mut(), info, 3).unwrap();
assert!(
test_helpers::read_mixnode_bond_amount(deps.as_ref().storage, &node_identity)
test_helpers::read_mixnode_pledge_amount(deps.as_ref().storage, &node_identity)
.unwrap()
.u128()
> bond_before_rewarding
> pledge_before_rewarding
);
assert!(
mixnodes_storage::TOTAL_DELEGATION
@@ -1210,7 +1210,7 @@ pub mod tests {
assert_eq!(mix1_delegator1_reward, U128::from_num(22552615));
assert_eq!(mix1_delegator2_reward, U128::from_num(5638153));
let pre_reward_bond = test_helpers::read_mixnode_bond_amount(&deps.storage, "alice")
let pre_reward_bond = test_helpers::read_mixnode_pledge_amount(&deps.storage, "alice")
.unwrap()
.u128();
assert_eq!(pre_reward_bond, 10_000_000_000);
@@ -1224,7 +1224,7 @@ pub mod tests {
try_reward_mixnode(deps.as_mut(), env, info, "alice".to_string(), params, 1).unwrap();
assert_eq!(
test_helpers::read_mixnode_bond_amount(&deps.storage, "alice")
test_helpers::read_mixnode_pledge_amount(&deps.storage, "alice")
.unwrap()
.u128(),
U128::from_num(pre_reward_bond) + U128::from_num(mix1_operator_profit)
+5 -5
View File
@@ -4,7 +4,7 @@
#[cfg(test)]
pub mod test_helpers {
use super::*;
use crate::contract::{instantiate, INITIAL_MIXNODE_BOND};
use crate::contract::{instantiate, INITIAL_MIXNODE_PLEDGE};
use crate::contract::{
query, DEFAULT_SYBIL_RESISTANCE_PERCENT, EPOCH_REWARD_PERCENT, INITIAL_REWARD_POOL,
};
@@ -174,14 +174,14 @@ pub mod test_helpers {
pub fn good_mixnode_bond() -> Vec<Coin> {
vec![Coin {
denom: DENOM.to_string(),
amount: INITIAL_MIXNODE_BOND,
amount: INITIAL_MIXNODE_PLEDGE,
}]
}
pub fn good_gateway_bond() -> Vec<Coin> {
vec![Coin {
denom: DENOM.to_string(),
amount: INITIAL_MIXNODE_BOND,
amount: INITIAL_MIXNODE_PLEDGE,
}]
}
@@ -198,12 +198,12 @@ pub mod test_helpers {
}
// currently not used outside tests
pub(crate) fn read_mixnode_bond_amount(
pub(crate) fn read_mixnode_pledge_amount(
storage: &dyn Storage,
identity: IdentityKeyRef,
) -> StdResult<cosmwasm_std::Uint128> {
let node = mixnodes_storage::mixnodes().load(storage, identity)?;
Ok(node.bond_amount.amount)
Ok(node.pledge_amount.amount)
}
pub(crate) fn save_dummy_delegation(
+4 -4
View File
@@ -75,9 +75,9 @@ pub fn try_bond_gateway(
env: Env,
deps: DepsMut,
) -> Result<Response, ContractError> {
let bond = validate_funds(&info.funds)?;
let pledge = validate_funds(&info.funds)?;
let account = account_from_address(info.sender.as_str(), deps.storage, deps.api)?;
account.try_bond_gateway(gateway, bond, &env, deps.storage)
account.try_bond_gateway(gateway, pledge, &env, deps.storage)
}
pub fn try_unbond_gateway(info: MessageInfo, deps: DepsMut) -> Result<Response, ContractError> {
@@ -105,9 +105,9 @@ pub fn try_bond_mixnode(
env: Env,
deps: DepsMut,
) -> Result<Response, ContractError> {
let bond = validate_funds(&info.funds)?;
let pledge = validate_funds(&info.funds)?;
let account = account_from_address(info.sender.as_str(), deps.storage, deps.api)?;
account.try_bond_mixnode(mix_node, bond, &env, deps.storage)
account.try_bond_mixnode(mix_node, pledge, &env, deps.storage)
}
pub fn try_unbond_mixnode(info: MessageInfo, deps: DepsMut) -> Result<Response, ContractError> {
@@ -3,7 +3,7 @@ use cosmwasm_std::{Coin, Env, Storage, Timestamp};
pub trait VestingAccount {
// locked_coins returns the set of coins that are not spendable (can still be delegated tough) (i.e. locked),
// defined as the vesting coins that are not delegated or bonded.
// defined as the vesting coins that are not delegated or pledged.
//
// To get spendable coins of a vesting account, first the total balance must
// be retrieved and the locked tokens can be subtracted from the total balance.
@@ -50,13 +50,13 @@ pub trait VestingAccount {
env: &Env,
storage: &dyn Storage,
) -> Result<Coin, ContractError>;
fn get_bonded_free(
fn get_pledged_free(
&self,
block_time: Option<Timestamp>,
env: &Env,
storage: &dyn Storage,
) -> Result<Coin, ContractError>;
fn get_bonded_vesting(
fn get_pledged_vesting(
&self,
block_time: Option<Timestamp>,
env: &Env,
@@ -1,4 +1,4 @@
use super::BondData;
use super::PledgeData;
use crate::errors::ContractError;
use crate::traits::GatewayBondingAccount;
use config::defaults::DEFAULT_MIXNET_CONTRACT_ADDRESS;
@@ -11,27 +11,27 @@ impl GatewayBondingAccount for Account {
fn try_bond_gateway(
&self,
gateway: Gateway,
bond: Coin,
pledge: Coin,
env: &Env,
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
if current_balance < bond.amount {
if current_balance < pledge.amount {
return Err(ContractError::InsufficientBalance(
self.address.as_str().to_string(),
current_balance.u128(),
));
}
let bond_data = if let Some(_bond) = self.load_gateway_bond(storage)? {
let pledge_data = if self.load_gateway_pledge(storage)?.is_some() {
return Err(ContractError::AlreadyBonded(
self.address.as_str().to_string(),
));
} else {
BondData {
PledgeData {
block_time: env.block.time,
amount: bond.amount,
amount: pledge.amount,
}
};
@@ -40,12 +40,12 @@ impl GatewayBondingAccount for Account {
owner: self.address().into_string(),
};
let new_balance = Uint128::new(current_balance.u128() - bond.amount.u128());
let new_balance = Uint128::new(current_balance.u128() - pledge.amount.u128());
let bond_mixnode_mag = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![bond])?;
let bond_mixnode_mag = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![pledge])?;
self.save_balance(new_balance, storage)?;
self.save_gateway_bond(bond_data, storage)?;
self.save_gateway_pledge(pledge_data, storage)?;
Ok(Response::new()
.add_attribute("action", "bond gateway on behalf")
@@ -57,7 +57,7 @@ impl GatewayBondingAccount for Account {
owner: self.address().into_string(),
};
if let Some(_bond) = self.load_gateway_bond(storage)? {
if let Some(_bond) = self.load_gateway_pledge(storage)? {
let unbond_msg = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![])?;
Ok(Response::new()
@@ -1,4 +1,4 @@
use super::BondData;
use super::PledgeData;
use crate::errors::ContractError;
use crate::traits::MixnodeBondingAccount;
use config::defaults::DEFAULT_MIXNET_CONTRACT_ADDRESS;
@@ -11,27 +11,27 @@ impl MixnodeBondingAccount for Account {
fn try_bond_mixnode(
&self,
mix_node: MixNode,
bond: Coin,
pledge: Coin,
env: &Env,
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
if current_balance < bond.amount {
if current_balance < pledge.amount {
return Err(ContractError::InsufficientBalance(
self.address.as_str().to_string(),
current_balance.u128(),
));
}
let bond_data = if let Some(_bond) = self.load_mixnode_bond(storage)? {
let pledge_data = if self.load_mixnode_pledge(storage)?.is_some() {
return Err(ContractError::AlreadyBonded(
self.address.as_str().to_string(),
));
} else {
BondData {
PledgeData {
block_time: env.block.time,
amount: bond.amount,
amount: pledge.amount,
}
};
@@ -40,12 +40,12 @@ impl MixnodeBondingAccount for Account {
owner: self.address().into_string(),
};
let new_balance = Uint128::new(current_balance.u128() - bond.amount.u128());
let new_balance = Uint128::new(current_balance.u128() - pledge.amount.u128());
let bond_mixnode_mag = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![bond])?;
let bond_mixnode_mag = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![pledge])?;
self.save_balance(new_balance, storage)?;
self.save_mixnode_bond(bond_data, storage)?;
self.save_mixnode_pledge(pledge_data, storage)?;
Ok(Response::new()
.add_attribute("action", "bond mixnode on behalf")
@@ -57,7 +57,7 @@ impl MixnodeBondingAccount for Account {
owner: self.address().into_string(),
};
if let Some(_bond) = self.load_mixnode_bond(storage)? {
if self.load_mixnode_pledge(storage)?.is_some() {
let unbond_msg = wasm_execute(DEFAULT_MIXNET_CONTRACT_ADDRESS, &msg, vec![])?;
Ok(Response::new()
+24 -24
View File
@@ -1,4 +1,4 @@
use super::{BondData, VestingPeriod};
use super::{PledgeData, VestingPeriod};
use crate::contract::NUM_VESTING_PERIODS;
use crate::errors::ContractError;
use crate::storage::save_account;
@@ -15,7 +15,7 @@ mod vesting_account;
const DELEGATIONS_SUFFIX: &str = "de";
const BALANCE_SUFFIX: &str = "ba";
const BOND_SUFFIX: &str = "bo";
const PLEDGE_SUFFIX: &str = "bo";
const GATEWAY_SUFFIX: &str = "ga";
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
@@ -26,8 +26,8 @@ pub struct Account {
coin: Coin,
delegations_key: String,
balance_key: String,
mixnode_bond_key: String,
gateway_bond_key: String,
mixnode_pledge_key: String,
gateway_pledge_key: String,
}
impl Account {
@@ -46,8 +46,8 @@ impl Account {
coin,
delegations_key: format!("{}_{}", address, DELEGATIONS_SUFFIX),
balance_key: format!("{}_{}", address, BALANCE_SUFFIX),
mixnode_bond_key: format!("{}_{}", address, BOND_SUFFIX),
gateway_bond_key: format!("{}_{}", address, GATEWAY_SUFFIX),
mixnode_pledge_key: format!("{}_{}", address, PLEDGE_SUFFIX),
gateway_pledge_key: format!("{}_{}", address, GATEWAY_SUFFIX),
};
save_account(&account, storage)?;
account.save_balance(amount, storage)?;
@@ -118,52 +118,52 @@ impl Account {
Item::new(self.balance_key.as_ref())
}
pub fn load_mixnode_bond(
pub fn load_mixnode_pledge(
&self,
storage: &dyn Storage,
) -> Result<Option<BondData>, ContractError> {
Ok(self.mixnode_bond().may_load(storage)?)
) -> Result<Option<PledgeData>, ContractError> {
Ok(self.mixnode_pledge().may_load(storage)?)
}
pub fn save_mixnode_bond(
pub fn save_mixnode_pledge(
&self,
bond: BondData,
pledge: PledgeData,
storage: &mut dyn Storage,
) -> Result<(), ContractError> {
Ok(self.mixnode_bond().save(storage, &bond)?)
Ok(self.mixnode_pledge().save(storage, &pledge)?)
}
pub fn remove_mixnode_bond(&self, storage: &mut dyn Storage) -> Result<(), ContractError> {
self.mixnode_bond().remove(storage);
self.mixnode_pledge().remove(storage);
Ok(())
}
fn mixnode_bond(&self) -> Item<BondData> {
Item::new(self.mixnode_bond_key.as_ref())
fn mixnode_pledge(&self) -> Item<PledgeData> {
Item::new(self.mixnode_pledge_key.as_ref())
}
pub fn load_gateway_bond(
pub fn load_gateway_pledge(
&self,
storage: &dyn Storage,
) -> Result<Option<BondData>, ContractError> {
Ok(self.gateway_bond().may_load(storage)?)
) -> Result<Option<PledgeData>, ContractError> {
Ok(self.gateway_pledge().may_load(storage)?)
}
pub fn save_gateway_bond(
pub fn save_gateway_pledge(
&self,
bond: BondData,
pledge: PledgeData,
storage: &mut dyn Storage,
) -> Result<(), ContractError> {
Ok(self.gateway_bond().save(storage, &bond)?)
Ok(self.gateway_pledge().save(storage, &pledge)?)
}
pub fn remove_gateway_bond(&self, storage: &mut dyn Storage) -> Result<(), ContractError> {
self.gateway_bond().remove(storage);
self.gateway_pledge().remove(storage);
Ok(())
}
fn gateway_bond(&self) -> Item<BondData> {
Item::new(self.gateway_bond_key.as_ref())
fn gateway_pledge(&self) -> Item<PledgeData> {
Item::new(self.gateway_pledge_key.as_ref())
}
fn delegations(&self) -> Map<(&[u8], u64), Uint128> {
@@ -26,7 +26,7 @@ impl VestingAccount for Account {
)
.ok_or(ContractError::Underflow)?
.checked_sub(
self.get_bonded_vesting(block_time, env, storage)?
self.get_pledged_vesting(block_time, env, storage)?
.amount
.u128(),
)
@@ -152,7 +152,7 @@ impl VestingAccount for Account {
})
}
fn get_bonded_free(
fn get_pledged_free(
&self,
block_time: Option<Timestamp>,
env: &Env,
@@ -164,8 +164,8 @@ impl VestingAccount for Account {
let start_time = self.periods[period].start_time;
let amount = if let Some(bond) = self
.load_mixnode_bond(storage)?
.or(self.load_gateway_bond(storage)?)
.load_mixnode_pledge(storage)?
.or(self.load_gateway_pledge(storage)?)
{
if bond.block_time.seconds() < start_time {
bond.amount
@@ -184,18 +184,18 @@ impl VestingAccount for Account {
})
}
fn get_bonded_vesting(
fn get_pledged_vesting(
&self,
block_time: Option<Timestamp>,
env: &Env,
storage: &dyn Storage,
) -> Result<Coin, ContractError> {
let block_time = block_time.unwrap_or(env.block.time);
let bonded_free = self.get_bonded_free(Some(block_time), env, storage)?;
let bonded_free = self.get_pledged_free(Some(block_time), env, storage)?;
if let Some(bond) = self
.load_mixnode_bond(storage)?
.or(self.load_gateway_bond(storage)?)
.load_mixnode_pledge(storage)?
.or(self.load_gateway_pledge(storage)?)
{
let amount = bond.amount - bonded_free.amount;
Ok(Coin {
+25 -25
View File
@@ -18,7 +18,7 @@ impl VestingPeriod {
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct BondData {
pub struct PledgeData {
amount: Uint128,
block_time: Timestamp,
}
@@ -287,53 +287,53 @@ mod tests {
);
assert!(err.is_err());
let bond = account.load_mixnode_bond(&deps.storage).unwrap().unwrap();
assert_eq!(Uint128::new(500_000_000_000), bond.amount);
let pledge = account.load_mixnode_pledge(&deps.storage).unwrap().unwrap();
assert_eq!(Uint128::new(500_000_000_000), pledge.amount);
// Current period -> block_time: None
let bonded_free = account.get_bonded_free(None, &env, &deps.storage).unwrap();
let bonded_free = account.get_pledged_free(None, &env, &deps.storage).unwrap();
assert_eq!(Uint128::new(0), bonded_free.amount);
let bonded_vesting = account
.get_bonded_vesting(None, &env, &deps.storage)
.get_pledged_vesting(None, &env, &deps.storage)
.unwrap();
assert_eq!(bond.amount - bonded_free.amount, bonded_vesting.amount);
assert_eq!(pledge.amount - bonded_free.amount, bonded_vesting.amount);
// All periods
for (i, period) in account.periods().iter().enumerate() {
let bonded_free = account
.get_bonded_free(
.get_pledged_free(
Some(Timestamp::from_seconds(period.start_time + 1)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(
(account.tokens_per_period().unwrap() * i as u128).min(bond.amount.u128()),
(account.tokens_per_period().unwrap() * i as u128).min(pledge.amount.u128()),
bonded_free.amount.u128()
);
let bonded_vesting = account
.get_bonded_vesting(
.get_pledged_vesting(
Some(Timestamp::from_seconds(period.start_time + 1)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(bond.amount - bonded_free.amount, bonded_vesting.amount);
assert_eq!(pledge.amount - bonded_free.amount, bonded_vesting.amount);
}
let bonded_free = account
.get_bonded_free(
.get_pledged_free(
Some(Timestamp::from_seconds(1764416964)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(bond.amount, bonded_free.amount);
assert_eq!(pledge.amount, bonded_free.amount);
let bonded_vesting = account
.get_bonded_vesting(
.get_pledged_vesting(
Some(Timestamp::from_seconds(1764416964)),
&env,
&deps.storage,
@@ -397,53 +397,53 @@ mod tests {
);
assert!(err.is_err());
let bond = account.load_gateway_bond(&deps.storage).unwrap().unwrap();
assert_eq!(Uint128::new(500_000_000_000), bond.amount);
let pledge = account.load_gateway_pledge(&deps.storage).unwrap().unwrap();
assert_eq!(Uint128::new(500_000_000_000), pledge.amount);
// Current period -> block_time: None
let bonded_free = account.get_bonded_free(None, &env, &deps.storage).unwrap();
let bonded_free = account.get_pledged_free(None, &env, &deps.storage).unwrap();
assert_eq!(Uint128::new(0), bonded_free.amount);
let bonded_vesting = account
.get_bonded_vesting(None, &env, &deps.storage)
.get_pledged_vesting(None, &env, &deps.storage)
.unwrap();
assert_eq!(bond.amount - bonded_free.amount, bonded_vesting.amount);
assert_eq!(pledge.amount - bonded_free.amount, bonded_vesting.amount);
// All periods
for (i, period) in account.periods().iter().enumerate() {
let bonded_free = account
.get_bonded_free(
.get_pledged_free(
Some(Timestamp::from_seconds(period.start_time + 1)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(
(account.tokens_per_period().unwrap() * i as u128).min(bond.amount.u128()),
(account.tokens_per_period().unwrap() * i as u128).min(pledge.amount.u128()),
bonded_free.amount.u128()
);
let bonded_vesting = account
.get_bonded_vesting(
.get_pledged_vesting(
Some(Timestamp::from_seconds(period.start_time + 1)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(bond.amount - bonded_free.amount, bonded_vesting.amount);
assert_eq!(pledge.amount - bonded_free.amount, bonded_vesting.amount);
}
let bonded_free = account
.get_bonded_free(
.get_pledged_free(
Some(Timestamp::from_seconds(1764416964)),
&env,
&deps.storage,
)
.unwrap();
assert_eq!(bond.amount, bonded_free.amount);
assert_eq!(pledge.amount, bonded_free.amount);
let bonded_vesting = account
.get_bonded_vesting(
.get_pledged_vesting(
Some(Timestamp::from_seconds(1764416964)),
&env,
&deps.storage,
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn mix_node_make_default_routes() -> Vec<Route> {
#[derive(Clone, Debug, Serialize, JsonSchema)]
pub(crate) struct PrettyMixNodeBondWithLocation {
pub location: Option<Location>,
pub bond_amount: Coin,
pub pledge_amount: Coin,
pub total_delegation: Coin,
pub owner: Addr,
pub layer: Layer,
+1 -1
View File
@@ -151,7 +151,7 @@ impl ThreadsafeMixNodesResult {
let copy = bond.clone();
PrettyMixNodeBondWithLocation {
location: location.and_then(|l| l.location.clone()),
bond_amount: copy.bond_amount,
pledge_amount: copy.pledge_amount,
total_delegation: copy.total_delegation,
owner: copy.owner,
layer: copy.layer,
+2 -2
View File
@@ -76,7 +76,7 @@ export const PageGateways: React.FC = () => {
field: 'bond',
width: 150,
type: 'number',
renderHeader: () => <CustomColumnHeading headingTitle="Bond" />,
renderHeader: () => <CustomColumnHeading headingTitle="Pledge" />,
headerClassName: 'MuiDataGrid-header-override',
headerAlign: 'left',
renderCell: (params: GridRenderCellParams) => {
@@ -85,7 +85,7 @@ export const PageGateways: React.FC = () => {
denom: 'upunk',
});
return (
<Typography sx={cellStyles} data-testid="bond-amount">
<Typography sx={cellStyles} data-testid="pledge-amount">
{bondAsPunk}
</Typography>
);
+2 -2
View File
@@ -28,8 +28,8 @@ const columns: ColumnsType[] = [
},
{
field: 'bond',
title: 'Bond',
field: 'pledge',
title: 'Pledge',
flex: 1,
headerAlign: 'left',
},
+6 -6
View File
@@ -10,8 +10,8 @@ use tokio::sync::RwLock;
#[cfg_attr(test, derive(ts_rs::TS))]
#[derive(Serialize, Deserialize)]
pub struct TauriContractStateParams {
minimum_mixnode_bond: String,
minimum_gateway_bond: String,
minimum_mixnode_pledge: String,
minimum_gateway_pledge: String,
mixnode_rewarded_set_size: u32,
mixnode_active_set_size: u32,
}
@@ -19,8 +19,8 @@ pub struct TauriContractStateParams {
impl From<ContractStateParams> for TauriContractStateParams {
fn from(p: ContractStateParams) -> TauriContractStateParams {
TauriContractStateParams {
minimum_mixnode_bond: p.minimum_mixnode_bond.to_string(),
minimum_gateway_bond: p.minimum_gateway_bond.to_string(),
minimum_mixnode_pledge: p.minimum_mixnode_pledge.to_string(),
minimum_gateway_pledge: p.minimum_gateway_pledge.to_string(),
mixnode_rewarded_set_size: p.mixnode_rewarded_set_size,
mixnode_active_set_size: p.mixnode_active_set_size,
}
@@ -32,8 +32,8 @@ impl TryFrom<TauriContractStateParams> for ContractStateParams {
fn try_from(p: TauriContractStateParams) -> Result<ContractStateParams, Self::Error> {
Ok(ContractStateParams {
minimum_mixnode_bond: Uint128::try_from(p.minimum_mixnode_bond.as_str())?,
minimum_gateway_bond: Uint128::try_from(p.minimum_gateway_bond.as_str())?,
minimum_mixnode_pledge: Uint128::try_from(p.minimum_mixnode_pledge.as_str())?,
minimum_gateway_pledge: Uint128::try_from(p.minimum_gateway_pledge.as_str())?,
mixnode_rewarded_set_size: p.mixnode_rewarded_set_size,
mixnode_active_set_size: p.mixnode_active_set_size,
})
+6 -6
View File
@@ -10,16 +10,16 @@ use tokio::sync::RwLock;
#[tauri::command]
pub async fn bond_gateway(
gateway: Gateway,
bond: Coin,
pledge: Coin,
state: tauri::State<'_, Arc<RwLock<State>>>,
) -> Result<(), String> {
let r_state = state.read().await;
let bond: CosmWasmCoin = match bond.try_into() {
let pledge: CosmWasmCoin = match pledge.try_into() {
Ok(b) => b,
Err(e) => return Err(format_err!(e)),
};
let client = r_state.client()?;
match client.bond_gateway(gateway, bond).await {
match client.bond_gateway(gateway, pledge).await {
Ok(_result) => Ok(()),
Err(e) => Err(format_err!(e)),
}
@@ -48,16 +48,16 @@ pub async fn unbond_mixnode(state: tauri::State<'_, Arc<RwLock<State>>>) -> Resu
#[tauri::command]
pub async fn bond_mixnode(
mixnode: MixNode,
bond: Coin,
pledge: Coin,
state: tauri::State<'_, Arc<RwLock<State>>>,
) -> Result<(), String> {
let r_state = state.read().await;
let bond: CosmWasmCoin = match bond.try_into() {
let pledge: CosmWasmCoin = match pledge.try_into() {
Ok(b) => b,
Err(e) => return Err(format_err!(e)),
};
let client = r_state.client()?;
match client.bond_mixnode(mixnode, bond).await {
match client.bond_mixnode(mixnode, pledge).await {
Ok(_result) => Ok(()),
Err(e) => Err(format_err!(e)),
}
@@ -23,16 +23,16 @@ pub async fn delegate_to_mixnode(
state: tauri::State<'_, Arc<RwLock<State>>>,
) -> Result<DelegationResult, String> {
let r_state = state.read().await;
let bond: CosmWasmCoin = match amount.try_into() {
let delegation: CosmWasmCoin = match amount.try_into() {
Ok(b) => b,
Err(e) => return Err(format_err!(e)),
};
let client = r_state.client()?;
match client.delegate_to_mixnode(identity, &bond).await {
match client.delegate_to_mixnode(identity, &delegation).await {
Ok(_result) => Ok(DelegationResult {
source_address: client.address().to_string(),
target_address: identity.to_string(),
amount: Some(bond.into()),
amount: Some(delegation.into()),
}),
Err(e) => Err(format_err!(e)),
}
+1 -1
View File
@@ -184,7 +184,7 @@ export const BondForm = ({
required
id="amount"
name="amount"
label="Amount to bond"
label="Amount to pledge"
fullWidth
error={!!errors.amount}
helperText={errors.amount?.message}
+2 -2
View File
@@ -1,6 +1,6 @@
export interface TauriContractStateParams {
minimum_mixnode_bond: string;
minimum_gateway_bond: string;
minimum_mixnode_pledge: string;
minimum_gateway_pledge: string;
mixnode_rewarded_set_size: number;
mixnode_active_set_size: number;
}
+2 -2
View File
@@ -48,7 +48,7 @@ export const BondNodeForm = ({
onChange={manageForm.handleAmountChange}
id="amount"
name="amount"
label={`Amount to bond ${
label={`Amount to pledge ${
matches
? '(minimum ' + nativeToPrintable(minimumBond.amount) + ')'
: ''
@@ -56,7 +56,7 @@ export const BondNodeForm = ({
error={manageForm.formData.amount.isValid === false}
helperText={
manageForm.formData.amount.isValid === false
? `Enter a valid bond amount (minimum ${nativeToPrintable(
? `Enter a valid pledge amount (minimum ${nativeToPrintable(
minimumBond.amount
)})`
: ''