### BenchmarkHelper Setup Method Implementation for () Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/pallet_mmr/trait.BenchmarkHelper.html An example implementation of the setup method for the unit type `()`. This demonstrates a minimal implementation. ```rust fn setup() {} ``` -------------------------------- ### Benchmark complexity parameter setup Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_sdk_frame/benchmarking/v1/macro.benchmarks.html Examples demonstrating how to define complexity parameters with ranges and associated setup logic. Ranges are inclusive on both sides. ```rust let x in 0 .. 10; ``` ```rust let x in 0 .. 10 => (); ``` ```rust let y in 0 .. 10 => setup(y?); ``` ```rust let z in 0 .. 10 => { let a = z * z / 5; let b = do_something(a)?; combine_into(z, b); } ``` -------------------------------- ### Benchmarking with Setup and Teardown Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/frame_benchmarking/macro.benchmarks.html Provides an example of a benchmark that includes setup logic before the core operation and potentially teardown logic after. This is useful for complex scenarios. ```rust #[benchmark] fn setup_teardown_benchmark() { // Setup let _ = T::Currency::deposit_creating(&T::Lookup::unverifiable(0), 1000000); let _ = T::Currency::deposit_creating(&T::Lookup::unverifiable(1), 1000000); // Core operation let _ = >::transfer(T::Lookup::unverifiable(0), T::Lookup::unverifiable(1), 1000); // Teardown (implicit or explicit) } ``` -------------------------------- ### Full benchmarks! macro example Source: https://paritytech.github.io/polkadot-sdk/master/frame_benchmarking/macro.benchmarks.html A comprehensive example demonstrating the `benchmarks!` macro with multiple dispatchable benchmarks, optional `where_clause`, complexity parameters, and setup code blocks. ```rust benchmarks! { where_clause { where T::A: From } // Optional line to give additional bound on `T`. // first dispatchable: foo; this is a user dispatchable and operates on a `u8` vector of // size `l` foo { let caller = account::(b"caller", 0, benchmarks_seed); let l in 1 .. MAX_LENGTH => initialize_l(l); }: _(RuntimeOrigin::Signed(caller), vec![0u8; l]) // second dispatchable: bar; this is a root dispatchable and accepts a `u8` vector of size // `l`. // In this case, we explicitly name the call using `bar` instead of `_`. bar { let l in 1 .. MAX_LENGTH => initialize_l(l); }: bar(RuntimeOrigin::Root, vec![0u8; l]) // third dispatchable: baz; this is a user dispatchable. It isn't dependent on length like the // other two but has its own complexity `c` that needs setting up. It uses `caller` (in the // pre-instancing block) within the code block. This is only allowed in the param instancers // of arms. baz1 { let caller = account::(b"caller", 0, benchmarks_seed); let c = 0 .. 10 => setup_c(&caller, c); }: baz(RuntimeOrigin::Signed(caller)) // this is a second benchmark of the baz dispatchable with a different setup. baz2 { let caller = account::(b"caller", 0, benchmarks_seed); let c = 0 .. 10 => setup_c_in_some_other_way(&caller, c); }: baz(RuntimeOrigin::Signed(caller)) // You may optionally specify the origin type if it can't be determined automatically like // this. baz3 { let caller = account::(b"caller", 0, benchmarks_seed); let l in 1 .. MAX_LENGTH => initialize_l(l); }: baz(RuntimeOrigin::Signed(caller), vec![0u8; l]) // this is benchmarking some code that is not a dispatchable. populate_a_set { let x in 0 .. 10_000; let mut m = Vec::::new(); for i in 0..x { m.insert(i); } }: { m.into_iter().collect::() } } ``` -------------------------------- ### Create a new Store with default configuration Source: https://paritytech.github.io/polkadot-sdk/master/node_testing/client/sc_executor/sp_wasm_interface/wasmtime/struct.Store.html Use `Store::default()` to create a store with default engine configuration. This is a convenient way to get started without explicit engine setup. ```rust let engine = Engine::default(); let my_state = MyApplicationState { my_state: 42, limits: StoreLimitsBuilder::new() .memory_size(1 << 20 /* 1 MB */) .instances(2) .build(), }; let mut store = Store::new(&engine, my_state); ``` -------------------------------- ### fn setup() Source: https://paritytech.github.io/polkadot-sdk/master/pallet_mmr/trait.BenchmarkHelper.html This is a required method for the BenchmarkHelper trait. It is used to set up benchmarking environments. ```APIDOC ## fn setup() ### Description Sets up the necessary environment for benchmarking. ### Method Associated function ### Parameters None ### Returns None ``` -------------------------------- ### Get Start of ParamRange Source: https://paritytech.github.io/polkadot-sdk/master/pallet_staking/benchmarking/struct.Linear.html Returns the inclusive starting number of this `ParamRange`. ```rust fn start(&self) -> u32 ``` -------------------------------- ### Get start of ParamRange Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/pallet_staking_async/benchmarking/struct.Linear.html Returns the inclusive starting number of the `ParamRange` for the `Linear` struct. ```rust fn start(&self) -> u32 ``` -------------------------------- ### Get Era Start Session Index Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_cli/service/westend_runtime/type.Staking.html Retrieves the session index at which a given era started. ```APIDOC ## pub fn eras_start_session_index(era_index: EncodeLikeEraIndex) -> Option where EncodeLikeEraIndex: EncodeLike, ### Description Get the session index at which the era starts for the last `Config::HistoryDepth` eras. ### Parameters * **era_index** (EncodeLikeEraIndex) - The era index. ### Returns * **Option** - The session index, if available. ``` -------------------------------- ### AvailabilityStoreSubsystem::start Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_cli/service/overseer/struct.AvailabilityStoreSubsystem.html Starts the AvailabilityStoreSubsystem, returning a SpawnedSubsystem. ```APIDOC ## fn start(self, ctx: Context) -> SpawnedSubsystem ### Description Start this `Subsystem` and return `SpawnedSubsystem`. ### Parameters - **self** (AvailabilityStoreSubsystem) - The subsystem instance. - **ctx** (Context) - The subsystem context. ``` -------------------------------- ### Babe API: Current Epoch Start Source: https://paritytech.github.io/polkadot-sdk/master/src/kitchensink_runtime/lib.rs.html Gets the starting slot of the current Babe epoch. ```rust fn current_epoch_start() -> sp_consensus_babe::Slot { Babe::current_epoch_start() } ``` -------------------------------- ### Getting the Start of a RangeInclusive Source: https://paritytech.github.io/polkadot-sdk/master/sp_std/ops/struct.RangeInclusive.html Demonstrates retrieving the lower bound of a RangeInclusive using the `start()` method. ```rust assert_eq!((3..=5).start(), &3); ``` -------------------------------- ### Trie Write Benchmark Setup Source: https://paritytech.github.io/polkadot-sdk/master/src/node_bench/trie.rs.html Implements the `setup` method for `TrieWriteBenchmarkDescription`. It generates a temporary database, populates it with random key-value pairs (including warmup keys), and builds an initial Trie. ```rust impl core::BenchmarkDescription for TrieWriteBenchmarkDescription { fn path(&self) -> Path { let mut path = Path::new(&["trie", "write"]); path.push(&format!("{}", self.database_size)); path } fn setup(self: Box) -> Box { let mut database = TempDatabase::new(); let mut rng = rand::thread_rng(); let warmup_prefix = KUSAMA_STATE_DISTRIBUTION.key(&mut rng); let mut key_values = KeyValues::new(); let mut warmup_keys = KeyValues::new(); let every_x_key = self.database_size.keys() / SAMPLE_SIZE; for idx in 0..self.database_size.keys() { let kv = ( KUSAMA_STATE_DISTRIBUTION.key(&mut rng).to_vec(), KUSAMA_STATE_DISTRIBUTION.value(&mut rng), ); if idx % every_x_key == 0 { // warmup keys go to separate tree with high prob let mut actual_warmup_key = warmup_prefix.clone(); actual_warmup_key[16..].copy_from_slice(&kv.0[16..]); warmup_keys.push((actual_warmup_key.clone(), kv.1.clone())); key_values.push((actual_warmup_key.clone(), kv.1.clone())); } key_values.push(kv) } assert_eq!(warmup_keys.len(), SAMPLE_SIZE); let root = generate_trie(database.open(self.database_type), key_values); Box::new(TrieWriteBenchmark { database, root, warmup_keys, database_type: self.database_type, }) } fn name(&self) -> Cow<'static, str> { format!( "Trie write benchmark({:?} database ({} keys), db_type = {:?})", self.database_size, pretty_print(self.database_size.keys()), self.database_type, ) .into() } } ``` -------------------------------- ### Basic Test Setup with Testing Prelude Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_sdk_frame/testing_prelude/index.html Import the entire testing prelude to bring in common FRAME testing utilities. This is the typical starting point for setting up tests. ```rust use polkadot_sdk_frame::testing_prelude::*; // rest of your test setup. ``` -------------------------------- ### Get Start of Linear Range Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/benchmarking/prelude/struct.Linear.html Returns the inclusive starting number of the `ParamRange` for the `Linear` struct. ```rust fn start(&self) -> u32; ``` -------------------------------- ### Get the starting index of the window Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_node_subsystem/overseer/gen/futures/io/struct.Window.html Returns the current starting index of the window within the underlying buffer. ```rust pub fn start(&self) -> usize ``` -------------------------------- ### instance Method - BenchmarkingSetup Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/frame_benchmarking/v1/v2/trait.BenchmarkingSetup.html Implement this method to set up the necessary storage and prepare a closure for running the actual benchmark logic. This is the core method for executing a benchmark instance. ```rust fn instance( &self, recording: &mut impl Recording, components: &[(BenchmarkParameter, u32)], verify: bool, ) -> Result<(), BenchmarkError>; ``` -------------------------------- ### Get Window Start Index Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_node_subsystem/gen/futures/io/struct.Window.html Returns the starting index of the current window within the underlying buffer. ```rust pub fn start(&self) -> usize ``` -------------------------------- ### BenchmarkingSetup::instance Method Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/benchmarking/prelude/trait.BenchmarkingSetup.html Implement this method to set up the necessary storage and prepare a closure for running the benchmark. This is the primary method for executing a benchmark instance. ```rust fn instance( &self, recording: &mut impl Recording, components: &[(BenchmarkParameter, u32)], verify: bool, ) -> Result<(), BenchmarkError> ``` -------------------------------- ### ProvisionerSubsystem::start Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_node_core_provisioner/struct.ProvisionerSubsystem.html Starts the ProvisionerSubsystem within a given context, returning a SpawnedSubsystem. ```APIDOC ## fn start(self, ctx: Context) -> SpawnedSubsystem ### Description Start this `Subsystem` and return `SpawnedSubsystem`. ### Parameters #### Path Parameters - **ctx** (Context) - Required - The context for the subsystem. ### Return Value - **SpawnedSubsystem** - The spawned subsystem. ``` -------------------------------- ### Start a simple GET request Source: https://paritytech.github.io/polkadot-sdk/master/sp_runtime/offchain/http/struct.Request.html Use this function to initiate a simple GET request. It requires the URL as a parameter. ```rust pub fn get(url: &'a str) -> Self ``` -------------------------------- ### CandidateBackingSubsystem::start Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_node_core_backing/struct.CandidateBackingSubsystem.html Starts the CandidateBackingSubsystem within a given context, returning a SpawnedSubsystem. ```APIDOC ## fn start(self, ctx: Context) -> SpawnedSubsystem ### Description Start this `Subsystem` and return `SpawnedSubsystem`. ### Parameters - **self** - The `CandidateBackingSubsystem` instance. - **ctx** (Context) - The context in which to start the subsystem. This context must implement `CandidateBackingContextTrait` and `SubsystemContext`. ### Returns - SpawnedSubsystem - The spawned subsystem. ``` -------------------------------- ### Implementors of Get Trait Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_sdk_frame/weights_prelude/trait.Get.html Lists various types that implement the Get trait, providing concrete examples of its usage. ```APIDOC ## Implementors§ ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::rococo_runtime::BrokerPot ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::westend_runtime::BrokerPot ### impl Get for HintNumVariants ### impl Get for DefaultForRound ### impl Get for MaybeSignedPhase ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::westend_runtime::AssetHubLocation ### impl Get for NextFeeMultiplierOnEmpty ### impl Get> for AllAssets ### impl Get<>::Balance> for ActiveIssuanceOf where C: Currency, ### impl Get<>::Balance> for TotalIssuanceOf where C: Currency, ### impl Get for yet_another_parachain_runtime::bp_polkadot_core::ExtrinsicBaseWeight where I: From, ### impl Get for MaxAssetTransferFilters where I: From, ### impl Get for MaxDispatchErrorLen where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v3::MaxPalletNameLen where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v3::MaxPalletsInfo where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v4::MaxPalletNameLen where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v4::MaxPalletsInfo where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v5::MaxPalletNameLen where I: From, ### impl Get for yet_another_parachain_runtime::emulated_integration_tests_common::impls::xcm::v5::MaxPalletsInfo where I: From, ### impl Get for yet_another_parachain_runtime::pallet_contracts::pallet::config_preludes::CodeHashLockupDepositPercent where I: From, ### impl Get for DefaultDepositLimit where I: From, ### impl Get for yet_another_parachain_runtime::pallet_contracts::pallet::config_preludes::DepositPerByte where I: From, ### impl Get for yet_another_parachain_runtime::pallet_contracts::pallet::config_preludes::DepositPerItem where I: From, ### impl Get for MaxDelegateDependencies where I: From, ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::rococo_runtime::BlockExecutionWeight where I: From, ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::rococo_runtime::ExtrinsicBaseWeight where I: From, ### impl Get for yet_another_parachain_runtime::polkadot_cli::service::westend_runtime::BlockExecutionWeight where I: From, ``` -------------------------------- ### Setup Benchmarking Client Configuration Source: https://paritytech.github.io/polkadot-sdk/master/src/node_testing/bench.rs.html Configures and initializes a client suitable for benchmarking. This includes setting up the database configuration with specific cache sizes and pruning modes, initializing a Wasm executor with a pooling strategy, and building the client itself. ```rust fn bench_client( database_type: DatabaseType, dir: &std::path::Path, keyring: &BenchKeyring, ) -> (Client, std::sync::Arc, TaskExecutor) { let db_config = sc_client_db::DatabaseSettings { trie_cache_maximum_size: Some(16 * 1024 * 1024), state_pruning: Some(PruningMode::ArchiveAll), source: database_type.into_settings(dir.into()), blocks_pruning: sc_client_db::BlocksPruning::KeepAll, metrics_registry: None, }; let task_executor = TaskExecutor::new(); let backend = sc_service::new_db_backend(db_config).expect("Should not fail"); let executor = sc_executor::WasmExecutor::builder() .with_execution_method(WasmExecutionMethod::Compiled { instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, }) .build(); let client_config = sc_service::ClientConfig::default(); let genesis_block_builder = sc_service::GenesisBlockBuilder::new( keyring.as_storage_builder(), !client_config.no_genesis, backend.clone(), executor.clone(), ) .expect("Failed to create genesis block builder"); let client = sc_service::new_client( backend.clone(), executor.clone(), genesis_block_builder, None, None, ExecutionExtensions::new(None, Arc::new(executor)), Box::new(task_executor.clone()), None, None, client_config, ) .expect("Should not fail"); (client, backend, task_executor) } ``` -------------------------------- ### Opts Initialization and Configuration Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_node_subsystem_util/metrics/prometheus/struct.Opts.html Demonstrates how to create and configure an Opts instance using its associated methods. ```APIDOC ## impl Opts ### Constructor #### pub fn new(name: S1, help: S2) -> Opts where S1: Into, S2: Into, `new` creates the Opts with the `name` and `help` arguments. ``` ```APIDOC ### Configuration Methods #### pub fn namespace(self, namespace: S) -> Opts where S: Into, `namespace` sets the namespace. ``` ```APIDOC #### pub fn subsystem(self, subsystem: S) -> Opts where S: Into, `subsystem` sets the sub system. ``` ```APIDOC #### pub fn const_labels(self, const_labels: HashMap) -> Opts `const_labels` sets the const labels. ``` ```APIDOC #### pub fn const_label(self, name: S1, value: S2) -> Opts where S1: Into, S2: Into, `const_label` adds a const label. ``` ```APIDOC #### pub fn variable_labels(self, variable_labels: Vec) -> Opts `variable_labels` sets the variable labels. ``` ```APIDOC #### pub fn variable_label(self, name: S) -> Opts where S: Into, `variable_label` adds a variable label. ``` -------------------------------- ### Get Start of ParamRange Source: https://paritytech.github.io/polkadot-sdk/master/frame_benchmarking/v2/struct.Linear.html Returns the inclusive starting number of the `ParamRange` for a `Linear` struct. This corresponds to the `A` generic parameter. ```rust fn start(&self) -> u32 ``` -------------------------------- ### get_value Source: https://paritytech.github.io/polkadot-sdk/master/cumulus_test_service/type.AnnounceBlockFn.html Start getting a value from the DHT. ```APIDOC ## fn get_value(&self, key: &Key) ``` -------------------------------- ### Basic Test Setup with testing_prelude Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/testing_prelude/index.html A typical test setup begins by importing the entire testing prelude. This brings in essential components for FRAME testing. ```rust use polkadot_sdk_frame::testing_prelude::*; // rest of your test setup. ``` -------------------------------- ### Initialize Test Environment Source: https://paritytech.github.io/polkadot-sdk/master/xcm_simulator/trait.TestExt.html Use `new_ext` to set up the testing environment before running simulations. ```rust fn new_ext() -> TestExternalities; ``` -------------------------------- ### Get size of pointed-to value Source: https://paritytech.github.io/polkadot-sdk/master/sp_std/mem/fn.size_of_val_raw.html Use `size_of_val_raw` to get the size of a value when its type might not have a statically known size. This example demonstrates getting the size of a slice. ```rust #![feature(layout_for_ptr)] use std::mem; assert_eq!(4, size_of_val(&5i32)); let x: [u8; 13] = [0; 13]; let y: &[u8] = &x; assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); ``` -------------------------------- ### start() Method Source: https://paritytech.github.io/polkadot-sdk/master/pallet_election_provider_multi_block/verifier/trait.AsynchronousVerifier.html Initiates an asynchronous verification process. It returns Ok(()) if successful or Err if a verification is already in progress. The SolutionDataProvider must be ready before calling this method. ```rust fn start() -> Result<(), &'static str>; ``` -------------------------------- ### Example Runtime Setup Source: https://paritytech.github.io/polkadot-sdk/master/src/pallet_example_authorization_tx_extension/lib.rs.html This snippet shows the configuration for an example runtime, including necessary pallets and traits for the authorization extension. ```rust pub trait Config: frame_system::Config { /// The aggregated origin which the dispatch will take. type RuntimeOrigin: OriginTrait + From + IsType<::RuntimeOrigin>; /// The caller origin, overarching type of all pallets origins. type PalletsOrigin: From> + TryInto, Error = Self::PalletsOrigin>; } #[pallet::pallet] pub struct Pallet(_); /// Origin that this pallet can authorize. For the purposes of this example, it's just two /// accounts that own something together. #[pallet::origin] #[derive( ``` -------------------------------- ### Get Epoch Start Slot Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/sc_consensus_babe/struct.Epoch.html Retrieves the starting slot number for the current epoch. This is part of the Epoch trait implementation. ```rust fn start_slot(&self) -> Slot ``` -------------------------------- ### CandidateBackingSubsystem::start Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_service/overseer/struct.CandidateBackingSubsystem.html Starts the CandidateBackingSubsystem. ```APIDOC ## fn start(self, ctx: Context) -> SpawnedSubsystem ### Description Start this `Subsystem` and return `SpawnedSubsystem`. ### Parameters * **ctx** (Context) - The context for the subsystem. ### Returns * SpawnedSubsystem - The spawned subsystem. ``` -------------------------------- ### Client::new Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/sc_service/client/struct.Client.html Creates a new Substrate Client instance with the provided configuration and components. ```APIDOC ## Client::new ### Description Creates new Substrate Client with given blockchain and code executor. ### Signature ```rust pub fn new( backend: Arc, executor: E, spawn_handle: Box, genesis_block_builder: G, fork_blocks: Option::Header as Header>::Number, ::Hash)>>, bad_blocks: Option::Hash>>, prometheus_registry: Option, telemetry: Option, config: ClientConfig, ) -> Result, Error> where G: BuildGenesisBlock>::BlockImportOperation>, E: Clone, B: 'static, ``` ### Parameters * `backend`: The backend implementation for block storage. * `executor`: The call executor for running runtime code. * `spawn_handle`: A handle for spawning tasks. * `genesis_block_builder`: A builder for the genesis block. * `fork_blocks`: Optional list of fork blocks to consider. * `bad_blocks`: Optional set of known bad block hashes. * `prometheus_registry`: Optional Prometheus registry for metrics. * `telemetry`: Optional telemetry handle for sending data. * `config`: Client configuration. ### Returns A `Result` containing the new `Client` instance or an `Error` if creation fails. ``` -------------------------------- ### Get Start of Linear Range Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/polkadot_sdk_frame/benchmarking/prelude/struct.Linear.html Implement the `ParamRange` trait for `Linear` to provide the inclusive starting number of the parameter range. ```rust fn start(&self) -> u32 ``` -------------------------------- ### Setup Block Construction Benchmark Source: https://paritytech.github.io/polkadot-sdk/master/src/node_bench/construct.rs.html Initializes the benchmark environment by creating a database, generating transactions based on specified content type and size, and preparing the client. This is called before running the benchmark. ```rust fn setup(self: Box) -> Box { let mut extrinsics: Vec> = Vec::new(); let mut bench_db = BenchDb::with_key_types(self.database_type, 50_000, self.key_types); let client = bench_db.client(); let content_type = self.block_type.to_content(self.size.transactions()); for transaction in bench_db.block_content(content_type, &client) { extrinsics.push(Arc::new(transaction.into())); } Box::new(ConstructionBenchmark { database: bench_db, transactions: Transactions(extrinsics), }) } // ... (rest of the impl) ``` -------------------------------- ### Slot::timestamp Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/emulated_integration_tests_common/xcm_emulator/struct.Slot.html Gets the timestamp of the start of the slot. ```APIDOC ## pub fn timestamp(&self, slot_duration: SlotDuration) -> Option ### Description Timestamp of the start of the slot. Returns `None` if would overflow for given `SlotDuration`. ### Parameters - **slot_duration** (SlotDuration) - The duration of a slot. ``` -------------------------------- ### Test Database Setup Source: https://paritytech.github.io/polkadot-sdk/master/src/polkadot_node_core_dispute_coordinator/db/v1.rs.html Creates an in-memory database backend for testing purposes. Initializes the `DbBackend` with a default configuration and metrics. ```rust fn make_db() -> DbBackend { let db = kvdb_memorydb::create(1); let db = polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter::new(db, &[0]); let store = Arc::new(db); let config = ColumnConfiguration { col_dispute_data: 0 }; DbBackend::new(store, config, Metrics::default()) } ``` -------------------------------- ### Example Runtime Setup with Transaction Extensions Source: https://paritytech.github.io/polkadot-sdk/master/pallet_example_authorization_tx_extension/index.html Defines the transaction extension pipeline for the example runtime, including signature verification, nonce checks, coownership authorization, and other essential transaction checks. This setup is crucial for enabling custom transaction authorization logic. ```rust mod example_runtime { use super::*; /// Our `TransactionExtension` fit for general transactions. pub type TxExtension = ( // Validate the signature of regular account transactions (substitutes the old signed // transaction). VerifySignature, // Nonce check (and increment) for the caller. CheckNonce, // If activated, will mutate the origin to a `pallet_coownership` origin of 2 accounts that own something. AuthorizeCoownership, // Some other extensions that we want to run for every possible origin and we want captured in any and all signature and authorization schemes (such as the traditional account signature or the double signature in `pallet_coownership`). CheckGenesis, CheckTxVersion, CheckEra, ); /// Convenience type to more easily construct the signature to be signed in case /// `AuthorizeCoownership` is activated. pub type InnerTxExtension = (CheckGenesis, CheckTxVersion, CheckEra); pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Header = generic::Header; pub type Block = generic::Block; pub type AccountId = <::Signer as IdentifyAccount>::AccountId; pub type Signature = MultiSignature; pub type BlockNumber = u32; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( pub enum Runtime { System: frame_system, VerifySignaturePallet: pallet_verify_signature, Assets: pallet_assets, Coownership: pallet_coownership, } ); #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Runtime { type AccountId = AccountId; type Block = Block; type Lookup = IdentityLookup; } impl pallet_verify_signature::Config for Runtime { type Signature = MultiSignature; type AccountIdentifier = MultiSigner; type WeightInfo = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } /// Type that enables any pallet to ask for a coowner origin. pub struct EnsureCoowner; impl EnsureOrigin for EnsureCoowner { type Success = (AccountId, AccountId); fn try_origin(o: RuntimeOrigin) -> Result { match o.clone().into() { Ok(pallet_coownership::Origin::::Coowners(first, second)) = => Ok((first, second)), _ => Err(o), } } #[cfg(feature = "runtime-benchmarks")] fn try_successful_origin() -> Result { unimplemented!() } } impl pallet_assets::Config for Runtime { type CoownerOrigin = EnsureCoowner; } impl pallet_coownership::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; } } ``` -------------------------------- ### start() Method Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/pallet_election_provider_multi_block/verifier/trait.AsynchronousVerifier.html Initiates an asynchronous verification process. Returns an error if a verification is already in progress. The SolutionDataProvider must be ready before calling this method. ```rust fn start() -> Result<(), &'static str>; ``` -------------------------------- ### start_bound() Examples Source: https://paritytech.github.io/polkadot-sdk/master/sp_std/ops/trait.RangeBounds.html Demonstrates how to use the `start_bound` method to retrieve the start boundary of a range. Works with unbounded and included start bounds. ```rust use std::ops::Bound::*; use std::ops::RangeBounds; assert_eq!((..10).start_bound(), Unbounded); assert_eq!((3..10).start_bound(), Included(&3)); ``` -------------------------------- ### Initialization and Configuration Creation Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/cumulus_client_cli/struct.PurgeChainCmd.html Methods for initializing the substrate environment and creating a runtime configuration. ```APIDOC ## fn init( &self, support_url: &String, impl_version: &String, logger_hook: F, ) -> Result<(), Error> where F: FnOnce(&mut LoggerBuilder), Initialize substrate. This must be done only once per process. Read more ``` ```APIDOC ## fn create_configuration( &self, cli: &C, tokio_handle: Handle, ) -> Result where C: SubstrateCli, Create a Configuration object from the current object ``` -------------------------------- ### Get Trait Implementations Source: https://paritytech.github.io/polkadot-sdk/master/frame_election_provider_support/trait.Get.html Examples of how the Get trait is implemented for various types, demonstrating its versatility in accessing different kinds of data. ```APIDOC ## Implementations on Foreign Types ### impl Get<>::Balance> for ActiveIssuanceOf where C: Currency #### fn get() -> >::Balance ### impl Get<>::Balance> for TotalIssuanceOf where C: Currency #### fn get() -> >::Balance ### impl Get for BlockExecutionWeight where I: From #### fn get() -> I ### impl Get for ExtrinsicBaseWeight where I: From #### fn get() -> I ### impl Get for ParityDbWeight where I: From #### fn get() -> I ### impl Get for RocksDbWeight where I: From #### fn get() -> I ### impl Get for TestBlockHashCount where I: From, C: Get #### fn get() -> I ### impl Get for KeyLenOf> where Prefix: StorageInstance, Hasher1: StorageHasher, Hasher2: StorageHasher, Key1: MaxEncodedLen, Key2: MaxEncodedLen #### fn get() -> u32 ### impl Get for KeyLenOf> where Prefix: StorageInstance, Hasher: StorageHasher, Key: FullCodec + MaxEncodedLen #### fn get() -> u32 ### impl Get for VariantCountOf where T: VariantCount #### fn get() -> u32 ### impl Get for () where T: Default #### fn get() -> T ### impl Get for ClassCountOf where P: Polling #### fn get() -> u32 ``` -------------------------------- ### Initialization and Configuration Creation Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/frame_benchmarking_cli/enum.BenchmarkCmd.html Methods for initializing the substrate environment and creating configuration objects. ```APIDOC ## init ### Description Initialize substrate. This must be done only once per process. ### Method `init(&self, support_url: &String, impl_version: &String, logger_hook: F) -> Result<(), Error>` where F: FnOnce(&mut LoggerBuilder) ## create_configuration ### Description Create a Configuration object from the current object. ### Method `create_configuration(&self, cli: &C, tokio_handle: Handle) -> Result` where C: SubstrateCli ``` -------------------------------- ### Get Current Epoch Start Slot Source: https://paritytech.github.io/polkadot-sdk/master/src/pallet_babe/lib.rs.html Retrieves the start slot of the current epoch. This is guaranteed to be correct after the initialization of the first block. ```rust /// Finds the start slot of the current epoch. /// /// Only guaranteed to give correct results after `initialize` of the first /// block in the chain (as its result is based off of `GenesisSlot`). pub fn current_epoch_start() -> Slot { sp_consensus_babe::epoch_start_slot( EpochIndex::::get(), GenesisSlot::::get(), T::EpochDuration::get(), ) } ``` -------------------------------- ### Complexity parameter instancing examples Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/benchmarking/v1/macro.benchmarks.html Illustrates different ways to define complexity parameters and their associated setup logic within benchmark definitions. ```rust // These two are equivalent: let x in 0 .. 10; let x in 0 .. 10 => (); ``` ```rust // This one calls a setup function and might return an error (which would be terminal). let y in 0 .. 10 => setup(y?); ``` ```rust // This one uses a code block to do lots of stuff: let z in 0 .. 10 => { let a = z * z / 5; let b = do_something(a)?; combine_into(z, b); } ``` -------------------------------- ### Get Start of ParamRange - Linear Source: https://paritytech.github.io/polkadot-sdk/master/pallet_staking_async/benchmarking/v1/v2/struct.Linear.html Returns the inclusive starting number of this `ParamRange`. This method is part of the `ParamRange` trait implementation for `Linear`. ```rust fn start(&self) -> u32 ``` -------------------------------- ### Benchmark Instantiate Setup and Execution Source: https://paritytech.github.io/polkadot-sdk/master/src/pallet_revive/benchmarking.rs.html Prepares for and benchmarks contract instantiation. It configures parameters like value transfer, deposit, input data, and salt, then executes the `bench_instantiate` function. ```rust let code = VmBinaryModule::dummy(); let hash = Contract::::with_index(1, VmBinaryModule::dummy(), vec![])?.info()?.code_hash; let hash_bytes = hash.encode(); let value: BalanceOf = (1_000_000u32 * t).into(); let dust = 100u32 * d; let evm_value = Pallet::::convert_native_to_evm(BalanceWithDust::new_unchecked::(value, dust)); let value_bytes = evm_value.encode(); let value_len = value_bytes.len() as u32; let deposit: BalanceOf = BalanceOf::::max_value(); let deposit_bytes = Into::::into(deposit).encode(); let deposit_len = deposit_bytes.len() as u32; let mut setup = CallSetup::::default(); setup.set_origin(ExecOrigin::from_account_id(setup.contract().account_id.clone())); setup.set_balance(value + 1u32.into() + (Pallet::::min_balance() * 2u32.into())); let account_id = &setup.contract().account_id.clone(); let (mut ext, _) = setup.ext(); let mut runtime = pvm::Runtime::<_, [u8]>::new(&mut ext, vec![]); let input = vec![42u8; i as _]; let input_len = hash_bytes.len() as u32 + input.len() as u32; let salt = [42u8; 32]; let deployer = T::AddressMapper::to_address(&account_id); let addr = crate::address::create2(&deployer, &code.code, &input, &salt); let mut memory = memory!(hash_bytes, input, deposit_bytes, value_bytes, salt,); let mut offset = { let mut current = 0u32; move |after: u32| { current += after; current } }; assert!(AccountInfoOf::::get(&addr).is_none()); let result; #[block] { result = runtime.bench_instantiate( memory.as_mut_slice(), u64::MAX, // ref_time_limit u64::MAX, // proof_size_limit pack_hi_lo(offset(input_len), offset(deposit_len)), // deposit_ptr + value_ptr ``` -------------------------------- ### Get Start of Linear Range Source: https://paritytech.github.io/polkadot-sdk/master/pallet_staking_async/benchmarking/struct.Linear.html Returns the inclusive starting number of the `ParamRange`. This is used to define the lower bound of a benchmarking variable. ```rust fn start(&self) -> u32; ``` -------------------------------- ### Initialization and Configuration Creation Source: https://paritytech.github.io/polkadot-sdk/master/sc_cli/commands/struct.ChainInfoCmd.html Methods for initializing the substrate environment and creating a configuration object. ```APIDOC ## Initialization and Configuration Creation ### `init(support_url: &String, impl_version: &String, logger_hook: F) -> Result<()>` **Description**: Initialize substrate. This must be done only once per process. ### `create_configuration(cli: &C, tokio_handle: Handle) -> Result` **Description**: Create a Configuration object from the current object. ``` -------------------------------- ### get_providers Source: https://paritytech.github.io/polkadot-sdk/master/cumulus_test_service/type.AnnounceBlockFn.html Start getting the list of providers for `key` on the DHT. ```APIDOC ## fn get_providers(&self, key: Key) ``` -------------------------------- ### Witness Backend Setup Source: https://paritytech.github.io/polkadot-sdk/master/src/substrate_test_runtime/lib.rs.html Initializes a memory-based trie database and inserts key-value pairs for testing state proofs. ```rust let mut root = crate::Hash::default(); let mut mdb = sp_trie::MemoryDB::::default(); { let mut trie = sp_trie::trie_types::TrieDBMutBuilderV1::new(&mut mdb, &mut root).build(); trie.insert(b"value3", &[142]).expect("insert failed"); trie.insert(b"value4", &[124]).expect("insert failed"); }; (mdb, root) ``` -------------------------------- ### v1 Benchmark Example Source: https://paritytech.github.io/polkadot-sdk/master/pallet_staking/benchmarking/v1/v2/index.html An example of a benchmark defined using the v1 benchmarking framework. This includes setup, extrinsic call, and verification steps. ```rust #![cfg(feature = "runtime-benchmarks")] use frame_benchmarking::v1::*; benchmarks! { // first dispatchable: this is a user dispatchable and operates on a `u8` vector of // size `l` foo { let caller = funded_account::(b"caller", 0); let l in 1 .. 10_000 => initialize_l(l); }: { _(RuntimeOrigin::Signed(caller), vec![0u8; l]) } verify { assert_last_event::(Event::FooExecuted { result: Ok(()) }.into()); } } ``` -------------------------------- ### Test Prelude Setup Source: https://paritytech.github.io/polkadot-sdk/master/src/frame_remote_externalities/lib.rs.html Provides necessary imports and helper functions for setting up tests, including block types and logger initialization. ```rust pub(crate) use super::*; pub(crate) use sp_runtime::testing::{Block as RawBlock, MockCallU64}; pub(crate) type UncheckedXt = sp_runtime::testing::TestXt; pub(crate) type Block = RawBlock; pub(crate) fn init_logger() { sp_tracing::try_init_simple(); } ``` -------------------------------- ### Get Start Slot of ViableEpochDescriptor Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/sc_consensus_epochs/enum.ViableEpochDescriptor.html Retrieves the starting slot number for a given epoch descriptor. This method is available for both UnimportedGenesis and Signaled variants. ```rust pub fn start_slot(&self) -> ::Slot ``` -------------------------------- ### Start Providing Source: https://paritytech.github.io/polkadot-sdk/master/src/sc_network/litep2p/discovery.rs.html Begins providing a given key on the DHT. ```APIDOC ## start_providing ### Description Starts providing a given key on the DHT, making its associated value discoverable by other nodes. This operation is performed with a specified quorum threshold. ### Method Signature `pub async fn start_providing(&mut self, key: KademliaKey) -> QueryId` ### Parameters - **key** (KademliaKey) - The key to start providing. ### Returns - **QueryId** - An identifier for the initiated operation. ``` -------------------------------- ### Get a mutable iterator over BTreeMap values Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/sp_npos_elections/type.SupportMap.html Illustrates how to get a mutable iterator over the values in a BTreeMap, allowing in-place modification. Values can be appended to, for example. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### start Source: https://paritytech.github.io/polkadot-sdk/master/frame_benchmarking/trait.Recording.html Start the benchmark. ```APIDOC ## start ### Description Start the benchmark. ### Method `start` ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Get mutable BTreeMap values Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_primitives/v9/type.TransposedClaimQueue.html Demonstrates how to get a mutable iterator over the values of a BTreeMap, allowing in-place modification. This example appends '!' to each string value. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### Setup and Teardown in Benchmarks Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/frame_benchmarking/v1/macro.benchmarks.html The `setup` and `teardown` blocks within `#[benchmark]` are optional and run before and after the benchmarked code, respectively. They are useful for preparing the state or cleaning up. ```rust #[benchmark] fn transfer_with_setup() { // Setup: Prepare initial state let caller = T::Currency::deposit_creating(&self.caller); let recipient = T::Currency::deposit_creating(&self.recipient); // Benchmark code #[block = 100] for _ in 0..100 { let _ = T::Currency::transfer(&caller, &recipient, 1000000); } // Teardown: Optional cleanup (not shown here, but would follow benchmark code) ``` -------------------------------- ### Client::new Source: https://paritytech.github.io/polkadot-sdk/master/polkadot_test_client/client/struct.Client.html Creates a new Substrate Client instance. This is the primary constructor for setting up a client for testing purposes. ```APIDOC ## Client::new ### Description Creates new Substrate Client with given blockchain and code executor. ### Method `pub fn new(... ) -> Result, Error>` ### Parameters - `backend`: `Arc` - The backend for the blockchain. - `executor`: `E` - The call executor. - `spawn_handle`: `Box` - Handle for spawning tasks. - `genesis_block_builder`: `G` where `G: BuildGenesisBlock>::BlockImportOperation>` - Builder for the genesis block. - `fork_blocks`: `Option::Header as Header>::Number, ::Hash)>>` - Optional list of blocks to fork from. - `bad_blocks`: `Option::Hash>>` - Optional set of bad block hashes. - `prometheus_registry`: `Option` - Optional Prometheus registry. - `telemetry`: `Option` - Optional telemetry handle. - `config`: `ClientConfig` - Client configuration. ### Returns - `Result, Error>` - A new `Client` instance or an `Error`. ``` -------------------------------- ### on_start Method Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/sc_consensus/block_import/trait.JustificationImport.html Called when the import queue starts. Returns a list of justifications to request from the network. ```rust fn on_start<'life0, 'async_trait>( &'life0 mut self, ) -> Pin::Hash, <::Header as Header>::Number)>> + Send + 'async_trait>> where 'life0: 'async_trait, Self: 'async_trait; ``` -------------------------------- ### Get Start Value of Linear Range Source: https://paritytech.github.io/polkadot-sdk/master/yet_another_parachain_runtime/frame_benchmarking/v1/v2/struct.Linear.html Implement the `ParamRange` trait for `Linear` to define the inclusive starting point of the benchmarking variable's range. ```rust fn start(&self) -> u32 ``` -------------------------------- ### Get Active Era Start Session Index Source: https://paritytech.github.io/polkadot-sdk/master/src/pallet_staking_async/pallet/impls.rs.html Retrieves the session index for the start of the active era. This function is a simple pass-through to the Rotator pallet. ```rust fn active_era_start_session_index() -> SessionIndex { Rotator::::active_era_start_session_index() } ```