Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
add new trait, still migration to make
Browse files Browse the repository at this point in the history
  • Loading branch information
gui1117 committed Mar 6, 2020
1 parent 8c672e1 commit b00aab3
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 20 deletions.
2 changes: 1 addition & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ parameter_types! {

impl pallet_staking::Trait for Runtime {
type Currency = Balances;
type Time = Timestamp;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler;
type RewardRemainder = Treasury;
type Event = Event;
Expand Down
30 changes: 15 additions & 15 deletions frame/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ mod mock;
#[cfg(test)]
mod tests;
mod slashing;
mod migration;
// mod migration;

pub mod inflation;

Expand All @@ -266,7 +266,7 @@ use frame_support::{
dispatch::DispatchResult,
traits::{
Currency, LockIdentifier, LockableCurrency,
WithdrawReasons, OnUnbalanced, Imbalance, Get, Time
WithdrawReasons, OnUnbalanced, Imbalance, Get, UnixTime
}
};
use pallet_session::historical::SessionManager;
Expand Down Expand Up @@ -301,14 +301,14 @@ pub type RewardPoint = u32;

/// Information regarding the active era (era in used in session).
#[derive(Encode, Decode, RuntimeDebug)]
pub struct ActiveEraInfo<Moment> {
pub struct ActiveEraInfo {
/// Index of era.
index: EraIndex,
/// Moment of start
/// Moment of start expresed as millisecond from `$UNIX_EPOCH`.
///
/// Start can be none if start hasn't been set for the era yet,
/// Start is set on the first on_finalize of the era to guarantee usage of `Time`.
start: Option<Moment>,
start: Option<u64>,
}

/// Reward points of an era. Used to split era total payout between validators.
Expand Down Expand Up @@ -565,7 +565,6 @@ type PositiveImbalanceOf<T> =
<<T as Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::PositiveImbalance;
type NegativeImbalanceOf<T> =
<<T as Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::NegativeImbalance;
type MomentOf<T> = <<T as Trait>::Time as Time>::Moment;

/// Means for interacting with a specialized version of the `session` trait.
///
Expand Down Expand Up @@ -614,7 +613,7 @@ pub trait Trait: frame_system::Trait {
///
/// It is guaranteed to start being called from the first `on_finalize`. Thus value at genesis
/// is not used.
type Time: Time;
type UnixTime: UnixTime;

/// Convert a balance into a number used for election calculation.
/// This must fit into a `u64` but is allowed to be sensibly lossy.
Expand Down Expand Up @@ -747,7 +746,7 @@ decl_storage! {
///
/// The active era is the era currently rewarded.
/// Validator set of this era must be equal to `SessionInterface::validators`.
pub ActiveEra get(fn active_era): Option<ActiveEraInfo<MomentOf<T>>>;
pub ActiveEra get(fn active_era): Option<ActiveEraInfo>;

/// The session index at which the era start for the last `HISTORY_DEPTH` eras
pub ErasStartSessionIndex get(fn eras_start_session_index):
Expand Down Expand Up @@ -944,15 +943,16 @@ decl_module! {
fn deposit_event() = default;

fn on_runtime_upgrade() {
migration::on_runtime_upgrade::<T>();
// migration::on_runtime_upgrade::<T>();
}

fn on_finalize() {
// Set the start of the first era.
if let Some(mut active_era) = Self::active_era() {
if active_era.start.is_none() {
active_era.start = Some(T::Time::now());
<ActiveEra<T>>::put(active_era);
let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::<u64>();
active_era.start = Some(now_as_millis_u64);
ActiveEra::put(active_era);
}
}
}
Expand Down Expand Up @@ -1678,7 +1678,7 @@ impl<T: Trait> Module<T> {
/// * reset `active_era.start`,
/// * update `BondedEras` and apply slashes.
fn start_era(start_session: SessionIndex) {
let active_era = <ActiveEra<T>>::mutate(|active_era| {
let active_era = ActiveEra::mutate(|active_era| {
let new_index = active_era.as_ref().map(|info| info.index + 1).unwrap_or(0);
*active_era = Some(ActiveEraInfo {
index: new_index,
Expand Down Expand Up @@ -1716,12 +1716,12 @@ impl<T: Trait> Module<T> {
}

/// Compute payout for era.
fn end_era(active_era: ActiveEraInfo<MomentOf<T>>, _session_index: SessionIndex) {
fn end_era(active_era: ActiveEraInfo, _session_index: SessionIndex) {
// Note: active_era_start can be None if end era is called during genesis config.
if let Some(active_era_start) = active_era.start {
let now = T::Time::now();
let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::<u64>();

let era_duration = now - active_era_start;
let era_duration = now_as_millis_u64 - active_era_start;
let (total_payout, _max_payout) = inflation::compute_total_payout(
&T::RewardCurve::get(),
Self::eras_total_stake(&active_era.index),
Expand Down
2 changes: 1 addition & 1 deletion frame/staking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ parameter_types! {
}
impl Trait for Test {
type Currency = pallet_balances::Module<Self>;
type Time = pallet_timestamp::Module<Self>;
type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = CurrencyToVoteHandler;
type RewardRemainder = ();
type Event = ();
Expand Down
6 changes: 6 additions & 0 deletions frame/support/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,12 @@ pub trait Time {
fn now() -> Self::Moment;
}

/// Trait to deal with unix time.
pub trait UnixTime {
/// Return duration since `SystemTime::UNIX_EPOCH`.
fn now() -> core::time::Duration;
}

impl WithdrawReasons {
/// Choose all variants except for `one`.
///
Expand Down
25 changes: 22 additions & 3 deletions frame/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,17 @@ mod benchmarking;

use sp_std::{result, cmp};
use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier};
use frame_support::{Parameter, decl_storage, decl_module};
use frame_support::traits::{Time, Get};
use frame_support::{
Parameter, decl_storage, decl_module, debug,
traits::{Time, UnixTime, Get},
weights::SimpleDispatchInfo,
};
use sp_runtime::{
RuntimeString,
traits::{
AtLeast32Bit, Zero, SaturatedConversion, Scale
}
};
use frame_support::weights::SimpleDispatchInfo;
use frame_system::ensure_none;
use sp_timestamp::{
InherentError, INHERENT_IDENTIFIER, InherentType,
Expand Down Expand Up @@ -239,6 +241,23 @@ impl<T: Trait> Time for Module<T> {
}
}

/// Before the timestamp inherent is applied, it returns the time of previous block.
///
/// On genesis the time returned is not valid.
impl<T: Trait> UnixTime for Module<T> {
fn now() -> core::time::Duration {
// now is duration since unix epoch in millisecond as documented in
// `sp_timestamp::InherentDataProvider`.
let now = Self::now();
if now == T::Moment::zero() {
debug::error!(
"`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0"
);
}
core::time::Duration::from_millis(now.saturated_into::<u64>())
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
1 change: 1 addition & 0 deletions primitives/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl TimestampInherentData for InherentData {
}
}

/// Provide duration since unix epoch in millisecond for timestamp inherent.
#[cfg(feature = "std")]
pub struct InherentDataProvider;

Expand Down

0 comments on commit b00aab3

Please sign in to comment.