Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

add pallet macro kitchensink example/template #14052

Merged
merged 21 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions frame/examples/kitchensink/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ sp-std = { version = "5.0.0", default-features = false, path = "../../../primiti

frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../../benchmarking" }

pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../../balances" }

[dev-dependencies]
sp-core = { version = "7.0.0", default-features = false, path = "../../../primitives/core" }

Expand All @@ -44,6 +46,8 @@ std = [
"sp-std/std",

"frame-benchmarking?/std",

"pallet-balances/std",
]
runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"]
try-runtime = ["frame-support/try-runtime"]
63 changes: 63 additions & 0 deletions frame/examples/kitchensink/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Benchmarking for `pallet-example-kitchensink`.

// Only enable this module for benchmarking.
#![cfg(feature = "runtime-benchmarks")]

use crate::*;
use frame_benchmarking::v2::*;
use frame_system::RawOrigin;

// To actually run this benchmark on pallet-example-kitchensink, we need to put this pallet into the
// runtime and compile it with `runtime-benchmarks` feature. The detail procedures are
// documented at:
// https://docs.substrate.io/reference/how-to-guides/weights/add-benchmarks/
//
// The auto-generated weight estimate of this pallet is copied over to the `weights.rs` file.
// The exact command of how the estimate generated is printed at the top of the file.

// Details on using the benchmarks macro can be seen at:
// https://paritytech.github.io/substrate/master/frame_benchmarking/trait.Benchmarking.html#tymethod.benchmarks
#[benchmarks]
mod benchmarks {
use super::*;

// This will measure the execution time of `set_foo`.
#[benchmark]
fn set_foo_benchmark() {
// This is the benchmark setup phase.
// `set_foo` is a constant time function, hence we hard-code some random value here.
let value = 1000u32.into();
#[extrinsic_call]
set_foo(RawOrigin::Root, value, 10u128); // The execution phase is just running `set_foo` extrinsic call

// This is the optional benchmark verification phase, asserting certain states.
assert_eq!(Pallet::<T>::foo(), Some(value))
}

// This line generates test cases for benchmarking, and could be run by:
// `cargo test -p pallet-example-kitchensink --all-features`, you will see one line per case:
// `test benchmarking::bench_sort_vector ... ok`
// `test benchmarking::bench_accumulate_dummy ... ok`
// `test benchmarking::bench_set_dummy_benchmark ... ok` in the result.
//
// The line generates three steps per benchmark, with repeat=1 and the three steps are
// [low, mid, high] of the range.
impl_benchmark_test_suite!(Pallet, crate::tests::new_test_ext(), crate::tests::Test);
}
20 changes: 16 additions & 4 deletions frame/examples/kitchensink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@
/// This example does not focus on pallet instancing, `dev_mode`, and does nto include any 'where'
/// clauses on `T`. These will both incur additional complexity to the syntax, but are not discussed
/// here.
// TODO: link to a particular example pallet that highlights each of these. https://github.com/paritytech/substrate/issues/13951
// TODO: link to a particular example pallet that highlights each of these.
gupnik marked this conversation as resolved.
Show resolved Hide resolved
// https://github.com/paritytech/substrate/issues/13951

// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;

#[cfg(test)]
mod tests;

mod benchmarking;

#[frame_support::pallet]
pub mod pallet {
use super::*;
Expand Down Expand Up @@ -164,10 +174,12 @@ pub mod pallet {
#[pallet::weight(0)]
pub fn set_foo(
_: OriginFor<T>,
_new_foo: u32,
new_foo: u32,
#[pallet::compact] _other_compact: u128,
) -> DispatchResult {
unimplemented!()
Foo::<T>::set(Some(new_foo));

Ok(())
}
}

Expand Down Expand Up @@ -242,7 +254,7 @@ pub mod pallet {
}

#[cfg(feature = "try-runtime")]
fn try_state(_n: _) -> Result<(), &'static str> {
fn try_state(_n: T::BlockNumber) -> Result<(), &'static str> {
unimplemented!()
}
}
Expand Down
123 changes: 123 additions & 0 deletions frame/examples/kitchensink/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tests for pallet-example-basic.

use crate::*;
use frame_support::{traits::ConstU64, parameter_types};
use sp_core::H256;
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
};
// Reexport crate as its pallet name for construct_runtime.
use crate as pallet_example_kitchensink;

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

// For testing the pallet, we construct a mock runtime.
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Kitchensink: pallet_example_kitchensink::{Pallet, Call, Storage, Config<T>, Event<T>},
}
);

impl frame_system::Config for Test {
gupnik marked this conversation as resolved.
Show resolved Hide resolved
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type RuntimeCall = RuntimeCall;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}

impl pallet_balances::Config for Test {
type MaxLocks = ();
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type Balance = u64;
type DustRemoval = ();
type RuntimeEvent = RuntimeEvent;
type ExistentialDeposit = ConstU64<1>;
type AccountStore = System;
type WeightInfo = ();
type FreezeIdentifier = ();
type MaxFreezes = ();
type HoldIdentifier = ();
type MaxHolds = ();
}

parameter_types! {
pub const InMetadata: u32 = 30;
}

impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type InMetadata = InMetadata;

const FOO:u32 = 100;

fn some_function() -> u32 {
5u32
}
}

// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = GenesisConfig {
gupnik marked this conversation as resolved.
Show resolved Hide resolved
// We use default for brevity, but you can configure as desired if needed.
system: Default::default(),
balances: Default::default(),
kitchensink: pallet_example_kitchensink::GenesisConfig {
bar: 32,
foo: 24,
},
}
.build_storage()
.unwrap();
t.into()
}