git.delta.rocks / unique-network / refs/commits / 369a51ded768

difftreelog

Merge pull request #974 from UniqueNetwork/fix/evm-coder-leftovers

Yaroslav Bolyukin2023-08-30parents: #0ce92f0 #c466f2a.patch.diff
in: master

25 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -528,7 +528,7 @@
 				|r: sc_service::Result<
 					up_data_structs::TokenDataVersion1<CrossAccountId>,
 					sp_runtime::DispatchError,
-				>| r.and_then(|value| Ok(value.into())),
+				>| r.map(|value| value.into()),
 			)
 			.or_else(|_| {
 				Ok(api
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -297,7 +297,7 @@
 				default_runtime,
 				// Sudo account
 				get_account_id_from_seed::<sr25519::Public>("Alice"),
-				vec![
+				[
 					(
 						get_account_id_from_seed::<sr25519::Public>("Alice"),
 						get_from_seed::<AuraId>("Alice"),
@@ -371,7 +371,7 @@
 				default_runtime,
 				// Sudo account
 				get_account_id_from_seed::<sr25519::Public>("Alice"),
-				vec![
+				[
 					(
 						get_account_id_from_seed::<sr25519::Public>("Alice"),
 						get_from_seed::<AuraId>("Alice"),
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -63,7 +63,7 @@
 	}
 	let bytes = id.to_string();
 	let len = data.len();
-	data[len - bytes.len()..].copy_from_slice(&bytes.as_bytes());
+	data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());
 	data
 }
 pub fn property_value() -> PropertyValue {
@@ -80,7 +80,7 @@
 	cast: impl FnOnce(CollectionHandle<T>) -> R,
 ) -> Result<R, DispatchError> {
 	let imbalance = <T as Config>::Currency::deposit(
-		&owner.as_sub(),
+		owner.as_sub(),
 		T::CollectionCreationPrice::get(),
 		Precision::Exact,
 	)?;
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2420,7 +2420,8 @@
 	}
 }
 
-#[cfg(feature = "tests")]
+#[cfg(any(feature = "tests", test))]
+#[allow(missing_docs)]
 pub mod tests {
 	use crate::{DispatchResult, DispatchError, LazyValue, Config};
 
@@ -2456,7 +2457,7 @@
 	}
 
 	#[rustfmt::skip]
-	pub const table: [TestCase; 16] = [
+	pub const TABLE: [TestCase; 16] = [
 		//                    ┌╴collection_admin
 		//                    │  ┌╴is_collection_admin
 		//                    │  │   ┌╴token_owner
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -286,7 +286,14 @@
 {
 	let call = C::parse_full(input)?;
 	if call.is_none() {
-		return Err("unrecognized selector".into());
+		let selector = if input.len() >= 4 {
+			let mut selector = [0; 4];
+			selector.copy_from_slice(&input[..4]);
+			u32::from_be_bytes(selector)
+		} else {
+			0
+		};
+		return Err(format!("unrecognized selector: 0x{selector:0>8x}").into());
 	}
 	let call = call.unwrap();
 
@@ -329,7 +336,7 @@
 		ERC165Call(ERC165Call, PhantomData<fn() -> T>),
 		OtherCall(ERC165Call),
 
-		#[weight(Weight::from_ref_time(a + b))]
+		#[weight(Weight::from_parts(a + b, 0))]
 		Example {
 			a: u64,
 			b: u64,
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -53,7 +53,7 @@
 		let data = (0..b).map(|i| {
 			bench_init!(to: cross_sub(i););
 			(to, 200)
-		}).collect::<BTreeMap<_, _>>().try_into().unwrap();
+		}).collect::<BTreeMap<_, _>>();
 	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
 
 	burn_item {
modifiedpallets/identity/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/identity/src/benchmarking.rs
+++ b/pallets/identity/src/benchmarking.rs
@@ -35,6 +35,7 @@
 //! Identity pallet benchmarking.
 
 #![cfg(feature = "runtime-benchmarks")]
+#![allow(clippy::no_effect)]
 
 use super::*;
 
modifiedpallets/identity/src/tests.rsdiffbeforeafterboth
--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -67,7 +67,7 @@
 
 parameter_types! {
 	pub BlockWeights: frame_system::limits::BlockWeights =
-		frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::from_ref_time(1024));
+		frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::from_parts(1024, 0));
 }
 impl frame_system::Config for Test {
 	type BaseCallFilter = frame_support::traits::Everything;
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -481,7 +481,7 @@
 		let mut registry = scale_info::Registry::new();
 		let type_id = registry.register_type(&scale_info::meta_type::<Data>());
 		let registry: scale_info::PortableRegistry = registry.into();
-		let type_info = registry.resolve(type_id.id()).unwrap();
+		let type_info = registry.resolve(type_id.id).unwrap();
 
 		let check_type_info = |data: &Data| {
 			let variant_name = match data {
@@ -492,20 +492,20 @@
 				Data::ShaThree256(_) => "ShaThree256".to_string(),
 				Data::Raw(bytes) => format!("Raw{}", bytes.len()),
 			};
-			if let scale_info::TypeDef::Variant(variant) = type_info.type_def() {
+			if let scale_info::TypeDef::Variant(variant) = &type_info.type_def {
 				let variant = variant
-					.variants()
+					.variants
 					.iter()
-					.find(|v| v.name() == &variant_name)
+					.find(|v| v.name == variant_name)
 					.expect(&format!("Expected to find variant {}", variant_name));
 
 				let field_arr_len = variant
-					.fields()
+					.fields
 					.first()
-					.and_then(|f| registry.resolve(f.ty().id()))
+					.and_then(|f| registry.resolve(f.ty.id))
 					.map(|ty| {
-						if let scale_info::TypeDef::Array(arr) = ty.type_def() {
-							arr.len()
+						if let scale_info::TypeDef::Array(arr) = &ty.type_def {
+							arr.len
 						} else {
 							panic!("Should be an array type")
 						}
@@ -513,7 +513,7 @@
 					.unwrap_or(0);
 
 				let encoded = data.encode();
-				assert_eq!(encoded[0], variant.index());
+				assert_eq!(encoded[0], variant.index);
 				assert_eq!(encoded.len() as u32 - 1, field_arr_len);
 			} else {
 				panic!("Should be a variant type")
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -78,7 +78,7 @@
 parameter_types! {
 	pub const BlockHashCount: u64 = 250;
 	pub BlockWeights: frame_system::limits::BlockWeights =
-		frame_system::limits::BlockWeights::simple_max(Weight::from_ref_time(1024));
+		frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 0));
 	pub const SS58Prefix: u8 = 42;
 }
 
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -43,12 +43,12 @@
 	owner: T::CrossAccountId,
 ) -> Result<TokenId, DispatchError> {
 	<Pallet<T>>::create_item(
-		&collection,
+		collection,
 		sender,
 		create_max_item_data::<T>(owner),
 		&Unlimited,
 	)?;
-	Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+	Ok(TokenId(<TokensMinted<T>>::get(collection.id)))
 }
 
 fn create_collection<T: Config>(
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -51,8 +51,8 @@
 	users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
 ) -> Result<TokenId, DispatchError> {
 	let data: CreateItemData<T> = create_max_item_data::<T>(users);
-	<Pallet<T>>::create_item(&collection, sender, data, &Unlimited)?;
-	Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+	<Pallet<T>>::create_item(collection, sender, data, &Unlimited)?;
+	Ok(TokenId(<TokensMinted<T>>::get(collection.id)))
 }
 
 fn create_collection<T: Config>(
@@ -104,7 +104,7 @@
 		let data = vec![create_max_item_data::<T>((0..b).map(|u| {
 			bench_init!(to: cross_sub(u););
 			(to, 200)
-		}))].try_into().unwrap();
+		}))];
 	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
 
 	// Other user left, token data is kept
modifiedpallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth
before · pallets/scheduler-v2/src/benchmarking.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Scheduler pallet benchmarking.3637use super::*;38use frame_benchmarking::{account, benchmarks};39use frame_support::{40	ensure,41	traits::{schedule::Priority, PreimageRecipient},42};43use frame_system::RawOrigin;44use sp_std::{prelude::*, vec};45use sp_io::hashing::blake2_256;4647use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};48use frame_system::Call as SystemCall;4950const SEED: u32 = 0;5152const BLOCK_NUMBER: u32 = 2;5354/// Add `n` items to the schedule.55///56/// For `resolved`:57/// - `58/// - `None`: aborted (hash without preimage)59/// - `Some(true)`: hash resolves into call if possible, plain call otherwise60/// - `Some(false)`: plain call61fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {62	let t = DispatchTime::At(when);63	let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();64	for i in 0..n {65		let call = make_call::<T>(None);66		let period = Some(((i + 100).into(), 100));67		let name = u32_to_name(i);68		Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;69	}70	ensure!(71		Agenda::<T>::get(when).agenda.len() == n as usize,72		"didn't fill schedule"73	);74	Ok(())75}7677/// Generate a name for a scheduled task from an unsigned integer.78fn u32_to_name(i: u32) -> TaskName {79	i.using_encoded(blake2_256)80}8182/// A utility for creating simple scheduled tasks.83///84/// # Arguments85/// * `periodic` - makes the task periodic.86/// 	Sets the task's period and repetition count to `100`.87/// * `named` - gives a name to the task: `u32_to_name(0)`.88/// * `signed` - determines the origin of the task.89/// 	If true, it will have the Signed origin. Otherwise it will have the Root origin.90/// 	See [`make_origin`] for details.91/// * maybe_lookup_len - sets optional lookup length. It is used to benchmark task fetching from the `Preimages` store.92/// * priority - the task's priority.93fn make_task<T: Config>(94	periodic: bool,95	named: bool,96	signed: bool,97	maybe_lookup_len: Option<u32>,98	priority: Priority,99) -> ScheduledOf<T> {100	let call = make_call::<T>(maybe_lookup_len);101	let maybe_periodic = match periodic {102		true => Some((100u32.into(), 100)),103		false => None,104	};105	let maybe_id = match named {106		true => Some(u32_to_name(0)),107		false => None,108	};109	let origin = make_origin::<T>(signed);110	Scheduled {111		maybe_id,112		priority,113		call,114		maybe_periodic,115		origin,116		_phantom: PhantomData,117	}118}119120/// Creates a `SystemCall::remark` scheduled call with a given `len` in bytes.121/// Returns `None` if the call is too large to encode.122fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {123	let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {124		remark: vec![0; len as usize],125	});126	ScheduledCall::new(call).ok()127}128129/// Creates a scheduled call and maximizes its size.130///131/// If the `maybe_lookup_len` is not supplied, the task will create the maximal `Inline` scheduled call.132///133/// Otherwise, the function will take the length value from the `maybe_lookup_len`134/// and find a minimal length value that ensures that the scheduled call will require a Preimage lookup.135fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {136	let bound = EncodedCall::bound() as u32;137	let mut len = match maybe_lookup_len {138		Some(len) => {139			len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)140				.max(bound) - 3141		}142		None => bound.saturating_sub(4),143	};144145	loop {146		let c = match bounded::<T>(len) {147			Some(x) => x,148			None => {149				len -= 1;150				continue;151			}152		};153		if c.lookup_needed() == maybe_lookup_len.is_some() {154			break c;155		}156		if maybe_lookup_len.is_some() {157			len += 1;158		} else {159			if len > 0 {160				len -= 1;161			} else {162				break c;163			}164		}165	}166}167168/// Creates an origin for a scheduled call.169///170/// If `signed` is true, it creates the Signed origin from a default account `account("origin", 0, SEED)`.171/// Otherwise, it creates the Root origin.172fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {173	match signed {174		true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),175		false => frame_system::RawOrigin::Root.into(),176	}177}178179/// Creates a dummy `WeightCounter` with the maximum possible weight limit.180fn dummy_counter() -> WeightCounter {181	WeightCounter {182		used: Weight::zero(),183		limit: Weight::MAX,184	}185}186187benchmarks! {188	// `service_agendas` when no work is done.189	// (multiple agendas - scheduled tasks in several blocks)190	service_agendas_base {191		let now = T::BlockNumber::from(BLOCK_NUMBER);192		IncompleteSince::<T>::put(now - One::one());193	}: {194		Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);195	} verify {196		assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));197	}198199	// `service_agenda` when no work is done.200	// (only one agenda - scheduled tasks in a single block)201	service_agenda_base {202		let now = BLOCK_NUMBER.into();203		let s in 0 .. T::MaxScheduledPerBlock::get();204		fill_schedule::<T>(now, s)?;205		let mut executed = 0;206	}: {207		Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);208	} verify {209		assert_eq!(executed, 0);210	}211212	// `service_task` when the task is a non-periodic, non-named, non-fetched call which is not213	// dispatched (e.g. due to being overweight).214	service_task_base {215		let now = BLOCK_NUMBER.into();216		let task = make_task::<T>(false, false, false, None, 0);217		// prevent any tasks from actually being executed as we only want the surrounding weight.218		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };219	}: {220		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);221	} verify {222		//assert_eq!(result, Ok(()));223	}224225	// TODO uncomment if we will use the Preimages226	// // `service_task` when the task is a non-periodic, non-named, fetched call (with a known227	// // preimage length) and which is not dispatched (e.g. due to being overweight).228	// service_task_fetched {229	// 	let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());230	// 	let now = BLOCK_NUMBER.into();231	// 	let task = make_task::<T>(false, false, false, Some(s), 0);232	// 	// prevent any tasks from actually being executed as we only want the surrounding weight.233	// 	let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };234	// }: {235	// 	let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);236	// } verify {237	// }238239	// `service_task` when the task is a non-periodic, named, non-fetched call which is not240	// dispatched (e.g. due to being overweight).241	service_task_named {242		let now = BLOCK_NUMBER.into();243		let task = make_task::<T>(false, true, false, None, 0);244		// prevent any tasks from actually being executed as we only want the surrounding weight.245		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };246	}: {247		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);248	} verify {249	}250251	// `service_task` when the task is a periodic, non-named, non-fetched call which is not252	// dispatched (e.g. due to being overweight).253	service_task_periodic {254		let now = BLOCK_NUMBER.into();255		let task = make_task::<T>(true, false, false, None, 0);256		// prevent any tasks from actually being executed as we only want the surrounding weight.257		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };258	}: {259		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);260	} verify {261	}262263	// `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.264	execute_dispatch_signed {265		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };266		let origin = make_origin::<T>(true);267		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;268	}: {269		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());270	}271	verify {272	}273274	// `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.275	execute_dispatch_unsigned {276		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };277		let origin = make_origin::<T>(false);278		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;279	}: {280		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());281	}282	verify {283	}284285	schedule {286		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);287		let when = BLOCK_NUMBER.into();288		let periodic = Some((T::BlockNumber::one(), 100));289		let priority = Some(0);290		// Essentially a no-op call.291		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());292293		fill_schedule::<T>(when, s)?;294	}: _(RawOrigin::Root, when, periodic, priority, call)295	verify {296		ensure!(297			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,298			"didn't add to schedule"299		);300	}301302	cancel {303		let s in 1 .. T::MaxScheduledPerBlock::get();304		let when = BLOCK_NUMBER.into();305306		fill_schedule::<T>(when, s)?;307		assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);308	}: _(RawOrigin::Root, when, 0)309	verify {310		ensure!(311			Lookup::<T>::get(u32_to_name(0)).is_none(),312			"didn't remove from lookup"313		);314		// Removed schedule is NONE315		ensure!(316			Agenda::<T>::get(when).agenda[0].is_none(),317			"didn't remove from schedule"318		);319	}320321	schedule_named {322		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);323		let id = u32_to_name(s);324		let when = BLOCK_NUMBER.into();325		let periodic = Some((T::BlockNumber::one(), 100));326		let priority = Some(0);327		// Essentially a no-op call.328		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());329330		fill_schedule::<T>(when, s)?;331	}: _(RawOrigin::Root, id, when, periodic, priority, call)332	verify {333		ensure!(334			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,335			"didn't add to schedule"336		);337	}338339	cancel_named {340		let s in 1 .. T::MaxScheduledPerBlock::get();341		let when = BLOCK_NUMBER.into();342343		fill_schedule::<T>(when, s)?;344	}: _(RawOrigin::Root, u32_to_name(0))345	verify {346		ensure!(347			Lookup::<T>::get(u32_to_name(0)).is_none(),348			"didn't remove from lookup"349		);350		// Removed schedule is NONE351		ensure!(352			Agenda::<T>::get(when).agenda[0].is_none(),353			"didn't remove from schedule"354		);355	}356357	change_named_priority {358		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;359		let s in 1 .. T::MaxScheduledPerBlock::get();360		let when = BLOCK_NUMBER.into();361		let idx = s - 1;362		let id = u32_to_name(idx);363		let priority = 42;364		fill_schedule::<T>(when, s)?;365	}: _(origin, id, priority)366	verify {367		ensure!(368			Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,369			"didn't change the priority"370		);371	}372373	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);374}
after · pallets/scheduler-v2/src/benchmarking.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Scheduler pallet benchmarking.3637use super::*;38use frame_benchmarking::{account, benchmarks};39use frame_support::{40	ensure,41	traits::{schedule::Priority, PreimageRecipient},42};43use frame_system::RawOrigin;44use sp_std::{prelude::*, vec};45use sp_io::hashing::blake2_256;4647use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};48use frame_system::Call as SystemCall;4950const SEED: u32 = 0;5152const BLOCK_NUMBER: u32 = 2;5354/// Add `n` items to the schedule.55///56/// For `resolved`:57/// - `58/// - `None`: aborted (hash without preimage)59/// - `Some(true)`: hash resolves into call if possible, plain call otherwise60/// - `Some(false)`: plain call61fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {62	let t = DispatchTime::At(when);63	let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();64	for i in 0..n {65		let call = make_call::<T>(None);66		let period = Some(((i + 100).into(), 100));67		let name = u32_to_name(i);68		Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;69	}70	ensure!(71		Agenda::<T>::get(when).agenda.len() == n as usize,72		"didn't fill schedule"73	);74	Ok(())75}7677/// Generate a name for a scheduled task from an unsigned integer.78fn u32_to_name(i: u32) -> TaskName {79	i.using_encoded(blake2_256)80}8182/// A utility for creating simple scheduled tasks.83///84/// # Arguments85/// * `periodic` - makes the task periodic.86///     Sets the task's period and repetition count to `100`.87/// * `named` - gives a name to the task: `u32_to_name(0)`.88/// * `signed` - determines the origin of the task.89///     If true, it will have the Signed origin. Otherwise it will have the Root origin.90///     See [`make_origin`] for details.91/// * maybe_lookup_len - sets optional lookup length. It is used to benchmark task fetching from the `Preimages` store.92/// * priority - the task's priority.93fn make_task<T: Config>(94	periodic: bool,95	named: bool,96	signed: bool,97	maybe_lookup_len: Option<u32>,98	priority: Priority,99) -> ScheduledOf<T> {100	let call = make_call::<T>(maybe_lookup_len);101	let maybe_periodic = match periodic {102		true => Some((100u32.into(), 100)),103		false => None,104	};105	let maybe_id = match named {106		true => Some(u32_to_name(0)),107		false => None,108	};109	let origin = make_origin::<T>(signed);110	Scheduled {111		maybe_id,112		priority,113		call,114		maybe_periodic,115		origin,116		_phantom: PhantomData,117	}118}119120/// Creates a `SystemCall::remark` scheduled call with a given `len` in bytes.121/// Returns `None` if the call is too large to encode.122fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {123	let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {124		remark: vec![0; len as usize],125	});126	ScheduledCall::new(call).ok()127}128129/// Creates a scheduled call and maximizes its size.130///131/// If the `maybe_lookup_len` is not supplied, the task will create the maximal `Inline` scheduled call.132///133/// Otherwise, the function will take the length value from the `maybe_lookup_len`134/// and find a minimal length value that ensures that the scheduled call will require a Preimage lookup.135fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {136	let bound = EncodedCall::bound() as u32;137	let mut len = match maybe_lookup_len {138		Some(len) => {139			len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)140				.max(bound) - 3141		}142		None => bound.saturating_sub(4),143	};144145	loop {146		let c = match bounded::<T>(len) {147			Some(x) => x,148			None => {149				len -= 1;150				continue;151			}152		};153		if c.lookup_needed() == maybe_lookup_len.is_some() {154			break c;155		}156		if maybe_lookup_len.is_some() {157			len += 1;158		} else if len > 0 {159			len -= 1;160		} else {161			break c;162		}163	}164}165166/// Creates an origin for a scheduled call.167///168/// If `signed` is true, it creates the Signed origin from a default account `account("origin", 0, SEED)`.169/// Otherwise, it creates the Root origin.170fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {171	match signed {172		true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),173		false => frame_system::RawOrigin::Root.into(),174	}175}176177/// Creates a dummy `WeightCounter` with the maximum possible weight limit.178fn dummy_counter() -> WeightCounter {179	WeightCounter {180		used: Weight::zero(),181		limit: Weight::MAX,182	}183}184185benchmarks! {186	// `service_agendas` when no work is done.187	// (multiple agendas - scheduled tasks in several blocks)188	service_agendas_base {189		let now = T::BlockNumber::from(BLOCK_NUMBER);190		IncompleteSince::<T>::put(now - One::one());191	}: {192		Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);193	} verify {194		assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));195	}196197	// `service_agenda` when no work is done.198	// (only one agenda - scheduled tasks in a single block)199	service_agenda_base {200		let now = BLOCK_NUMBER.into();201		let s in 0 .. T::MaxScheduledPerBlock::get();202		fill_schedule::<T>(now, s)?;203		let mut executed = 0;204	}: {205		Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);206	} verify {207		assert_eq!(executed, 0);208	}209210	// `service_task` when the task is a non-periodic, non-named, non-fetched call which is not211	// dispatched (e.g. due to being overweight).212	service_task_base {213		let now = BLOCK_NUMBER.into();214		let task = make_task::<T>(false, false, false, None, 0);215		// prevent any tasks from actually being executed as we only want the surrounding weight.216		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };217	}: {218		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);219	} verify {220		//assert_eq!(result, Ok(()));221	}222223	// TODO uncomment if we will use the Preimages224	// // `service_task` when the task is a non-periodic, non-named, fetched call (with a known225	// // preimage length) and which is not dispatched (e.g. due to being overweight).226	// service_task_fetched {227	// 	let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());228	// 	let now = BLOCK_NUMBER.into();229	// 	let task = make_task::<T>(false, false, false, Some(s), 0);230	// 	// prevent any tasks from actually being executed as we only want the surrounding weight.231	// 	let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };232	// }: {233	// 	let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);234	// } verify {235	// }236237	// `service_task` when the task is a non-periodic, named, non-fetched call which is not238	// dispatched (e.g. due to being overweight).239	service_task_named {240		let now = BLOCK_NUMBER.into();241		let task = make_task::<T>(false, true, false, None, 0);242		// prevent any tasks from actually being executed as we only want the surrounding weight.243		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };244	}: {245		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);246	} verify {247	}248249	// `service_task` when the task is a periodic, non-named, non-fetched call which is not250	// dispatched (e.g. due to being overweight).251	service_task_periodic {252		let now = BLOCK_NUMBER.into();253		let task = make_task::<T>(true, false, false, None, 0);254		// prevent any tasks from actually being executed as we only want the surrounding weight.255		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };256	}: {257		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);258	} verify {259	}260261	// `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.262	execute_dispatch_signed {263		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };264		let origin = make_origin::<T>(true);265		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;266	}: {267		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());268	}269	verify {270	}271272	// `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.273	execute_dispatch_unsigned {274		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };275		let origin = make_origin::<T>(false);276		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;277	}: {278		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());279	}280	verify {281	}282283	schedule {284		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);285		let when = BLOCK_NUMBER.into();286		let periodic = Some((T::BlockNumber::one(), 100));287		let priority = Some(0);288		// Essentially a no-op call.289		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());290291		fill_schedule::<T>(when, s)?;292	}: _(RawOrigin::Root, when, periodic, priority, call)293	verify {294		ensure!(295			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,296			"didn't add to schedule"297		);298	}299300	cancel {301		let s in 1 .. T::MaxScheduledPerBlock::get();302		let when = BLOCK_NUMBER.into();303304		fill_schedule::<T>(when, s)?;305		assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);306	}: _(RawOrigin::Root, when, 0)307	verify {308		ensure!(309			Lookup::<T>::get(u32_to_name(0)).is_none(),310			"didn't remove from lookup"311		);312		// Removed schedule is NONE313		ensure!(314			Agenda::<T>::get(when).agenda[0].is_none(),315			"didn't remove from schedule"316		);317	}318319	schedule_named {320		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);321		let id = u32_to_name(s);322		let when = BLOCK_NUMBER.into();323		let periodic = Some((T::BlockNumber::one(), 100));324		let priority = Some(0);325		// Essentially a no-op call.326		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());327328		fill_schedule::<T>(when, s)?;329	}: _(RawOrigin::Root, id, when, periodic, priority, call)330	verify {331		ensure!(332			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,333			"didn't add to schedule"334		);335	}336337	cancel_named {338		let s in 1 .. T::MaxScheduledPerBlock::get();339		let when = BLOCK_NUMBER.into();340341		fill_schedule::<T>(when, s)?;342	}: _(RawOrigin::Root, u32_to_name(0))343	verify {344		ensure!(345			Lookup::<T>::get(u32_to_name(0)).is_none(),346			"didn't remove from lookup"347		);348		// Removed schedule is NONE349		ensure!(350			Agenda::<T>::get(when).agenda[0].is_none(),351			"didn't remove from schedule"352		);353	}354355	change_named_priority {356		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;357		let s in 1 .. T::MaxScheduledPerBlock::get();358		let when = BLOCK_NUMBER.into();359		let idx = s - 1;360		let id = u32_to_name(idx);361		let priority = 42;362		fill_schedule::<T>(when, s)?;363	}: _(origin, id, priority)364	verify {365		ensure!(366			Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,367			"didn't change the priority"368		);369	}370371	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);372}
modifiedpallets/scheduler-v2/src/mock.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/mock.rs
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -33,6 +33,7 @@
 // limitations under the License.
 
 //! # Scheduler test environment.
+#![allow(deprecated)]
 
 use super::*;
 
@@ -229,6 +230,10 @@
 			r => Err(O::from(r)),
 		})
 	}
+	#[cfg(feature = "runtime-benchmarks")]
+	fn try_successful_origin() -> Result<O, ()> {
+		Ok(O::from(RawOrigin::Root))
+	}
 }
 
 pub struct Executor;
modifiedpallets/scheduler-v2/src/tests.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/tests.rs
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -33,6 +33,7 @@
 // limitations under the License.
 
 //! # Scheduler tests.
+#![allow(deprecated)]
 
 use super::*;
 use crate::mock::{
modifiedpallets/structure/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -19,8 +19,7 @@
 use frame_benchmarking::{benchmarks, account};
 use frame_support::traits::{fungible::Balanced, Get, tokens::Precision};
 use up_data_structs::{
-	CreateCollectionData, CollectionMode, CreateItemData, CollectionFlags, CreateNftData,
-	budget::Unlimited,
+	CreateCollectionData, CollectionMode, CreateItemData, CreateNftData, budget::Unlimited,
 };
 use pallet_common::Config as CommonConfig;
 use pallet_evm::account::CrossAccountId;
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,8 +24,7 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
-	Balances,
+	Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS, Balances,
 };
 use frame_support::traits::{ConstU32, ConstU64, Currency};
 use up_common::{
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -161,7 +161,8 @@
 					}
 				}
 				CollectionMode::ReFungible => {
-					let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
+					let call =
+						<UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
 					refungible::call_sponsor(call, collection, who).map(|()| sponsor)
 				}
 				CollectionMode::Fungible(_) => {
modifiedruntime/common/tests/mod.rsdiffbeforeafterboth
--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -16,7 +16,6 @@
 
 use sp_runtime::{BuildStorage, Storage};
 use sp_core::{Public, Pair};
-use sp_std::vec;
 use up_common::types::AuraId;
 use crate::{Runtime, GenesisConfig, ParachainInfoConfig, RuntimeEvent, System};
 
@@ -76,7 +75,7 @@
 		AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
 	}
 
-	let accounts = vec!["Alice", "Bob"];
+	let accounts = ["Alice", "Bob"];
 	let keys = accounts
 		.iter()
 		.map(|&acc| {
@@ -104,7 +103,7 @@
 		..GenesisConfig::default()
 	};
 
-	cfg.build_storage().unwrap().into()
+	cfg.build_storage().unwrap()
 }
 
 #[cfg(not(feature = "collator-selection"))]
modifiedruntime/common/tests/xcm.rsdiffbeforeafterboth
--- a/runtime/common/tests/xcm.rs
+++ b/runtime/common/tests/xcm.rs
@@ -26,7 +26,7 @@
 const ALICE: AccountId = AccountId::new([0u8; 32]);
 const BOB: AccountId = AccountId::new([1u8; 32]);
 
-const INITIAL_BALANCE: u128 = 1000000000000000000_0000; // 1000 UNQ
+const INITIAL_BALANCE: u128 = 10_000_000_000_000_000_000_000; // 10_000 UNQ
 
 #[test]
 pub fn xcm_transact_is_forbidden() {
modifiedruntime/tests/Cargo.tomldiffbeforeafterboth
--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -5,7 +5,6 @@
 
 [features]
 default = ['refungible']
-tests = ['pallet-common/tests']
 
 refungible = []
 
@@ -44,3 +43,6 @@
 evm-coder = { workspace = true }
 up-sponsorship = { workspace = true }
 xcm = { workspace = true }
+
+[dev-dependencies]
+pallet-common = { workspace = true, features = ["tests"] }
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -99,7 +99,7 @@
 	.try_into()
 	.unwrap();
 
-	let data: CreateCollectionData<u64> = CreateCollectionData {
+	let data = CreateCollectionData {
 		name: col_name1.try_into().unwrap(),
 		description: col_desc1.try_into().unwrap(),
 		token_prefix: token_prefix1.try_into().unwrap(),
@@ -204,14 +204,13 @@
 		let description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
 		let token_prefix: Vec<u8> = b"token_prefix1\0".to_vec();
 
-		let data: CreateCollectionData<<Test as frame_system::Config>::AccountId> =
-			CreateCollectionData {
-				name: name.try_into().unwrap(),
-				description: description.try_into().unwrap(),
-				token_prefix: token_prefix.try_into().unwrap(),
-				mode: CollectionMode::NFT,
-				..Default::default()
-			};
+		let data = CreateCollectionData {
+			name: name.try_into().unwrap(),
+			description: description.try_into().unwrap(),
+			token_prefix: token_prefix.try_into().unwrap(),
+			mode: CollectionMode::NFT,
+			..Default::default()
+		};
 
 		let result = Unique::create_collection_ex(RuntimeOrigin::signed(acc), data);
 		assert_err!(result, <CommonError<Test>>::NotSufficientFounds);
@@ -225,7 +224,7 @@
 		let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
 		let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
 
-		let data: CreateCollectionData<u64> = CreateCollectionData {
+		let data = CreateCollectionData {
 			name: col_name1.try_into().unwrap(),
 			description: col_desc1.try_into().unwrap(),
 			token_prefix: token_prefix1.try_into().unwrap(),
@@ -2364,7 +2363,7 @@
 		let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
 		let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
 
-		let data: CreateCollectionData<u64> = CreateCollectionData {
+		let data = CreateCollectionData {
 			name: col_name1.try_into().unwrap(),
 			description: col_desc1.try_into().unwrap(),
 			token_prefix: token_prefix1.try_into().unwrap(),
@@ -2618,9 +2617,7 @@
 
 mod check_token_permissions {
 	use super::*;
-	use frame_support::once_cell::sync::Lazy;
 	use pallet_common::LazyValue;
-	use sp_runtime::DispatchError;
 
 	fn test<FTE: FnOnce() -> bool>(
 		i: usize,
@@ -2662,7 +2659,7 @@
 	fn no_permission_only() {
 		new_test_ext().execute_with(|| {
 			let mut check_token_existence = LazyValue::new(|| true);
-			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+			for (i, row) in pallet_common::tests::TABLE.iter().enumerate() {
 				test(i, row, &mut check_token_existence);
 			}
 		});
@@ -2671,7 +2668,7 @@
 	#[test]
 	fn no_permission_and_token_not_found() {
 		new_test_ext().execute_with(|| {
-			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+			for (i, row) in pallet_common::tests::TABLE.iter().enumerate() {
 				// This is inside the loop to keep track of whether the lambda was called
 				let mut check_token_existence = LazyValue::new(|| false);
 				test(i, row, &mut check_token_existence);
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -106,15 +106,17 @@
       flags: [CollectionFlag.Erc721metadata],
     }, 'nft');
 
-    await mintCollectionHelper(helper, alice, {
+    // User can not set Foreign flag itself
+
+    await expect(mintCollectionHelper(helper, alice, {
       name: 'name', description: 'descr', tokenPrefix: 'COL',
       flags: [CollectionFlag.Foreign],
-    }, 'nft');
+    }, 'nft')).to.be.rejectedWith(/common.NoPermission/);
 
-    await mintCollectionHelper(helper, alice, {
+    await expect(mintCollectionHelper(helper, alice, {
       name: 'name', description: 'descr', tokenPrefix: 'COL',
       flags: [CollectionFlag.Erc721metadata, CollectionFlag.Foreign],
-    }, 'nft');
+    }, 'nft')).to.be.rejectedWith(/common.NoPermission/);
   });
 
   itSub('Create new collection with extra fields', async ({helper}) => {
modifiedtests/src/eth/collectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionLimits.test.ts
+++ b/tests/src/eth/collectionLimits.test.ts
@@ -106,7 +106,7 @@
 
       // Cannot disable limits
       await expect(collectionEvm.methods
-        .setCollectionLimit({field: CollectionLimitField.AccountTokenOwnership, value: {status: false, value: 200}})
+        .setCollectionLimit({field: CollectionLimitField.AccountTokenOwnership, value: {status: false, value: 0}})
         .call()).to.be.rejectedWith('user can\'t disable limits');
 
       await expect(collectionEvm.methods
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -41,7 +41,7 @@
       for(const arg of args) {
         if(typeof arg !== 'string')
           continue;
-        const skippedWarnings = ['1000:: Normal connection closure', 'Not decorating unknown runtime apis:', 'RPC methods not decorated:', 'Not decorating runtime apis'];
+        const skippedWarnings = ['1000:: Normal connection closure', 'Not decorating unknown runtime apis:', 'RPC methods not decorated:', 'Not decorating runtime apis', 'Bad input data provided to validate_transaction', 'account balance too low', '1006:: Abnormal Closure'];
         const needToSkip = skippedWarnings.reduce((a,  b) => a || arg.includes(b), false);
         if(needToSkip || arg === 'Normal connection closure')
           return;