Skip to content

Commit

Permalink
Complete asset mining (paritytech#146)
Browse files Browse the repository at this point in the history
* Impl depositor reward

* Add TreasuryAccount associate type

As Asset Mining Module also needs to know the treasury account when the
depositor doesn't have a referral.

* Fix genesis

* Exclude PCX for OnAssetChanged hook

* Apply mint and slash in start_session()

* Optimize can_fore_chilled() using try_for_each()

Refine tx chill()

* Optimize force_chilled filter

Close paritytech#139
(Staking Validator, Session Key, ...)

.

* Initial Staking RPC

.

* Add im_online in SessionKeys

* Fix a few unused warnings
  • Loading branch information
liuchengxu authored Jul 19, 2020
1 parent 42b5407 commit 1a5b419
Show file tree
Hide file tree
Showing 26 changed files with 442 additions and 186 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
os: [ubuntu-latest]

steps:
- name: Checkout repository
Expand Down
27 changes: 27 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ members = [
"xpallets/dex/spot",
"xpallets/mining/asset",
"xpallets/mining/staking",
"xpallets/mining/staking/rpc",
"xpallets/mining/staking/rpc/runtime-api",
"xpallets/protocol",
"xpallets/support",
"xpallets/transaction-payment",
Expand Down
3 changes: 3 additions & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ sp-inherents = { git = "https://github.com/paritytech/substrate.git", tag = "v2.
sp-runtime = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
sp-transaction-pool = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }

# Substrate pallets
pallet-im-online = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }

chainx-primitives = { path = "../primitives" }
chainx-runtime = { path = "../runtime" }
chainx-rpc = { path = "../rpc" }
Expand Down
35 changes: 19 additions & 16 deletions cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use chainx_runtime::{
XStakingConfig, XSystemConfig,
};

use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use sc_service::ChainType;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{sr25519, Pair, Public};
Expand Down Expand Up @@ -41,12 +42,15 @@ where
}

/// Helper function to generate an authority key for Aura
pub fn authority_keys_from_seed(seed: &str) -> (AccountId, AccountId, AuraId, GrandpaId) {
pub fn authority_keys_from_seed(
seed: &str,
) -> (AccountId, AccountId, AuraId, GrandpaId, ImOnlineId) {
(
get_account_id_from_seed::<sr25519::Public>(&format!("{}//validator", seed)),
get_account_id_from_seed::<sr25519::Public>(seed),
get_account_id_from_seed::<sr25519::Public>(&format!("{}//blockauthor", seed)),
get_from_seed::<AuraId>(seed),
get_from_seed::<GrandpaId>(seed),
get_from_seed::<ImOnlineId>(seed),
)
}

Expand Down Expand Up @@ -162,12 +166,16 @@ fn testnet_assets() -> Vec<(AssetId, AssetInfo, AssetRestrictions, bool, bool)>
assets
}

fn session_keys(aura: AuraId, grandpa: GrandpaId) -> SessionKeys {
SessionKeys { grandpa, aura }
fn session_keys(aura: AuraId, grandpa: GrandpaId, im_online: ImOnlineId) -> SessionKeys {
SessionKeys {
grandpa,
aura,
im_online,
}
}

fn testnet_genesis(
initial_authorities: Vec<(AccountId, AccountId, AuraId, GrandpaId)>,
initial_authorities: Vec<(AccountId, AccountId, AuraId, GrandpaId, ImOnlineId)>,
root_key: AccountId,
assets: Vec<(AssetId, AssetInfo, AssetRestrictions, bool, bool)>,
endowed: BTreeMap<AssetId, Vec<(AccountId, Balance)>>,
Expand All @@ -179,13 +187,10 @@ fn testnet_genesis(
changes_trie_config: Default::default(),
}),
pallet_aura: Some(AuraConfig {
authorities: initial_authorities.iter().map(|x| (x.2.clone())).collect(),
authorities: vec![],
}),
pallet_grandpa: Some(GrandpaConfig {
authorities: initial_authorities
.iter()
.map(|x| (x.3.clone(), 1))
.collect(),
authorities: vec![],
}),
pallet_im_online: Some(ImOnlineConfig { keys: vec![] }),
pallet_session: Some(SessionConfig {
Expand All @@ -195,14 +200,12 @@ fn testnet_genesis(
(
x.0.clone(),
x.1.clone(),
session_keys(x.2.clone(), x.3.clone()),
session_keys(x.2.clone(), x.3.clone(), x.4.clone()),
)
})
.collect::<Vec<_>>(),
}),
pallet_sudo: Some(SudoConfig {
key: root_key.clone(),
}),
pallet_sudo: Some(SudoConfig { key: root_key }),
xpallet_system: Some(XSystemConfig {
network_props: NetworkType::Testnet,
}),
Expand Down Expand Up @@ -264,9 +267,9 @@ fn testnet_genesis(
})
.collect()
},
validator_count: 100,
validator_count: 1000,
minimum_validator_count: 4,
sessions_per_era: 3,
sessions_per_era: 12,
vesting_account: get_account_id_from_seed::<sr25519::Public>("vesting"),
glob_dist_ratio: (12, 88),
mining_ratio: (10, 90),
Expand Down
31 changes: 25 additions & 6 deletions primitives/mining/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,28 @@ pub trait ComputeMiningWeight<AccountId, BlockNumber: Copy> {

fn _calc_latest_vote_weight(weight_factors: WeightFactors) -> WeightType {
let (last_acum_weight, amount, duration) = weight_factors;
last_acum_weight + WeightType::from(amount) * WeightType::from(duration)
last_acum_weight + amount * duration
}

/// Computes the dividend according to the latest mining weight proportion.
fn compute_dividend<Balance: BaseArithmetic>(
claimer: &AccountId,
claimee: &Self::Claimee,
current_block: BlockNumber,
reward_pot_balance: Balance,
) -> Result<(Balance, WeightType, WeightType), Self::Error> {
// 1. calculates the latest mining weight.
let (source_weight, target_weight) =
Self::settle_weight_on_claim(claimer, claimee, current_block)?;

// 2. calculates the dividend by the mining weight proportion.
let dividend = compute_dividend::<AccountId, Balance>(
source_weight,
target_weight,
reward_pot_balance,
);

Ok((dividend, source_weight, target_weight))
}
}

Expand Down Expand Up @@ -183,14 +204,12 @@ pub fn generic_weight_factors<
/// Computes the dividend according to the ratio of source_vote_weight/target_vote_weight.
///
/// dividend = source_vote_weight/target_vote_weight * balance_of(claimee_reward_pot)
pub fn compute_dividend<AccountId, Balance: BaseArithmetic, F: FnOnce(&AccountId) -> Balance>(
pub fn compute_dividend<AccountId, Balance: BaseArithmetic>(
source_vote_weight: WeightType,
target_vote_weight: WeightType,
claimee_reward_pot: &AccountId,
reward_pot_balance: F,
reward_pot_balance: Balance,
) -> Balance {
let total_reward_pot = reward_pot_balance(&claimee_reward_pot);
match source_vote_weight.checked_mul(total_reward_pot.saturated_into()) {
match source_vote_weight.checked_mul(reward_pot_balance.saturated_into()) {
Some(x) => (x / target_vote_weight).saturated_into(),
None => panic!("source_vote_weight * total_reward_pot overflow, this should not happen"),
}
Expand Down
2 changes: 2 additions & 0 deletions rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ chainx-primitives = { path = "../primitives" }
# ChainX pallets
xpallet-assets-rpc = { path = "../xpallets/assets/rpc" }
xpallet-assets-rpc-runtime-api = { path = "../xpallets/assets/rpc/runtime-api" }
xpallet-mining-staking-rpc = { path = "../xpallets/mining/staking/rpc" }
xpallet-mining-staking-rpc-runtime-api = { path = "../xpallets/mining/staking/rpc/runtime-api" }
xpallet-contracts-rpc = { path = "../xpallets/contracts/rpc" }
xpallet-contracts-rpc-runtime-api = { path = "../xpallets/contracts/rpc/runtime-api" }
xpallet-transaction-payment-rpc = { path = "../xpallets/transaction-payment/rpc" }
4 changes: 4 additions & 0 deletions rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ where
>,
<Client<BE, E, Block, RA> as ProvideRuntimeApi<Block>>::Api:
xpallet_assets_rpc_runtime_api::AssetsApi<Block, AccountId, Balance>,
<Client<BE, E, Block, RA> as ProvideRuntimeApi<Block>>::Api:
xpallet_mining_staking_rpc_runtime_api::XStakingApi<Block, AccountId>,
<Client<BE, E, Block, RA> as ProvideRuntimeApi<Block>>::Api:
xpallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber>,
<<Client<BE, E, Block, RA> as ProvideRuntimeApi<Block>>::Api as sp_api::ApiErrorExt>::Error:
Expand All @@ -82,6 +84,7 @@ where
use substrate_frame_rpc_system::{FullSystem, SystemApi};
use xpallet_assets_rpc::{Assets, AssetsApi};
use xpallet_contracts_rpc::{Contracts, ContractsApi};
use xpallet_mining_staking_rpc::{XStaking, XStakingApi};
use xpallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};

let mut io = jsonrpc_core::IoHandler::default();
Expand All @@ -101,6 +104,7 @@ where
)));
io.extend_with(AssetsApi::to_delegate(Assets::new(client.clone())));
io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));
io.extend_with(XStakingApi::to_delegate(XStaking::new(client.clone())));
io
}

Expand Down
2 changes: 2 additions & 0 deletions runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ xpallet-contracts-primitives = { path = "../xpallets/contracts/common", default-
xpallet-contracts-rpc-runtime-api = { path = "../xpallets/contracts/rpc/runtime-api", default-features = false }
xpallet-dex-spot = { path = "../xpallets/dex/spot", default-features = false }
xpallet-mining-staking = { path = "../xpallets/mining/staking", default-features = false }
xpallet-mining-staking-rpc-runtime-api = { path = "../xpallets/mining/staking/rpc/runtime-api", default-features = false }
xpallet-mining-asset = { path = "../xpallets/mining/asset", default-features = false }
xpallet-protocol = { path = "../xpallets/protocol", default-features = false }
xpallet-system = { path = "../xpallets/system", default-features = false }
Expand Down Expand Up @@ -108,6 +109,7 @@ std = [
"xpallet-contracts-rpc-runtime-api/std",
"xpallet-dex-spot/std",
"xpallet-mining-staking/std",
"xpallet-mining-staking-rpc-runtime-api/std",
"xpallet-mining-asset/std",
"xpallet-protocol/std",
"xpallet-system/std",
Expand Down
20 changes: 16 additions & 4 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
BlakeTwo256, Block as BlockT, Convert, DispatchInfoOf, IdentityLookup, NumberFor,
OpaqueKeys, Saturating, SignedExtension,
AccountIdConversion, BlakeTwo256, Block as BlockT, Convert, DispatchInfoOf, IdentityLookup,
NumberFor, OpaqueKeys, Saturating, SignedExtension,
},
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
ApplyExtrinsicResult, FixedPointNumber, Perbill, Permill, Perquintill,
ApplyExtrinsicResult, FixedPointNumber, ModuleId, Perbill, Permill, Perquintill,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
#[cfg(feature = "std")]
Expand Down Expand Up @@ -77,6 +77,7 @@ impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
pub grandpa: Grandpa,
pub im_online: ImOnline,
}
}

Expand Down Expand Up @@ -305,10 +306,14 @@ impl xpallet_contracts::Trait for Runtime {
type WeightPrice = xpallet_transaction_payment::Module<Self>;
}

parameter_types! {
pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");
}

pub struct SimpleTreasuryAccount;
impl xp_mining_staking::TreasuryAccount<AccountId> for SimpleTreasuryAccount {
fn treasury_account() -> AccountId {
todo!("Treasury::account_id()")
TreasuryModuleId::get().into_account()
}
}

Expand All @@ -324,6 +329,7 @@ impl xpallet_mining_staking::Trait for Runtime {

impl xpallet_mining_asset::Trait for Runtime {
type Event = Event;
type TreasuryAccount = SimpleTreasuryAccount;
type DetermineRewardPotAccount =
xpallet_mining_asset::SimpleAssetRewardPotAccountDeterminer<Runtime>;
}
Expand Down Expand Up @@ -612,6 +618,12 @@ impl_runtime_apis! {
}
}

impl xpallet_mining_staking_rpc_runtime_api::XStakingApi<Block, AccountId> for Runtime {
fn validators() -> Vec<AccountId> {
XStaking::validators_info()
}
}

impl xpallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>
for Runtime
{
Expand Down
3 changes: 2 additions & 1 deletion xpallets/mining/asset/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ xp-mining-staking = { path = "../../../primitives/mining/staking", default-feat

# ChainX pallets
xpallet-assets = { path = "../../assets", default-features = false }
xpallet-protocol = { path = "../../protocol", default-features = false }
xpallet-support = { path = "../../support", default-features = false }
xpallet-mining-staking = { path = "../../mining/staking", default-features = false }

[dev-dependencies]
xpallet-protocol = { path = "../../protocol" }
sp-core = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
sp-io = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
pallet-session = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
Expand All @@ -55,6 +55,7 @@ std = [
"xp-mining-staking/std",

"xpallet-assets/std",
"xpallet-protocol/std",
"xpallet-support/std",
"xpallet-mining-staking/std",
]
Loading

0 comments on commit 1a5b419

Please sign in to comment.