snapshot before rebranding

This commit is contained in:
2025-12-14 07:37:21 +03:00
parent 5520d491a5
commit 09735eb97a
1752 changed files with 58116 additions and 15986 deletions
@@ -0,0 +1,59 @@
[package]
name = "pezpallet-xcm-benchmarks"
authors.workspace = true
edition.workspace = true
license.workspace = true
version = "7.0.0"
description = "Benchmarks for the XCM pallet"
homepage.workspace = true
repository.workspace = true
documentation = "https://docs.rs/pezpallet-xcm-benchmarks"
publish = false
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { workspace = true }
pezframe-benchmarking = { workspace = true }
pezframe-support = { workspace = true }
pezframe-system = { workspace = true }
scale-info = { features = ["derive"], workspace = true }
pezsp-io = { workspace = true }
pezsp-runtime = { workspace = true }
xcm = { workspace = true }
xcm-builder = { workspace = true }
xcm-executor = { workspace = true }
[dev-dependencies]
pezpallet-balances = { workspace = true, default-features = true }
pezsp-tracing = { workspace = true, default-features = true }
xcm = { workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"codec/std",
"pezframe-benchmarking/std",
"pezframe-support/std",
"pezframe-system/std",
"scale-info/std",
"pezsp-io/std",
"pezsp-runtime/std",
"xcm-builder/std",
"xcm-executor/std",
]
runtime-benchmarks = [
"pezframe-benchmarking/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezpallet-balances/runtime-benchmarks",
"pezsp-io/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
"xcm/runtime-benchmarks",
]
@@ -0,0 +1,339 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use crate::{account_and_location, new_executor, AssetTransactorOf, EnsureDelivery, XcmCallOf};
use alloc::{vec, vec::Vec};
use pezframe_benchmarking::{benchmarks_instance_pallet, BenchmarkError, BenchmarkResult};
use pezframe_support::{
pezpallet_prelude::Get,
traits::fungible::{Inspect, Mutate},
weights::Weight,
BoundedVec,
};
use pezsp_runtime::traits::Bounded;
use xcm::latest::{prelude::*, AssetTransferFilter, MAX_ITEMS_IN_ASSETS};
use xcm_executor::traits::{ConvertLocation, FeeReason, TransactAsset};
benchmarks_instance_pallet! {
where_clause { where
<
<
T::TransactAsset
as
Inspect<T::AccountId>
>::Balance
as
TryInto<u128>
>::Error: core::fmt::Debug,
}
withdraw_asset {
let (sender_account, sender_location) = account_and_location::<T>(1);
let worst_case_holding = T::worst_case_holding(0);
let asset = T::get_asset();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location, None).unwrap();
let mut executor = new_executor::<T>(sender_location);
executor.set_holding(worst_case_holding.into());
let instruction = Instruction::<XcmCallOf<T>>::WithdrawAsset(vec![asset.clone()].into());
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
assert!(executor.holding().ensure_contains(&vec![asset].into()).is_ok());
}
transfer_asset {
let (sender_account, sender_location) = account_and_location::<T>(1);
let asset = T::get_asset();
let assets: Assets = vec![asset.clone()].into();
// this xcm doesn't use holding
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert_location(&dest_location).unwrap();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location, None).unwrap();
// We deposit the asset twice so we have enough for ED after transferring
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location, None).unwrap();
let mut executor = new_executor::<T>(sender_location);
let instruction = Instruction::TransferAsset { assets, beneficiary: dest_location };
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
}
transfer_reserve_asset {
let (sender_account, sender_location) = account_and_location::<T>(1);
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert_location(&dest_location).unwrap();
let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&dest_location,
FeeReason::TransferReserveAsset
);
let asset = T::get_asset();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location, None).unwrap();
// We deposit the asset twice so we have enough for ED after transferring
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location, None).unwrap();
let assets: Assets = vec![asset].into();
let mut executor = new_executor::<T>(sender_location);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
let instruction = Instruction::TransferReserveAsset {
assets,
dest: dest_location,
xcm: Xcm::new()
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
// TODO: Check sender queue is not empty. #4426
}
reserve_asset_deposited {
let (trusted_reserve, transferable_reserve_asset) = T::TrustedReserve::get()
.ok_or(BenchmarkError::Override(
BenchmarkResult::from_weight(Weight::MAX)
))?;
let assets: Assets = vec![ transferable_reserve_asset ].into();
let mut executor = new_executor::<T>(trusted_reserve);
let instruction = Instruction::ReserveAssetDeposited(assets.clone());
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
assert!(executor.holding().ensure_contains(&assets).is_ok());
}
initiate_reserve_withdraw {
let (sender_account, sender_location) = account_and_location::<T>(1);
let reserve = T::valid_destination().map_err(|_| BenchmarkError::Skip)?;
let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&reserve,
FeeReason::InitiateReserveWithdraw,
);
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
// generate holding and add possible required fees
let holding = if let Some(expected_assets_in_holding) = expected_assets_in_holding {
let mut holding = T::worst_case_holding(1 + expected_assets_in_holding.len() as u32);
for a in expected_assets_in_holding.into_inner() {
holding.push(a);
}
holding
} else {
T::worst_case_holding(1)
};
let mut executor = new_executor::<T>(sender_location);
executor.set_holding(holding.clone().into());
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
let instruction = Instruction::InitiateReserveWithdraw {
// Worst case is looking through all holdings for every asset explicitly - respecting the limit `MAX_ITEMS_IN_ASSETS`.
assets: Definite(holding.into_inner().into_iter().take(MAX_ITEMS_IN_ASSETS).collect::<Vec<_>>().into()),
reserve,
xcm: Xcm(vec![])
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// The execute completing successfully is as good as we can check.
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
}
receive_teleported_asset {
// If there is no trusted teleporter, then we skip this benchmark.
let (trusted_teleporter, teleportable_asset) = T::TrustedTeleporter::get()
.ok_or(BenchmarkError::Skip)?;
if let Some((checked_account, _)) = T::CheckedAccount::get() {
T::TransactAsset::mint_into(
&checked_account,
<
T::TransactAsset
as
Inspect<T::AccountId>
>::Balance::max_value() / 2u32.into(),
)?;
}
let assets: Assets = vec![ teleportable_asset ].into();
let mut executor = new_executor::<T>(trusted_teleporter);
let instruction = Instruction::ReceiveTeleportedAsset(assets.clone());
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm).map_err(|_| {
BenchmarkError::Override(
BenchmarkResult::from_weight(Weight::MAX)
)
})?;
} verify {
assert!(executor.holding().ensure_contains(&assets).is_ok());
}
deposit_asset {
let asset = T::get_asset();
let mut holding = T::worst_case_holding(1);
// Add our asset to the holding.
holding.push(asset.clone());
// our dest must have no balance initially.
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert_location(&dest_location).unwrap();
// Ensure that origin can send to destination (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&dest_location,
FeeReason::ChargeFees,
);
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding.into());
let instruction = Instruction::<XcmCallOf<T>>::DepositAsset {
assets: asset.into(),
beneficiary: dest_location,
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
}
deposit_reserve_asset {
let asset = T::get_asset();
let mut holding = T::worst_case_holding(1);
// Add our asset to the holding.
holding.push(asset.clone());
// our dest must have no balance initially.
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert_location(&dest_location).unwrap();
// Ensure that origin can send to destination (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&dest_location,
FeeReason::ChargeFees,
);
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding.into());
let instruction = Instruction::<XcmCallOf<T>>::DepositReserveAsset {
assets: asset.into(),
dest: dest_location,
xcm: Xcm::new(),
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
}
initiate_teleport {
let asset = T::get_asset();
let mut holding = T::worst_case_holding(0);
// Add our asset to the holding.
holding.push(asset.clone());
let dest_location = T::valid_destination()?;
// Ensure that origin can send to destination (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&dest_location,
FeeReason::ChargeFees,
);
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding.into());
let instruction = Instruction::<XcmCallOf<T>>::InitiateTeleport {
assets: asset.into(),
dest: dest_location,
xcm: Xcm::new(),
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
}
initiate_transfer {
let (sender_account, sender_location) = account_and_location::<T>(1);
let asset = T::get_asset();
let mut holding = T::worst_case_holding(1);
let dest_location = T::valid_destination()?;
// Ensure that origin can send to destination (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&dest_location,
FeeReason::ChargeFees,
);
// Add our asset to the holding.
holding.push(asset.clone());
let mut executor = new_executor::<T>(sender_location);
executor.set_holding(holding.into());
let instruction = Instruction::<XcmCallOf<T>>::InitiateTransfer {
destination: dest_location,
// ReserveDeposit is the most expensive filter.
remote_fees: Some(AssetTransferFilter::ReserveDeposit(asset.clone().into())),
// It's more expensive if we reanchor the origin.
preserve_origin: true,
assets: BoundedVec::truncate_from(vec![AssetTransferFilter::ReserveDeposit(asset.into())]),
remote_xcm: Xcm::new(),
};
let xcm = Xcm(vec![instruction]);
}: {
executor.bench_process(xcm)?;
} verify {
}
impl_benchmark_test_suite!(
Pallet,
crate::fungible::mock::new_test_ext(),
crate::fungible::mock::Test
);
}
@@ -0,0 +1,181 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! A mock runtime for XCM benchmarking.
use crate::{fungible as xcm_balances_benchmark, generate_holding_assets, mock::*};
use pezframe_benchmarking::BenchmarkError;
use pezframe_support::{
derive_impl, parameter_types,
traits::{Everything, Nothing},
};
use xcm::latest::prelude::*;
use xcm_builder::{
AllowUnpaidExecutionFrom, EnsureDecodableXcm, FrameTransactionalProcessor, MintLocation,
};
type Block = pezframe_system::mocking::MockBlock<Test>;
// For testing the pallet, we construct a mock runtime.
pezframe_support::construct_runtime!(
pub enum Test
{
System: pezframe_system,
Balances: pezpallet_balances,
XcmBalancesBenchmark: xcm_balances_benchmark,
}
);
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
impl pezframe_system::Config for Test {
type Block = Block;
type AccountData = pezpallet_balances::AccountData<u64>;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 7;
}
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
impl pezpallet_balances::Config for Test {
type ReserveIdentifier = [u8; 8];
type AccountStore = System;
}
parameter_types! {
pub const AssetDeposit: u64 = 100 * ExistentialDeposit::get();
pub const ApprovalDeposit: u64 = 1 * ExistentialDeposit::get();
pub const StringLimit: u32 = 50;
pub const MetadataDepositBase: u64 = 10 * ExistentialDeposit::get();
pub const MetadataDepositPerByte: u64 = 1 * ExistentialDeposit::get();
}
pub struct MatchAnyFungible;
impl xcm_executor::traits::MatchesFungible<u64> for MatchAnyFungible {
fn matches_fungible(m: &Asset) -> Option<u64> {
use pezsp_runtime::traits::SaturatedConversion;
match m {
Asset { fun: Fungible(amount), .. } => Some((*amount).saturated_into::<u64>()),
_ => None,
}
}
}
// Use balances as the asset transactor.
pub type AssetTransactor = xcm_builder::FungibleAdapter<
Balances,
MatchAnyFungible,
AccountIdConverter,
u64,
CheckingAccount,
>;
parameter_types! {
/// Maximum number of instructions in a single XCM fragment. A sanity check against weight
/// calculations getting too crazy.
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = EnsureDecodableXcm<DevNull>;
type XcmEventEmitter = ();
type AssetTransactor = AssetTransactor;
type OriginConverter = ();
type IsReserve = TrustedReserves;
type IsTeleporter = TrustedTeleporters;
type UniversalLocation = UniversalLocation;
type Barrier = AllowUnpaidExecutionFrom<Everything>;
type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type Trader = xcm_builder::FixedRateOfFungible<WeightPrice, ()>;
type ResponseHandler = DevNull;
type AssetTrap = ();
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type FeeManager = ();
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = ();
}
impl crate::Config for Test {
type XcmConfig = XcmConfig;
type AccountIdConverter = AccountIdConverter;
type DeliveryHelper = ();
fn valid_destination() -> Result<Location, BenchmarkError> {
let valid_destination: Location = [AccountId32 { network: None, id: [0u8; 32] }].into();
Ok(valid_destination)
}
fn worst_case_holding(depositable_count: u32) -> Assets {
generate_holding_assets(
<XcmConfig as xcm_executor::Config>::MaxAssetsIntoHolding::get() - depositable_count,
)
}
}
pub type TrustedTeleporters = xcm_builder::Case<TeleportConcreteFungible>;
pub type TrustedReserves = xcm_builder::Case<ReserveConcreteFungible>;
parameter_types! {
pub const CheckingAccount: Option<(u64, MintLocation)> = Some((100, MintLocation::Local));
pub ChildTeleporter: Location = Teyrchain(1000).into_location();
pub TrustedTeleporter: Option<(Location, Asset)> = Some((
ChildTeleporter::get(),
Asset { id: AssetId(Here.into_location()), fun: Fungible(100) },
));
pub TrustedReserve: Option<(Location, Asset)> = Some((
ChildTeleporter::get(),
Asset { id: AssetId(Here.into_location()), fun: Fungible(100) },
));
pub TeleportConcreteFungible: (AssetFilter, Location) =
(Wild(AllOf { fun: WildFungible, id: AssetId(Here.into_location()) }), ChildTeleporter::get());
pub ReserveConcreteFungible: (AssetFilter, Location) =
(Wild(AllOf { fun: WildFungible, id: AssetId(Here.into_location()) }), ChildTeleporter::get());
}
impl xcm_balances_benchmark::Config for Test {
type TransactAsset = Balances;
type CheckedAccount = CheckingAccount;
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_asset() -> Asset {
let amount = 1_000_000_000_000;
Asset { id: AssetId(Here.into()), fun: Fungible(amount) }
}
}
#[cfg(feature = "runtime-benchmarks")]
pub fn new_test_ext() -> pezsp_io::TestExternalities {
use pezsp_runtime::BuildStorage;
let t = RuntimeGenesisConfig { ..Default::default() }.build_storage().unwrap();
pezsp_tracing::try_init_simple();
t.into()
}
@@ -0,0 +1,52 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
// Benchmarking for the `AssetTransactor` trait via `Fungible`.
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
#[cfg(test)]
mod mock;
#[pezframe_support::pallet]
pub mod pallet {
use pezframe_support::pezpallet_prelude::Get;
#[pallet::config]
pub trait Config<I: 'static = ()>: pezframe_system::Config + crate::Config {
/// The type of `fungible` that is being used under the hood.
///
/// This is useful for testing and checking.
type TransactAsset: pezframe_support::traits::fungible::Mutate<Self::AccountId>;
/// The account used to check assets being teleported.
type CheckedAccount: Get<Option<(Self::AccountId, xcm_builder::MintLocation)>>;
/// A trusted location which we allow teleports from, and the asset we allow to teleport.
type TrustedTeleporter: Get<Option<(xcm::latest::Location, xcm::latest::Asset)>>;
/// A trusted location where reserve assets are stored, and the asset we allow to be
/// reserves.
type TrustedReserve: Get<Option<(xcm::latest::Location, xcm::latest::Asset)>>;
/// Give me a fungible asset that your asset transactor is going to accept.
fn get_asset() -> xcm::latest::Asset;
}
#[pallet::pallet]
pub struct Pallet<T, I = ()>(_);
}
@@ -0,0 +1,969 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use crate::{account_and_location, new_executor, EnsureDelivery, XcmCallOf};
use alloc::{vec, vec::Vec};
use codec::Encode;
use pezframe_benchmarking::v2::*;
use pezframe_support::{traits::fungible::Inspect, BoundedVec};
use xcm::{
latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight, MAX_ITEMS_IN_ASSETS},
DoubleEncoded,
};
use xcm_executor::{
traits::{ConvertLocation, FeeReason},
ExecutorError, FeesMode,
};
#[benchmarks]
mod benchmarks {
use super::*;
#[benchmark]
fn report_holding() -> Result<(), BenchmarkError> {
let (sender_account, sender_location) = account_and_location::<T>(1);
let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?;
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&destination,
FeeReason::Report,
);
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
// generate holding and add possible required fees
let holding = if let Some(expected_assets_in_holding) = expected_assets_in_holding {
let mut holding = T::worst_case_holding(expected_assets_in_holding.len() as u32);
for a in expected_assets_in_holding.into_inner() {
holding.push(a);
}
holding
} else {
T::worst_case_holding(0)
};
let mut executor = new_executor::<T>(sender_location);
executor.set_holding(holding.clone().into());
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
let instruction = Instruction::<XcmCallOf<T>>::ReportHolding {
response_info: QueryResponseInfo {
destination,
query_id: Default::default(),
max_weight: Weight::MAX,
},
// Worst case is looking through all holdings for every asset explicitly - respecting
// the limit `MAX_ITEMS_IN_ASSETS`.
assets: Definite(
holding
.into_inner()
.into_iter()
.take(MAX_ITEMS_IN_ASSETS)
.collect::<Vec<_>>()
.into(),
),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
Ok(())
}
// This benchmark does not use any additional orders or instructions. This should be managed
// by the `deep` and `shallow` implementation.
#[benchmark]
fn buy_execution() -> Result<(), BenchmarkError> {
let holding = T::worst_case_holding(0).into();
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding);
// The worst case we want for buy execution in terms of
// fee asset and weight
let (fee_asset, weight_limit) = T::worst_case_for_trader()?;
let instruction = Instruction::<XcmCallOf<T>>::BuyExecution {
fees: fee_asset,
weight_limit: weight_limit.into(),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
Ok(())
}
#[benchmark]
fn pay_fees() -> Result<(), BenchmarkError> {
let holding = T::worst_case_holding(0).into();
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding);
// Set some weight to be paid for.
executor.set_message_weight(Weight::from_parts(100_000_000, 100_000));
let (fee_asset, _): (Asset, WeightLimit) = T::worst_case_for_trader().unwrap();
let instruction = Instruction::<XcmCallOf<T>>::PayFees { asset: fee_asset };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
Ok(())
}
#[benchmark]
fn asset_claimer() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let (_, sender_location) = account_and_location::<T>(1);
let instruction = Instruction::SetHints {
hints: BoundedVec::<Hint, HintNumVariants>::truncate_from(vec![AssetClaimer {
location: sender_location.clone(),
}]),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.asset_claimer(), Some(sender_location.clone()));
Ok(())
}
#[benchmark]
fn query_response() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let (query_id, response) = T::worst_case_response();
let max_weight = Weight::MAX;
let querier: Option<Location> = Some(Here.into());
let instruction = Instruction::QueryResponse { query_id, response, max_weight, querier };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// The assert above is enough to show this XCM succeeded
Ok(())
}
// We don't care about the call itself, since that is accounted for in the weight parameter
// and included in the final weight calculation. So this is just the overhead of submitting
// a noop call.
#[benchmark]
fn transact() -> Result<(), BenchmarkError> {
let (origin, noop_call) = T::transact_origin_and_runtime_call()?;
let mut executor = new_executor::<T>(origin);
let double_encoded_noop_call: DoubleEncoded<_> = noop_call.encode().into();
let instruction = Instruction::Transact {
origin_kind: OriginKind::SovereignAccount,
call: double_encoded_noop_call,
fallback_max_weight: None,
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// TODO Make the assertion configurable?
Ok(())
}
#[benchmark]
fn refund_surplus() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let holding_assets = T::worst_case_holding(1);
// We can already buy execution since we'll load the holding register manually
let (asset_for_fees, _): (Asset, WeightLimit) = T::worst_case_for_trader().unwrap();
let previous_xcm = Xcm(vec![BuyExecution {
fees: asset_for_fees,
weight_limit: Limited(Weight::from_parts(1337, 1337)),
}]);
executor.set_holding(holding_assets.into());
executor.set_total_surplus(Weight::from_parts(1337, 1337));
executor.set_total_refunded(Weight::zero());
executor
.bench_process(previous_xcm)
.expect("Holding has been loaded, so we can buy execution here");
let instruction = Instruction::<XcmCallOf<T>>::RefundSurplus;
let xcm = Xcm(vec![instruction]);
#[block]
{
let _result = executor.bench_process(xcm)?;
}
assert_eq!(executor.total_surplus(), &Weight::from_parts(1337, 1337));
assert_eq!(executor.total_refunded(), &Weight::from_parts(1337, 1337));
Ok(())
}
#[benchmark]
fn set_error_handler() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let instruction = Instruction::<XcmCallOf<T>>::SetErrorHandler(Xcm(vec![]));
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.error_handler(), &Xcm(vec![]));
Ok(())
}
#[benchmark]
fn set_appendix() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let appendix = Xcm(vec![]);
let instruction = Instruction::<XcmCallOf<T>>::SetAppendix(appendix);
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.appendix(), &Xcm(vec![]));
Ok(())
}
#[benchmark]
fn clear_error() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_error(Some((5u32, XcmError::Overflow)));
let instruction = Instruction::<XcmCallOf<T>>::ClearError;
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(executor.error().is_none());
Ok(())
}
#[benchmark]
fn descend_origin() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let who = Junctions::from([OnlyChild, OnlyChild]);
let instruction = Instruction::DescendOrigin(who.clone());
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.origin(), &Some(Location { parents: 0, interior: who }),);
Ok(())
}
#[benchmark]
fn execute_with_origin() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let who: Junctions = Junctions::from([AccountId32 { id: [0u8; 32], network: None }]);
let instruction = Instruction::ExecuteWithOrigin {
descendant_origin: Some(who.clone()),
xcm: Xcm(vec![]),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor
.bench_process(xcm)
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
}
assert_eq!(executor.origin(), &Some(Location { parents: 0, interior: Here }),);
Ok(())
}
#[benchmark]
fn clear_origin() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let instruction = Instruction::ClearOrigin;
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.origin(), &None);
Ok(())
}
#[benchmark]
fn report_error() -> Result<(), BenchmarkError> {
let (sender_account, sender_location) = account_and_location::<T>(1);
let query_id = Default::default();
let max_weight = Default::default();
let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?;
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&destination,
FeeReason::Report,
);
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
let mut executor = new_executor::<T>(sender_location);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
executor.set_error(Some((0u32, XcmError::Unimplemented)));
let instruction =
Instruction::ReportError(QueryResponseInfo { query_id, destination, max_weight });
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
Ok(())
}
#[benchmark]
fn claim_asset() -> Result<(), BenchmarkError> {
use xcm_executor::traits::DropAssets;
let (origin, ticket, assets) = T::claimable_asset()?;
// We place some items into the asset trap to claim.
<T::XcmConfig as xcm_executor::Config>::AssetTrap::drop_assets(
&origin,
assets.clone().into(),
&XcmContext { origin: Some(origin.clone()), message_id: [0; 32], topic: None },
);
// Assets should be in the trap now.
let mut executor = new_executor::<T>(origin);
let instruction = Instruction::ClaimAsset { assets: assets.clone(), ticket };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(executor.holding().ensure_contains(&assets).is_ok());
Ok(())
}
#[benchmark]
fn trap() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let instruction = Instruction::Trap(10);
let xcm = Xcm(vec![instruction]);
// In order to access result in the verification below, it needs to be defined here.
let result;
#[block]
{
result = executor.bench_process(xcm);
}
assert!(matches!(result, Err(ExecutorError { xcm_error: XcmError::Trap(10), .. })));
Ok(())
}
#[benchmark]
fn subscribe_version() -> Result<(), BenchmarkError> {
use xcm_executor::traits::VersionChangeNotifier;
let origin = T::subscribe_origin()?;
let query_id = Default::default();
let max_response_weight = Default::default();
let mut executor = new_executor::<T>(origin.clone());
let instruction = Instruction::SubscribeVersion { query_id, max_response_weight };
let xcm = Xcm(vec![instruction]);
T::DeliveryHelper::ensure_successful_delivery(&origin, &origin, FeeReason::QueryPallet);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(<T::XcmConfig as xcm_executor::Config>::SubscriptionService::is_subscribed(
&origin
));
Ok(())
}
#[benchmark]
fn unsubscribe_version() -> Result<(), BenchmarkError> {
use xcm_executor::traits::VersionChangeNotifier;
// First we need to subscribe to notifications.
let (origin, _) = T::transact_origin_and_runtime_call()?;
T::DeliveryHelper::ensure_successful_delivery(&origin, &origin, FeeReason::QueryPallet);
let query_id = Default::default();
let max_response_weight = Default::default();
<T::XcmConfig as xcm_executor::Config>::SubscriptionService::start(
&origin,
query_id,
max_response_weight,
&XcmContext { origin: Some(origin.clone()), message_id: [0; 32], topic: None },
)
.map_err(|_| "Could not start subscription")?;
assert!(<T::XcmConfig as xcm_executor::Config>::SubscriptionService::is_subscribed(
&origin
));
let mut executor = new_executor::<T>(origin.clone());
let instruction = Instruction::UnsubscribeVersion;
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(!<T::XcmConfig as xcm_executor::Config>::SubscriptionService::is_subscribed(
&origin
));
Ok(())
}
#[benchmark]
fn burn_asset() -> Result<(), BenchmarkError> {
let holding = T::worst_case_holding(0);
let assets = holding.clone();
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding.into());
let instruction = Instruction::BurnAsset(assets.into());
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(executor.holding().is_empty());
Ok(())
}
#[benchmark]
fn expect_asset() -> Result<(), BenchmarkError> {
let holding = T::worst_case_holding(0);
let assets = holding.clone();
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(holding.into());
let instruction = Instruction::ExpectAsset(assets.into());
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// `execute` completing successfully is as good as we can check.
Ok(())
}
#[benchmark]
fn expect_origin() -> Result<(), BenchmarkError> {
let expected_origin = Parent.into();
let mut executor = new_executor::<T>(Default::default());
let instruction = Instruction::ExpectOrigin(Some(expected_origin));
let xcm = Xcm(vec![instruction]);
let mut _result = Ok(());
#[block]
{
_result = executor.bench_process(xcm);
}
assert!(matches!(
_result,
Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, .. })
));
Ok(())
}
#[benchmark]
fn expect_error() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_error(Some((3u32, XcmError::Overflow)));
let instruction = Instruction::ExpectError(None);
let xcm = Xcm(vec![instruction]);
let mut _result = Ok(());
#[block]
{
_result = executor.bench_process(xcm);
}
assert!(matches!(
_result,
Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, .. })
));
Ok(())
}
#[benchmark]
fn expect_transact_status() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let worst_error =
|| -> MaybeErrorCode { vec![0; MaxDispatchErrorLen::get() as usize].into() };
executor.set_transact_status(worst_error());
let instruction = Instruction::ExpectTransactStatus(worst_error());
let xcm = Xcm(vec![instruction]);
let mut _result = Ok(());
#[block]
{
_result = executor.bench_process(xcm);
}
assert!(matches!(_result, Ok(..)));
Ok(())
}
#[benchmark]
fn query_pallet() -> Result<(), BenchmarkError> {
let (sender_account, sender_location) = account_and_location::<T>(1);
let query_id = Default::default();
let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?;
let max_weight = Default::default();
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&destination,
FeeReason::QueryPallet,
);
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
let mut executor = new_executor::<T>(sender_location);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
let valid_pallet = T::valid_pallet();
let instruction = Instruction::QueryPallet {
module_name: valid_pallet.module_name.as_bytes().to_vec(),
response_info: QueryResponseInfo { destination, query_id, max_weight },
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
Ok(())
}
#[benchmark]
fn expect_pallet() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let valid_pallet = T::valid_pallet();
let instruction = Instruction::ExpectPallet {
index: valid_pallet.index as u32,
name: valid_pallet.name.as_bytes().to_vec(),
module_name: valid_pallet.module_name.as_bytes().to_vec(),
crate_major: valid_pallet.crate_version.major.into(),
min_crate_minor: valid_pallet.crate_version.minor.into(),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// the execution succeeding is all we need to verify this xcm was successful
Ok(())
}
#[benchmark]
fn report_transact_status() -> Result<(), BenchmarkError> {
let (sender_account, sender_location) = account_and_location::<T>(1);
let query_id = Default::default();
let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?;
let max_weight = Default::default();
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&sender_location,
&destination,
FeeReason::Report,
);
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
let mut executor = new_executor::<T>(sender_location);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
executor.set_transact_status(b"MyError".to_vec().into());
let instruction = Instruction::ReportTransactStatus(QueryResponseInfo {
query_id,
destination,
max_weight,
});
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
Ok(())
}
#[benchmark]
fn clear_transact_status() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_transact_status(b"MyError".to_vec().into());
let instruction = Instruction::ClearTransactStatus;
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.transact_status(), &MaybeErrorCode::Success);
Ok(())
}
#[benchmark]
fn set_topic() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
let instruction = Instruction::SetTopic([1; 32]);
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.topic(), &Some([1; 32]));
Ok(())
}
#[benchmark]
fn clear_topic() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_topic(Some([2; 32]));
let instruction = Instruction::ClearTopic;
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.topic(), &None);
Ok(())
}
#[benchmark]
fn exchange_asset() -> Result<(), BenchmarkError> {
let (give, want) = T::worst_case_asset_exchange().map_err(|_| BenchmarkError::Skip)?;
let assets = give.clone();
let mut executor = new_executor::<T>(Default::default());
executor.set_holding(give.into());
let instruction =
Instruction::ExchangeAsset { give: assets.into(), want: want.clone(), maximal: true };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert!(executor.holding().contains(&want.into()));
Ok(())
}
#[benchmark]
fn universal_origin() -> Result<(), BenchmarkError> {
let (origin, alias) = T::universal_alias().map_err(|_| BenchmarkError::Skip)?;
let mut executor = new_executor::<T>(origin);
let instruction = Instruction::UniversalOrigin(alias);
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
use pezframe_support::traits::Get;
let universal_location = <T::XcmConfig as xcm_executor::Config>::UniversalLocation::get();
assert_eq!(
executor.origin(),
&Some(Junctions::from([alias]).relative_to(&universal_location))
);
Ok(())
}
#[benchmark]
fn export_message(x: Linear<1, 1000>) -> Result<(), BenchmarkError> {
// The `inner_xcm` influences `ExportMessage` total weight based on
// `inner_xcm.encoded_size()`, so for this benchmark use smallest encoded instruction
// to approximate weight per "unit" of encoded size; then actual weight can be estimated
// to be `inner_xcm.encoded_size() * benchmarked_unit`.
// Use `ClearOrigin` as the small encoded instruction.
let inner_xcm = Xcm(vec![ClearOrigin; x as usize]);
// Get `origin`, `network` and `destination` from configured runtime.
let (origin, network, destination) = T::export_message_origin_and_destination()?;
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&origin,
&destination.clone().into(),
FeeReason::Export { network, destination: destination.clone() },
);
let sender_account = T::AccountIdConverter::convert_location(&origin).unwrap();
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
let mut executor = new_executor::<T>(origin);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
let xcm =
Xcm(vec![ExportMessage { network, destination: destination.clone(), xcm: inner_xcm }]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
Ok(())
}
#[benchmark]
fn set_fees_mode() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_fees_mode(FeesMode { jit_withdraw: false });
let instruction = Instruction::SetFeesMode { jit_withdraw: true };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.fees_mode(), &FeesMode { jit_withdraw: true });
Ok(())
}
#[benchmark]
fn lock_asset() -> Result<(), BenchmarkError> {
let (unlocker, owner, asset) = T::unlockable_asset()?;
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(&owner, &unlocker, FeeReason::LockAsset);
let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap();
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
// generate holding and add possible required fees
let mut holding: Assets = asset.clone().into();
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
for a in expected_assets_in_holding.into_inner() {
holding.push(a);
}
};
let mut executor = new_executor::<T>(owner);
executor.set_holding(holding.into());
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
let instruction = Instruction::LockAsset { asset, unlocker };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
Ok(())
}
#[benchmark]
fn unlock_asset() -> Result<(), BenchmarkError> {
use xcm_executor::traits::{AssetLock, Enact};
let (unlocker, owner, asset) = T::unlockable_asset()?;
let mut executor = new_executor::<T>(unlocker.clone());
// We first place the asset in lock first...
<T::XcmConfig as xcm_executor::Config>::AssetLocker::prepare_lock(
unlocker,
asset.clone(),
owner.clone(),
)
.map_err(|_| BenchmarkError::Skip)?
.enact()
.map_err(|_| BenchmarkError::Skip)?;
// ... then unlock them with the UnlockAsset instruction.
let instruction = Instruction::UnlockAsset { asset, target: owner };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
Ok(())
}
#[benchmark]
fn note_unlockable() -> Result<(), BenchmarkError> {
use xcm_executor::traits::{AssetLock, Enact};
let (unlocker, owner, asset) = T::unlockable_asset()?;
let mut executor = new_executor::<T>(unlocker.clone());
// We first place the asset in lock first...
<T::XcmConfig as xcm_executor::Config>::AssetLocker::prepare_lock(
unlocker,
asset.clone(),
owner.clone(),
)
.map_err(|_| BenchmarkError::Skip)?
.enact()
.map_err(|_| BenchmarkError::Skip)?;
// ... then note them as unlockable with the NoteUnlockable instruction.
let instruction = Instruction::NoteUnlockable { asset, owner };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
Ok(())
}
#[benchmark]
fn request_unlock() -> Result<(), BenchmarkError> {
use xcm_executor::traits::{AssetLock, Enact};
let (locker, owner, asset) = T::unlockable_asset()?;
// We first place the asset in lock first...
<T::XcmConfig as xcm_executor::Config>::AssetLocker::prepare_lock(
locker.clone(),
asset.clone(),
owner.clone(),
)
.map_err(|_| BenchmarkError::Skip)?
.enact()
.map_err(|_| BenchmarkError::Skip)?;
let (expected_fees_mode, expected_assets_in_holding) =
T::DeliveryHelper::ensure_successful_delivery(
&owner,
&locker,
FeeReason::RequestUnlock,
);
let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap();
let sender_account_balance_before = T::TransactAsset::balance(&sender_account);
// ... then request for an unlock with the RequestUnlock instruction.
let mut executor = new_executor::<T>(owner);
if let Some(expected_fees_mode) = expected_fees_mode {
executor.set_fees_mode(expected_fees_mode);
}
if let Some(expected_assets_in_holding) = expected_assets_in_holding {
executor.set_holding(expected_assets_in_holding.into());
}
let instruction = Instruction::RequestUnlock { asset, locker };
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
// Check we charged the delivery fees
assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before);
// TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426
Ok(())
}
#[benchmark]
fn unpaid_execution() -> Result<(), BenchmarkError> {
let mut executor = new_executor::<T>(Default::default());
executor.set_origin(Some(Here.into()));
let instruction = Instruction::<XcmCallOf<T>>::UnpaidExecution {
weight_limit: WeightLimit::Unlimited,
check_origin: Some(Here.into()),
};
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
Ok(())
}
#[benchmark]
fn alias_origin() -> Result<(), BenchmarkError> {
let (origin, target) = T::alias_origin().map_err(|_| BenchmarkError::Skip)?;
let mut executor = new_executor::<T>(origin);
let instruction = Instruction::AliasOrigin(target.clone());
let xcm = Xcm(vec![instruction]);
#[block]
{
executor.bench_process(xcm)?;
}
assert_eq!(executor.origin(), &Some(target));
Ok(())
}
impl_benchmark_test_suite!(
Pallet,
crate::generic::mock::new_test_ext(),
crate::generic::mock::Test
);
}
@@ -0,0 +1,221 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! A mock runtime for XCM benchmarking.
use crate::{generic, mock::*, *};
use codec::Decode;
use pezframe_support::{
derive_impl, parameter_types,
traits::{Contains, Everything, OriginTrait},
};
use pezsp_runtime::traits::TrailingZeroInput;
use xcm_builder::{
test_utils::{
AssetsInHolding, TestAssetExchanger, TestAssetLocker, TestAssetTrap,
TestSubscriptionService, TestUniversalAliases,
},
AliasForeignAccountId32, AllowUnpaidExecutionFrom, EnsureDecodableXcm,
FrameTransactionalProcessor,
};
use xcm_executor::traits::ConvertOrigin;
type Block = pezframe_system::mocking::MockBlock<Test>;
pezframe_support::construct_runtime!(
pub enum Test
{
System: pezframe_system,
Balances: pezpallet_balances,
XcmGenericBenchmarks: generic,
}
);
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
impl pezframe_system::Config for Test {
type Block = Block;
type AccountData = pezpallet_balances::AccountData<u64>;
}
/// The benchmarks in this pallet should never need an asset transactor to begin with.
pub struct NoAssetTransactor;
impl xcm_executor::traits::TransactAsset for NoAssetTransactor {
fn deposit_asset(_: &Asset, _: &Location, _: Option<&XcmContext>) -> Result<(), XcmError> {
unreachable!();
}
fn withdraw_asset(
_: &Asset,
_: &Location,
_: Option<&XcmContext>,
) -> Result<AssetsInHolding, XcmError> {
unreachable!();
}
}
parameter_types! {
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub struct OnlyTeyrchains;
impl Contains<Location> for OnlyTeyrchains {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (0, [Teyrchain(_)]))
}
}
type Aliasers = AliasForeignAccountId32<OnlyTeyrchains>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = EnsureDecodableXcm<DevNull>;
type XcmEventEmitter = ();
type AssetTransactor = NoAssetTransactor;
type OriginConverter = AlwaysSignedByDefault<RuntimeOrigin>;
type IsReserve = AllAssetLocationsPass;
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = AllowUnpaidExecutionFrom<Everything>;
type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type Trader = xcm_builder::FixedRateOfFungible<WeightPrice, ()>;
type ResponseHandler = DevNull;
type AssetTrap = TestAssetTrap;
type AssetLocker = TestAssetLocker;
type AssetExchanger = TestAssetExchanger;
type AssetClaims = TestAssetTrap;
type SubscriptionService = TestSubscriptionService;
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type FeeManager = ();
// No bridges yet...
type MessageExporter = ();
type UniversalAliases = TestUniversalAliases;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Aliasers;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 7;
}
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
impl pezpallet_balances::Config for Test {
type ReserveIdentifier = [u8; 8];
type AccountStore = System;
}
impl crate::Config for Test {
type XcmConfig = XcmConfig;
type AccountIdConverter = AccountIdConverter;
type DeliveryHelper = ();
fn valid_destination() -> Result<Location, BenchmarkError> {
let valid_destination: Location =
Junction::AccountId32 { network: None, id: [0u8; 32] }.into();
Ok(valid_destination)
}
fn worst_case_holding(depositable_count: u32) -> Assets {
generate_holding_assets(
<XcmConfig as xcm_executor::Config>::MaxAssetsIntoHolding::get() - depositable_count,
)
}
}
impl generic::Config for Test {
type TransactAsset = Balances;
type RuntimeCall = RuntimeCall;
fn worst_case_response() -> (u64, Response) {
let assets: Assets = (AssetId(Here.into()), 100).into();
(0, Response::Assets(assets))
}
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Ok(Default::default())
}
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Ok((Here.into(), GlobalConsensus(ByGenesis([0; 32]))))
}
fn transact_origin_and_runtime_call(
) -> Result<(Location, <Self as generic::Config>::RuntimeCall), BenchmarkError> {
Ok((Default::default(), pezframe_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(Default::default())
}
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let assets: Assets = (AssetId(Here.into()), 100).into();
let ticket = Location { parents: 0, interior: [GeneralIndex(0)].into() };
Ok((Default::default(), ticket, assets))
}
fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
Ok((Asset { id: AssetId(Here.into()), fun: Fungible(1_000_000) }, WeightLimit::Unlimited))
}
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
let assets: Asset = (AssetId(Here.into()), 100).into();
Ok((Default::default(), account_id_junction::<Test>(1).into(), assets))
}
fn export_message_origin_and_destination(
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
// No MessageExporter in tests
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
let origin: Location = (Teyrchain(1), AccountId32 { network: None, id: [0; 32] }).into();
let target: Location = AccountId32 { network: None, id: [0; 32] }.into();
Ok((origin, target))
}
}
#[cfg(feature = "runtime-benchmarks")]
pub fn new_test_ext() -> pezsp_io::TestExternalities {
use pezsp_runtime::BuildStorage;
let t = RuntimeGenesisConfig { ..Default::default() }.build_storage().unwrap();
pezsp_tracing::try_init_simple();
t.into()
}
pub struct AlwaysSignedByDefault<RuntimeOrigin>(core::marker::PhantomData<RuntimeOrigin>);
impl<RuntimeOrigin> ConvertOrigin<RuntimeOrigin> for AlwaysSignedByDefault<RuntimeOrigin>
where
RuntimeOrigin: OriginTrait,
<RuntimeOrigin as OriginTrait>::AccountId: Decode,
{
fn convert_origin(
_origin: impl Into<Location>,
_kind: OriginKind,
) -> Result<RuntimeOrigin, Location> {
Ok(RuntimeOrigin::signed(
<RuntimeOrigin as OriginTrait>::AccountId::decode(&mut TrailingZeroInput::zeroes())
.expect("infinite length input; no invalid inputs for type; qed"),
))
}
}
@@ -0,0 +1,115 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
#[cfg(test)]
mod mock;
#[pezframe_support::pallet]
pub mod pallet {
use pezframe_benchmarking::BenchmarkError;
use pezframe_support::{dispatch::GetDispatchInfo, pezpallet_prelude::Encode};
use pezsp_runtime::traits::Dispatchable;
use xcm::latest::{
Asset, Assets, InteriorLocation, Junction, Location, NetworkId, Response, WeightLimit,
};
#[pallet::config]
pub trait Config<I: 'static = ()>: pezframe_system::Config + crate::Config {
type RuntimeCall: Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
+ GetDispatchInfo
+ From<pezframe_system::Call<Self>>
+ Encode;
/// The type of `fungible` that is being used under the hood.
///
/// This is useful for testing and checking.
type TransactAsset: pezframe_support::traits::fungible::Mutate<Self::AccountId>;
/// The response which causes the most runtime weight.
fn worst_case_response() -> (u64, Response);
/// The pair of asset collections which causes the most runtime weight if demanded to be
/// exchanged.
///
/// The first element in the returned tuple represents the assets that are being exchanged
/// from, whereas the second element represents the assets that are being exchanged to.
///
/// If set to `Err`, benchmarks which rely on an `exchange_asset` will be skipped.
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError>;
/// A `(Location, Junction)` that is one of the `UniversalAliases` configured by the
/// XCM executor.
///
/// If set to `Err`, benchmarks which rely on a universal alias will be skipped.
fn universal_alias() -> Result<(Location, Junction), BenchmarkError>;
/// The `Location` and `RuntimeCall` used for successful transaction XCMs.
///
/// If set to `Err`, benchmarks which rely on a `transact_origin_and_runtime_call` will be
/// skipped.
fn transact_origin_and_runtime_call(
) -> Result<(Location, <Self as crate::generic::Config<I>>::RuntimeCall), BenchmarkError>;
/// A valid `Location` we can successfully subscribe to.
///
/// If set to `Err`, benchmarks which rely on a `subscribe_origin` will be skipped.
fn subscribe_origin() -> Result<Location, BenchmarkError>;
/// Return an origin, ticket, and assets that can be trapped and claimed.
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError>;
/// The worst case buy execution weight limit and
/// asset to trigger the Trader::buy_execution in the XCM executor
/// Used to buy weight in benchmarks, for example in
/// `refund_surplus`.
fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError>;
/// Return an unlocker, owner and assets that can be locked and unlocked.
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError>;
/// A `(Location, NetworkId, InteriorLocation)` we can successfully export message
/// to.
///
/// If set to `Err`, benchmarks which rely on `export_message` will be skipped.
fn export_message_origin_and_destination(
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError>;
/// A `(Location, Location)` that is one of the `Aliasers` configured by the XCM
/// executor.
///
/// If set to `Err`, benchmarks which rely on a universal alias will be skipped.
fn alias_origin() -> Result<(Location, Location), BenchmarkError>;
/// Returns a valid pallet info for `ExpectPallet` or `QueryPallet` benchmark.
///
/// By default returns `pezframe_system::Pallet` info with expected pallet index `0`.
fn valid_pallet() -> pezframe_support::traits::PalletInfoData {
pezframe_support::traits::PalletInfoData {
index: <pezframe_system::Pallet<Self> as pezframe_support::traits::PalletInfoAccess>::index(),
name: <pezframe_system::Pallet<Self> as pezframe_support::traits::PalletInfoAccess>::name(),
module_name: <pezframe_system::Pallet<Self> as pezframe_support::traits::PalletInfoAccess>::module_name(),
crate_version: <pezframe_system::Pallet<Self> as pezframe_support::traits::PalletInfoAccess>::crate_version(),
}
}
}
#[pallet::pallet]
pub struct Pallet<T, I = ()>(_);
}
@@ -0,0 +1,121 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Pallet that serves no other purpose than benchmarking raw messages [`Xcm`].
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use alloc::vec::Vec;
use codec::Encode;
use pezframe_benchmarking::{account, BenchmarkError};
use xcm::latest::prelude::*;
use xcm_builder::EnsureDelivery;
use xcm_executor::{traits::ConvertLocation, Config as XcmConfig};
pub mod fungible;
pub mod generic;
#[cfg(test)]
mod mock;
/// A base trait for all individual pallets
pub trait Config: pezframe_system::Config {
/// The XCM configurations.
///
/// These might affect the execution of XCM messages, such as defining how the
/// `TransactAsset` is implemented.
type XcmConfig: XcmConfig;
/// A converter between a location to a sovereign account.
type AccountIdConverter: ConvertLocation<Self::AccountId>;
/// Helper that ensures successful delivery for XCM instructions which need `SendXcm`.
type DeliveryHelper: EnsureDelivery;
/// Does any necessary setup to create a valid destination for XCM messages.
/// Returns that destination's location to be used in benchmarks.
fn valid_destination() -> Result<Location, BenchmarkError>;
/// Worst case scenario for a holding account in this runtime.
/// - `depositable_count` specifies the count of assets we plan to add to the holding on top of
/// those generated by the `worst_case_holding` implementation.
fn worst_case_holding(depositable_count: u32) -> Assets;
}
const SEED: u32 = 0;
/// The XCM executor to use for doing stuff.
pub type ExecutorOf<T> = xcm_executor::XcmExecutor<<T as Config>::XcmConfig>;
/// The overarching call type.
pub type RuntimeCallOf<T> = <T as pezframe_system::Config>::RuntimeCall;
/// The asset transactor of our executor
pub type AssetTransactorOf<T> = <<T as Config>::XcmConfig as XcmConfig>::AssetTransactor;
/// The call type of executor's config. Should eventually resolve to the same overarching call type.
pub type XcmCallOf<T> = <<T as Config>::XcmConfig as XcmConfig>::RuntimeCall;
pub fn generate_holding_assets(max_assets: u32) -> Assets {
let fungibles_amount: u128 = 100;
let holding_fungibles = max_assets / 2;
let holding_non_fungibles = max_assets - holding_fungibles - 1; // -1 because of adding `Here` asset
// add count of `holding_fungibles`
(0..holding_fungibles)
.map(|i| {
Asset {
id: AssetId(GeneralIndex(i as u128).into()),
fun: Fungible(fungibles_amount * (i + 1) as u128), // non-zero amount
}
.into()
})
// add one more `Here` asset
.chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) }))
// add count of `holding_non_fungibles`
.chain((0..holding_non_fungibles).map(|i| Asset {
id: AssetId(GeneralIndex(i as u128).into()),
fun: NonFungible(asset_instance_from(i)),
}))
.collect::<Vec<_>>()
.into()
}
pub fn asset_instance_from(x: u32) -> AssetInstance {
let bytes = x.encode();
let mut instance = [0u8; 4];
instance.copy_from_slice(&bytes);
AssetInstance::Array4(instance)
}
pub fn new_executor<T: Config>(origin: Location) -> ExecutorOf<T> {
ExecutorOf::<T>::new(origin, [0; 32])
}
/// Build a location from an account id.
fn account_id_junction<T: pezframe_system::Config>(index: u32) -> Junction {
let account: T::AccountId = account("account", index, SEED);
let mut encoded = account.encode();
encoded.resize(32, 0u8);
let mut id = [0u8; 32];
id.copy_from_slice(&encoded);
Junction::AccountId32 { network: None, id }
}
pub fn account_and_location<T: Config>(index: u32) -> (T::AccountId, Location) {
let location: Location = account_id_junction::<T>(index).into();
let account = T::AccountIdConverter::convert_location(&location).unwrap();
(account, location)
}
@@ -0,0 +1,71 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::*;
use pezframe_support::{parameter_types, traits::ContainsPair};
use xcm::latest::Weight;
// An xcm sender/receiver akin to > /dev/null
pub struct DevNull;
impl xcm::opaque::latest::SendXcm for DevNull {
type Ticket = ();
fn validate(_: &mut Option<Location>, _: &mut Option<Xcm<()>>) -> SendResult<()> {
Ok(((), Assets::new()))
}
fn deliver(_: ()) -> Result<XcmHash, SendError> {
Ok([0; 32])
}
}
impl xcm_executor::traits::OnResponse for DevNull {
fn expecting_response(_: &Location, _: u64, _: Option<&Location>) -> bool {
false
}
fn on_response(
_: &Location,
_: u64,
_: Option<&Location>,
_: Response,
_: Weight,
_: &XcmContext,
) -> Weight {
Weight::zero()
}
}
pub struct AccountIdConverter;
impl xcm_executor::traits::ConvertLocation<u64> for AccountIdConverter {
fn convert_location(ml: &Location) -> Option<u64> {
match ml.unpack() {
(0, [Junction::AccountId32 { id, .. }]) =>
Some(<u64 as codec::Decode>::decode(&mut &*id.to_vec()).unwrap()),
_ => None,
}
}
}
parameter_types! {
pub UniversalLocation: InteriorLocation = [GlobalConsensus(ByGenesis([1; 32])), Junction::Teyrchain(101)].into();
pub UnitWeightCost: Weight = Weight::from_parts(10, 10);
pub WeightPrice: (AssetId, u128, u128) = (AssetId(Here.into()), 1_000_000, 1024);
}
pub struct AllAssetLocationsPass;
impl ContainsPair<Asset, Location> for AllAssetLocationsPass {
fn contains(_: &Asset, _: &Location) -> bool {
true
}
}
@@ -0,0 +1,64 @@
{{header}}
//! Autogenerated weights for `{{pallet}}`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE BIZINIKIWI BENCHMARK CLI VERSION {{version}}
//! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}`
//! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}`
//! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}`
//! WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}}
// Executed Command:
{{#each args as |arg|}}
// {{arg}}
{{/each}}
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
use frame_support::{traits::Get, weights::Weight};
use core::marker::PhantomData;
/// Weight functions for `{{pallet}}`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo<T> {
{{#each benchmarks as |benchmark|}}
{{#each benchmark.comments as |comment|}}
/// {{comment}}
{{/each}}
{{#each benchmark.component_ranges as |range|}}
/// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`.
{{/each}}
pub(crate) fn {{benchmark.name~}}
(
{{~#each benchmark.components as |c| ~}}
{{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}}
) -> Weight {
// Proof Size summary in bytes:
// Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}`
// Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}`
// Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds.
Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}})
{{#each benchmark.component_weight as |cw|}}
// Standard Error: {{underscore cw.error}}
.saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into()))
{{/each}}
{{#if (ne benchmark.base_reads "0")}}
.saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}))
{{/if}}
{{#each benchmark.component_reads as |cr|}}
.saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into())))
{{/each}}
{{#if (ne benchmark.base_writes "0")}}
.saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}))
{{/if}}
{{#each benchmark.component_writes as |cw|}}
.saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into())))
{{/each}}
{{#each benchmark.component_calculated_proof_size as |cp|}}
.saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into()))
{{/each}}
}
{{/each}}
}