Skip to content

Commit

Permalink
Feature/adjust staking (paritytech#274)
Browse files Browse the repository at this point in the history
* Fix trustee setup

- pass partial staking tests
- adjust parameters in genesis_config to in line with docs 0.6.
- add intention_bonding_duration particularly.

* 20% goes to team

* Validate Bitcoin trustee entity

* Init trustee entities

* Make initial reward a configuration item

* Mark convert_to_stake

* No discount for tokens mining

* Use trans_pcx_stake provided by xspot

- add jackpot_address in rpc.

* Fix overflow in vote_weight

* Update wasm

* Div first

* Add XTokensCall and calculate ratio first

* !=

* Fix mock in tests

* Tweak parameters in genesis_config

* Don't use f64

* Panic when overflow

* Remove useless comment
  • Loading branch information
liuchengxu authored Feb 15, 2019
1 parent 4b3646d commit 1b3aa62
Show file tree
Hide file tree
Showing 15 changed files with 256 additions and 296 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

60 changes: 44 additions & 16 deletions cli/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use chainx_runtime::{
XTokensConfig,
};

use ed25519;
use ed25519::{self, Public};
use sr_primitives::Permill;

use self::btc_chain::BlockHeader;
Expand Down Expand Up @@ -98,28 +98,51 @@ pub fn testnet_genesis(genesis_spec: GenesisSpec) -> GenesisConfig {
)
.unwrap();

let apply_prec = |x| x * 10_u64.pow(pcx_precision as u32);
let apply_prec = |x| (x * 10_u64.pow(pcx_precision as u32) as f64) as u64;

let mut full_endowed = vec![
(
auth1,
apply_prec(30),
b"Alice".to_vec(),
b"Alice.com".to_vec(),
auth1, // auth
apply_prec(12.5), // balance
b"Alice".to_vec(), // name
b"Alice.com".to_vec(), // url
b"03f72c448a0e59f48d4adef86cba7b278214cece8e56ef32ba1d179e0a8129bdba".to_vec(), // hot_entity
b"02a79800dfed17ad4c78c52797aa3449925692bc8c83de469421080f42d27790ee".to_vec(), // cold_entity
),
(
auth2,
apply_prec(12.5),
b"Bob".to_vec(),
b"Bob.com".to_vec(),
b"0306117a360e5dbe10e1938a047949c25a86c0b0e08a0a7c1e611b97de6b2917dd".to_vec(),
b"03ece1a20b5468b12fd7beda3e62ef6b2f6ad9774489e9aff1c8bc684d87d70780".to_vec(),
),
(auth2, apply_prec(10), b"Bob".to_vec(), b"Bob.com".to_vec()),
(
auth3,
apply_prec(10),
b"Charlie".to_vec(),
apply_prec(12.5),
b"Charlie".to_vec(),
b"Charlie.com".to_vec(),
b"0311252930af8ba766b9c7a6580d8dc4bbf9b0befd17a8ef7fabac275bba77ae40".to_vec(),
b"02e34d10113f2dd162e8d8614a4afbb8e2eb14eddf4036042b35d12cf5529056a2".to_vec(),
),
(
auth4,
apply_prec(12.5),
b"Satoshi".to_vec(),
b"Satoshi.com".to_vec(),
b"0227e54b65612152485a812b8856e92f41f64788858466cc4d8df674939a5538c3".to_vec(),
b"020699bf931859cafdacd8ac4d3e055eae7551427487e281e3efba618bdd395f2f".to_vec(),
),
];

full_endowed.truncate(initial_authorities.len());

let endowed = full_endowed
.clone()
.into_iter()
.map(|(auth, balance, _, _)| (auth, balance))
.map(|(auth, balance, _, _, _, _)| (auth, balance))
.collect::<Vec<_>>();

GenesisConfig {
consensus: Some(ConsensusConfig {
code: include_bytes!(
Expand All @@ -137,7 +160,7 @@ pub fn testnet_genesis(genesis_spec: GenesisSpec) -> GenesisConfig {
}),
session: Some(SessionConfig {
validators: endowed.iter().cloned().map(|(account, balance)| (account.into(), balance)).collect(),
session_length: 10, // 30 blocks per session
session_length: 150, // 150 blocks per session
}),
sudo: Some(SudoConfig {
key: auth1.into(),
Expand Down Expand Up @@ -172,15 +195,20 @@ pub fn testnet_genesis(genesis_spec: GenesisSpec) -> GenesisConfig {
_genesis_phantom_data: Default::default(),
}),
xstaking: Some(XStakingConfig {
validator_count: 7,
minimum_validator_count: 1,
sessions_per_era: 1,
bonding_duration: 30,
initial_reward: apply_prec(50.0),
validator_count: 100,
minimum_validator_count: 4,
sessions_per_era: 12, // update validators set per 12 sessions
sessions_per_epoch: 12 * 10, // update trustees set per 120 sessions
bonding_duration: 150 * 12, // 150 blocks per bonding
intention_bonding_duration: 150 * 12 * 10,
current_era: 0,
penalty: 0,
funding: Default::default(),
intentions: full_endowed.into_iter().map(|(who, value, name, url)| (who.into(), value, name, url)).collect(),
intentions: full_endowed.clone().into_iter().map(|(who, value, name, url, _, _)| (who.into(), value, name, url)).collect(),
validator_stake_threshold: 1,
trustee_intentions: full_endowed.into_iter().map(|(who, _, _, _, hot_entity, cold_entity)| (who.into(), hot_entity, cold_entity)).collect(),
team_address: Public::from_ss58check("5CSff76SK7qcWYq5MpvoHDVRrjWFwpxurwUu6Bqw25hKPQiy").unwrap().0.into(),
}),
xtokens: Some(XTokensConfig {
token_discount: Permill::from_percent(30),
Expand Down
2 changes: 0 additions & 2 deletions cli/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ use substrate_service::{
};
use transaction_pool::{self, txpool::Pool as TransactionPool};

use network::ManageNetwork;

use self::xrml_xsystem::InherentDataProvider;

type XSystemInherentDataProvider = InherentDataProvider<AccountId>;
Expand Down
5 changes: 3 additions & 2 deletions rpc/src/chainx/impl_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ where
{
let free = <balances::FreeBalance<Runtime>>::key_for(&jackpot_addr);
info.jackpot = Self::pickout::<Balance>(&state, &free)?.unwrap_or_default();
info.jackpot_address = jackpot_addr;
info.total_nomination = profs.total_nomination;
info.last_total_vote_weight = profs.last_total_vote_weight;
info.last_total_vote_weight_update = profs.last_total_vote_weight_update;
Expand Down Expand Up @@ -314,7 +315,7 @@ where
{
let free = <balances::FreeBalance<Runtime>>::key_for(&jackpot_addr);
info.jackpot = Self::pickout::<Balance>(&state, &free)?.unwrap_or_default();
// info.jackpot = vote_weight.jackpot;
info.jackpot_address = jackpot_addr;
info.last_total_deposit_weight = vote_weight.last_total_deposit_weight;
info.last_total_deposit_weight_update =
vote_weight.last_total_deposit_weight_update;
Expand All @@ -328,7 +329,7 @@ where
.ok()
{
info.price = price;
//注意
//注意
//这里返回的是以PCX计价的"单位"token的价格,已含pcx精度
//譬如1BTC=10000PCX,则返回的是10000*(10.pow(pcx精度))
//因此,如果前端要换算折合投票数的时候
Expand Down
4 changes: 4 additions & 0 deletions rpc/src/chainx/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ pub struct IntentionInfo {
pub self_vote: Balance,
/// jackpot
pub jackpot: Balance,
/// jackpot address
pub jackpot_address: H256,
/// total nomination from all nominators
pub total_nomination: Balance,
/// vote weight at last update
Expand Down Expand Up @@ -130,6 +132,8 @@ pub struct PseduIntentionInfo {
pub price: Balance,
/// jackpot
pub jackpot: Balance,
/// jackpot address
pub jackpot_address: H256,
/// vote weight at last update
pub last_total_deposit_weight: u64,
/// last update time of vote weight
Expand Down
5 changes: 5 additions & 0 deletions runtime/src/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use xdot::Call as XdotCall;
use xprocess::Call as XAssetsProcessCall;
use xspot::Call as XSpotCall;
use xstaking::Call as XStakingCall;
use xtokens::Call as XTokensCall;

use Acceleration;
use Call;
Expand Down Expand Up @@ -54,6 +55,10 @@ impl CheckFee for Call {
XStakingCall::claim(_) => Some(3),
_ => None,
},
Call::XTokens(call) => match call {
XTokensCall::claim(_) => Some(3),
_ => None,
},
Call::XSpot(call) => match call {
XSpotCall::put_order(_, _, _, _, _) => Some(8),
XSpotCall::cancel_order(_, _) => Some(2),
Expand Down
1 change: 1 addition & 0 deletions runtime/wasm/Cargo.lock

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

Binary file not shown.
2 changes: 2 additions & 0 deletions xrml/xmining/staking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ xrml-xsystem = { path = "../../xsystem", default_features = false }
xrml-xsupport = { path = "../../xsupport", default_features = false }
xrml-xaccounts = { path = "../../xaccounts", default_features = false }
xrml-xassets-assets = { path = "../../xassets/assets", default_features = false }
xrml-xassets-records = { path = "../../xassets/records", default_features = false }
xrml-session = { path = "../../xsession", default_features = false }
xrml-bridge-bitcoin = { path = "../../xbridge/bitcoin", default_features = false }

Expand Down Expand Up @@ -60,5 +61,6 @@ std = [
"xrml-xsupport/std",
"xrml-xaccounts/std",
"xrml-xassets-assets/std",
"xrml-xassets-records/std",
"xrml-bridge-bitcoin/std",
]
58 changes: 38 additions & 20 deletions xrml/xmining/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ extern crate xr_primitives;
extern crate xrml_bridge_bitcoin as xbitcoin;
extern crate xrml_xaccounts as xaccounts;
extern crate xrml_xassets_assets as xassets;
#[cfg(test)]
extern crate xrml_xassets_records as xrecords;
extern crate xrml_xsupport as xsupport;
extern crate xrml_xsystem as xsystem;

Expand Down Expand Up @@ -64,9 +66,6 @@ const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4;
const MIMIMUM_TRSUTEE_INTENSION_COUNT: u32 = 4;
const MAXIMUM_TRSUTEE_INTENSION_COUNT: u32 = 16;

// FIXME lazy static
const INITIAL_REWARD: u64 = 5_000_000_000;

/// Intention mutable properties
#[derive(PartialEq, Eq, Clone, Encode, Decode, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
Expand Down Expand Up @@ -264,7 +263,8 @@ decl_module! {
xaccounts::is_valid_about::<T>(&about)?;

// TODO validate addr
Self::validate_trustee_entity(&chain, &hot_entity, &cold_entity)?;
Self::validate_trustee_entity(&chain, &hot_entity)?;
Self::validate_trustee_entity(&chain, &cold_entity)?;

<xaccounts::TrusteeIntentionPropertiesOf<T>>::insert(
&(who, chain),
Expand Down Expand Up @@ -331,6 +331,7 @@ decl_event!(

decl_storage! {
trait Store for Module<T: Trait> as XStaking {
InitialReward get(initial_reward) config(): T::Balance;
/// The ideal number of staking participants.
pub ValidatorCount get(validator_count) config(): u32;
/// Minimum number of staking participants before emergency conditions are imposed.
Expand All @@ -339,6 +340,11 @@ decl_storage! {
pub SessionsPerEra get(sessions_per_era) config(): T::BlockNumber = T::BlockNumber::sa(1000);
/// The length of the bonding duration in blocks.
pub BondingDuration get(bonding_duration) config(): T::BlockNumber = T::BlockNumber::sa(1000);
/// The length of the bonding duration in blocks for intention.
pub IntentionBondingDuration get(intention_bonding_duration) config(): T::BlockNumber = T::BlockNumber::sa(10_000);

pub SessionsPerEpoch get(sessions_per_epoch) config(): T::BlockNumber = T::BlockNumber::sa(10_000);
pub TeamAddress get(team_address) config(): T::AccountId;

pub ValidatorStakeThreshold get(validator_stake_threshold) config(): T::Balance = T::Balance::sa(1);

Expand Down Expand Up @@ -368,6 +374,7 @@ decl_storage! {

add_extra_genesis {
config(intentions): Vec<(T::AccountId, T::Balance, Name, URL)>;
config(trustee_intentions): Vec<(T::AccountId, Vec<u8>, Vec<u8>)>;
build(|storage: &mut runtime_primitives::StorageMap, _: &mut runtime_primitives::ChildrenStorageMap, config: &GenesisConfig<T>| {
use codec::Encode;
use runtime_io::with_externalities;
Expand Down Expand Up @@ -405,7 +412,22 @@ decl_storage! {

storage.insert(hash(&<StakeWeight<T>>::key_for(&intention)), value.encode());
}
// FIXME set up trustee intentions

let mut trustees = Vec::new();
for (i, hot_entity, cold_entity) in config.trustee_intentions.clone().into_iter() {
trustees.push(i.clone());
<xaccounts::TrusteeIntentionPropertiesOf<T>>::insert(
&(i, xassets::Chain::Bitcoin),
TrusteeIntentionProps {
about: b"".to_vec(),
hot_entity: TrusteeEntity::Bitcoin(hot_entity),
cold_entity: TrusteeEntity::Bitcoin(cold_entity),
}
);
}
<xaccounts::TrusteeIntentions<T>>::put(trustees);

let _ = xbitcoin::Module::<T>::update_trustee_addr();
});

let init: StorageMap = init.into();
Expand Down Expand Up @@ -438,22 +460,14 @@ impl<T: Trait> Module<T> {
<xaccounts::Module<T>>::intention_name_of(who).is_some()
}

pub fn validate_trustee_entity(
chain: &Chain,
hot_entity: &TrusteeEntity,
cold_entity: &TrusteeEntity,
) -> Result {
pub fn validate_trustee_entity(chain: &Chain, entity: &TrusteeEntity) -> Result {
match chain {
Chain::Bitcoin => {
// FIXME check bitcoin pubkey
match hot_entity {
TrusteeEntity::Bitcoin(_pubkey) => (),
}

match cold_entity {
TrusteeEntity::Bitcoin(_pubkey) => (),
Chain::Bitcoin => match entity {
TrusteeEntity::Bitcoin(pubkey) if pubkey.len() != 33 && pubkey.len() != 65 => {
return Err("Valid pubkeys are either 33 or 65 bytes.");
}
}
_ => (),
},
_ => return Err("Unsupported chain."),
}

Expand Down Expand Up @@ -522,7 +536,11 @@ impl<T: Trait> Module<T> {
}

fn apply_unnominate(source: &T::AccountId, target: &T::AccountId, value: T::Balance) -> Result {
let freeze_until = <system::Module<T>>::block_number() + Self::bonding_duration();
let freeze_until = if Self::is_intention(source) && *source == *target {
<system::Module<T>>::block_number() + Self::intention_bonding_duration()
} else {
<system::Module<T>>::block_number() + Self::bonding_duration()
};

let mut revocations = Self::nomination_record_of(source, target).revocations;

Expand Down
Loading

0 comments on commit 1b3aa62

Please sign in to comment.