I would like to store a date and later on compare it to the current date.
How can I do it?
Thanks
Substrate and Polkadot Stack Exchange is a question and answer site for developers building blockchains with the Substrate SDK. It only takes a minute to sign up.
Sign up to join this communityI would like to store a date and later on compare it to the current date.
How can I do it?
Thanks
It is not recommended to store and use dates on chain, since dates are not a native measurement of the blockchain.
Instead you can use the BlockNumber
type, which is going to be a much better unit for time passing in your runtime logic.
Otherwise, if you are really insistent to use some kind of human date, you can use the Timestamp Pallet via the Time
trait, which uses Moment
type.
Both options would look something like this:
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use frame_support::traits::Time;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type Time: Time;
}
type MomentOf<T> = <<T as Config>::Time as Time>::Moment;
#[pallet::storage]
pub type TimeStorage<T> = StorageValue<_, MomentOf<T>>;
#[pallet::storage]
pub type BlockNumberStorage<T: Config> = StorageValue<_, T::BlockNumber>;
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(0)]
pub fn store_time(origin: OriginFor<T>) -> DispatchResult {
let _who = ensure_signed(origin)?;
let current_time = T::Time::now();
TimeStorage::<T>::put(current_time);
Ok(())
}
#[pallet::weight(0)]
pub fn store_block_number(origin: OriginFor<T>) -> DispatchResult {
let _who = ensure_signed(origin)?;
let current_block_number = frame_system::Pallet::<T>::block_number();
BlockNumberStorage::<T>::put(current_block_number);
Ok(())
}
}
}