簡體   English   中英

基板框架V2如何使用pallet_timestamp

[英]Substrate frame V2 how to use 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 源代碼中找到

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()T::TimeProvider::now()形式返回以毫秒為單位的 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!`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM