Skip to content

Commit f815c87

Browse files
libreloisTarekkMA
andauthored
Benchmark XCM instructions from polkadot-sdk pallet_xcm_benchmarks (#3624)
* Enable benchmarks for pallet_xcm_benchmarks and fix all issues with `pallet_xcm_benchmarks::generic` * Cleanup AccountIdConverter * Use `MaxAssetsIntoHolding` in `worst_case_holding` * Increase worst_case_for_trader * Use new template for xcm weights * Fix all issues with benchmarks * use new benchmarks weights * Fix failing tests * clarify refund_weight impl var names * fix xcm benchmarks * regenerate xcm fungible benchmarks * fix some dev-tests * fix dev-test D023913 * config TrustedReserve * regen xcm benchmarks * fix dev test D023908 * fix dev-tests tests-assets * fix dev-tests test-xcm-v3 * fix some dev-tests * fix precompile tests * biome * fix test D024014 * fix test D024013 * fix test D024012 * fix test D024010 * fix test D024009 * biome * disable initial_teleport * apply suggestion * remove initiate_teleport --------- Co-authored-by: Tarek Mohamed Abdalla <tarekkma@gmail.com>
1 parent 3254991 commit f815c87

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+2717
-3273
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
{{header}}
2+
//! Autogenerated weights for `{{pallet}}`
3+
//!
4+
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}}
5+
//! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}`
6+
//! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}`
7+
//! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}`
8+
//! WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}}
9+
10+
// Executed Command:
11+
{{#each args as |arg|}}
12+
// {{arg}}
13+
{{/each}}
14+
15+
#![cfg_attr(rustfmt, rustfmt_skip)]
16+
#![allow(unused_parens)]
17+
#![allow(unused_imports)]
18+
19+
use frame_support::{traits::Get, weights::Weight};
20+
use core::marker::PhantomData;
21+
22+
/// Weight functions for `{{pallet}}`.
23+
pub struct WeightInfo<T>(PhantomData<T>);
24+
impl<T: frame_system::Config> WeightInfo<T> {
25+
{{#each benchmarks as |benchmark|}}
26+
{{#each benchmark.comments as |comment|}}
27+
/// {{comment}}
28+
{{/each}}
29+
{{#each benchmark.component_ranges as |range|}}
30+
/// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`.
31+
{{/each}}
32+
pub(crate) fn {{benchmark.name~}}
33+
(
34+
{{~#each benchmark.components as |c| ~}}
35+
{{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}}
36+
) -> Weight {
37+
// Proof Size summary in bytes:
38+
// Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}`
39+
// Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}`
40+
// Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds.
41+
Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}})
42+
{{#each benchmark.component_weight as |cw|}}
43+
// Standard Error: {{underscore cw.error}}
44+
.saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into()))
45+
{{/each}}
46+
{{#if (ne benchmark.base_reads "0")}}
47+
.saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}))
48+
{{/if}}
49+
{{#each benchmark.component_reads as |cr|}}
50+
.saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into())))
51+
{{/each}}
52+
{{#if (ne benchmark.base_writes "0")}}
53+
.saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}))
54+
{{/if}}
55+
{{#each benchmark.component_writes as |cw|}}
56+
.saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into())))
57+
{{/each}}
58+
{{#each benchmark.component_calculated_proof_size as |cp|}}
59+
.saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into()))
60+
{{/each}}
61+
}
62+
{{/each}}
63+
}

pallets/moonbeam-foreign-assets/src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,16 @@ pub mod pallet {
467467
AssetsByLocation::<T>::insert(&asset_location, (asset_id, AssetStatus::Active));
468468
AssetsById::<T>::insert(&asset_id, asset_location);
469469
}
470+
471+
#[cfg(feature = "runtime-benchmarks")]
472+
pub fn create_asset_contract(
473+
asset_id: AssetId,
474+
decimals: u8,
475+
symbol: &str,
476+
name: &str,
477+
) -> Result<H160, Error<T>> {
478+
EvmCaller::<T>::erc20_create(asset_id, decimals, symbol, name)
479+
}
470480
}
471481

472482
#[pallet::call]
@@ -815,6 +825,17 @@ pub mod pallet {
815825

816826
Ok(what.clone().into())
817827
}
828+
829+
#[cfg(feature = "runtime-benchmarks")]
830+
fn can_check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult {
831+
// Needed for the benchmarks to work
832+
Ok(())
833+
}
834+
835+
#[cfg(feature = "runtime-benchmarks")]
836+
fn check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) {
837+
// Needed for benchmarks to work
838+
}
818839
}
819840

820841
impl<T: Config> sp_runtime::traits::MaybeEquivalence<Location, AssetId> for Pallet<T> {

pallets/xcm-weight-trader/src/lib.rs

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -447,11 +447,11 @@ impl<T: crate::Config> WeightTrader for Trader<T> {
447447
}
448448
}
449449

450-
fn refund_weight(&mut self, actual_weight: Weight, context: &XcmContext) -> Option<Asset> {
450+
fn refund_weight(&mut self, weight_to_refund: Weight, context: &XcmContext) -> Option<Asset> {
451451
log::trace!(
452452
target: "xcm-weight-trader",
453453
"refund_weight weight: {:?}, context: {:?}, available weight: {:?}, asset: {:?}",
454-
actual_weight,
454+
weight_to_refund,
455455
context,
456456
self.0,
457457
self.1
@@ -461,32 +461,28 @@ impl<T: crate::Config> WeightTrader for Trader<T> {
461461
id: XcmAssetId(location),
462462
}) = self.1.take()
463463
{
464-
if actual_weight == self.0 {
465-
self.1 = Some(Asset {
466-
fun: Fungibility::Fungible(initial_amount),
467-
id: XcmAssetId(location),
468-
});
469-
None
470-
} else {
471-
let weight = actual_weight.min(self.0);
472-
let amount: u128 =
473-
Self::compute_amount_to_charge(&weight, &location).unwrap_or(u128::MAX);
474-
let final_amount = amount.min(initial_amount);
475-
let amount_to_refund = initial_amount.saturating_sub(final_amount);
476-
self.0 -= weight;
477-
self.1 = Some(Asset {
478-
fun: Fungibility::Fungible(final_amount),
479-
id: XcmAssetId(location.clone()),
480-
});
481-
log::trace!(
482-
target: "xcm-weight-trader",
483-
"refund_weight amount to refund: {:?}",
484-
amount_to_refund
485-
);
464+
let weight_to_refund = weight_to_refund.min(self.0);
465+
let amount_to_refund: u128 =
466+
Self::compute_amount_to_charge(&weight_to_refund, &location).unwrap_or(u128::MAX);
467+
let final_amount = amount_to_refund.min(initial_amount);
468+
let amount_to_refund = initial_amount.saturating_sub(final_amount);
469+
self.0 -= weight_to_refund;
470+
self.1 = Some(Asset {
471+
fun: Fungibility::Fungible(final_amount),
472+
id: XcmAssetId(location.clone()),
473+
});
474+
log::trace!(
475+
target: "xcm-weight-trader",
476+
"refund_weight amount to refund: {:?}",
477+
amount_to_refund
478+
);
479+
if amount_to_refund > 0 {
486480
Some(Asset {
487481
fun: Fungibility::Fungible(amount_to_refund),
488482
id: XcmAssetId(location),
489483
})
484+
} else {
485+
None
490486
}
491487
} else {
492488
None

runtime/common/src/apis.rs

Lines changed: 96 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,33 @@ macro_rules! impl_runtime_apis_plus_common {
4444
}
4545
}
4646

47+
/// AccountId Converter used for benchmarks.
48+
///
49+
/// * AccountId32 Junction is being used in pallet_xcm_benchmarks
50+
/// * Parent is used as valid destination location for benchmarking.
51+
#[cfg(feature = "runtime-benchmarks")]
52+
pub struct BenchAccountIdConverter<AccountId>(sp_std::marker::PhantomData<AccountId>);
53+
54+
#[cfg(feature = "runtime-benchmarks")]
55+
impl<AccountId: From<[u8; 20]> + Into<[u8; 20]> + Clone> xcm_executor::traits::ConvertLocation<AccountId>
56+
for BenchAccountIdConverter<AccountId>
57+
{
58+
fn convert_location(location: &xcm::latest::prelude::Location) -> Option<AccountId> {
59+
match location.unpack() {
60+
(0, [xcm::latest::prelude::AccountId32 { id, network: None }]) => {
61+
// take the first 20 bytes of the id and convert to fixed-size array
62+
let mut id20: [u8; 20] = [0u8; 20];
63+
id20.copy_from_slice(&id[..20]);
64+
Some(id20.into())
65+
},
66+
(1, []) => {
67+
Some([1u8; 20].into())
68+
},
69+
_ => return None,
70+
}
71+
}
72+
}
73+
4774
impl_runtime_apis! {
4875
$($custom)*
4976

@@ -833,11 +860,13 @@ macro_rules! impl_runtime_apis_plus_common {
833860
use cumulus_primitives_core::ParaId;
834861

835862
use xcm::latest::prelude::{
836-
GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId,
837-
Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent, WeightLimit
863+
GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId, Here,
864+
Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent, WeightLimit,
865+
AccountId32,
838866
};
839-
use xcm_config::SelfReserve;
867+
use xcm_config::{SelfReserve, MaxAssetsIntoHolding, AssetHubLocation, RelayLocation};
840868
use frame_benchmarking::BenchmarkError;
869+
use xcm_executor::traits::ConvertLocation;
841870

842871
use frame_system_benchmarking::Pallet as SystemBench;
843872
// Needed to run `set_code` and `apply_authorized_upgrade` frame_system benchmarks
@@ -984,16 +1013,15 @@ macro_rules! impl_runtime_apis_plus_common {
9841013

9851014
impl pallet_xcm_benchmarks::Config for Runtime {
9861015
type XcmConfig = xcm_config::XcmExecutorConfig;
987-
type AccountIdConverter = xcm_config::LocationToAccountId;
1016+
type AccountIdConverter = BenchAccountIdConverter<AccountId>;
9881017
type DeliveryHelper = TestDeliveryHelper;
9891018
fn valid_destination() -> Result<Location, BenchmarkError> {
9901019
Ok(Location::parent())
9911020
}
9921021
fn worst_case_holding(_depositable_count: u32) -> XcmAssets {
993-
// 100 fungibles
994-
const HOLDING_FUNGIBLES: u32 = 100;
995-
let fungibles_amount: u128 = 100;
996-
let assets = (0..HOLDING_FUNGIBLES).map(|i| {
1022+
const HOLDING_FUNGIBLES: u32 = MaxAssetsIntoHolding::get();
1023+
let fungibles_amount: u128 = 1_000 * ExistentialDeposit::get();
1024+
let assets = (1..=HOLDING_FUNGIBLES).map(|i| {
9971025
let location: Location = GeneralIndex(i as u128).into();
9981026
Asset {
9991027
id: AssetId(location),
@@ -1023,14 +1051,65 @@ macro_rules! impl_runtime_apis_plus_common {
10231051
);
10241052
XcmWeightTrader::set_asset_price(
10251053
location.clone(),
1026-
1u128.pow(18)
1054+
10u128.pow(18)
10271055
);
10281056
}
10291057
}
10301058
assets.into()
10311059
}
10321060
}
10331061

1062+
parameter_types! {
1063+
// Native token location
1064+
pub const TokenLocation: Location = Here.into_location();
1065+
pub TrustedTeleporter: Option<(Location, Asset)> = None;
1066+
pub CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1067+
// Reserve location and asset used by the `reserve_asset_deposited` benchmark.
1068+
// We use DOT (asset id = `RelayLocation`) whose reserve is Asset Hub.
1069+
pub TrustedReserve: Option<(Location, Asset)> = Some((
1070+
AssetHubLocation::get(),
1071+
Asset {
1072+
id: AssetId(RelayLocation::get()),
1073+
fun: Fungible(100 * ExistentialDeposit::get()),
1074+
}
1075+
));
1076+
}
1077+
1078+
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1079+
type TransactAsset = Balances;
1080+
1081+
type CheckedAccount = CheckedAccount;
1082+
type TrustedTeleporter = TrustedTeleporter;
1083+
type TrustedReserve = TrustedReserve;
1084+
1085+
fn get_asset() -> Asset {
1086+
// We put more than ED here for being able to keep accounts alive when transferring
1087+
// and paying the delivery fees.
1088+
let location: Location = GeneralIndex(1).into();
1089+
let asset_id = 1u128;
1090+
let decimals = 18u8;
1091+
let asset = Asset {
1092+
id: AssetId(location.clone()),
1093+
fun: Fungible(100 * ExistentialDeposit::get()),
1094+
};
1095+
EvmForeignAssets::set_asset(
1096+
location.clone(),
1097+
asset_id,
1098+
);
1099+
XcmWeightTrader::set_asset_price(
1100+
location.clone(),
1101+
10u128.pow(decimals as u32)
1102+
);
1103+
EvmForeignAssets::create_asset_contract(
1104+
asset_id,
1105+
decimals,
1106+
"TKN",
1107+
"Token",
1108+
).unwrap();
1109+
asset
1110+
}
1111+
}
1112+
10341113
impl pallet_xcm_benchmarks::generic::Config for Runtime {
10351114
type RuntimeCall = RuntimeCall;
10361115
type TransactAsset = Balances;
@@ -1074,7 +1153,14 @@ macro_rules! impl_runtime_apis_plus_common {
10741153
}
10751154

10761155
fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1077-
Err(BenchmarkError::Skip)
1156+
let location: Location = GeneralIndex(1).into();
1157+
Ok((
1158+
Asset {
1159+
id: AssetId(Location::parent()),
1160+
fun: Fungible(1_000_000_000_000_000 as u128)
1161+
},
1162+
WeightLimit::Limited(Weight::from_parts(5000, 5000)),
1163+
))
10781164
}
10791165

10801166
fn unlockable_asset()
@@ -1151,9 +1237,6 @@ macro_rules! impl_runtime_apis_plus_common {
11511237

11521238
add_benchmarks!(params, batches);
11531239

1154-
if batches.is_empty() {
1155-
return Err("Benchmark not found for this pallet.".into());
1156-
}
11571240
Ok(batches)
11581241
}
11591242
}

runtime/moonbase/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,6 +1579,8 @@ mod benches {
15791579
[pallet_collective, TreasuryCouncilCollective]
15801580
[pallet_collective, OpenTechCommitteeCollective]
15811581
[cumulus_pallet_weight_reclaim, WeightReclaim]
1582+
[pallet_xcm_benchmarks::fungible, pallet_xcm_benchmarks::fungible::Pallet<Runtime>]
1583+
[pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet<Runtime>]
15821584
);
15831585
}
15841586

0 commit comments

Comments
 (0)