Skip to content

Commit

Permalink
Feature/v0.6 staking (paritytech#247)
Browse files Browse the repository at this point in the history
* Initial v0.6

* New_trustees

* Quick sketch

* Remove unused cert in xaccounts module

* Need to resolve finalized paritytech#30

* Fixes unfinalized issue after 30 blocks

* Avoid invoke pcx_move

* Draft

* Split out

* Rebuild wasm

* Init session validators

* Ok to build

* Threshold to be an validator

* Check address

* Move trustee intentions to xaccounts module

* 50_000!!!

* Transform revocations to kv style

* Init tokens psedu intentions

* 30 blocks per session

* Update wasm

* Tweak XDOT related

* Replace IntentionImmutablePropertiesOf with IntentionNameOf

* Extract convert_to_stake and price_for in tokens module

* Introduce TrusteeEntity

- TrusteeEntity could a pubkey or an address.

* Filter these who should be punished

* Force punished to be inactive

* Add is_trustee in rpc

* Force punished to be inactive first

* Remove needless timestamp

* Nits
  • Loading branch information
liuchengxu authored Jan 29, 2019
1 parent 4aa2011 commit 846a71c
Show file tree
Hide file tree
Showing 16 changed files with 297 additions and 307 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

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

23 changes: 11 additions & 12 deletions cli/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ use chainx_runtime::{
};
use chainx_runtime::{
BalancesConfig, ConsensusConfig, GenesisConfig, IndicesConfig, Params, SessionConfig,
SudoConfig, TimestampConfig, XAccountsConfig, XAssetsConfig, XBridgeOfBTCConfig,
XFeeManagerConfig, XSpotConfig, XStakingConfig, XSystemConfig,
SudoConfig, TimestampConfig, XAssetsConfig, XBridgeOfBTCConfig, XFeeManagerConfig, XSpotConfig,
XStakingConfig, XSystemConfig, XTokensConfig,
};

use ed25519;
use sr_primitives::Permill;

use self::btc_chain::BlockHeader;
use self::btc_primitives::{compact::Compact, hash::H256};
Expand Down Expand Up @@ -130,13 +131,6 @@ pub fn testnet_genesis(genesis_spec: GenesisSpec) -> GenesisConfig {
burn_account: substrate_primitives::H256::repeat_byte(0x1),
banned_account: auth1.into(),
}),
xaccounts: Some(XAccountsConfig {
activation_per_share: 100_000_000,
maximum_cert_count: 180,
shares_per_cert: 50,
total_issued: 1,
_genesis_phantom_data: Default::default(),
}),
fee_manager: Some(XFeeManagerConfig {
switch: false,
_genesis_phantom_data: Default::default(),
Expand All @@ -147,20 +141,25 @@ pub fn testnet_genesis(genesis_spec: GenesisSpec) -> GenesisConfig {
// asset, is_psedu_intention, init for account
// Vec<(Asset, bool, Vec<(T::AccountId, u64)>)>;
asset_list: vec![
(btc_asset, true, vec![(Keyring::Alice.to_raw_public().into(), 1_000_000_000),(Keyring::Bob.to_raw_public().into(), 1_000_000_000)]),
(btc_asset, true, vec![(Keyring::Alice.to_raw_public().into(), 100),(Keyring::Bob.to_raw_public().into(), 100)]),
(dot_asset.clone(), false, vec![(Keyring::Alice.to_raw_public().into(), 1_000_000_000),(Keyring::Bob.to_raw_public().into(), 1_000_000_000)]),
(xdot_asset.clone(), true, vec![(Keyring::Alice.to_raw_public().into(), 1_000_000_000),(Keyring::Bob.to_raw_public().into(), 1_000_000_000)])
(xdot_asset.clone(), true, vec![(Keyring::Alice.to_raw_public().into(), 100),(Keyring::Bob.to_raw_public().into(), 100)])
],
}),
xstaking: Some(XStakingConfig {
validator_count: 7,
minimum_validator_count: 1,
sessions_per_era: 1,
bonding_duration: 10,
bonding_duration: 30,
current_era: 0,
penalty: 100,
funding: Default::default(),
intentions: endowed.iter().cloned().map(|(account, balance)| (account.into(), balance)).collect(),
validator_stake_threshold: 1,
}),
xtokens: Some(XTokensConfig {
token_discount: Permill::from_percent(30),
_genesis_phantom_data: Default::default(),
}),
xspot: Some(XSpotConfig {
pair_list: vec![(<xassets::Module<Runtime> as ChainT>::TOKEN.to_vec(),<bitcoin::Module<Runtime> as ChainT>::TOKEN.to_vec(),9,2,100000,true),
Expand Down
1 change: 1 addition & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ extern crate substrate_finality_grandpa as grandpa;
#[macro_use]
extern crate substrate_service;
extern crate chainx_executor;
extern crate sr_primitives;
extern crate substrate_inherents as inherents;
extern crate substrate_rpc_servers as rpc;

Expand Down
116 changes: 45 additions & 71 deletions rpc/src/chainx/impl_rpc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright 2019 Chainpool.

use self::types::Revocation;
use super::*;
use runtime_primitives::traits::{Header, ProvideRuntimeApi};
use std::iter::FromIterator;
Expand Down Expand Up @@ -33,44 +34,6 @@ where
Ok(self.client.block(&BlockId::Hash(block_hash))?)
}

fn cert(&self, owner: AccountId) -> Result<Option<Vec<CertInfo>>> {
let state = self.best_state()?;

let key = <xaccounts::CertNamesOf<Runtime>>::key_for(&owner);
let names: Vec<Vec<u8>> = if let Some(names) = Self::pickout(&state, &key)? {
names
} else {
return Ok(None);
};

let mut certs = Vec::new();
for name in names.iter() {
let key = <xaccounts::CertImmutablePropertiesOf<Runtime>>::key_for(name);
let props: CertImmutableProps<BlockNumber, Timestamp> =
if let Some(props) = Self::pickout(&state, &key)? {
props
} else {
return Ok(None);
};

let key = <xaccounts::RemainingSharesOf<Runtime>>::key_for(name);
let shares: u32 = if let Some(shares) = Self::pickout(&state, &key)? {
shares
} else {
return Ok(None);
};

certs.push(CertInfo {
name: String::from_utf8_lossy(name).into_owned(),
issued_at: props.issued_at.1,
frozen_duration: props.frozen_duration,
remaining_shares: shares,
});
}

Ok(Some(certs))
}

fn assets_of(
&self,
who: AccountId,
Expand Down Expand Up @@ -163,13 +126,6 @@ where
Some(info) => info,
None => unreachable!("should not reach this branch, the token info must be exists"),
};
// let (is_native , asset) = match asset {
// Some(info) => match info.chain() {
// Chain::ChainX => (true, info),
// _ => (false, info),
// },
// None => unreachable!("should not reach this branch, the token info must be exists"),
// };

// PCX free balance
if token.as_slice() == xassets::Module::<Runtime>::TOKEN {
Expand Down Expand Up @@ -304,7 +260,7 @@ where
fn nomination_records(
&self,
who: AccountId,
) -> Result<Option<Vec<(AccountId, NominationRecord<Balance, BlockNumber>)>>> {
) -> Result<Option<Vec<(AccountId, NominationRecord)>>> {
let state = self.best_state()?;

let mut records = Vec::new();
Expand All @@ -314,9 +270,25 @@ where
for intention in intentions {
let key = <xstaking::NominationRecords<Runtime>>::key_for(&(who, intention));
if let Some(record) =
Self::pickout::<NominationRecord<Balance, BlockNumber>>(&state, &key)?
Self::pickout::<xstaking::NominationRecord<Balance, BlockNumber>>(&state, &key)?
{
records.push((intention, record));
let revocations = record
.revocations
.iter()
.map(|x| Revocation {
block_numer: x.0,
value: x.1,
})
.collect::<Vec<_>>();
records.push((
intention,
NominationRecord {
nomination: record.nomination,
last_vote_weight: record.last_vote_weight,
last_vote_weight_update: record.last_vote_weight_update,
revocations,
},
));
}
}
}
Expand All @@ -332,6 +304,11 @@ where
let validators =
Self::pickout::<Vec<AccountId>>(&state, &key)?.expect("Validators can't be empty");

let key = <xaccounts::TrusteeIntentions<Runtime>>::key();

// FIXME trustees should not empty
let trustees = Self::pickout::<Vec<AccountId>>(&state, &key)?.unwrap_or_default();

let key = <xstaking::Intentions<Runtime>>::key();

if let Some(intentions) = Self::pickout::<Vec<AccountId>>(&state, &key)? {
Expand All @@ -345,9 +322,9 @@ where
for (intention, jackpot_addr) in intentions.into_iter().zip(jackpot_addr_list) {
let mut info = IntentionInfo::default();

let key = <xaccounts::IntentionImmutablePropertiesOf<Runtime>>::key_for(&intention);
if let Some(props) = Self::pickout::<IntentionImmutableProps>(&state, &key)? {
info.name = String::from_utf8_lossy(&props.name).into_owned();
let key = <xaccounts::IntentionNameOf<Runtime>>::key_for(&intention);
if let Some(name) = Self::pickout::<xaccounts::Name>(&state, &key)? {
info.name = String::from_utf8_lossy(&name).into_owned();
}

let key = <xaccounts::IntentionPropertiesOf<Runtime>>::key_for(&intention);
Expand All @@ -370,12 +347,13 @@ where

let key = <xstaking::NominationRecords<Runtime>>::key_for(&(intention, intention));
if let Some(record) =
Self::pickout::<NominationRecord<Balance, BlockNumber>>(&state, &key)?
Self::pickout::<xstaking::NominationRecord<Balance, BlockNumber>>(&state, &key)?
{
info.self_vote = record.nomination;
}

info.is_validator = validators.iter().any(|&i| i == intention);
info.is_trustee = trustees.iter().any(|&i| i == intention);
info.account = intention;

intention_info.push(info);
Expand Down Expand Up @@ -413,15 +391,15 @@ where
vote_weight.last_total_deposit_weight_update;
}


let b = self.best_number()?;
if let Some(Some(price)) = self.client
if let Some(Some(price)) = self
.client
.runtime_api()
.aver_asset_price(&b, token.clone())
.ok(){
info.price = price;
};

.ok()
{
info.price = price;
};

let key = <xassets::TotalAssetBalance<Runtime>>::key_for(&token);
if let Some(total_asset_balance) =
Expand Down Expand Up @@ -494,7 +472,7 @@ where
info.currency = String::from_utf8_lossy(&pair.second).into_owned();
info.precision = pair.precision;
info.used = pair.used;
info.unit_precision=pair.unit_precision;
info.unit_precision = pair.unit_precision;

let price_key = <xspot::OrderPairPriceOf<Runtime>>::key_for(&i);
if let Some(price) =
Expand All @@ -506,9 +484,11 @@ where
}

let handicap_key = <xspot::HandicapMap<Runtime>>::key_for(&i);
if let Some(handicap) = Self::pickout::<HandicapT<Runtime>>(&state, &handicap_key)? {
if let Some(handicap) =
Self::pickout::<HandicapT<Runtime>>(&state, &handicap_key)?
{
info.buy_one = handicap.buy;
info.sell_one= handicap.sell;
info.sell_one = handicap.sell;
}

pairs.push(info);
Expand All @@ -531,8 +511,8 @@ where
let state = self.best_state()?;
let pair_key = <xspot::OrderPairOf<Runtime>>::key_for(&id);
if let Some(pair) = Self::pickout::<OrderPair>(&state, &pair_key)? {
let min_unit=10_u64.pow(pair.unit_precision);
let min_unit = 10_u64.pow(pair.unit_precision);

//盘口
let handicap_key = <xspot::HandicapMap<Runtime>>::key_for(&id);

Expand Down Expand Up @@ -578,13 +558,10 @@ where
n += 1;
};

opponent_price = match opponent_price
.checked_sub(As::sa(min_unit))
{
opponent_price = match opponent_price.checked_sub(As::sa(min_unit)) {
Some(v) => v,
None => Default::default(),
};

}
//再卖档
opponent_price = handicap.sell;
Expand Down Expand Up @@ -615,13 +592,10 @@ where
n += 1;
};

opponent_price = match opponent_price
.checked_add(As::sa(min_unit))
{
opponent_price = match opponent_price.checked_add(As::sa(min_unit)) {
Some(v) => v,
None => Default::default(),
};

}
};
} else {
Expand Down
16 changes: 7 additions & 9 deletions rpc/src/chainx/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use srml_support::storage::{StorageMap, StorageValue};
use chainx_primitives::{AccountId, Balance, BlockNumber, Timestamp};
use chainx_runtime::Runtime;

use xaccounts::{self, CertImmutableProps, IntentionImmutableProps, IntentionProps};
use xaccounts::{self, IntentionProps};
use xassets::{self, assetdef::ChainT, Asset, AssetType, Chain, Token};
use xbitcoin::{
self, from, AccountMap, BestIndex, BlockHeaderFor, BlockHeaderInfo, IrrBlock, TrusteeAddress,
Expand All @@ -33,20 +33,21 @@ use xbitcoin::{
use xrecords::{self, Application};
use xspot::def::{OrderPair, OrderPairID, ID};
use xspot::{HandicapT, OrderT};
use xstaking::{self, IntentionProfs, NominationRecord};
use xstaking::{self, IntentionProfs};
use xsupport::storage::btree_map::CodecBTreeMap;
use xtokens::{self, DepositVoteWeight, PseduIntentionVoteWeight};

use self::runtime_api::{xassets_api::XAssetsApi, xmining_api::XMiningApi,xspot_api::XSpotApi};
use self::runtime_api::{xassets_api::XAssetsApi, xmining_api::XMiningApi, xspot_api::XSpotApi};

mod error;
mod impl_rpc;
pub mod types;

use self::error::Result;
use self::types::{
ApplicationWrapper, AssetInfo, CertInfo, DepositInfo, IntentionInfo, PageData, PairInfo,
PseduIntentionInfo, PseduNominationRecord, QuotationsList, TotalAssetInfo, WithdrawalState,
ApplicationWrapper, AssetInfo, DepositInfo, IntentionInfo, NominationRecord, PageData,
PairInfo, PseduIntentionInfo, PseduNominationRecord, QuotationsList, TotalAssetInfo,
WithdrawalState,
};
use chainx::error::ErrorKind::{OrderPairIDErr, PageIndexErr, PageSizeErr, QuotationssPieceErr};

Expand All @@ -60,9 +61,6 @@ build_rpc_trait! {
#[rpc(name = "chainx_getBlockByNumber")]
fn block_info(&self, Trailing<Number>) -> Result<Option<SignedBlock>>;

#[rpc(name = "chainx_getCertByAccount")]
fn cert(&self, AccountId) -> Result<Option<Vec<CertInfo>>>;

#[rpc(name = "chainx_getAssetsByAccount")]
fn assets_of(&self, AccountId, u32, u32) -> Result<Option<PageData<AssetInfo>>>;

Expand All @@ -82,7 +80,7 @@ build_rpc_trait! {
fn withdrawal_list_of(&self, AccountId, u32, u32) -> Result<Option<PageData<ApplicationWrapper>>>;

#[rpc(name = "chainx_getNominationRecords")]
fn nomination_records(&self, AccountId) -> Result<Option<Vec<(AccountId, NominationRecord<Balance, BlockNumber>)>>>;
fn nomination_records(&self, AccountId) -> Result<Option<Vec<(AccountId, NominationRecord)>>>;

#[rpc(name = "chainx_getIntentions")]
fn intentions(&self) -> Result<Option<Vec<IntentionInfo>>>;
Expand Down
Loading

0 comments on commit 846a71c

Please sign in to comment.