frame_benchmarking_cli/extrinsic/extrinsic_factory.rs
1// This file is part of Substrate.
2
3// Copyright (C) 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//! Provides the [`ExtrinsicFactory`] and the [`ExtrinsicBuilder`] types.
19//! Is used by the *overhead* and *extrinsic* benchmarks to build extrinsics.
20
21use sp_runtime::OpaqueExtrinsic;
22
23/// Helper to manage [`ExtrinsicBuilder`] instances.
24#[derive(Default)]
25pub struct ExtrinsicFactory(pub Vec<Box<dyn ExtrinsicBuilder>>);
26
27impl ExtrinsicFactory {
28 /// Returns a builder for a pallet and extrinsic name.
29 ///
30 /// Is case in-sensitive.
31 pub fn try_get(&self, pallet: &str, extrinsic: &str) -> Option<&dyn ExtrinsicBuilder> {
32 let pallet = pallet.to_lowercase();
33 let extrinsic = extrinsic.to_lowercase();
34
35 self.0
36 .iter()
37 .find(|b| b.pallet() == pallet && b.extrinsic() == extrinsic)
38 .map(|b| b.as_ref())
39 }
40}
41
42/// Used by the benchmark to build signed extrinsics.
43///
44/// The built extrinsics only need to be valid in the first block
45/// who's parent block is the genesis block.
46/// This assumption simplifies the generation of the extrinsics.
47/// The signer should be one of the pre-funded dev accounts.
48pub trait ExtrinsicBuilder {
49 /// Name of the pallet this builder is for.
50 ///
51 /// Should be all lowercase.
52 fn pallet(&self) -> &str;
53
54 /// Name of the extrinsic this builder is for.
55 ///
56 /// Should be all lowercase.
57 fn extrinsic(&self) -> &str;
58
59 /// Builds an extrinsic.
60 ///
61 /// Will be called multiple times with increasing nonces.
62 fn build(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str>;
63}
64
65impl dyn ExtrinsicBuilder + '_ {
66 /// Name of this builder in CSV format: `pallet, extrinsic`.
67 pub fn name(&self) -> String {
68 format!("{}, {}", self.pallet(), self.extrinsic())
69 }
70}