Skip to content

Commit ada6d58

Browse files
shawntabriziParity Benchmarking Bot
authored andcommitted
Participation Lottery Pallet (paritytech#7221)
* Basic design * start adding tests * finish tests * clean up crates * use call index for match * finish benchmarks * add to runtime * fix * cargo run --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_lottery --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/lottery/src/weights.rs --template=./.maintain/frame-weight-template.hbs * more efficient storage * cargo run --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_lottery --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/lottery/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Update lib.rs * Update bin/node/runtime/src/lib.rs * trait -> config * add repeating lottery * new benchmarks * fix build * move trait for warning * feedback from @xlc * add stop_repeat * fix * cargo run --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_lottery --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/lottery/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Support static calls * cargo run --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_lottery --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/lottery/src/weights.rs --template=./.maintain/frame-weight-template.hbs * fix test * add loop to mitigate modulo bias * Update weights for worst case scenario loop * Initialize pot with ED * cargo run --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_lottery --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/lottery/src/weights.rs --template=./.maintain/frame-weight-template.hbs Co-authored-by: Parity Benchmarking Bot <admin@parity.io>
1 parent ce5876e commit ada6d58

10 files changed

Lines changed: 1250 additions & 0 deletions

File tree

Cargo.lock

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ members = [
8181
"frame/identity",
8282
"frame/im-online",
8383
"frame/indices",
84+
"frame/lottery",
8485
"frame/membership",
8586
"frame/merkle-mountain-range",
8687
"frame/metadata",

bin/node/runtime/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ pallet-grandpa = { version = "2.0.0", default-features = false, path = "../../..
5959
pallet-im-online = { version = "2.0.0", default-features = false, path = "../../../frame/im-online" }
6060
pallet-indices = { version = "2.0.0", default-features = false, path = "../../../frame/indices" }
6161
pallet-identity = { version = "2.0.0", default-features = false, path = "../../../frame/identity" }
62+
pallet-lottery = { version = "2.0.0", default-features = false, path = "../../../frame/lottery" }
6263
pallet-membership = { version = "2.0.0", default-features = false, path = "../../../frame/membership" }
6364
pallet-mmr = { version = "2.0.0", default-features = false, path = "../../../frame/merkle-mountain-range" }
6465
pallet-multisig = { version = "2.0.0", default-features = false, path = "../../../frame/multisig" }
@@ -113,6 +114,7 @@ std = [
113114
"pallet-im-online/std",
114115
"pallet-indices/std",
115116
"sp-inherents/std",
117+
"pallet-lottery/std",
116118
"pallet-membership/std",
117119
"pallet-mmr/std",
118120
"pallet-multisig/std",
@@ -167,6 +169,7 @@ runtime-benchmarks = [
167169
"pallet-identity/runtime-benchmarks",
168170
"pallet-im-online/runtime-benchmarks",
169171
"pallet-indices/runtime-benchmarks",
172+
"pallet-lottery/runtime-benchmarks",
170173
"pallet-mmr/runtime-benchmarks",
171174
"pallet-multisig/runtime-benchmarks",
172175
"pallet-proxy/runtime-benchmarks",

bin/node/runtime/src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -952,6 +952,25 @@ impl pallet_mmr::Config for Runtime {
952952
type WeightInfo = ();
953953
}
954954

955+
parameter_types! {
956+
pub const LotteryModuleId: ModuleId = ModuleId(*b"py/lotto");
957+
pub const MaxCalls: usize = 10;
958+
pub const MaxGenerateRandom: u32 = 10;
959+
}
960+
961+
impl pallet_lottery::Config for Runtime {
962+
type ModuleId = LotteryModuleId;
963+
type Call = Call;
964+
type Event = Event;
965+
type Currency = Balances;
966+
type Randomness = RandomnessCollectiveFlip;
967+
type ManagerOrigin = EnsureRoot<AccountId>;
968+
type MaxCalls = MaxCalls;
969+
type ValidateCall = Lottery;
970+
type MaxGenerateRandom = MaxGenerateRandom;
971+
type WeightInfo = pallet_lottery::weights::SubstrateWeight<Runtime>;
972+
}
973+
955974
parameter_types! {
956975
pub const AssetDepositBase: Balance = 100 * DOLLARS;
957976
pub const AssetDepositPerZombie: Balance = 1 * DOLLARS;
@@ -1009,6 +1028,7 @@ construct_runtime!(
10091028
Tips: pallet_tips::{Module, Call, Storage, Event<T>},
10101029
Assets: pallet_assets::{Module, Call, Storage, Event<T>},
10111030
Mmr: pallet_mmr::{Module, Storage},
1031+
Lottery: pallet_lottery::{Module, Call, Storage, Event<T>},
10121032
}
10131033
);
10141034

@@ -1291,6 +1311,7 @@ impl_runtime_apis! {
12911311
add_benchmark!(params, batches, pallet_identity, Identity);
12921312
add_benchmark!(params, batches, pallet_im_online, ImOnline);
12931313
add_benchmark!(params, batches, pallet_indices, Indices);
1314+
add_benchmark!(params, batches, pallet_lottery, Lottery);
12941315
add_benchmark!(params, batches, pallet_mmr, Mmr);
12951316
add_benchmark!(params, batches, pallet_multisig, Multisig);
12961317
add_benchmark!(params, batches, pallet_offences, OffencesBench::<Runtime>);

frame/lottery/Cargo.toml

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
[package]
2+
name = "pallet-lottery"
3+
version = "2.0.0"
4+
authors = ["Parity Technologies <admin@parity.io>"]
5+
edition = "2018"
6+
license = "Apache-2.0"
7+
homepage = "https://substrate.dev"
8+
repository = "https://github.com/paritytech/substrate/"
9+
description = "FRAME Participation Lottery Pallet"
10+
readme = "README.md"
11+
12+
[package.metadata.docs.rs]
13+
targets = ["x86_64-unknown-linux-gnu"]
14+
15+
[dependencies]
16+
codec = { package = "parity-scale-codec", version = "1.3.4", default-features = false, features = ["derive"] }
17+
sp-std = { version = "2.0.0", default-features = false, path = "../../primitives/std" }
18+
sp-runtime = { version = "2.0.0", default-features = false, path = "../../primitives/runtime" }
19+
frame-support = { version = "2.0.0", default-features = false, path = "../support" }
20+
frame-system = { version = "2.0.0", default-features = false, path = "../system" }
21+
22+
frame-benchmarking = { version = "2.0.0", default-features = false, path = "../benchmarking", optional = true }
23+
24+
[dev-dependencies]
25+
pallet-balances = { version = "2.0.0", path = "../balances" }
26+
sp-core = { version = "2.0.0", path = "../../primitives/core" }
27+
sp-io = { version = "2.0.0", path = "../../primitives/io" }
28+
29+
[features]
30+
default = ["std"]
31+
std = [
32+
"codec/std",
33+
"sp-std/std",
34+
"frame-support/std",
35+
"sp-runtime/std",
36+
"frame-system/std",
37+
]
38+
runtime-benchmarks = [
39+
"frame-benchmarking",
40+
"frame-system/runtime-benchmarks",
41+
"frame-support/runtime-benchmarks",
42+
]

frame/lottery/src/benchmarking.rs

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
// This file is part of Substrate.
2+
3+
// Copyright (C) 2020 Parity Technologies (UK) Ltd.
4+
// SPDX-License-Identifier: Apache-2.0
5+
6+
// Licensed under the Apache License, Version 2.0 (the "License");
7+
// you may not use this file except in compliance with the License.
8+
// You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing, software
13+
// distributed under the License is distributed on an "AS IS" BASIS,
14+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
// See the License for the specific language governing permissions and
16+
// limitations under the License.
17+
18+
//! Lottery pallet benchmarking.
19+
20+
#![cfg(feature = "runtime-benchmarks")]
21+
22+
use super::*;
23+
24+
use frame_system::RawOrigin;
25+
use frame_support::traits::{OnInitialize, UnfilteredDispatchable};
26+
use frame_benchmarking::{benchmarks, account, whitelisted_caller};
27+
use sp_runtime::traits::{Bounded, Zero};
28+
29+
use crate::Module as Lottery;
30+
31+
// Set up and start a lottery
32+
fn setup_lottery<T: Config>(repeat: bool) -> Result<(), &'static str> {
33+
let price = T::Currency::minimum_balance();
34+
let length = 10u32.into();
35+
let delay = 5u32.into();
36+
// Calls will be maximum length...
37+
let mut calls = vec![
38+
frame_system::Call::<T>::set_code(vec![]).into();
39+
T::MaxCalls::get().saturating_sub(1)
40+
];
41+
// Last call will be the match for worst case scenario.
42+
calls.push(frame_system::Call::<T>::remark(vec![]).into());
43+
let origin = T::ManagerOrigin::successful_origin();
44+
Lottery::<T>::set_calls(origin.clone(), calls)?;
45+
Lottery::<T>::start_lottery(origin, price, length, delay, repeat)?;
46+
Ok(())
47+
}
48+
49+
benchmarks! {
50+
_ { }
51+
52+
buy_ticket {
53+
let caller = whitelisted_caller();
54+
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
55+
setup_lottery::<T>(false)?;
56+
// force user to have a long vec of calls participating
57+
let set_code_index: CallIndex = Lottery::<T>::call_to_index(
58+
&frame_system::Call::<T>::set_code(vec![]).into()
59+
)?;
60+
let already_called: (u32, Vec<CallIndex>) = (
61+
LotteryIndex::get(),
62+
vec![
63+
set_code_index;
64+
T::MaxCalls::get().saturating_sub(1)
65+
],
66+
);
67+
Participants::<T>::insert(&caller, already_called);
68+
69+
let call = frame_system::Call::<T>::remark(vec![]);
70+
}: _(RawOrigin::Signed(caller), Box::new(call.into()))
71+
verify {
72+
assert_eq!(TicketsCount::get(), 1);
73+
}
74+
75+
set_calls {
76+
let n in 0 .. T::MaxCalls::get() as u32;
77+
let calls = vec![frame_system::Call::<T>::remark(vec![]).into(); n as usize];
78+
79+
let call = Call::<T>::set_calls(calls);
80+
let origin = T::ManagerOrigin::successful_origin();
81+
assert!(CallIndices::get().is_empty());
82+
}: { call.dispatch_bypass_filter(origin)? }
83+
verify {
84+
if !n.is_zero() {
85+
assert!(!CallIndices::get().is_empty());
86+
}
87+
}
88+
89+
start_lottery {
90+
let price = BalanceOf::<T>::max_value();
91+
let end = 10u32.into();
92+
let payout = 5u32.into();
93+
94+
let call = Call::<T>::start_lottery(price, end, payout, true);
95+
let origin = T::ManagerOrigin::successful_origin();
96+
}: { call.dispatch_bypass_filter(origin)? }
97+
verify {
98+
assert!(crate::Lottery::<T>::get().is_some());
99+
}
100+
101+
stop_repeat {
102+
setup_lottery::<T>(true)?;
103+
assert_eq!(crate::Lottery::<T>::get().unwrap().repeat, true);
104+
let call = Call::<T>::stop_repeat();
105+
let origin = T::ManagerOrigin::successful_origin();
106+
}: { call.dispatch_bypass_filter(origin)? }
107+
verify {
108+
assert_eq!(crate::Lottery::<T>::get().unwrap().repeat, false);
109+
}
110+
111+
on_initialize_end {
112+
setup_lottery::<T>(false)?;
113+
let winner = account("winner", 0, 0);
114+
// User needs more than min balance to get ticket
115+
T::Currency::make_free_balance_be(&winner, T::Currency::minimum_balance() * 10u32.into());
116+
// Make sure lottery account has at least min balance too
117+
let lottery_account = Lottery::<T>::account_id();
118+
T::Currency::make_free_balance_be(&lottery_account, T::Currency::minimum_balance() * 10u32.into());
119+
// Buy a ticket
120+
let call = frame_system::Call::<T>::remark(vec![]);
121+
Lottery::<T>::buy_ticket(RawOrigin::Signed(winner.clone()).into(), Box::new(call.into()))?;
122+
// Kill user account for worst case
123+
T::Currency::make_free_balance_be(&winner, 0u32.into());
124+
// Assert that lotto is set up for winner
125+
assert_eq!(TicketsCount::get(), 1);
126+
assert!(!Lottery::<T>::pot().1.is_zero());
127+
}: {
128+
// Generate `MaxGenerateRandom` numbers for worst case scenario
129+
for i in 0 .. T::MaxGenerateRandom::get() {
130+
Lottery::<T>::generate_random_number(i);
131+
}
132+
// Start lottery has block 15 configured for payout
133+
Lottery::<T>::on_initialize(15u32.into());
134+
}
135+
verify {
136+
assert!(crate::Lottery::<T>::get().is_none());
137+
assert_eq!(TicketsCount::get(), 0);
138+
assert_eq!(Lottery::<T>::pot().1, 0u32.into());
139+
assert!(!T::Currency::free_balance(&winner).is_zero())
140+
}
141+
142+
on_initialize_repeat {
143+
setup_lottery::<T>(true)?;
144+
let winner = account("winner", 0, 0);
145+
// User needs more than min balance to get ticket
146+
T::Currency::make_free_balance_be(&winner, T::Currency::minimum_balance() * 10u32.into());
147+
// Make sure lottery account has at least min balance too
148+
let lottery_account = Lottery::<T>::account_id();
149+
T::Currency::make_free_balance_be(&lottery_account, T::Currency::minimum_balance() * 10u32.into());
150+
// Buy a ticket
151+
let call = frame_system::Call::<T>::remark(vec![]);
152+
Lottery::<T>::buy_ticket(RawOrigin::Signed(winner.clone()).into(), Box::new(call.into()))?;
153+
// Kill user account for worst case
154+
T::Currency::make_free_balance_be(&winner, 0u32.into());
155+
// Assert that lotto is set up for winner
156+
assert_eq!(TicketsCount::get(), 1);
157+
assert!(!Lottery::<T>::pot().1.is_zero());
158+
}: {
159+
// Generate `MaxGenerateRandom` numbers for worst case scenario
160+
for i in 0 .. T::MaxGenerateRandom::get() {
161+
Lottery::<T>::generate_random_number(i);
162+
}
163+
// Start lottery has block 15 configured for payout
164+
Lottery::<T>::on_initialize(15u32.into());
165+
}
166+
verify {
167+
assert!(crate::Lottery::<T>::get().is_some());
168+
assert_eq!(LotteryIndex::get(), 2);
169+
assert_eq!(TicketsCount::get(), 0);
170+
assert_eq!(Lottery::<T>::pot().1, 0u32.into());
171+
assert!(!T::Currency::free_balance(&winner).is_zero())
172+
}
173+
}
174+
175+
#[cfg(test)]
176+
mod tests {
177+
use super::*;
178+
use crate::mock::{new_test_ext, Test};
179+
use frame_support::assert_ok;
180+
181+
#[test]
182+
fn test_benchmarks() {
183+
new_test_ext().execute_with(|| {
184+
assert_ok!(test_benchmark_buy_ticket::<Test>());
185+
assert_ok!(test_benchmark_set_calls::<Test>());
186+
assert_ok!(test_benchmark_start_lottery::<Test>());
187+
assert_ok!(test_benchmark_stop_repeat::<Test>());
188+
assert_ok!(test_benchmark_on_initialize_end::<Test>());
189+
assert_ok!(test_benchmark_on_initialize_repeat::<Test>());
190+
});
191+
}
192+
}

0 commit comments

Comments
 (0)