基板框架V2如何使用pallet_timestamp

问题描述

按照基板教程并声明托盘配置如下 在托盘 lib.rs

use pallet_timestamp as timestamp;
    #[pallet::config]
    pub trait Config: frame_system::Config + pallet_timestamp::Config{
        type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
    }

Caego.toml 中的配置

pallet-timestamp = { version = '3.0',default-features = false}

std = [
    'codec/std','frame-support/std','frame-system/std','sp-runtime/std','pallet-timestamp/std','log/std',]

我需要使用 pallet_timestamp

获取时间戳
#[pallet::call]
impl<T: Config> Pallet<T> {

        #[pallet::weight(0)]
        pub fn update_recoed(origin: OriginFor<T>,record: Vec<u8>) -> dispatchResultWithPostInfo {
            let pallet_time = <timestamp::Module<T>>::get(); // Error
            Ok(().into())
        }
}

如何在 Substrate Pallet V2 中获取时间?

解决方法

与其直接使用托盘,不如直​​接使用托盘,而应使用托盘提供的两个特性之一和托盘的松散耦合。

我提到的两个特征可以在 pallet_timestamp source code 中找到:

impl<T: Config> Time for Pallet<T> {
    type Moment = T::Moment;

    /// Before the first set of now with inherent the value returned is zero.
    fn now() -> Self::Moment {
        Self::now()
    }
}

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

要使用它,您应该在新托盘中执行以下操作:

  1. 更新您的配置以获得使用这些特征之一的新配置。您无需将托盘与 pallet_timestamp 紧密连接:
use frame_support::traits::UnixTime;

#[pallet::config]
pub trait Config: frame_system::Config {
    type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
    type TimeProvider: UnixTime;
}
  1. 然后,您可以在托盘中的任何位置调用 T::TimeProvider::now() 以 u64 形式返回以毫秒为单位的 Unix 时间。
let time: u64 = T::TimeProvider::now();
  1. 然后,要使其正常工作,您需要将 pallet_timstamp 托盘插入为您的“TimeProvider”。您可以通过在 impl my_pallet::Config 时进行配置:
impl my_pallet::Config for Runtime {
    type Event = Event;
    type TimeProvider = pallet_timestamp::Pallet<Runtime>;
    // Or more easily just `Timestamp` assuming you used that name in `construct_runtime!`
}