Skip to content

Commit

Permalink
anonymous account pallet creation
Browse files Browse the repository at this point in the history
  • Loading branch information
amiyatulu committed Nov 7, 2024
1 parent da76d0b commit af17284
Show file tree
Hide file tree
Showing 9 changed files with 412 additions and 17 deletions.
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 19 additions & 17 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@ homepage = "https://substrate.io"

[workspace]
members = [
"node",
"pallets/template",
"custom-pallets/department-funding",
"custom-pallets/positive-externality",
"custom-pallets/profile-validation",
"custom-pallets/project-tips",
"custom-pallets/schelling-game-shared",
"custom-pallets/shared-storage",
"custom-pallets/sortition-sum-game",
"custom-pallets/spaces",
"custom-pallets/support",
"custom-pallets/departments",
"runtime",
"custom-pallets/simple-approval-voting",
"custom-pallets/first-past-the-post",
"node",
"pallets/template",
"custom-pallets/department-funding",
"custom-pallets/positive-externality",
"custom-pallets/profile-validation",
"custom-pallets/project-tips",
"custom-pallets/schelling-game-shared",
"custom-pallets/shared-storage",
"custom-pallets/sortition-sum-game",
"custom-pallets/spaces",
"custom-pallets/support",
"custom-pallets/departments",
"runtime",
"custom-pallets/simple-approval-voting",
"custom-pallets/first-past-the-post",
"custom-pallets/anonymous-account",
]
resolver = "2"
[profile.release]
Expand Down Expand Up @@ -72,6 +73,7 @@ pallet-project-tips = { path = "custom-pallets/project-tips", default-features =
pallet-positive-externality = { path = "custom-pallets/positive-externality", default-features = false }
pallet-department-funding = { path = "custom-pallets/department-funding", default-features = false }
pallet-departments = { path = "custom-pallets/departments", default-features = false }
pallet-anonymous-account = { path = "custom-pallets/anonymous-account", default-features = false }
pallet-simple-approval-voting = { path = "custom-pallets/simple-approval-voting", default-features = false }
pallet-first-past-the-post = { path = "custom-pallets/first-past-the-post" }

Expand Down Expand Up @@ -110,10 +112,10 @@ hex-literal = { version = " 0.4.1" }
## New end

parity-scale-codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [
"derive",
"derive",
] }
scale-info = { version = "2.10.0", default-features = false, features = [
"derive",
"derive",
] }

# frame deps
Expand Down
37 changes: 37 additions & 0 deletions custom-pallets/anonymous-account/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
[package]
name = "pallet-anonymous-account"
version = "4.0.0-dev"
description = "FRAME pallet template for defining custom runtime logic."
authors = ["Substrate DevHub <https://github.com/substrate-developer-hub>"]
homepage = "https://substrate.io"
edition = "2021"
license = "MIT-0"
publish = false
repository = "https://github.com/substrate-developer-hub/substrate-node-template/"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
parity-scale-codec = { workspace = true }
scale-info = { workspace = true }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }

[dev-dependencies]
sp-core = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }

[features]
default = ["std"]
std = [
"parity-scale-codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"scale-info/std",
]
runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"]
try-runtime = ["frame-support/try-runtime"]
1 change: 1 addition & 0 deletions custom-pallets/anonymous-account/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
License: MIT-0
35 changes: 35 additions & 0 deletions custom-pallets/anonymous-account/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//! Benchmarking setup for pallet-template
#![cfg(feature = "runtime-benchmarks")]
use super::*;

#[allow(unused)]
use crate::Pallet as Template;
use frame_benchmarking::v2::*;
use frame_system::RawOrigin;

#[benchmarks]
mod benchmarks {
use super::*;

#[benchmark]
fn do_something() {
let value = 100u32.into();
let caller: T::AccountId = whitelisted_caller();
#[extrinsic_call]
do_something(RawOrigin::Signed(caller), value);

assert_eq!(Something::<T>::get(), Some(value));
}

#[benchmark]
fn cause_error() {
Something::<T>::put(100u32);
let caller: T::AccountId = whitelisted_caller();
#[extrinsic_call]
cause_error(RawOrigin::Signed(caller));

assert_eq!(Something::<T>::get(), Some(101u32));
}

impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test);
}
121 changes: 121 additions & 0 deletions custom-pallets/anonymous-account/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#![cfg_attr(not(feature = "std"), no_std)]

/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://docs.substrate.io/reference/frame-pallets/>
pub use pallet::*;

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod weights;
pub use weights::*;

pub type DepartmentId = u64;

#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;

#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);

/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Type representing the weight of this pallet
type WeightInfo: WeightInfo;
}

// The pallet's runtime storage items.
// https://docs.substrate.io/main-docs/build/runtime-storage/
#[pallet::storage]
#[pallet::getter(fn something)]
// Learn more about declaring storage items:
// https://docs.substrate.io/main-docs/build/runtime-storage/#declaring-storage-items
pub type Something<T> = StorageValue<_, u32>;

#[pallet::storage]
#[pallet::getter(fn kyc_accounts)]
pub type KYCAccounts<T: Config> =
StorageMap<_, Blake2_128Concat, DepartmentId, Vec<(T::AccountId, [u8; 64])>>;

#[pallet::storage]
#[pallet::getter(fn hash_by_range)]
pub type HashByRange<T: Config> =
StorageMap<_, Blake2_128Concat, (DepartmentId, u32, u32), [u8; 32]>;

// Pallets use events to inform users when important changes are made.
// https://docs.substrate.io/main-docs/build/events-errors/
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Event documentation should end with an array that provides descriptive names for event
/// parameters. [something, who]
SomethingStored { something: u32, who: T::AccountId },
}

// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T> {
/// Error names should be descriptive.
NoneValue,
/// Errors should have helpful documentation associated with them.
StorageOverflow,
}

// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call]
impl<T: Config> Pallet<T> {
/// An example dispatchable that takes a singles value as a parameter, writes the value to
/// storage and emits an event. This function must be dispatched by a signed extrinsic.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::do_something())]
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult {
// Check that the extrinsic was signed and get the signer.
// This function will return an error if the extrinsic is not signed.
// https://docs.substrate.io/main-docs/build/origins/
let who = ensure_signed(origin)?;

// Update storage.
<Something<T>>::put(something);

// Emit an event.
Self::deposit_event(Event::SomethingStored { something, who });
// Return a successful DispatchResultWithPostInfo
Ok(())
}

/// An example dispatchable that may throw a custom error.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::cause_error())]
pub fn cause_error(origin: OriginFor<T>) -> DispatchResult {
let _who = ensure_signed(origin)?;

// Read a value from storage.
match <Something<T>>::get() {
// Return an error if the value has not been set.
None => return Err(Error::<T>::NoneValue.into()),
Some(old) => {
// Increment the value read from storage; will error in the event of overflow.
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
// Update the value in storage with the incremented result.
<Something<T>>::put(new);
Ok(())
},
}
}
}
}
61 changes: 61 additions & 0 deletions custom-pallets/anonymous-account/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use crate as pallet_template;
use frame_support::{
derive_impl,
traits::{ConstU16, ConstU64},
};
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
};

type Block = frame_system::mocking::MockBlock<Test>;

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system,
TemplateModule: pallet_template,
}
);

#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ConstU16<42>;
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}

impl pallet_template::Config for Test {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
}

// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
frame_system::GenesisConfig::<Test>::default()
.build_storage()
.unwrap()
.into()
}
33 changes: 33 additions & 0 deletions custom-pallets/anonymous-account/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::{mock::*, Error, Event};
use frame_support::{assert_noop, assert_ok};

#[test]
fn it_works_for_default_value() {
new_test_ext().execute_with(|| {
// Go past genesis block so events get deposited
System::set_block_number(1);
// Dispatch a signed extrinsic.
assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42));
// Read pallet storage and assert an expected result.
assert_eq!(TemplateModule::something(), Some(42));
// Assert that the correct event was deposited
System::assert_last_event(
Event::SomethingStored {
something: 42,
who: 1,
}
.into(),
);
});
}

#[test]
fn correct_error_for_none_value() {
new_test_ext().execute_with(|| {
// Ensure the expected error is thrown when no value is present.
assert_noop!(
TemplateModule::cause_error(RuntimeOrigin::signed(1)),
Error::<Test>::NoneValue
);
});
}
Loading

0 comments on commit af17284

Please sign in to comment.