Skip to content

Commit 5179879

Browse files
authored
Initial integration with session module (paritytech#137)
* Add new_era() in election * Intergate new_session() * Add reward proposal09 * Add TreasuryAccount trait to get accound id of Treasury Module in Staking * SimpleTreasuryAccount * Start rewarding test * Impl proposal09 reward distribution * Impl asset mining reward * Start session management test in staking * Nits * Fix tests * Add pallet-session into runtime * //blockauthor? * .
1 parent 9c04f97 commit 5179879

File tree

16 files changed

+1027
-245
lines changed

16 files changed

+1027
-245
lines changed

Cargo.lock

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cli/src/chain_spec.rs

+29-7
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ use chainx_runtime::{
66
};
77
use chainx_runtime::{AccountId, AssetId, Balance, Runtime, Signature, WASM_BINARY};
88
use chainx_runtime::{
9-
AuraConfig, GenesisConfig, GrandpaConfig, SudoConfig, SystemConfig, XAssetsConfig,
10-
XBridgeBitcoinConfig, XContractsConfig, XMiningStakingConfig, XSpotConfig, XSystemConfig,
9+
AuraConfig, GenesisConfig, GrandpaConfig, SessionConfig, SessionKeys, SudoConfig, SystemConfig,
10+
XAssetsConfig, XBridgeBitcoinConfig, XContractsConfig, XSpotConfig, XStakingConfig,
11+
XSystemConfig,
1112
};
1213

1314
use sc_service::ChainType;
@@ -40,8 +41,13 @@ where
4041
}
4142

4243
/// Helper function to generate an authority key for Aura
43-
pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
44-
(get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
44+
pub fn authority_keys_from_seed(seed: &str) -> (AccountId, AccountId, AuraId, GrandpaId) {
45+
(
46+
get_account_id_from_seed::<sr25519::Public>(&format!("{}//validator", seed)),
47+
get_account_id_from_seed::<sr25519::Public>(&format!("{}//blockauthor", seed)),
48+
get_from_seed::<AuraId>(seed),
49+
get_from_seed::<GrandpaId>(seed),
50+
)
4551
}
4652

4753
#[inline]
@@ -156,8 +162,12 @@ fn testnet_assets() -> Vec<(AssetId, AssetInfo, AssetRestrictions, bool, bool)>
156162
assets
157163
}
158164

165+
fn session_keys(aura: AuraId, grandpa: GrandpaId) -> SessionKeys {
166+
SessionKeys { grandpa, aura }
167+
}
168+
159169
fn testnet_genesis(
160-
initial_authorities: Vec<(AuraId, GrandpaId)>,
170+
initial_authorities: Vec<(AccountId, AccountId, AuraId, GrandpaId)>,
161171
root_key: AccountId,
162172
assets: Vec<(AssetId, AssetInfo, AssetRestrictions, bool, bool)>,
163173
endowed: BTreeMap<AssetId, Vec<(AccountId, Balance)>>,
@@ -169,14 +179,26 @@ fn testnet_genesis(
169179
changes_trie_config: Default::default(),
170180
}),
171181
pallet_aura: Some(AuraConfig {
172-
authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),
182+
authorities: initial_authorities.iter().map(|x| (x.2.clone())).collect(),
173183
}),
174184
pallet_grandpa: Some(GrandpaConfig {
175185
authorities: initial_authorities
176186
.iter()
177-
.map(|x| (x.1.clone(), 1))
187+
.map(|x| (x.3.clone(), 1))
178188
.collect(),
179189
}),
190+
pallet_session: Some(SessionConfig {
191+
keys: initial_authorities
192+
.iter()
193+
.map(|x| {
194+
(
195+
x.0.clone(),
196+
x.1.clone(),
197+
session_keys(x.2.clone(), x.3.clone()),
198+
)
199+
})
200+
.collect::<Vec<_>>(),
201+
}),
180202
pallet_sudo: Some(SudoConfig {
181203
key: root_key.clone(),
182204
}),

primitives/mining/staking/src/lib.rs

+22-15
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,38 @@ pub type UnbondedIndex = u32;
1515
/// Type for measuring the non-validator entity's mining power.
1616
pub type MiningPower = u128;
1717

18-
///
19-
pub trait CollectAssetMiningInfo {
20-
///
21-
fn collect_asset_mining_info() -> Vec<(AssetId, MiningPower)>;
22-
23-
///
24-
fn total_mining_power() -> MiningPower {
25-
Self::collect_asset_mining_info()
18+
/// Trait to retrieve and operate on Asset Mining participants in Staking.
19+
pub trait AssetMining<Balance> {
20+
/// Collects the mining power of all mining assets.
21+
fn asset_mining_power() -> Vec<(AssetId, MiningPower)>;
22+
23+
/// Issues reward to the reward pot of an Asset.
24+
fn reward(_asset_id: AssetId, _reward_value: Balance);
25+
26+
/// Returns the mining power of all mining assets.
27+
fn total_asset_mining_power() -> MiningPower {
28+
Self::asset_mining_power()
2629
.iter()
2730
.map(|(_, power)| power)
2831
.sum()
2932
}
3033
}
3134

32-
impl CollectAssetMiningInfo for () {
33-
fn collect_asset_mining_info() -> Vec<(AssetId, MiningPower)> {
35+
impl<Balance> AssetMining<Balance> for () {
36+
fn asset_mining_power() -> Vec<(AssetId, MiningPower)> {
3437
Vec::new()
3538
}
39+
40+
fn reward(_: AssetId, _: Balance) {}
3641
}
3742

38-
/// Issue the fresh PCX to the non-validator mining entities.
39-
pub trait OnMinting<MiningEntity, Balance> {
40-
fn mint(_: &MiningEntity, _: Balance);
43+
/// This trait provides a simple way to get the treasury account.
44+
pub trait TreasuryAccount<AccountId> {
45+
fn treasury_account() -> AccountId;
4146
}
4247

43-
impl<MiningEntity, Balance> OnMinting<MiningEntity, Balance> for () {
44-
fn mint(_: &MiningEntity, _: Balance) {}
48+
impl<AccountId: Default> TreasuryAccount<AccountId> for () {
49+
fn treasury_account() -> AccountId {
50+
Default::default()
51+
}
4552
}

runtime/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,13 @@ pallet-aura = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0
3535
pallet-grandpa = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
3636
pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
3737
pallet-sudo = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
38+
pallet-session = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
3839
pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
3940
pallet-utility = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
4041

4142
# ChainX primitives
4243
chainx-primitives = { path = "../primitives", default-features = false }
44+
xp-mining-staking = { path = "../primitives/mining/staking", default-features = false }
4345

4446
# ChainX pallets
4547
xpallet-assets = { path = "../xpallets/assets", default-features = false }
@@ -88,9 +90,11 @@ std = [
8890
"pallet-randomness-collective-flip/std",
8991
"pallet-sudo/std",
9092
"pallet-timestamp/std",
93+
"pallet-session/std",
9194
"pallet-utility/std",
9295

9396
"chainx-primitives/std",
97+
"xp-mining-staking/std",
9498

9599
"xpallet-assets/std",
96100
"xpallet-assets-rpc-runtime-api/std",

runtime/src/lib.rs

+31-5
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
1616
use sp_runtime::{
1717
create_runtime_str, generic, impl_opaque_keys,
1818
traits::{
19-
BlakeTwo256, Block as BlockT, DispatchInfoOf, IdentityLookup, NumberFor, Saturating,
20-
SignedExtension,
19+
BlakeTwo256, Block as BlockT, DispatchInfoOf, IdentityLookup, NumberFor, OpaqueKeys,
20+
Saturating, SignedExtension,
2121
},
2222
transaction_validity::{
2323
InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
@@ -300,10 +300,17 @@ impl xpallet_contracts::Trait for Runtime {
300300
type WeightPrice = xpallet_transaction_payment::Module<Self>;
301301
}
302302

303+
pub struct SimpleTreasuryAccount;
304+
impl xp_mining_staking::TreasuryAccount<AccountId> for SimpleTreasuryAccount {
305+
fn treasury_account() -> AccountId {
306+
todo!("Treasury::account_id()")
307+
}
308+
}
309+
303310
impl xpallet_mining_staking::Trait for Runtime {
304311
type Event = Event;
305-
type CollectAssetMiningInfo = ();
306-
type OnMinting = ();
312+
type TreasuryAccount = SimpleTreasuryAccount;
313+
type AssetMining = ();
307314
type DetermineRewardPotAccount =
308315
xpallet_mining_staking::SimpleValidatorRewardPotAccountDeterminer<Runtime>;
309316
}
@@ -328,6 +335,24 @@ impl xpallet_transaction_payment::Trait for Runtime {
328335
TargetedFeeAdjustment<Self, TargetBlockFullness, AdjustmentVariable, MinimumMultiplier>;
329336
}
330337

338+
parameter_types! {
339+
pub const Offset: BlockNumber = 0;
340+
pub const Period: BlockNumber = 50;
341+
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
342+
}
343+
344+
impl pallet_session::Trait for Runtime {
345+
type Event = Event;
346+
type ValidatorId = <Self as frame_system::Trait>::AccountId;
347+
type ValidatorIdOf = ();
348+
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
349+
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
350+
type SessionManager = XStaking;
351+
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
352+
type Keys = SessionKeys;
353+
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
354+
}
355+
331356
construct_runtime!(
332357
pub enum Runtime where
333358
Block = Block,
@@ -340,13 +365,14 @@ construct_runtime!(
340365
Aura: pallet_aura::{Module, Config<T>, Inherent(Timestamp)},
341366
Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},
342367
Utility: pallet_utility::{Module, Call, Event},
368+
Session: pallet_session::{Module, Call, Storage, Event, Config<T>},
343369
Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},
344370

345371
XSystem: xpallet_system::{Module, Call, Storage, Event<T>, Config},
346372
XAssets: xpallet_assets::{Module, Call, Storage, Event<T>, Config<T>},
347373
XBridgeBitcoin: xpallet_bridge_bitcoin::{Module, Call, Storage, Event<T>, Config},
348374
XContracts: xpallet_contracts::{Module, Call, Config, Storage, Event<T>},
349-
XMiningStaking: xpallet_mining_staking::{Module, Call, Storage, Event<T>, Config<T>},
375+
XStaking: xpallet_mining_staking::{Module, Call, Storage, Event<T>, Config<T>},
350376
XMiningAsset: xpallet_mining_asset::{Module, Call, Storage, Event<T>},
351377
XTransactionPayment: xpallet_transaction_payment::{Module, Storage},
352378
XSpot: xpallet_dex_spot::{Module, Call, Storage, Event<T>, Config<T>},

xpallets/mining/asset/src/impls.rs

+14-11
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,12 @@ impl<T: Trait> xpallet_assets::OnAssetChanged<T::AccountId, T::Balance> for Modu
110110

111111
impl<T: Trait> Module<T> {
112112
fn allocate_dividend(
113-
claimer: &T::AccountId,
114-
claimee: &AssetId,
115-
claimee_reward_pot: &T::AccountId,
116-
dividend: T::Balance,
113+
_claimer: &T::AccountId,
114+
_claimee: &AssetId,
115+
_claimee_reward_pot: &T::AccountId,
116+
_dividend: T::Balance,
117117
) -> Result<(), Error<T>> {
118-
todo!("")
118+
todo!("referral_or_treasury 10%, claimer 90%")
119119
}
120120
}
121121

@@ -191,13 +191,16 @@ where
191191
{
192192
fn reward_pot_account_for(asset_id: &AssetId) -> T::AccountId {
193193
let id_hash = T::Hashing::hash(&asset_id.to_le_bytes()[..]);
194-
let registered_time = <xpallet_assets::Module<T>>::asset_registered_block(asset_id);
195-
let block_num_hash =
196-
<T as frame_system::Trait>::Hashing::hash(registered_time.encode().as_ref());
194+
let registered_block = <xpallet_assets::Module<T>>::asset_registered_block(asset_id);
195+
let registered_block_hash =
196+
<T as frame_system::Trait>::Hashing::hash(registered_block.encode().as_ref());
197197

198-
let mut buf = Vec::new();
199-
buf.extend_from_slice(id_hash.as_ref());
200-
buf.extend_from_slice(block_num_hash.as_ref());
198+
let id_slice = id_hash.as_ref();
199+
let registered_slice = registered_block_hash.as_ref();
200+
201+
let mut buf = Vec::with_capacity(id_slice.len() + registered_slice.len());
202+
buf.extend_from_slice(id_slice);
203+
buf.extend_from_slice(registered_slice);
201204

202205
UncheckedFrom::unchecked_from(T::Hashing::hash(&buf[..]))
203206
}

xpallets/mining/asset/src/mock.rs

+2-11
Original file line numberDiff line numberDiff line change
@@ -78,20 +78,11 @@ impl xpallet_assets::Trait for Test {
7878

7979
impl xpallet_mining_staking::Trait for Test {
8080
type Event = ();
81-
type OnMinting = ();
82-
type CollectAssetMiningInfo = ();
81+
type AssetMining = ();
82+
type TreasuryAccount = ();
8383
type DetermineRewardPotAccount = ();
8484
}
8585

86-
// This function basically just builds a genesis storage key/value store according to
87-
// our desired mockup.
88-
pub fn new_test_ext() -> sp_io::TestExternalities {
89-
system::GenesisConfig::default()
90-
.build_storage::<Test>()
91-
.unwrap()
92-
.into()
93-
}
94-
9586
thread_local! {
9687
static SESSION: RefCell<(Vec<AccountId>, HashSet<AccountId>)> = RefCell::new(Default::default());
9788
static SESSION_PER_ERA: RefCell<SessionIndex> = RefCell::new(3);

xpallets/mining/staking/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ xpallet-support = { path = "../../support", default-features = false }
3232
xpallet-protocol = { path = "../../protocol" }
3333
sp-core = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
3434
sp-io = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
35+
pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", tag = "v2.0.0-rc4" }
3536
env_logger = "0.7.1"
3637

3738
[features]

0 commit comments

Comments
 (0)