XCM Benchmarks for Asset Transactor w/ Fungible Asset (#3818)

* benchmarks for fungibles

* add benchmark to westend

* fix hex

* clean up a bit

* update code doc

* fix warnings

* cargo run --quiet --release --features runtime-benchmarks -- benchmark --chain=westend-dev --pallet=pallet_xcm_benchmarks::fungible --extrinsic=* --steps=10 --repeat=10 --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./ --execution=wasm --wasm-execution=compiled

* use skip

* fix spelling

* Update Cargo.lock

* add scale-info

* Update Cargo.lock

* update bench

* cargo run --quiet --release --features=runtime-benchmarks -- benchmark --chain=westend-dev --steps=50 --repeat=20 --pallet=pallet_xcm_benchmarks::fungible --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs

* weights compile

* update westend to use weights

* fmt

* spelling fixes

* Delete pallet_xcm_benchmarks::fungible.rs

* Apply suggestions from code review

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* fix code review

* update weight

* fix report_error

* fix spell check

Co-authored-by: Parity Bot <admin@parity.io>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Shawn Tabrizi
2021-09-27 00:38:46 -04:00
committed by GitHub
parent 37a5f95c29
commit 7c8804c049
22 changed files with 1206 additions and 16 deletions
@@ -0,0 +1,219 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use crate::{account_and_location, new_executor, worst_case_holding, AssetTransactorOf, XcmCallOf};
use frame_benchmarking::{
benchmarks_instance_pallet, impl_benchmark_test_suite, BenchmarkError, BenchmarkResult,
};
use frame_support::{pallet_prelude::Get, traits::fungible::Inspect};
use sp_runtime::traits::Zero;
use sp_std::{convert::TryInto, prelude::*, vec};
use xcm::latest::prelude::*;
use xcm_executor::traits::{Convert, TransactAsset};
benchmarks_instance_pallet! {
where_clause { where
<
<
T::TransactAsset
as
Inspect<T::AccountId>
>::Balance
as
TryInto<u128>
>::Error: sp_std::fmt::Debug,
}
withdraw_asset {
let (sender_account, sender_location) = account_and_location::<T>(1);
let worst_case_holding = worst_case_holding();
let asset = T::get_multi_asset();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location).unwrap();
// check the assets of origin.
assert!(!T::TransactAsset::balance(&sender_account).is_zero());
let mut executor = new_executor::<T>(sender_location);
executor.holding = worst_case_holding;
let instruction = Instruction::<XcmCallOf<T>>::WithdrawAsset(vec![asset.clone()].into());
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
// check one of the assets of origin.
assert!(T::TransactAsset::balance(&sender_account).is_zero());
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_multi_asset();
let assets: MultiAssets = vec![ asset.clone() ].into();
// this xcm doesn't use holding
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert(dest_location.clone()).unwrap();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location).unwrap();
assert!(T::TransactAsset::balance(&dest_account).is_zero());
let mut executor = new_executor::<T>(sender_location);
let instruction = Instruction::TransferAsset { assets, beneficiary: dest_location };
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
assert!(T::TransactAsset::balance(&sender_account).is_zero());
assert!(!T::TransactAsset::balance(&dest_account).is_zero());
}
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(dest_location.clone()).unwrap();
let asset = T::get_multi_asset();
<AssetTransactorOf<T>>::deposit_asset(&asset, &sender_location).unwrap();
let assets: MultiAssets = vec![ asset ].into();
assert!(T::TransactAsset::balance(&dest_account).is_zero());
let mut executor = new_executor::<T>(sender_location);
let instruction = Instruction::TransferReserveAsset {
assets,
dest: dest_location,
xcm: Xcm::new()
};
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
assert!(T::TransactAsset::balance(&sender_account).is_zero());
assert!(!T::TransactAsset::balance(&dest_account).is_zero());
// TODO: Check sender queue is not empty.
}
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::Override(
BenchmarkResult::from_weight(T::BlockWeights::get().max_block)
)
)?;
let assets: MultiAssets = vec![ teleportable_asset ].into();
let mut executor = new_executor::<T>(trusted_teleporter);
let instruction = Instruction::ReceiveTeleportedAsset(assets.clone());
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm).map_err(|_| {
BenchmarkError::Override(
BenchmarkResult::from_weight(T::BlockWeights::get().max_block)
)
})?;
} verify {
assert!(executor.holding.ensure_contains(&assets).is_ok());
}
deposit_asset {
let asset = T::get_multi_asset();
let mut holding = worst_case_holding();
// Add our asset to the holding.
holding.subsume(asset.clone());
// our dest must have no balance initially.
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert(dest_location.clone()).unwrap();
assert!(T::TransactAsset::balance(&dest_account).is_zero());
let mut executor = new_executor::<T>(Default::default());
executor.holding = holding;
let instruction = Instruction::<XcmCallOf<T>>::DepositAsset {
assets: asset.into(),
max_assets: 1,
beneficiary: dest_location,
};
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
// dest should have received some asset.
assert!(!T::TransactAsset::balance(&dest_account).is_zero())
}
deposit_reserve_asset {
let asset = T::get_multi_asset();
let mut holding = worst_case_holding();
// Add our asset to the holding.
holding.subsume(asset.clone());
// our dest must have no balance initially.
let dest_location = T::valid_destination()?;
let dest_account = T::AccountIdConverter::convert(dest_location.clone()).unwrap();
assert!(T::TransactAsset::balance(&dest_account).is_zero());
let mut executor = new_executor::<T>(Default::default());
executor.holding = holding;
let instruction = Instruction::<XcmCallOf<T>>::DepositReserveAsset {
assets: asset.into(),
max_assets: 1,
dest: dest_location,
xcm: Xcm::new(),
};
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
// dest should have received some asset.
assert!(!T::TransactAsset::balance(&dest_account).is_zero())
}
initiate_teleport {
let asset = T::get_multi_asset();
let mut holding = worst_case_holding();
// Add our asset to the holding.
holding.subsume(asset.clone());
// Checked account starts at zero
assert!(T::CheckedAccount::get().map_or(true, |c| T::TransactAsset::balance(&c).is_zero()));
let mut executor = new_executor::<T>(Default::default());
executor.holding = holding;
let instruction = Instruction::<XcmCallOf<T>>::InitiateTeleport {
assets: asset.into(),
dest: T::valid_destination()?,
xcm: Xcm::new(),
};
let xcm = Xcm(vec![instruction]);
}: {
executor.execute(xcm)?;
} verify {
if let Some(checked_account) = T::CheckedAccount::get() {
// teleport checked account should have received some asset.
assert!(!T::TransactAsset::balance(&checked_account).is_zero());
}
}
}
impl_benchmark_test_suite!(
Pallet,
crate::fungible::mock::new_test_ext(),
crate::fungible::mock::Test
);
@@ -0,0 +1,180 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! A mock runtime for XCM benchmarking.
use crate::{fungible as xcm_balances_benchmark, mock::*};
use frame_support::{parameter_types, traits::Everything};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
};
use xcm::latest::prelude::*;
use xcm_builder::AllowUnpaidExecutionFrom;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
// For testing the pallet, we construct a mock runtime.
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
XcmBalancesBenchmark: xcm_balances_benchmark::{Pallet},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(1024);
}
impl frame_system::Config for Test {
type BaseCallFilter = Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Call = Call;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 7;
}
impl pallet_balances::Config for Test {
type MaxLocks = ();
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type Balance = u64;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = ();
}
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: &MultiAsset) -> Option<u64> {
use sp_runtime::traits::SaturatedConversion;
match m {
MultiAsset { fun: Fungible(amount), .. } => Some((*amount).saturated_into::<u64>()),
_ => None,
}
}
}
// Use balances as the asset transactor.
pub type AssetTransactor = xcm_builder::CurrencyAdapter<
Balances,
MatchAnyFungible,
AccountIdConverter,
u64,
CheckedAccount,
>;
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 struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type Call = Call;
type XcmSender = DevNull;
type AssetTransactor = AssetTransactor;
type OriginConverter = ();
type IsReserve = ();
type IsTeleporter = ();
type LocationInverter = xcm_builder::LocationInverter<Ancestry>;
type Barrier = AllowUnpaidExecutionFrom<Everything>;
type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
type Trader = xcm_builder::FixedRateOfFungible<WeightPrice, ()>;
type ResponseHandler = DevNull;
type AssetTrap = ();
type AssetClaims = ();
type SubscriptionService = ();
}
impl crate::Config for Test {
type XcmConfig = XcmConfig;
type AccountIdConverter = AccountIdConverter;
fn valid_destination() -> Result<MultiLocation, sp_runtime::DispatchError> {
let valid_destination: MultiLocation =
X1(AccountId32 { network: NetworkId::Any, id: [0u8; 32] }).into();
Ok(valid_destination)
}
}
parameter_types! {
pub const CheckedAccount: Option<u64> = Some(100);
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
X1(OnlyChild).into(),
MultiAsset { id: Concrete(Here.into()), fun: Fungible(100) },
));
}
impl xcm_balances_benchmark::Config for Test {
type TransactAsset = Balances;
type CheckedAccount = CheckedAccount;
type TrustedTeleporter = TrustedTeleporter;
fn get_multi_asset() -> MultiAsset {
let amount =
<Balances as frame_support::traits::fungible::Inspect<u64>>::minimum_balance() as u128;
MultiAsset { id: Concrete(Here.into()), fun: Fungible(amount) }
}
}
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = GenesisConfig { ..Default::default() }.build_storage().unwrap();
sp_tracing::try_init_simple();
t.into()
}
@@ -0,0 +1,47 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
// Benchmarking for the `AssetTransactor` trait via `Fungible`.
pub use pallet::*;
pub mod benchmarking;
#[cfg(test)]
mod mock;
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::Get;
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config + crate::Config {
/// The type of `fungible` that is being used under the hood.
///
/// This is useful for testing and checking.
type TransactAsset: frame_support::traits::fungible::Mutate<Self::AccountId>;
/// The account used to check assets being teleported.
type CheckedAccount: Get<Option<Self::AccountId>>;
/// A trusted location which we allow teleports from, and the asset we allow to teleport.
type TrustedTeleporter: Get<Option<(xcm::latest::MultiLocation, xcm::latest::MultiAsset)>>;
/// Give me a fungible asset that your asset transactor is going to accept.
fn get_multi_asset() -> xcm::latest::MultiAsset;
}
#[pallet::pallet]
pub struct Pallet<T, I = ()>(_);
}