Incorporate Randomness
On-chain randomness techniques and tools detailed.
Import Randomness
Randomnessuse frame_support::traits::Randomness;#[pallet::config] pub trait frame_system::Config { type MyRandomness: Randomness<Self::Hash, Self::BlockNumber>; }
Create a nonce and use it in your randomness implementation
fn get_and_increment_nonce() -> Vec<u8> { let nonce = Nonce::<T>::get(); Nonce::<T>::put(nonce.wrapping_add(1)); nonce.encode() }#[pallet::weight(100)] pub fn create_unique( origin: OriginFor<T>) -> DispatchResultWithPostInfo { // Account calling this dispatchable. let sender = ensure_signed(origin)?; // Random value. let nonce = Self::get_and_increment_nonce(); let (randomValue, _) = T::MyRandomness::random(&nonce); // Write the random value to storage. <MyStorageItem<T>>::put(randomValue); Self::deposit_event(Event::UniqueCreated(randomValue)); }impl my_pallet::Config for Runtime{ type Event; type MyRandomness = RandomCollectiveFlip; }
Examples
Related material
Last updated