Created
September 23, 2023 05:58
-
-
Save javiermatias/92156cdfa39c59aa65bf412f1fb567b6 to your computer and use it in GitHub Desktop.
Pallet Random dummy value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![cfg_attr(not(feature = "std"), no_std)] | |
pub use pallet::*; | |
#[frame_support::pallet(dev_mode)] | |
pub mod pallet { | |
use crate::pallet::storage::StorageValue; | |
use frame_support::{pallet_prelude::*, traits::Randomness}; /* import the Randomness | |
* trait: */ | |
use frame_system::pallet_prelude::*; | |
#[pallet::pallet] | |
#[pallet::generate_store(pub(super) trait Store)] | |
pub struct Pallet<T>(_); | |
#[pallet::config] | |
pub trait Config: frame_system::Config { | |
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; | |
//Include in configuration trait: | |
type MyRandomness: Randomness<Self::Hash, BlockNumberFor<Self>>; | |
} | |
#[pallet::event] | |
#[pallet::generate_deposit(pub(super) fn deposit_event)] | |
pub enum Event<T: Config> { | |
/// Event emitted when a random number is create | |
UniqueCreated(u32), | |
} | |
//Nonce storage item | |
#[pallet::storage] | |
type Nonce<T> = StorageValue<_, u32, ValueQuery>; | |
//Random Number Storage | |
#[pallet::storage] | |
type RandomNumber<T> = StorageValue<_, u32, ValueQuery>; | |
//private function to increment the nonce | |
fn get_and_increment_nonce() -> Vec<u8> { | |
let nonce = Nonce::get(); | |
Nonce::put(nonce.wrapping_add(1)); | |
nonce.encode() | |
} | |
#[pallet::call] | |
impl<T: Config> Pallet<T> { | |
#[pallet::weight(0)] | |
#[pallet::call_index(1)] | |
pub fn generate_random_number(origin: OriginFor<T>) -> DispatchResultWithPostInfo { | |
// Account calling this dispatchable. | |
let sender = ensure_signed(origin)?; | |
// Increment Nonce | |
let nonce = Self::get_and_increment_nonce(); | |
//call the random() method that Randomness exposes | |
let randomValue = T::MyRandomness::random(&nonce); | |
// Write the random value to storage. | |
<RandomNumber<T>>::put(randomValue); | |
//Dispatch event | |
Self::deposit_event(Event::UniqueCreated(randomValue)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment