![](/img/trans.png)
[英]How to include <T as Trait>::Blocknumber in a struct within a Substrate FRAME pallet
[英]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>())
}
}
要使用它,您應該在新托盤中執行以下操作:
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;
}
T::TimeProvider::now()
以T::TimeProvider::now()
形式返回以毫秒為單位的 unix 時間。let time: u64 = T::TimeProvider::now();
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.