git.delta.rocks / unique-network / refs/commits / a64769ff6bff

difftreelog

refactor upgrade code for new substrate

Yaroslav Bolyukin2023-10-02parent: #c318883.patch.diff
in: master

39 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -153,11 +153,12 @@
 	) => {{
 		use $runtime::*;
 
-		GenesisConfig {
+		RuntimeGenesisConfig {
 			system: SystemConfig {
 				code: WASM_BINARY
 					.expect("WASM binary was not build, please build it!")
 					.to_vec(),
+				..Default::default()
 			},
 			balances: BalancesConfig {
 				balances: $endowed_accounts
@@ -167,10 +168,6 @@
 					.map(|k| (k, 1 << 100))
 					.collect(),
 			},
-			common: Default::default(),
-			configuration: Default::default(),
-			nonfungible: Default::default(),
-			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
 			sudo: SudoConfig {
 				key: Some($root_key),
@@ -179,8 +176,8 @@
 			vesting: VestingConfig { vesting: vec![] },
 			parachain_info: ParachainInfoConfig {
 				parachain_id: $id.into(),
+				..Default::default()
 			},
-			parachain_system: Default::default(),
 			collator_selection: CollatorSelectionConfig {
 				invulnerables: $initial_invulnerables
 					.iter()
@@ -200,14 +197,10 @@
 					})
 					.collect(),
 			},
-			aura: Default::default(),
-			aura_ext: Default::default(),
 			evm: EVMConfig {
 				accounts: BTreeMap::new(),
+				..Default::default()
 			},
-			ethereum: EthereumConfig {},
-			polkadot_xcm: Default::default(),
-			transaction_payment: Default::default(),
 			..Default::default()
 		}
 	}};
@@ -224,15 +217,13 @@
 	) => {{
 		use $runtime::*;
 
-		GenesisConfig {
+		RuntimeGenesisConfig {
 			system: SystemConfig {
 				code: WASM_BINARY
 					.expect("WASM binary was not build, please build it!")
 					.to_vec(),
+				..Default::default()
 			},
-			common: Default::default(),
-			configuration: Default::default(),
-			nonfungible: Default::default(),
 			balances: BalancesConfig {
 				balances: $endowed_accounts
 					.iter()
@@ -241,7 +232,6 @@
 					.map(|k| (k, 1 << 100))
 					.collect(),
 			},
-			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
 			sudo: SudoConfig {
 				key: Some($root_key),
@@ -249,21 +239,19 @@
 			vesting: VestingConfig { vesting: vec![] },
 			parachain_info: ParachainInfoConfig {
 				parachain_id: $id.into(),
+				Default::default()
 			},
-			parachain_system: Default::default(),
 			aura: AuraConfig {
 				authorities: $initial_invulnerables
 					.into_iter()
 					.map(|(_, aura)| aura)
 					.collect(),
 			},
-			aura_ext: Default::default(),
 			evm: EVMConfig {
 				accounts: BTreeMap::new(),
+				..Default::default()
 			},
-			ethereum: EthereumConfig {},
-			polkadot_xcm: Default::default(),
-			transaction_payment: Default::default(),
+			..Default::default()
 		}
 	}};
 }
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -135,19 +135,6 @@
 	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
 		load_spec(id)
 	}
-
-	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
-		match chain_spec.runtime_id() {
-			#[cfg(feature = "unique-runtime")]
-			RuntimeId::Unique => &unique_runtime::VERSION,
-
-			#[cfg(feature = "quartz-runtime")]
-			RuntimeId::Quartz => &quartz_runtime::VERSION,
-
-			RuntimeId::Opal => &opal_runtime::VERSION,
-			runtime_id => panic!("{}", no_runtime_err!(runtime_id)),
-		}
-	}
 }
 
 impl SubstrateCli for RelayChainCli {
@@ -184,25 +171,21 @@
 
 	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
 		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
-	}
-
-	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
-		polkadot_cli::Cli::native_runtime_version(chain_spec)
 	}
 }
 
 macro_rules! async_run_with_runtime {
 	(
-		$runtime_api:path, $executor:path,
+		$runtime:path, $runtime_api:path, $executor:path,
 		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
 		$( $code:tt )*
 	) => {
 		$runner.async_run(|$config| {
 			let $components = new_partial::<
-				$runtime_api, $executor, _
+				$runtime, $runtime_api, $executor, _
 			>(
 				&$config,
-				crate::service::parachain_build_import_queue,
+				crate::service::parachain_build_import_queue::<$runtime, _, _>,
 			)?;
 			let task_manager = $components.task_manager;
 
@@ -218,18 +201,18 @@
 		match runner.config().chain_spec.runtime_id() {
 			#[cfg(feature = "unique-runtime")]
 			RuntimeId::Unique => async_run_with_runtime!(
-				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+				unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			#[cfg(feature = "quartz-runtime")]
 			RuntimeId::Quartz => async_run_with_runtime!(
-				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+				quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			RuntimeId::Opal => async_run_with_runtime!(
-				opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+				opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
@@ -240,11 +223,18 @@
 
 macro_rules! sync_run_with_runtime {
 	(
-		$runtime_api:path, $executor:path,
+		$runtime:path, $runtime_api:path, $executor:path,
 		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
 		$( $code:tt )*
 	) => {
 		$runner.sync_run(|$config| {
+			let $components = new_partial::<
+				$runtime, $runtime_api, $executor, _
+			>(
+				&$config,
+				crate::service::parachain_build_import_queue::<$runtime, _, _>,
+			)?;
+
 			$( $code )*
 		})
 	};
@@ -257,18 +247,18 @@
 		match runner.config().chain_spec.runtime_id() {
 			#[cfg(feature = "unique-runtime")]
 			RuntimeId::Unique => sync_run_with_runtime!(
-				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+				unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			#[cfg(feature = "quartz-runtime")]
 			RuntimeId::Quartz => sync_run_with_runtime!(
-				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+				quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			RuntimeId::Opal => sync_run_with_runtime!(
-				opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+				opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
@@ -362,12 +352,11 @@
 		Some(Subcommand::ExportGenesisState(cmd)) => {
 			construct_sync_run!(|components, cli, cmd, _config| {
 				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
-				let state_version = Cli::native_runtime_version(&spec).state_version();
-				cmd.run::<Block>(&*spec, state_version)
+				cmd.run(&*spec, &*components.client)
 			})
 		}
 		Some(Subcommand::ExportGenesisWasm(cmd)) => {
-			construct_sync_run!(|components, cli, cmd, _config| {
+			construct_sync_run!(|_components, cli, cmd, _config| {
 				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
 				cmd.run(&*spec)
 			})
@@ -411,6 +400,7 @@
 		#[cfg(feature = "try-runtime")]
 		Some(Subcommand::TryRuntime(cmd)) => {
 			use std::{future::Future, pin::Pin};
+
 			use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
 			use try_runtime_cli::block_building_info::timestamp_with_aura_info;
 
@@ -506,12 +496,6 @@
 					AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
 						&para_id,
 					);
-
-				let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();
-				let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
-					.map_err(|e| format!("{e:?}"))?;
-				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
-				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
 
 				let polkadot_config = SubstrateCli::create_configuration(
 					&polkadot_cli,
@@ -522,9 +506,6 @@
 
 				info!("Parachain id: {:?}", para_id);
 				info!("Parachain Account: {}", parachain_account);
-				info!("Parachain genesis state: {}", genesis_state);
-				info!("Parachain genesis hash: {}", genesis_hash);
-				debug!("Parachain genesis block: {:?}", block);
 				info!(
 					"Is collating: {}",
 					if config.role.is_authority() {
modifiednode/cli/src/service.rsdiffbeforeafterboth
--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -185,7 +185,7 @@
 	}
 }
 
-pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(
+pub fn open_frontier_backend<C: HeaderBackend<Block>>(
 	client: Arc<C>,
 	config: &Configuration,
 ) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {
@@ -210,12 +210,42 @@
 type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =
 	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;
 
+/// Generate a supertrait based on bounds, and blanket impl for it.
+macro_rules! ez_bounds {
+	($vis:vis trait $name:ident$(<$($gen:ident $(: $($(+)? $bound:path)*)?),* $(,)?>)? $(:)? $($(+)? $super:path)* {}) => {
+		$vis trait $name $(<$($gen $(: $($bound+)*)?,)*>)?: $($super +)* {}
+		impl<T, $($($gen $(: $($bound+)*)?,)*)?> $name$(<$($gen,)*>)? for T
+		where T: $($super +)* {}
+	}
+}
+ez_bounds!(
+	pub trait RuntimeApiDep<Runtime: RuntimeInstance>:
+		sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+		+ sp_consensus_aura::AuraApi<Block, AuraId>
+		+ fp_rpc::EthereumRuntimeRPCApi<Block>
+		+ sp_session::SessionKeys<Block>
+		+ sp_block_builder::BlockBuilder<Block>
+		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
+		+ sp_api::ApiExt<Block>
+		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
+		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+		+ up_pov_estimate_rpc::PovEstimateApi<Block>
+		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>
+		+ sp_api::Metadata<Block>
+		+ sp_offchain::OffchainWorkerApi<Block>
+		+ cumulus_primitives_core::CollectCollationInfo<Block>
+		// Deprecated, not used.
+		+ fp_rpc::ConvertTransactionRuntimeApi<Block>
+	{
+	}
+);
+
 /// Starts a `ServiceBuilder` for a full service.
 ///
 /// Use this macro if you don't actually need the full service, but just the builder in order to
 /// be able to perform chain operations.
 #[allow(clippy::type_complexity)]
-pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(
+pub fn new_partial<Runtime, RuntimeApi, ExecutorDispatch, BIQ>(
 	config: &Configuration,
 	build_import_queue: BIQ,
 ) -> Result<
@@ -223,7 +253,7 @@
 		FullClient<RuntimeApi, ExecutorDispatch>,
 		FullBackend,
 		FullSelectChain,
-		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
+		sc_consensus::DefaultImportQueue<Block>,
 		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
 		OtherPartial,
 	>,
@@ -235,7 +265,8 @@
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,
+	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+	Runtime: RuntimeInstance,
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
 	BIQ: FnOnce(
 		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
@@ -243,10 +274,7 @@
 		&Configuration,
 		Option<TelemetryHandle>,
 		&TaskManager,
-	) -> Result<
-		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
-		sc_service::Error,
-	>,
+	) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,
 {
 	let telemetry = config
 		.telemetry_endpoints
@@ -317,35 +345,6 @@
 	};
 
 	Ok(params)
-}
-
-async fn build_relay_chain_interface(
-	polkadot_config: Configuration,
-	parachain_config: &Configuration,
-	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
-	task_manager: &mut TaskManager,
-	collator_options: CollatorOptions,
-	hwbench: Option<sc_sysinfo::HwBench>,
-) -> RelayChainResult<(
-	Arc<(dyn RelayChainInterface + 'static)>,
-	Option<CollatorPair>,
-)> {
-	if collator_options.relay_chain_rpc_urls.is_empty() {
-		build_inprocess_relay_chain(
-			polkadot_config,
-			parachain_config,
-			telemetry_worker_handle,
-			task_manager,
-			hwbench,
-		)
-	} else {
-		build_minimal_relay_chain_node(
-			polkadot_config,
-			task_manager,
-			collator_options.relay_chain_rpc_urls,
-		)
-		.await
-	}
 }
 
 macro_rules! clone {
@@ -360,13 +359,11 @@
 ///
 /// This is the actual implementation that is abstract over the executor and the runtime api.
 #[sc_tracing::logging::prefix_logs_with("Parachain")]
-async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(
+pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(
 	parachain_config: Configuration,
 	polkadot_config: Configuration,
 	collator_options: CollatorOptions,
-	id: ParaId,
-	build_import_queue: BIQ,
-	build_consensus: BIC,
+	para_id: ParaId,
 	hwbench: Option<sc_sysinfo::HwBench>,
 ) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>
 where
@@ -378,48 +375,16 @@
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
-		+ fp_rpc::EthereumRuntimeRPCApi<Block>
-		+ fp_rpc::ConvertTransactionRuntimeApi<Block>
-		+ sp_session::SessionKeys<Block>
-		+ sp_block_builder::BlockBuilder<Block>
-		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
-		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
-		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
-		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
-		+ up_pov_estimate_rpc::PovEstimateApi<Block>
-		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
-		+ sp_api::Metadata<Block>
-		+ sp_offchain::OffchainWorkerApi<Block>
-		+ cumulus_primitives_core::CollectCollationInfo<Block>,
+	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+	Runtime: RuntimeInstance,
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
-	BIQ: FnOnce(
-		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
-		Arc<FullBackend>,
-		&Configuration,
-		Option<TelemetryHandle>,
-		&TaskManager,
-	) -> Result<
-		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
-		sc_service::Error,
-	>,
-	BIC: FnOnce(
-		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
-		Arc<FullBackend>,
-		Option<&Registry>,
-		Option<TelemetryHandle>,
-		&TaskManager,
-		Arc<dyn RelayChainInterface>,
-		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,
-		Arc<SyncingService<Block>>,
-		KeystorePtr,
-		bool,
-	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,
 {
 	let parachain_config = prepare_node_config(parachain_config);
 
-	let params =
-		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;
+	let params = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
+		&parachain_config,
+		parachain_build_import_queue,
+	)?;
 	let OtherPartial {
 		mut telemetry,
 		telemetry_worker_handle,
@@ -443,9 +408,9 @@
 	.await
 	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
 
-	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);
+	let block_announce_validator =
+		RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), para_id);
 
-	let force_authoring = parachain_config.force_authoring;
 	let validator = parachain_config.role.is_authority();
 	let prometheus_registry = parachain_config.prometheus_registry().cloned();
 	let transaction_pool = params.transaction_pool.clone();
@@ -531,7 +496,7 @@
 
 			let mut rpc_handle = RpcModule::new(());
 
-			let full_deps = unique_rpc::FullDeps {
+			let full_deps = FullDeps {
 				client: client.clone(),
 				runtime_id,
 
@@ -551,9 +516,9 @@
 				select_chain,
 			};
 
-			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;
+			create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;
 
-			let eth_deps = unique_rpc::EthDeps {
+			let eth_deps = EthDeps {
 				client,
 				graph: transaction_pool.pool().clone(),
 				pool: transaction_pool,
@@ -571,9 +536,18 @@
 				eth_pubsub_notification_sinks,
 				overrides,
 				sync: sync_service.clone(),
+				pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
 			};
 
-			unique_rpc::create_eth(
+			create_eth::<
+				_,
+				_,
+				_,
+				_,
+				_,
+				_,
+				DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
+			>(
 				&mut rpc_handle,
 				eth_deps,
 				subscription_task_executor.clone(),
@@ -624,8 +598,25 @@
 		.overseer_handle()
 		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
 
+	start_relay_chain_tasks(StartRelayChainTasksParams {
+		client: client.clone(),
+		announce_block: announce_block.clone(),
+		para_id,
+		relay_chain_interface: relay_chain_interface.clone(),
+		task_manager: &mut task_manager,
+		da_recovery_profile: if validator {
+			DARecoveryProfile::Collator
+		} else {
+			DARecoveryProfile::FullNode
+		},
+		import_queue: import_queue_service,
+		relay_chain_slot_duration,
+		recovery_handle: Box::new(overseer_handle.clone()),
+		sync_service: sync_service.clone(),
+	})?;
+
 	if validator {
-		let parachain_consensus = build_consensus(
+		start_consensus(
 			client.clone(),
 			backend.clone(),
 			prometheus_registry.as_ref(),
@@ -635,42 +626,12 @@
 			transaction_pool,
 			sync_service.clone(),
 			params.keystore_container.keystore(),
-			force_authoring,
-		)?;
-
-		let spawner = task_manager.spawn_handle();
-
-		let params = StartCollatorParams {
-			para_id: id,
-			block_status: client.clone(),
-			announce_block,
-			client: client.clone(),
-			task_manager: &mut task_manager,
-			spawner,
-			parachain_consensus,
-			import_queue: import_queue_service,
-			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),
-			relay_chain_interface,
+			overseer_handle,
 			relay_chain_slot_duration,
-			recovery_handle: Box::new(overseer_handle),
-			sync_service,
-		};
-
-		start_collator(params).await?;
-	} else {
-		let params = StartFullNodeParams {
-			client: client.clone(),
+			para_id,
+			collator_key.expect("cli args do not allow this"),
 			announce_block,
-			task_manager: &mut task_manager,
-			para_id: id,
-			import_queue: import_queue_service,
-			relay_chain_interface,
-			relay_chain_slot_duration,
-			recovery_handle: Box::new(overseer_handle),
-			sync_service,
-		};
-
-		start_full_node(params)?;
+		)?;
 	}
 
 	start_network.start_network();
@@ -679,25 +640,20 @@
 }
 
 /// Build the import queue for the the parachain runtime.
-pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(
+pub fn parachain_build_import_queue<Runtime, RuntimeApi, ExecutorDispatch>(
 	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
 	backend: Arc<FullBackend>,
 	config: &Configuration,
 	telemetry: Option<TelemetryHandle>,
 	task_manager: &TaskManager,
-) -> Result<
-	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
-	sc_service::Error,
->
+) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
 where
 	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
-		+ sp_block_builder::BlockBuilder<Block>
-		+ sp_consensus_aura::AuraApi<Block, AuraId>
-		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
+	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+	Runtime: RuntimeInstance,
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
 {
 	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
@@ -732,120 +688,81 @@
 	.map_err(Into::into)
 }
 
-/// Start a normal parachain node.
-pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(
-	parachain_config: Configuration,
-	polkadot_config: Configuration,
-	collator_options: CollatorOptions,
-	id: ParaId,
-	hwbench: Option<sc_sysinfo::HwBench>,
-) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>
+pub fn start_consensus<ExecutorDispatch, RuntimeApi, Runtime>(
+	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
+	backend: Arc<FullBackend>,
+	prometheus_registry: Option<&Registry>,
+	telemetry: Option<TelemetryHandle>,
+	task_manager: &TaskManager,
+	relay_chain_interface: Arc<dyn RelayChainInterface>,
+	transaction_pool: Arc<
+		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
+	>,
+	sync_oracle: Arc<SyncingService<Block>>,
+	keystore: KeystorePtr,
+	overseer_handle: OverseerHandle,
+	relay_chain_slot_duration: Duration,
+	para_id: ParaId,
+	collator_key: CollatorPair,
+	announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
+) -> Result<(), sc_service::Error>
 where
-	Runtime: RuntimeInstance + Send + Sync + 'static,
-	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,
-	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,
+	ExecutorDispatch: NativeExecutionDispatch + 'static,
 	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
-		+ fp_rpc::EthereumRuntimeRPCApi<Block>
-		+ fp_rpc::ConvertTransactionRuntimeApi<Block>
-		+ sp_session::SessionKeys<Block>
-		+ sp_block_builder::BlockBuilder<Block>
-		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
-		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
-		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
-		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
-		+ up_pov_estimate_rpc::PovEstimateApi<Block>
-		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
-		+ sp_api::Metadata<Block>
-		+ sp_offchain::OffchainWorkerApi<Block>
-		+ cumulus_primitives_core::CollectCollationInfo<Block>
-		+ sp_consensus_aura::AuraApi<Block, AuraId>,
-	ExecutorDispatch: NativeExecutionDispatch + 'static,
+	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+	Runtime: RuntimeInstance,
 {
-	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(
-		parachain_config,
-		polkadot_config,
-		collator_options,
-		id,
-		parachain_build_import_queue,
-		|client,
-		 backend,
-		 prometheus_registry,
-		 telemetry,
-		 task_manager,
-		 relay_chain_interface,
-		 transaction_pool,
-		 sync_oracle,
-		 keystore,
-		 force_authoring| {
-			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
+	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
 
-			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
-				task_manager.spawn_handle(),
-				client.clone(),
-				transaction_pool,
-				prometheus_registry,
-				telemetry.clone(),
-			);
+	let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
+		task_manager.spawn_handle(),
+		client.clone(),
+		transaction_pool,
+		prometheus_registry,
+		telemetry.clone(),
+	);
+	let proposer = Proposer::new(proposer_factory);
 
-			let block_import = ParachainBlockImport::new(client.clone(), backend);
+	let collator_service = CollatorService::new(
+		client.clone(),
+		Arc::new(task_manager.spawn_handle()),
+		announce_block,
+		client.clone(),
+	);
 
-			Ok(AuraConsensus::build::<
-				sp_consensus_aura::sr25519::AuthorityPair,
-				_,
-				_,
-				_,
-				_,
-				_,
-				_,
-			>(BuildAuraConsensusParams {
-				proposer_factory,
-				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {
-					let relay_chain_interface = relay_chain_interface.clone();
-					async move {
-						let parachain_inherent =
-						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(
-							relay_parent,
-							&relay_chain_interface,
-							&validation_data,
-							id,
-						).await;
+	let block_import = ParachainBlockImport::new(client.clone(), backend);
 
-						let time = sp_timestamp::InherentDataProvider::from_system_time();
+	let params = BuildAuraConsensusParams {
+		create_inherent_data_providers: move |_, ()| async move { Ok(()) },
+		block_import,
+		para_client: client,
+		#[cfg(feature = "lookahead")]
+		para_backend: backend,
+		para_id,
+		relay_client: relay_chain_interface,
+		sync_oracle,
+		keystore,
+		slot_duration,
+		proposer,
+		collator_service,
+		// With async-baking, we allowed to be both slower (longer authoring) and faster (multiple para blocks per relay block)
+		authoring_duration: Duration::from_millis(500),
+		overseer_handle,
+		#[cfg(feature = "lookahead")]
+		code_hash_provider: || {},
+		collator_key,
+		relay_chain_slot_duration,
+	};
 
-						let slot =
-						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
-							*time,
-							slot_duration,
-						);
-
-						let parachain_inherent = parachain_inherent.ok_or_else(|| {
-							Box::<dyn std::error::Error + Send + Sync>::from(
-								"Failed to create parachain inherent",
-							)
-						})?;
-						Ok((slot, time, parachain_inherent))
-					}
-				},
-				block_import,
-				para_client: client,
-				backoff_authoring_blocks: Option::<()>::None,
-				sync_oracle,
-				keystore,
-				force_authoring,
-				slot_duration,
-				// We got around 500ms for proposing
-				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),
-				telemetry,
-				max_block_proposal_slot_portion: None,
-			}))
-		},
-		hwbench,
-	)
-	.await
+	task_manager.spawn_essential_handle().spawn(
+		"aura",
+		None,
+		run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _>(params),
+	);
+	Ok(())
 }
 
 fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(
@@ -854,17 +771,14 @@
 	config: &Configuration,
 	_: Option<TelemetryHandle>,
 	task_manager: &TaskManager,
-) -> Result<
-	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
-	sc_service::Error,
->
+) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
 where
 	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
-		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
+	RuntimeApi::RuntimeApi:
+		sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> + sp_api::ApiExt<Block>,
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
 {
 	Ok(sc_consensus_manual_seal::import_queue(
@@ -881,6 +795,15 @@
 	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
 }
 
+struct DefaultEthConfig<C>(PhantomData<C>);
+impl<C> EthConfig<Block, C> for DefaultEthConfig<C>
+where
+	C: StorageProvider<Block, FullBackend> + Sync + Send + 'static,
+{
+	type EstimateGasAdapter = ();
+	type RuntimeStorageOverride = SystemAccountId32StorageOverride<Block, C, FullBackend>;
+}
+
 /// Builds a new development service. This service uses instant seal, and mocks
 /// the parachain inherent
 pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(
@@ -897,28 +820,14 @@
 		+ Send
 		+ Sync
 		+ 'static,
-	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
-		+ fp_rpc::EthereumRuntimeRPCApi<Block>
-		+ fp_rpc::ConvertTransactionRuntimeApi<Block>
-		+ sp_session::SessionKeys<Block>
-		+ sp_block_builder::BlockBuilder<Block>
-		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
-		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
-		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
-		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
-		+ up_pov_estimate_rpc::PovEstimateApi<Block>
-		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
-		+ sp_api::Metadata<Block>
-		+ sp_offchain::OffchainWorkerApi<Block>
-		+ cumulus_primitives_core::CollectCollationInfo<Block>
-		+ sp_consensus_aura::AuraApi<Block, AuraId>,
+	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
 {
+	use fc_consensus::FrontierBlockImport;
 	use sc_consensus_manual_seal::{
 		run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,
 		DelayedFinalizeParams,
 	};
-	use fc_consensus::FrontierBlockImport;
 
 	let sc_service::PartialComponents {
 		client,
@@ -935,7 +844,7 @@
 				eth_backend,
 				telemetry_worker_handle: _,
 			},
-	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(
+	} = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
 		&config,
 		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,
 	)?;
@@ -953,15 +862,6 @@
 			block_announce_validator_builder: None,
 			warp_sync_params: None,
 		})?;
-
-	if config.offchain_worker.enabled {
-		sc_service::build_offchain_workers(
-			&config,
-			task_manager.spawn_handle(),
-			client.clone(),
-			network.clone(),
-		);
-	}
 
 	let collator = config.role.is_authority();
 
@@ -1141,7 +1041,7 @@
 
 			let mut rpc_module = RpcModule::new(());
 
-			let full_deps = unique_rpc::FullDeps {
+			let full_deps = FullDeps {
 				runtime_id,
 
 				#[cfg(feature = "pov-estimate")]
@@ -1161,9 +1061,9 @@
 				select_chain,
 			};
 
-			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;
+			create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;
 
-			let eth_deps = unique_rpc::EthDeps {
+			let eth_deps = EthDeps {
 				client,
 				graph: transaction_pool.pool().clone(),
 				pool: transaction_pool,
@@ -1181,9 +1081,19 @@
 				eth_pubsub_notification_sinks,
 				overrides,
 				sync: sync_service.clone(),
+				// We don't have any inherents except parachain built-ins, which we can't even extract from inside `run_aura`.
+				pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
 			};
 
-			unique_rpc::create_eth(
+			create_eth::<
+				_,
+				_,
+				_,
+				_,
+				_,
+				_,
+				DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
+			>(
 				&mut rpc_module,
 				eth_deps,
 				subscription_task_executor.clone(),
@@ -1241,37 +1151,35 @@
 	})
 }
 
-pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {
+pub struct FrontierTaskParams<'a, C, B> {
 	pub task_manager: &'a TaskManager,
 	pub client: Arc<C>,
-	pub substrate_backend: Arc<BE>,
-	pub eth_backend: Arc<fc_db::kv::Backend<B>>,
+	pub substrate_backend: Arc<B>,
+	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
 	pub eth_filter_pool: Option<FilterPool>,
-	pub overrides: Arc<OverrideHandle<B>>,
+	pub overrides: Arc<OverrideHandle<Block>>,
 	pub fee_history_limit: u64,
 	pub fee_history_cache: FeeHistoryCache,
 	pub sync_strategy: SyncStrategy,
 	pub prometheus_registry: Option<Registry>,
 }
 
-pub fn spawn_frontier_tasks<B, C, BE>(
-	params: FrontierTaskParams<B, C, BE>,
-	sync: Arc<SyncingService<B>>,
+pub fn spawn_frontier_tasks<C, B>(
+	params: FrontierTaskParams<C, B>,
+	sync: Arc<SyncingService<Block>>,
 	pubsub_notification_sinks: Arc<
-		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,
+		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,
 	>,
-) -> Arc<EthBlockDataCacheTask<B>>
+) -> Arc<EthBlockDataCacheTask<Block>>
 where
-	C: ProvideRuntimeApi<B> + BlockOf,
-	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,
-	C: BlockchainEvents<B> + StorageProvider<B, BE>,
+	C: ProvideRuntimeApi<Block> + BlockOf,
+	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
+	C: BlockchainEvents<Block> + StorageProvider<Block, B>,
 	C: Send + Sync + 'static,
-	C::Api: EthereumRuntimeRPCApi<B>,
-	C::Api: BlockBuilder<B>,
-	B: BlockT<Hash = H256> + Send + Sync + 'static,
-	B::Header: HeaderT<Number = u32>,
-	BE: Backend<B> + 'static,
-	BE::State: StateBackend<BlakeTwo256>,
+	C::Api: EthereumRuntimeRPCApi<Block>,
+	C::Api: BlockBuilder<Block>,
+	B: Backend<Block> + 'static,
+	B::State: StateBackend<BlakeTwo256>,
 {
 	let FrontierTaskParams {
 		task_manager,
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -32,7 +32,7 @@
 fn set_admin<T>() -> Result<T::AccountId, sp_runtime::DispatchError>
 where
 	T: Config + pallet_unique::Config + pallet_evm_migration::Config,
-	T::BlockNumber: From<u32> + Into<u32>,
+	BlockNumberFor<T>: From<u32> + Into<u32>,
 	BalanceOf<T>: Sum + From<u128>,
 {
 	let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
@@ -53,7 +53,7 @@
 benchmarks! {
 	where_clause{
 		where T:  Config + pallet_unique::Config + pallet_evm_migration::Config ,
-		T::BlockNumber: From<u32> + Into<u32>,
+		BlockNumberFor<T>: From<u32> + Into<u32>,
 		BalanceOf<T>: Sum + From<u128>
 	}
 
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -125,11 +125,11 @@
 
 		/// In relay blocks.
 		#[pallet::constant]
-		type RecalculationInterval: Get<Self::BlockNumber>;
+		type RecalculationInterval: Get<BlockNumberFor<Self>>;
 
 		/// In parachain blocks.
 		#[pallet::constant]
-		type PendingInterval: Get<Self::BlockNumber>;
+		type PendingInterval: Get<BlockNumberFor<Self>>;
 
 		/// Rate of return for interval in blocks defined in `RecalculationInterval`.
 		#[pallet::constant]
@@ -146,7 +146,7 @@
 		type WeightInfo: WeightInfo;
 
 		// The relay block number provider
-		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
 
 		/// Events compatible with [`frame_system::Config::Event`].
 		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
@@ -230,9 +230,9 @@
 	pub type Staked<T: Config> = StorageNMap<
 		Key = (
 			Key<Blake2_128Concat, T::AccountId>,
-			Key<Twox64Concat, T::BlockNumber>,
+			Key<Twox64Concat, BlockNumberFor<T>>,
 		),
-		Value = (BalanceOf<T>, T::BlockNumber),
+		Value = (BalanceOf<T>, BlockNumberFor<T>),
 		QueryKind = ValueQuery,
 	>;
 
@@ -252,7 +252,7 @@
 	pub type PendingUnstake<T: Config> = StorageMap<
 		_,
 		Twox64Concat,
-		T::BlockNumber,
+		BlockNumberFor<T>,
 		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
 		ValueQuery,
 	>;
@@ -262,16 +262,16 @@
 	#[pallet::storage]
 	#[pallet::getter(fn get_next_calculated_record)]
 	pub type PreviousCalculatedRecord<T: Config> =
-		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
+		StorageValue<Value = (T::AccountId, BlockNumberFor<T>), QueryKind = OptionQuery>;
 
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
 		/// implies the execution of a strictly limited number of relatively lightweight operations.
 		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.
-		fn on_initialize(current_block_number: T::BlockNumber) -> Weight
+		fn on_initialize(current_block_number: BlockNumberFor<T>) -> Weight
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			if T::IsMaintenanceModeEnabled::get() {
 				return T::DbWeight::get().reads_writes(1, 0);
@@ -302,7 +302,7 @@
 	#[pallet::call]
 	impl<T: Config> Pallet<T>
 	where
-		T::BlockNumber: From<u32> + Into<u32>,
+		BlockNumberFor<T>: From<u32> + Into<u32>,
 		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,
 	{
 		/// Sets an address as the the admin.
@@ -369,7 +369,7 @@
 
 			// Calculation of the number of recalculation periods,
 			// after how much the first interest calculation should be performed for the stake
-			let recalculate_after_interval: T::BlockNumber =
+			let recalculate_after_interval: BlockNumberFor<T> =
 				if block_number % config.recalculation_interval == 0u32.into() {
 					1u32.into()
 				} else {
@@ -705,7 +705,7 @@
 		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]
 		pub fn force_unstake(
 			origin: OriginFor<T>,
-			pending_blocks: Vec<T::BlockNumber>,
+			pending_blocks: Vec<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 
@@ -917,7 +917,7 @@
 	/// - `staker`: staker account.
 	pub fn total_staked_by_id_per_block(
 		staker: impl EncodeLike<T::AccountId>,
-	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
+	) -> Option<Vec<(BlockNumberFor<T>, BalanceOf<T>)>> {
 		let mut staked = Staked::<T>::iter_prefix((staker,))
 			.map(|(block, (amount, _))| (block, amount))
 			.collect::<Vec<_>>();
@@ -944,14 +944,14 @@
 	/// - `staker`: staker account.
 	pub fn cross_id_total_staked_per_block(
 		staker: T::CrossAccountId,
-	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+	) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
 		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()
 	}
 
 	fn recalculate_and_insert_stake(
 		staker: &T::AccountId,
-		staked_block: T::BlockNumber,
-		next_recalc_block: T::BlockNumber,
+		staked_block: BlockNumberFor<T>,
+		next_recalc_block: BlockNumberFor<T>,
 		base: BalanceOf<T>,
 		iters: u32,
 		income_acc: &mut BalanceOf<T>,
@@ -979,9 +979,9 @@
 	/// Get relay block number rounded down to multiples of config.recalculation_interval.
 	/// We need it to reward stakers in integer parts of recalculation_interval
 	fn get_current_recalc_block(
-		current_relay_block: T::BlockNumber,
+		current_relay_block: BlockNumberFor<T>,
 		config: &PalletConfiguration<T>,
-	) -> T::BlockNumber {
+	) -> BlockNumberFor<T> {
 		(current_relay_block / config.recalculation_interval) * config.recalculation_interval
 	}
 
@@ -1028,7 +1028,7 @@
 	/// - `staker`: staker account.
 	pub fn cross_id_pending_unstake_per_block(
 		staker: T::CrossAccountId,
-	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+	) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
 		let mut unsorted_res = vec![];
 		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
 			pendings.into_iter().for_each(|(id, amount)| {
modifiedpallets/app-promotion/src/types.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -114,9 +114,9 @@
 }
 pub(crate) struct PalletConfiguration<T: crate::Config> {
 	/// In relay blocks.
-	pub recalculation_interval: T::BlockNumber,
+	pub recalculation_interval: BlockNumberFor<T>,
 	/// In parachain blocks.
-	pub pending_interval: T::BlockNumber,
+	pub pending_interval: BlockNumberFor<T>,
 	/// Value for `RecalculationInterval` based on 0.05% per 24h.
 	pub interval_income: Perbill,
 	/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.
modifiedpallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/benchmarking.rs
+++ b/pallets/collator-selection/src/benchmarking.rs
@@ -51,6 +51,10 @@
 use pallet_session::{self as session, SessionManager};
 use sp_std::prelude::*;
 
+use super::*;
+#[allow(unused)]
+use crate::{BalanceOf, Pallet as CollatorSelection};
+
 const SEED: u32 = 0;
 
 // TODO: remove if this is given in substrate commit.
@@ -317,7 +321,7 @@
 			balance_unit::<T>() * 4u32.into(),
 		);
 		let author = account("author", 0, SEED);
-		let new_block: T::BlockNumber = 10u32.into();
+		let new_block: BlockNumberFor<T>= 10u32.into();
 
 		frame_system::Pallet::<T>::set_block_number(new_block);
 		assert!(T::Currency::balance(&author) == 0u32.into());
@@ -338,7 +342,7 @@
 		register_validators::<T>(c);
 		register_candidates::<T>(c);
 
-		let new_block: T::BlockNumber = 1800u32.into();
+		let new_block: BlockNumberFor<T>= 1800u32.into();
 		let zero_block: T::BlockNumber = 0u32.into();
 		let candidates = <Candidates<T>>::get();
 
modifiedpallets/collator-selection/src/lib.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -131,8 +131,11 @@
 	pub trait Config: frame_system::Config {
 		/// Overarching event type.
 		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+		/// Overarching hold reason.
+		type RuntimeHoldReason: From<HoldReason>;
+
 		type Currency: Mutate<Self::AccountId>
-			+ MutateHold<Self::AccountId>
+			+ MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
 			+ BalancedHold<Self::AccountId>;
 
 		/// Origin that can dictate updating parameters of this pallet.
@@ -164,14 +167,17 @@
 		/// The weight information of this pallet.
 		type WeightInfo: WeightInfo;
 
-		#[pallet::constant]
-		type LicenceBondIdentifier: Get<<Self::Currency as InspectHold<Self::AccountId>>::Reason>;
-
 		type DesiredCollators: Get<u32>;
 
 		type LicenseBond: Get<BalanceOf<Self>>;
 
-		type KickThreshold: Get<Self::BlockNumber>;
+		type KickThreshold: Get<BlockNumberFor<Self>>;
+	}
+
+	#[pallet::composite_enum]
+	pub enum HoldReason {
+		/// The funds are held as the license bond.
+		LicenseBond,
 	}
 
 	#[pallet::pallet]
@@ -199,14 +205,13 @@
 	#[pallet::storage]
 	#[pallet::getter(fn last_authored_block)]
 	pub type LastAuthoredBlock<T: Config> =
-		StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
+		StorageMap<_, Twox64Concat, T::AccountId, BlockNumberFor<T>, ValueQuery>;
 
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T: Config> {
 		pub invulnerables: Vec<T::AccountId>,
 	}
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self {
@@ -216,12 +221,11 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
-			let duplicate_invulnerables = self
-				.invulnerables
-				.iter()
-				.collect::<std::collections::BTreeSet<_>>();
+			use sp_std::collections::btree_set::BTreeSet;
+
+			let duplicate_invulnerables = self.invulnerables.iter().collect::<BTreeSet<_>>();
 			assert!(
 				duplicate_invulnerables.len() == self.invulnerables.len(),
 				"duplicate invulnerables in genesis."
@@ -375,7 +379,7 @@
 
 			let deposit = T::LicenseBond::get();
 
-			T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;
+			T::Currency::hold(&HoldReason::LicenseBond.into(), &who, deposit)?;
 			LicenseDepositOf::<T>::insert(who.clone(), deposit);
 
 			Self::deposit_event(Event::LicenseObtained {
@@ -538,7 +542,7 @@
 						let remaining = deposit - slashed;
 
 						let (imbalance, _) =
-							T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);
+							T::Currency::slash(&HoldReason::LicenseBond.into(), who, slashed);
 						deposit_returned = remaining;
 
 						T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)
@@ -548,7 +552,7 @@
 					}
 
 					T::Currency::release(
-						&T::LicenceBondIdentifier::get(),
+						&HoldReason::LicenseBond.into(),
 						who,
 						deposit_returned,
 						Precision::Exact,
@@ -608,7 +612,7 @@
 	/// Keep track of number of authored blocks per authority, uncles are counted as well since
 	/// they're a valid proof of being online.
 	impl<T: Config + pallet_authorship::Config>
-		pallet_authorship::EventHandler<T::AccountId, T::BlockNumber> for Pallet<T>
+		pallet_authorship::EventHandler<T::AccountId, BlockNumberFor<T>> for Pallet<T>
 	{
 		fn note_author(author: T::AccountId) {
 			let pot = Self::account_id();
modifiedpallets/collator-selection/src/mock.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/mock.rs
+++ b/pallets/collator-selection/src/mock.rs
@@ -51,18 +51,14 @@
 
 // Configure a mock runtime to test the pallet.
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
-		Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
-		Aura: pallet_aura::{Pallet, Storage, Config<T>},
-		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
-		CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},
-		Authorship: pallet_authorship::{Pallet, Storage},
+	pub enum Test {
+		System: frame_system,
+		Timestamp: pallet_timestamp,
+		Session: pallet_session,
+		Aura: pallet_aura,
+		Balances: pallet_balances,
+		CollatorSelection: collator_selection,
+		Authorship: pallet_authorship,
 	}
 );
 
@@ -78,13 +74,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = RuntimeEvent;
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
@@ -115,7 +109,6 @@
 	type MaxLocks = ();
 	type MaxReserves = MaxReserves;
 	type ReserveIdentifier = [u8; 8];
-	type HoldIdentifier = [u8; 16];
 	type FreezeIdentifier = [u8; 16];
 	type MaxHolds = MaxHolds;
 	type MaxFreezes = MaxFreezes;
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/src/lib.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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59	marker::PhantomData,60};61use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};62use sp_std::vec::Vec;63use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};64use evm_coder::ToLog;65use frame_support::{66	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},67	ensure,68	traits::{69		Get,70		fungible::{Balanced, Debt, Inspect},71		tokens::{Imbalance, Precision, Preservation},72	},73	dispatch::Pays,74	transactional, fail,75};76use up_data_structs::{77	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,78	CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,79	TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,80	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,81	CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,82	SponsoringRateLimit, budget::Budget, PhantomType, Property,83	CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,84	PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,85	PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,86};87use up_pov_estimate_rpc::PovInfo;8889pub use pallet::*;90use sp_core::H160;91use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9293#[cfg(feature = "runtime-benchmarks")]94pub mod benchmarking;95pub mod dispatch;96pub mod erc;97pub mod eth;98pub mod helpers;99#[allow(missing_docs)]100pub mod weights;101102use weights::WeightInfo;103104/// Weight info.105pub type SelfWeightOf<T> = <T as Config>::WeightInfo;106107/// Collection handle contains information about collection data and id.108/// Also provides functionality to count consumed gas.109///110/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).111/// It allows to perform common operations and queries on any collection type,112/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].113#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]114pub struct CollectionHandle<T: Config> {115	/// Collection id116	pub id: CollectionId,117	collection: Collection<T::AccountId>,118	/// Substrate recorder for counting consumed gas119	pub recorder: SubstrateRecorder<T>,120}121122impl<T: Config> WithRecorder<T> for CollectionHandle<T> {123	fn recorder(&self) -> &SubstrateRecorder<T> {124		&self.recorder125	}126	fn into_recorder(self) -> SubstrateRecorder<T> {127		self.recorder128	}129}130131impl<T: Config> CollectionHandle<T> {132	/// Same as [CollectionHandle::new] but with an explicit gas limit.133	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {134		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))135	}136137	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].138	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {139		<CollectionById<T>>::get(id).map(|collection| Self {140			id,141			collection,142			recorder,143		})144	}145146	/// Retrives collection data from storage and creates collection handle with default parameters.147	/// If collection not found return `None`148	pub fn new(id: CollectionId) -> Option<Self> {149		Self::new_with_gas_limit(id, u64::MAX)150	}151152	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.153	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {154		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)155	}156157	/// Consume gas for reading.158	pub fn consume_store_reads(159		&self,160		reads: u64,161	) -> pallet_evm_coder_substrate::execution::Result<()> {162		self.recorder().consume_store_reads(reads)163	}164165	/// Consume gas for writing.166	pub fn consume_store_writes(167		&self,168		writes: u64,169	) -> pallet_evm_coder_substrate::execution::Result<()> {170		self.recorder().consume_store_writes(writes)171	}172173	/// Consume gas for reading and writing.174	pub fn consume_store_reads_and_writes(175		&self,176		reads: u64,177		writes: u64,178	) -> pallet_evm_coder_substrate::execution::Result<()> {179		self.recorder()180			.consume_store_reads_and_writes(reads, writes)181	}182183	/// Save collection to storage.184	pub fn save(&self) -> DispatchResult {185		<CollectionById<T>>::insert(self.id, &self.collection);186		Ok(())187	}188189	/// Set collection sponsor.190	///191	/// Unique collections allows sponsoring for certain actions.192	/// This method allows you to set the sponsor of the collection.193	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].194	pub fn set_sponsor(195		&mut self,196		sender: &T::CrossAccountId,197		sponsor: T::AccountId,198	) -> DispatchResult {199		self.check_is_internal()?;200		self.check_is_owner_or_admin(sender)?;201202		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());203204		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));205		<PalletEvm<T>>::deposit_log(206			erc::CollectionHelpersEvents::CollectionChanged {207				collection_id: eth::collection_id_to_address(self.id),208			}209			.to_log(T::ContractAddress::get()),210		);211212		self.save()213	}214215	/// Force set `sponsor`.216	///217	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation218	/// from the `sponsor` is not required.219	///220	/// # Arguments221	///222	/// * `sponsor`: ID of the account of the sponsor-to-be.223	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {224		self.check_is_internal()?;225226		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());227228		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));229		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));230		<PalletEvm<T>>::deposit_log(231			erc::CollectionHelpersEvents::CollectionChanged {232				collection_id: eth::collection_id_to_address(self.id),233			}234			.to_log(T::ContractAddress::get()),235		);236237		self.save()238	}239240	/// Confirm sponsorship241	///242	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.243	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].244	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {245		self.check_is_internal()?;246		ensure!(247			self.collection.sponsorship.pending_sponsor() == Some(sender),248			Error::<T>::ConfirmSponsorshipFail249		);250251		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());252253		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));254		<PalletEvm<T>>::deposit_log(255			erc::CollectionHelpersEvents::CollectionChanged {256				collection_id: eth::collection_id_to_address(self.id),257			}258			.to_log(T::ContractAddress::get()),259		);260261		self.save()262	}263264	/// Remove collection sponsor.265	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {266		self.check_is_internal()?;267		self.check_is_owner_or_admin(sender)?;268269		self.collection.sponsorship = SponsorshipState::Disabled;270271		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));272		<PalletEvm<T>>::deposit_log(273			erc::CollectionHelpersEvents::CollectionChanged {274				collection_id: eth::collection_id_to_address(self.id),275			}276			.to_log(T::ContractAddress::get()),277		);278		self.save()279	}280281	/// Force remove `sponsor`.282	///283	/// Differs from `remove_sponsor` in that284	/// it doesn't require consent from the `owner` of the collection.285	pub fn force_remove_sponsor(&mut self) -> DispatchResult {286		self.check_is_internal()?;287288		self.collection.sponsorship = SponsorshipState::Disabled;289290		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));291		<PalletEvm<T>>::deposit_log(292			erc::CollectionHelpersEvents::CollectionChanged {293				collection_id: eth::collection_id_to_address(self.id),294			}295			.to_log(T::ContractAddress::get()),296		);297		self.save()298	}299300	/// Checks that the collection was created with, and must be operated upon through **Unique API**.301	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.302	pub fn check_is_internal(&self) -> DispatchResult {303		if self.flags.external {304			return Err(<Error<T>>::CollectionIsExternal)?;305		}306307		Ok(())308	}309310	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.311	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.312	pub fn check_is_external(&self) -> DispatchResult {313		if !self.flags.external {314			return Err(<Error<T>>::CollectionIsInternal)?;315		}316317		Ok(())318	}319}320321impl<T: Config> Deref for CollectionHandle<T> {322	type Target = Collection<T::AccountId>;323324	fn deref(&self) -> &Self::Target {325		&self.collection326	}327}328329impl<T: Config> DerefMut for CollectionHandle<T> {330	fn deref_mut(&mut self) -> &mut Self::Target {331		&mut self.collection332	}333}334335impl<T: Config> CollectionHandle<T> {336	/// Checks if the `user` is the owner of the collection.337	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {338		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);339		Ok(())340	}341342	/// Returns **true** if the `user` is the owner or administrator of the collection.343	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {344		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))345	}346347	/// Checks if the `user` is the owner or administrator of the collection.348	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {349		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);350		Ok(())351	}352353	/// Returns **true** if354	/// * the `user`is a collection owner or admin355	/// * the collection limits allow the owner/admins to transfer/burn any collection token356	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {357		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)358	}359360	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.361	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {362		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)363	}364365	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.366	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {367		ensure!(368			<Allowlist<T>>::get((self.id, user)),369			<Error<T>>::AddressNotInAllowlist370		);371		Ok(())372	}373374	/// Changes collection owner to another account375	/// #### Store read/writes376	/// 1 writes377	pub fn change_owner(378		&mut self,379		caller: T::CrossAccountId,380		new_owner: T::CrossAccountId,381	) -> DispatchResult {382		self.check_is_internal()?;383		self.check_is_owner(&caller)?;384		self.collection.owner = new_owner.as_sub().clone();385386		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(387			self.id,388			new_owner.as_sub().clone(),389		));390		<PalletEvm<T>>::deposit_log(391			erc::CollectionHelpersEvents::CollectionChanged {392				collection_id: eth::collection_id_to_address(self.id),393			}394			.to_log(T::ContractAddress::get()),395		);396397		self.save()398	}399}400401#[frame_support::pallet]402pub mod pallet {403404	use super::*;405	use dispatch::CollectionDispatch;406	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};407	use up_data_structs::{TokenId, mapping::TokenAddressMapping};408	use scale_info::TypeInfo;409	use weights::WeightInfo;410411	#[pallet::config]412	pub trait Config:413		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo414	{415		/// Weight information for functions of this pallet.416		type WeightInfo: WeightInfo;417418		/// Events compatible with [`frame_system::Config::Event`].419		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;420421		/// Handler of accounts and payment.422		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;423424		/// Set price to create a collection.425		#[pallet::constant]426		type CollectionCreationPrice: Get<427			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,428		>;429430		/// Dispatcher of operations on collections.431		type CollectionDispatch: CollectionDispatch<Self>;432433		/// Account which holds the chain's treasury.434		type TreasuryAccountId: Get<Self::AccountId>;435436		/// Address under which the CollectionHelper contract would be available.437		#[pallet::constant]438		type ContractAddress: Get<H160>;439440		/// Mapper for token addresses to Ethereum addresses.441		type EvmTokenAddressMapping: TokenAddressMapping<H160>;442443		/// Mapper for token addresses to [`CrossAccountId`].444		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;445	}446447	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);448	/// Collection id for native fungible collction.449	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);450451	#[pallet::pallet]452	#[pallet::storage_version(STORAGE_VERSION)]453	pub struct Pallet<T>(_);454455	#[pallet::extra_constants]456	impl<T: Config> Pallet<T> {457		/// Maximum admins per collection.458		pub fn collection_admins_limit() -> u32 {459			COLLECTION_ADMINS_LIMIT460		}461	}462463	#[pallet::genesis_config]464	pub struct GenesisConfig<T>(PhantomData<T>);465466	#[cfg(feature = "std")]467	impl<T: Config> Default for GenesisConfig<T> {468		fn default() -> Self {469			Self(Default::default())470		}471	}472473	#[pallet::genesis_build]474	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {475		fn build(&self) {476			StorageVersion::new(1).put::<Pallet<T>>();477		}478	}479480	impl<T: Config> Pallet<T> {481		/// Helper function that handles deposit events482		pub fn deposit_event(event: Event<T>) {483			let event = <T as Config>::RuntimeEvent::from(event);484			let event = event.into();485			<frame_system::Pallet<T>>::deposit_event(event)486		}487	}488489	#[pallet::event]490	pub enum Event<T: Config> {491		/// New collection was created492		CollectionCreated(493			/// Globally unique identifier of newly created collection.494			CollectionId,495			/// [`CollectionMode`] converted into _u8_.496			u8,497			/// Collection owner.498			T::AccountId,499		),500501		/// New collection was destroyed502		CollectionDestroyed(503			/// Globally unique identifier of collection.504			CollectionId,505		),506507		/// New item was created.508		ItemCreated(509			/// Id of the collection where item was created.510			CollectionId,511			/// Id of an item. Unique within the collection.512			TokenId,513			/// Owner of newly created item514			T::CrossAccountId,515			/// Always 1 for NFT516			u128,517		),518519		/// Collection item was burned.520		ItemDestroyed(521			/// Id of the collection where item was destroyed.522			CollectionId,523			/// Identifier of burned NFT.524			TokenId,525			/// Which user has destroyed its tokens.526			T::CrossAccountId,527			/// Amount of token pieces destroed. Always 1 for NFT.528			u128,529		),530531		/// Item was transferred532		Transfer(533			/// Id of collection to which item is belong.534			CollectionId,535			/// Id of an item.536			TokenId,537			/// Original owner of item.538			T::CrossAccountId,539			/// New owner of item.540			T::CrossAccountId,541			/// Amount of token pieces transfered. Always 1 for NFT.542			u128,543		),544545		/// Amount pieces of token owned by `sender` was approved for `spender`.546		Approved(547			/// Id of collection to which item is belong.548			CollectionId,549			/// Id of an item.550			TokenId,551			/// Original owner of item.552			T::CrossAccountId,553			/// Id for which the approval was granted.554			T::CrossAccountId,555			/// Amount of token pieces transfered. Always 1 for NFT.556			u128,557		),558559		/// A `sender` approves operations on all owned tokens for `spender`.560		ApprovedForAll(561			/// Id of collection to which item is belong.562			CollectionId,563			/// Owner of a wallet.564			T::CrossAccountId,565			/// Id for which operator status was granted or rewoked.566			T::CrossAccountId,567			/// Is operator status granted or revoked?568			bool,569		),570571		/// The colletion property has been added or edited.572		CollectionPropertySet(573			/// Id of collection to which property has been set.574			CollectionId,575			/// The property that was set.576			PropertyKey,577		),578579		/// The property has been deleted.580		CollectionPropertyDeleted(581			/// Id of collection to which property has been deleted.582			CollectionId,583			/// The property that was deleted.584			PropertyKey,585		),586587		/// The token property has been added or edited.588		TokenPropertySet(589			/// Identifier of the collection whose token has the property set.590			CollectionId,591			/// The token for which the property was set.592			TokenId,593			/// The property that was set.594			PropertyKey,595		),596597		/// The token property has been deleted.598		TokenPropertyDeleted(599			/// Identifier of the collection whose token has the property deleted.600			CollectionId,601			/// The token for which the property was deleted.602			TokenId,603			/// The property that was deleted.604			PropertyKey,605		),606607		/// The token property permission of a collection has been set.608		PropertyPermissionSet(609			/// ID of collection to which property permission has been set.610			CollectionId,611			/// The property permission that was set.612			PropertyKey,613		),614615		/// Address was added to the allow list.616		AllowListAddressAdded(617			/// ID of the affected collection.618			CollectionId,619			/// Address of the added account.620			T::CrossAccountId,621		),622623		/// Address was removed from the allow list.624		AllowListAddressRemoved(625			/// ID of the affected collection.626			CollectionId,627			/// Address of the removed account.628			T::CrossAccountId,629		),630631		/// Collection admin was added.632		CollectionAdminAdded(633			/// ID of the affected collection.634			CollectionId,635			/// Admin address.636			T::CrossAccountId,637		),638639		/// Collection admin was removed.640		CollectionAdminRemoved(641			/// ID of the affected collection.642			CollectionId,643			/// Removed admin address.644			T::CrossAccountId,645		),646647		/// Collection limits were set.648		CollectionLimitSet(649			/// ID of the affected collection.650			CollectionId,651		),652653		/// Collection owned was changed.654		CollectionOwnerChanged(655			/// ID of the affected collection.656			CollectionId,657			/// New owner address.658			T::AccountId,659		),660661		/// Collection permissions were set.662		CollectionPermissionSet(663			/// ID of the affected collection.664			CollectionId,665		),666667		/// Collection sponsor was set.668		CollectionSponsorSet(669			/// ID of the affected collection.670			CollectionId,671			/// New sponsor address.672			T::AccountId,673		),674675		/// New sponsor was confirm.676		SponsorshipConfirmed(677			/// ID of the affected collection.678			CollectionId,679			/// New sponsor address.680			T::AccountId,681		),682683		/// Collection sponsor was removed.684		CollectionSponsorRemoved(685			/// ID of the affected collection.686			CollectionId,687		),688	}689690	#[pallet::error]691	pub enum Error<T> {692		/// This collection does not exist.693		CollectionNotFound,694		/// Sender parameter and item owner must be equal.695		MustBeTokenOwner,696		/// No permission to perform action697		NoPermission,698		/// Destroying only empty collections is allowed699		CantDestroyNotEmptyCollection,700		/// Collection is not in mint mode.701		PublicMintingNotAllowed,702		/// Address is not in allow list.703		AddressNotInAllowlist,704705		/// Collection name can not be longer than 63 char.706		CollectionNameLimitExceeded,707		/// Collection description can not be longer than 255 char.708		CollectionDescriptionLimitExceeded,709		/// Token prefix can not be longer than 15 char.710		CollectionTokenPrefixLimitExceeded,711		/// Total collections bound exceeded.712		TotalCollectionsLimitExceeded,713		/// Exceeded max admin count714		CollectionAdminCountExceeded,715		/// Collection limit bounds per collection exceeded716		CollectionLimitBoundsExceeded,717		/// Tried to enable permissions which are only permitted to be disabled718		OwnerPermissionsCantBeReverted,719		/// Collection settings not allowing items transferring720		TransferNotAllowed,721		/// Account token limit exceeded per collection722		AccountTokenLimitExceeded,723		/// Collection token limit exceeded724		CollectionTokenLimitExceeded,725		/// Metadata flag frozen726		MetadataFlagFrozen,727728		/// Item does not exist729		TokenNotFound,730		/// Item is balance not enough731		TokenValueTooLow,732		/// Requested value is more than the approved733		ApprovedValueTooLow,734		/// Tried to approve more than owned735		CantApproveMoreThanOwned,736		/// Only spending from eth mirror could be approved737		AddressIsNotEthMirror,738739		/// Can't transfer tokens to ethereum zero address740		AddressIsZero,741742		/// The operation is not supported743		UnsupportedOperation,744745		/// Insufficient funds to perform an action746		NotSufficientFounds,747748		/// User does not satisfy the nesting rule749		UserIsNotAllowedToNest,750		/// Only tokens from specific collections may nest tokens under this one751		SourceCollectionIsNotAllowedToNest,752753		/// Tried to store more data than allowed in collection field754		CollectionFieldSizeExceeded,755756		/// Tried to store more property data than allowed757		NoSpaceForProperty,758759		/// Tried to store more property keys than allowed760		PropertyLimitReached,761762		/// Property key is too long763		PropertyKeyIsTooLong,764765		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed766		InvalidCharacterInPropertyKey,767768		/// Empty property keys are forbidden769		EmptyPropertyKey,770771		/// Tried to access an external collection with an internal API772		CollectionIsExternal,773774		/// Tried to access an internal collection with an external API775		CollectionIsInternal,776777		/// This address is not set as sponsor, use setCollectionSponsor first.778		ConfirmSponsorshipFail,779780		/// The user is not an administrator.781		UserIsNotCollectionAdmin,782	}783784	/// Storage of the count of created collections. Essentially contains the last collection ID.785	#[pallet::storage]786	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;787788	/// Storage of the count of deleted collections.789	#[pallet::storage]790	pub type DestroyedCollectionCount<T> =791		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;792793	/// Storage of collection info.794	#[pallet::storage]795	pub type CollectionById<T> = StorageMap<796		Hasher = Blake2_128Concat,797		Key = CollectionId,798		Value = Collection<<T as frame_system::Config>::AccountId>,799		QueryKind = OptionQuery,800	>;801802	/// Storage of collection properties.803	#[pallet::storage]804	#[pallet::getter(fn collection_properties)]805	pub type CollectionProperties<T> = StorageMap<806		Hasher = Blake2_128Concat,807		Key = CollectionId,808		Value = CollectionPropertiesT,809		QueryKind = ValueQuery,810	>;811812	/// Storage of token property permissions of a collection.813	#[pallet::storage]814	#[pallet::getter(fn property_permissions)]815	pub type CollectionPropertyPermissions<T> = StorageMap<816		Hasher = Blake2_128Concat,817		Key = CollectionId,818		Value = PropertiesPermissionMap,819		QueryKind = ValueQuery,820	>;821822	/// Storage of the amount of collection admins.823	#[pallet::storage]824	pub type AdminAmount<T> = StorageMap<825		Hasher = Blake2_128Concat,826		Key = CollectionId,827		Value = u32,828		QueryKind = ValueQuery,829	>;830831	/// List of collection admins.832	#[pallet::storage]833	pub type IsAdmin<T: Config> = StorageNMap<834		Key = (835			Key<Blake2_128Concat, CollectionId>,836			Key<Blake2_128Concat, T::CrossAccountId>,837		),838		Value = bool,839		QueryKind = ValueQuery,840	>;841842	/// Allowlisted collection users.843	#[pallet::storage]844	pub type Allowlist<T: Config> = StorageNMap<845		Key = (846			Key<Blake2_128Concat, CollectionId>,847			Key<Blake2_128Concat, T::CrossAccountId>,848		),849		Value = bool,850		QueryKind = ValueQuery,851	>;852853	/// Not used by code, exists only to provide some types to metadata.854	#[pallet::storage]855	pub type DummyStorageValue<T: Config> = StorageValue<856		Value = (857			CollectionStats,858			CollectionId,859			TokenId,860			TokenChild,861			PhantomType<(862				TokenData<T::CrossAccountId>,863				RpcCollection<T::AccountId>,864				// PoV Estimate Info865				PovInfo,866			)>,867		),868		QueryKind = OptionQuery,869	>;870}871872/// Value representation with delayed initialization time.873pub struct LazyValue<T, F: FnOnce() -> T> {874	value: Option<T>,875	f: Option<F>,876}877878impl<T, F: FnOnce() -> T> LazyValue<T, F> {879	/// Create a new LazyValue.880	pub fn new(f: F) -> Self {881		Self {882			value: None,883			f: Some(f),884		}885	}886887	/// Get the value. If it is called the first time, the value will be initialized.888	pub fn value(&mut self) -> &T {889		self.compute_value_if_not_already();890		self.value.as_ref().unwrap()891	}892893	/// Get the value. If it is called the first time, the value will be initialized.894	pub fn value_mut(&mut self) -> &mut T {895		self.compute_value_if_not_already();896		self.value.as_mut().unwrap()897	}898899	fn into_inner(mut self) -> T {900		self.compute_value_if_not_already();901		self.value.unwrap()902	}903904	/// Is value initialized?905	pub fn has_value(&self) -> bool {906		self.value.is_some()907	}908909	fn compute_value_if_not_already(&mut self) {910		if self.value.is_none() {911			self.value = Some(self.f.take().unwrap()())912		}913	}914}915916fn check_token_permissions<T, FCA, FTO, FTE>(917	collection_admin_permitted: bool,918	token_owner_permitted: bool,919	is_collection_admin: &mut LazyValue<bool, FCA>,920	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,921	is_token_exist: &mut LazyValue<bool, FTE>,922) -> DispatchResult923where924	T: Config,925	FCA: FnOnce() -> bool,926	FTO: FnOnce() -> Result<bool, DispatchError>,927	FTE: FnOnce() -> bool,928{929	if !(collection_admin_permitted && *is_collection_admin.value()930		|| token_owner_permitted && (*is_token_owner.value())?)931	{932		fail!(<Error<T>>::NoPermission);933	}934935	let token_exist_due_to_owner_check_success =936		is_token_owner.has_value() && (*is_token_owner.value())?;937938	// If the token owner check has occurred and succeeded,939	// we know the token exists (otherwise, the owner check must fail).940	if !token_exist_due_to_owner_check_success {941		// If the token owner check didn't occur,942		// we must check the token's existence ourselves.943		if !is_token_exist.value() {944			fail!(<Error<T>>::TokenNotFound);945		}946	}947948	Ok(())949}950951impl<T: Config> Pallet<T> {952	/// Enshure that receiver address is correct.953	///954	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.955	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {956		ensure!(957			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,958			<Error<T>>::AddressIsZero959		);960		Ok(())961	}962963	/// Get a vector of collection admins.964	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {965		<IsAdmin<T>>::iter_prefix((collection,))966			.map(|(a, _)| a)967			.collect()968	}969970	/// Get a vector of users allowed to mint tokens.971	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {972		<Allowlist<T>>::iter_prefix((collection,))973			.map(|(a, _)| a)974			.collect()975	}976977	/// Is `user` allowed to mint token in `collection`.978	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {979		<Allowlist<T>>::get((collection, user))980	}981982	/// Get statistics of collections.983	pub fn collection_stats() -> CollectionStats {984		let created = <CreatedCollectionCount<T>>::get();985		let destroyed = <DestroyedCollectionCount<T>>::get();986		CollectionStats {987			created: created.0,988			destroyed: destroyed.0,989			alive: created.0 - destroyed.0,990		}991	}992993	/// Get the effective limits for the collection.994	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {995		let collection = <CollectionById<T>>::get(collection)?;996		let limits = collection.limits;997		let effective_limits = CollectionLimits {998			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),999			sponsored_data_size: Some(limits.sponsored_data_size()),1000			sponsored_data_rate_limit: Some(1001				limits1002					.sponsored_data_rate_limit1003					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1004			),1005			token_limit: Some(limits.token_limit()),1006			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1007				match collection.mode {1008					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1009					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1010					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1011				},1012			)),1013			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1014			owner_can_transfer: Some(limits.owner_can_transfer()),1015			owner_can_destroy: Some(limits.owner_can_destroy()),1016			transfers_enabled: Some(limits.transfers_enabled()),1017		};10181019		Some(effective_limits)1020	}10211022	/// Returns information about the `collection` adapted for rpc.1023	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1024		let Collection {1025			name,1026			description,1027			owner,1028			mode,1029			token_prefix,1030			sponsorship,1031			limits,1032			permissions,1033			flags,1034		} = <CollectionById<T>>::get(collection)?;10351036		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1037			.into_iter()1038			.map(|(key, permission)| PropertyKeyPermission { key, permission })1039			.collect();10401041		let properties = <CollectionProperties<T>>::get(collection)1042			.into_iter()1043			.map(|(key, value)| Property { key, value })1044			.collect();10451046		let permissions = CollectionPermissions {1047			access: Some(permissions.access()),1048			mint_mode: Some(permissions.mint_mode()),1049			nesting: Some(permissions.nesting().clone()),1050		};10511052		Some(RpcCollection {1053			name: name.into_inner(),1054			description: description.into_inner(),1055			owner,1056			mode,1057			token_prefix: token_prefix.into_inner(),1058			sponsorship,1059			limits,1060			permissions,1061			token_property_permissions,1062			properties,1063			read_only: flags.external,10641065			flags: RpcCollectionFlags {1066				foreign: flags.foreign,1067				erc721metadata: flags.erc721metadata,1068			},1069		})1070	}1071}10721073macro_rules! limit_default {1074	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1075		$(1076			if let Some($new) = $new.$field {1077				let $old = $old.$field($($arg)?);1078				let _ = $new;1079				let _ = $old;1080				$check1081			} else {1082				$new.$field = $old.$field1083			}1084		)*1085	}};1086}1087macro_rules! limit_default_clone {1088	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1089		$(1090			if let Some($new) = $new.$field.clone() {1091				let $old = $old.$field($($arg)?);1092				let _ = $new;1093				let _ = $old;1094				$check1095			} else {1096				$new.$field = $old.$field.clone()1097			}1098		)*1099	}};1100}11011102impl<T: Config> Pallet<T> {1103	/// Create new collection.1104	///1105	/// * `owner` - The owner of the collection.1106	/// * `data` - Description of the created collection.1107	/// * `flags` - Extra flags to store.1108	pub fn init_collection(1109		owner: T::CrossAccountId,1110		payer: T::CrossAccountId,1111		data: CreateCollectionData<T::CrossAccountId>,1112	) -> Result<CollectionId, DispatchError> {1113		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1114		Self::init_collection_internal(owner, payer, data)1115	}11161117	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1118	pub fn init_foreign_collection(1119		owner: T::CrossAccountId,1120		payer: T::CrossAccountId,1121		mut data: CreateCollectionData<T::CrossAccountId>,1122	) -> Result<CollectionId, DispatchError> {1123		data.flags.foreign = true;1124		let id = Self::init_collection_internal(owner, payer, data)?;1125		Ok(id)1126	}11271128	fn init_collection_internal(1129		owner: T::CrossAccountId,1130		payer: T::CrossAccountId,1131		data: CreateCollectionData<T::CrossAccountId>,1132	) -> Result<CollectionId, DispatchError> {1133		{1134			ensure!(1135				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1136				Error::<T>::CollectionTokenPrefixLimitExceeded1137			);1138		}11391140		let created_count = <CreatedCollectionCount<T>>::get()1141			.01142			.checked_add(1)1143			.ok_or(ArithmeticError::Overflow)?;1144		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1145		let id = CollectionId(created_count);11461147		// bound Total number of collections1148		ensure!(1149			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1150			<Error<T>>::TotalCollectionsLimitExceeded1151		);11521153		// =========11541155		let collection = Collection {1156			owner: owner.as_sub().clone(),1157			name: data.name,1158			mode: data.mode.clone(),1159			description: data.description,1160			token_prefix: data.token_prefix,1161			sponsorship: data1162				.pending_sponsor1163				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1164				.unwrap_or_default(),1165			limits: data1166				.limits1167				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1168				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1169			permissions: data1170				.permissions1171				.map(|permissions| {1172					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1173				})1174				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1175			flags: data.flags,1176		};11771178		let mut collection_properties = CollectionPropertiesT::new();1179		collection_properties1180			.try_set_from_iter(data.properties.into_iter())1181			.map_err(<Error<T>>::from)?;11821183		CollectionProperties::<T>::insert(id, collection_properties);11841185		let mut token_props_permissions = PropertiesPermissionMap::new();1186		token_props_permissions1187			.try_set_from_iter(data.token_property_permissions.into_iter())1188			.map_err(<Error<T>>::from)?;11891190		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11911192		let mut admin_amount = 0u32;1193		for admin in data.admin_list.iter() {1194			if !<IsAdmin<T>>::get((id, admin)) {1195				<IsAdmin<T>>::insert((id, admin), true);1196				admin_amount = admin_amount1197					.checked_add(1)1198					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1199			}1200		}1201		ensure!(1202			admin_amount <= Self::collection_admins_limit(),1203			<Error<T>>::CollectionAdminCountExceeded,1204		);1205		<AdminAmount<T>>::insert(id, admin_amount);12061207		// Take a (non-refundable) deposit of collection creation1208		{1209			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1210			imbalance.subsume(<T as Config>::Currency::deposit(1211				&T::TreasuryAccountId::get(),1212				T::CollectionCreationPrice::get(),1213				Precision::Exact,1214			)?);1215			let credit =1216				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1217					.map_err(|_| Error::<T>::NotSufficientFounds)?;12181219			debug_assert!(credit.peek().is_zero())1220		}12211222		<CreatedCollectionCount<T>>::put(created_count);1223		<Pallet<T>>::deposit_event(Event::CollectionCreated(1224			id,1225			data.mode.id(),1226			owner.as_sub().clone(),1227		));1228		<PalletEvm<T>>::deposit_log(1229			erc::CollectionHelpersEvents::CollectionCreated {1230				owner: *owner.as_eth(),1231				collection_id: eth::collection_id_to_address(id),1232			}1233			.to_log(T::ContractAddress::get()),1234		);1235		<CollectionById<T>>::insert(id, collection);1236		Ok(id)1237	}12381239	/// Destroy collection.1240	///1241	/// * `collection` - Collection handler.1242	/// * `sender` - The owner or administrator of the collection.1243	pub fn destroy_collection(1244		collection: CollectionHandle<T>,1245		sender: &T::CrossAccountId,1246	) -> DispatchResult {1247		ensure!(1248			collection.limits.owner_can_destroy(),1249			<Error<T>>::NoPermission,1250		);1251		collection.check_is_owner(sender)?;12521253		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1254			.01255			.checked_add(1)1256			.ok_or(ArithmeticError::Overflow)?;12571258		// =========12591260		<DestroyedCollectionCount<T>>::put(destroyed_collections);1261		<CollectionById<T>>::remove(collection.id);1262		<AdminAmount<T>>::remove(collection.id);1263		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1264		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1265		<CollectionProperties<T>>::remove(collection.id);12661267		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12681269		<PalletEvm<T>>::deposit_log(1270			erc::CollectionHelpersEvents::CollectionDestroyed {1271				collection_id: eth::collection_id_to_address(collection.id),1272			}1273			.to_log(T::ContractAddress::get()),1274		);1275		Ok(())1276	}12771278	/// This function sets or removes a collection properties according to1279	/// `properties_updates` contents:1280	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1281	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1282	///1283	/// This function fires an event for each property change.1284	/// In case of an error, all the changes (including the events) will be reverted1285	/// since the function is transactional.1286	#[transactional]1287	fn modify_collection_properties(1288		collection: &CollectionHandle<T>,1289		sender: &T::CrossAccountId,1290		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1291	) -> DispatchResult {1292		collection.check_is_owner_or_admin(sender)?;12931294		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12951296		for (key, value) in properties_updates {1297			match value {1298				Some(value) => {1299					stored_properties1300						.try_set(key.clone(), value)1301						.map_err(<Error<T>>::from)?;13021303					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1304					<PalletEvm<T>>::deposit_log(1305						erc::CollectionHelpersEvents::CollectionChanged {1306							collection_id: eth::collection_id_to_address(collection.id),1307						}1308						.to_log(T::ContractAddress::get()),1309					);1310				}1311				None => {1312					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13131314					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1315					<PalletEvm<T>>::deposit_log(1316						erc::CollectionHelpersEvents::CollectionChanged {1317							collection_id: eth::collection_id_to_address(collection.id),1318						}1319						.to_log(T::ContractAddress::get()),1320					);1321				}1322			}1323		}13241325		<CollectionProperties<T>>::set(collection.id, stored_properties);13261327		Ok(())1328	}13291330	/// Sets or unsets the approval of a given operator.1331	///1332	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1333	/// - `owner`: Token owner1334	/// - `operator`: Operator1335	/// - `approve`: Should operator status be granted or revoked?1336	pub fn set_allowance_for_all(1337		collection: &CollectionHandle<T>,1338		owner: &T::CrossAccountId,1339		operator: &T::CrossAccountId,1340		approve: bool,1341		set_allowance: impl FnOnce(),1342		log: evm_coder::ethereum::Log,1343	) -> DispatchResult {1344		if collection.permissions.access() == AccessMode::AllowList {1345			collection.check_allowlist(owner)?;1346			collection.check_allowlist(operator)?;1347		}13481349		Self::ensure_correct_receiver(operator)?;13501351		set_allowance();13521353		<PalletEvm<T>>::deposit_log(log);1354		Self::deposit_event(Event::ApprovedForAll(1355			collection.id,1356			owner.clone(),1357			operator.clone(),1358			approve,1359		));1360		Ok(())1361	}13621363	/// Set collection property.1364	///1365	/// * `collection` - Collection handler.1366	/// * `sender` - The owner or administrator of the collection.1367	/// * `property` - The property to set.1368	pub fn set_collection_property(1369		collection: &CollectionHandle<T>,1370		sender: &T::CrossAccountId,1371		property: Property,1372	) -> DispatchResult {1373		Self::set_collection_properties(collection, sender, [property].into_iter())1374	}13751376	/// Set a scoped collection property, where the scope is a special prefix1377	/// prohibiting a user access to change the property directly.1378	///1379	/// * `collection_id` - ID of the collection for which the property is being set.1380	/// * `scope` - Property scope.1381	/// * `property` - The property to set.1382	pub fn set_scoped_collection_property(1383		collection_id: CollectionId,1384		scope: PropertyScope,1385		property: Property,1386	) -> DispatchResult {1387		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1388			properties.try_scoped_set(scope, property.key, property.value)1389		})1390		.map_err(<Error<T>>::from)?;13911392		Ok(())1393	}13941395	/// Set scoped collection properties, where the scope is a special prefix1396	/// prohibiting a user access to change the properties directly.1397	///1398	/// * `collection_id` - ID of the collection for which the properties is being set.1399	/// * `scope` - Property scope.1400	/// * `properties` - The properties to set.1401	pub fn set_scoped_collection_properties(1402		collection_id: CollectionId,1403		scope: PropertyScope,1404		properties: impl Iterator<Item = Property>,1405	) -> DispatchResult {1406		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1407			stored_properties.try_scoped_set_from_iter(scope, properties)1408		})1409		.map_err(<Error<T>>::from)?;14101411		Ok(())1412	}14131414	/// Set collection properties.1415	///1416	/// * `collection` - Collection handler.1417	/// * `sender` - The owner or administrator of the collection.1418	/// * `properties` - The properties to set.1419	pub fn set_collection_properties(1420		collection: &CollectionHandle<T>,1421		sender: &T::CrossAccountId,1422		properties: impl Iterator<Item = Property>,1423	) -> DispatchResult {1424		Self::modify_collection_properties(1425			collection,1426			sender,1427			properties.map(|property| (property.key, Some(property.value))),1428		)1429	}14301431	/// Delete collection property.1432	///1433	/// * `collection` - Collection handler.1434	/// * `sender` - The owner or administrator of the collection.1435	/// * `property` - The property to delete.1436	pub fn delete_collection_property(1437		collection: &CollectionHandle<T>,1438		sender: &T::CrossAccountId,1439		property_key: PropertyKey,1440	) -> DispatchResult {1441		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1442	}14431444	/// Delete collection properties.1445	///1446	/// * `collection` - Collection handler.1447	/// * `sender` - The owner or administrator of the collection.1448	/// * `properties` - The properties to delete.1449	pub fn delete_collection_properties(1450		collection: &CollectionHandle<T>,1451		sender: &T::CrossAccountId,1452		property_keys: impl Iterator<Item = PropertyKey>,1453	) -> DispatchResult {1454		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1455	}14561457	/// Set collection propetry permission without any checks.1458	///1459	/// Used for migrations.1460	///1461	/// * `collection` - Collection handler.1462	/// * `property_permissions` - Property permissions.1463	pub fn set_property_permission_unchecked(1464		collection: CollectionId,1465		property_permission: PropertyKeyPermission,1466	) -> DispatchResult {1467		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1468			permissions.try_set(property_permission.key, property_permission.permission)1469		})1470		.map_err(<Error<T>>::from)?;1471		Ok(())1472	}14731474	/// Set collection property permission.1475	///1476	/// * `collection` - Collection handler.1477	/// * `sender` - The owner or administrator of the collection.1478	/// * `property_permission` - Property permission.1479	pub fn set_property_permission(1480		collection: &CollectionHandle<T>,1481		sender: &T::CrossAccountId,1482		property_permission: PropertyKeyPermission,1483	) -> DispatchResult {1484		Self::set_scoped_property_permission(1485			collection,1486			sender,1487			PropertyScope::None,1488			property_permission,1489		)1490	}14911492	/// Set collection property permission with scope.1493	///1494	/// * `collection` - Collection handler.1495	/// * `sender` - The owner or administrator of the collection.1496	/// * `scope` - Property scope.1497	/// * `property_permission` - Property permission.1498	pub fn set_scoped_property_permission(1499		collection: &CollectionHandle<T>,1500		sender: &T::CrossAccountId,1501		scope: PropertyScope,1502		property_permission: PropertyKeyPermission,1503	) -> DispatchResult {1504		collection.check_is_owner_or_admin(sender)?;15051506		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1507		let current_permission = all_permissions.get(&property_permission.key);1508		if matches![1509			current_permission,1510			Some(PropertyPermission { mutable: false, .. })1511		] {1512			return Err(<Error<T>>::NoPermission.into());1513		}15141515		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1516			let property_permission = property_permission.clone();1517			permissions.try_scoped_set(1518				scope,1519				property_permission.key,1520				property_permission.permission,1521			)1522		})1523		.map_err(<Error<T>>::from)?;15241525		Self::deposit_event(Event::PropertyPermissionSet(1526			collection.id,1527			property_permission.key,1528		));1529		<PalletEvm<T>>::deposit_log(1530			erc::CollectionHelpersEvents::CollectionChanged {1531				collection_id: eth::collection_id_to_address(collection.id),1532			}1533			.to_log(T::ContractAddress::get()),1534		);15351536		Ok(())1537	}15381539	/// Set token property permission.1540	///1541	/// * `collection` - Collection handler.1542	/// * `sender` - The owner or administrator of the collection.1543	/// * `property_permissions` - Property permissions.1544	#[transactional]1545	pub fn set_token_property_permissions(1546		collection: &CollectionHandle<T>,1547		sender: &T::CrossAccountId,1548		property_permissions: Vec<PropertyKeyPermission>,1549	) -> DispatchResult {1550		Self::set_scoped_token_property_permissions(1551			collection,1552			sender,1553			PropertyScope::None,1554			property_permissions,1555		)1556	}15571558	/// Set token property permission with scope.1559	///1560	/// * `collection` - Collection handler.1561	/// * `sender` - The owner or administrator of the collection.1562	/// * `scope` - Property scope.1563	/// * `property_permissions` - Property permissions.1564	#[transactional]1565	pub fn set_scoped_token_property_permissions(1566		collection: &CollectionHandle<T>,1567		sender: &T::CrossAccountId,1568		scope: PropertyScope,1569		property_permissions: Vec<PropertyKeyPermission>,1570	) -> DispatchResult {1571		for prop_pemission in property_permissions {1572			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1573		}15741575		Ok(())1576	}15771578	/// Get collection property.1579	pub fn get_collection_property(1580		collection_id: CollectionId,1581		key: &PropertyKey,1582	) -> Option<PropertyValue> {1583		Self::collection_properties(collection_id).get(key).cloned()1584	}15851586	/// Convert byte vector to property key vector.1587	pub fn bytes_keys_to_property_keys(1588		keys: Vec<Vec<u8>>,1589	) -> Result<Vec<PropertyKey>, DispatchError> {1590		keys.into_iter()1591			.map(|key| -> Result<PropertyKey, DispatchError> {1592				key.try_into()1593					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1594			})1595			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1596	}15971598	/// Get properties according to given keys.1599	pub fn filter_collection_properties(1600		collection_id: CollectionId,1601		keys: Option<Vec<PropertyKey>>,1602	) -> Result<Vec<Property>, DispatchError> {1603		let properties = Self::collection_properties(collection_id);16041605		let properties = keys1606			.map(|keys| {1607				keys.into_iter()1608					.filter_map(|key| {1609						properties.get(&key).map(|value| Property {1610							key,1611							value: value.clone(),1612						})1613					})1614					.collect()1615			})1616			.unwrap_or_else(|| {1617				properties1618					.into_iter()1619					.map(|(key, value)| Property { key, value })1620					.collect()1621			});16221623		Ok(properties)1624	}16251626	/// Get property permissions according to given keys.1627	pub fn filter_property_permissions(1628		collection_id: CollectionId,1629		keys: Option<Vec<PropertyKey>>,1630	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1631		let permissions = Self::property_permissions(collection_id);16321633		let key_permissions = keys1634			.map(|keys| {1635				keys.into_iter()1636					.filter_map(|key| {1637						permissions1638							.get(&key)1639							.map(|permission| PropertyKeyPermission {1640								key,1641								permission: permission.clone(),1642							})1643					})1644					.collect()1645			})1646			.unwrap_or_else(|| {1647				permissions1648					.into_iter()1649					.map(|(key, permission)| PropertyKeyPermission { key, permission })1650					.collect()1651			});16521653		Ok(key_permissions)1654	}16551656	/// Toggle `user` participation in the `collection`'s allow list.1657	/// #### Store read/writes1658	/// 1 writes1659	pub fn toggle_allowlist(1660		collection: &CollectionHandle<T>,1661		sender: &T::CrossAccountId,1662		user: &T::CrossAccountId,1663		allowed: bool,1664	) -> DispatchResult {1665		collection.check_is_owner_or_admin(sender)?;16661667		// =========16681669		if allowed {1670			<Allowlist<T>>::insert((collection.id, user), true);1671			Self::deposit_event(Event::<T>::AllowListAddressAdded(1672				collection.id,1673				user.clone(),1674			));1675		} else {1676			<Allowlist<T>>::remove((collection.id, user));1677			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1678				collection.id,1679				user.clone(),1680			));1681		}16821683		<PalletEvm<T>>::deposit_log(1684			erc::CollectionHelpersEvents::CollectionChanged {1685				collection_id: eth::collection_id_to_address(collection.id),1686			}1687			.to_log(T::ContractAddress::get()),1688		);16891690		Ok(())1691	}16921693	/// Toggle `user` participation in the `collection`'s admin list.1694	/// #### Store read/writes1695	/// 2 reads, 2 writes1696	pub fn toggle_admin(1697		collection: &CollectionHandle<T>,1698		sender: &T::CrossAccountId,1699		user: &T::CrossAccountId,1700		admin: bool,1701	) -> DispatchResult {1702		collection.check_is_internal()?;1703		collection.check_is_owner(sender)?;17041705		let is_admin = <IsAdmin<T>>::get((collection.id, user));1706		if is_admin == admin {1707			if admin {1708				return Ok(());1709			} else {1710				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1711			}1712		}1713		let amount = <AdminAmount<T>>::get(collection.id);17141715		// =========17161717		if admin {1718			let amount = amount1719				.checked_add(1)1720				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1721			ensure!(1722				amount <= Self::collection_admins_limit(),1723				<Error<T>>::CollectionAdminCountExceeded,1724			);17251726			<AdminAmount<T>>::insert(collection.id, amount);1727			<IsAdmin<T>>::insert((collection.id, user), true);17281729			Self::deposit_event(Event::<T>::CollectionAdminAdded(1730				collection.id,1731				user.clone(),1732			));1733		} else {1734			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1735			<IsAdmin<T>>::remove((collection.id, user));17361737			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1738				collection.id,1739				user.clone(),1740			));1741		}17421743		<PalletEvm<T>>::deposit_log(1744			erc::CollectionHelpersEvents::CollectionChanged {1745				collection_id: eth::collection_id_to_address(collection.id),1746			}1747			.to_log(T::ContractAddress::get()),1748		);17491750		Ok(())1751	}17521753	/// Update collection limits.1754	pub fn update_limits(1755		user: &T::CrossAccountId,1756		collection: &mut CollectionHandle<T>,1757		new_limit: CollectionLimits,1758	) -> DispatchResult {1759		collection.check_is_internal()?;1760		collection.check_is_owner_or_admin(user)?;17611762		collection.limits =1763			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17641765		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1766		<PalletEvm<T>>::deposit_log(1767			erc::CollectionHelpersEvents::CollectionChanged {1768				collection_id: eth::collection_id_to_address(collection.id),1769			}1770			.to_log(T::ContractAddress::get()),1771		);17721773		collection.save()1774	}17751776	/// Merge set fields from `new_limit` to `old_limit`.1777	fn clamp_limits(1778		mode: CollectionMode,1779		old_limit: &CollectionLimits,1780		mut new_limit: CollectionLimits,1781	) -> Result<CollectionLimits, DispatchError> {1782		let limits = old_limit;1783		limit_default!(old_limit, new_limit,1784			account_token_ownership_limit => ensure!(1785				new_limit <= MAX_TOKEN_OWNERSHIP,1786				<Error<T>>::CollectionLimitBoundsExceeded,1787			),1788			sponsored_data_size => ensure!(1789				new_limit <= CUSTOM_DATA_LIMIT,1790				<Error<T>>::CollectionLimitBoundsExceeded,1791			),17921793			sponsored_data_rate_limit => {},1794			token_limit => ensure!(1795				old_limit >= new_limit && new_limit > 0,1796				<Error<T>>::CollectionTokenLimitExceeded1797			),17981799			sponsor_transfer_timeout(match mode {1800				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1801				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1802				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1803			}) => ensure!(1804				new_limit <= MAX_SPONSOR_TIMEOUT,1805				<Error<T>>::CollectionLimitBoundsExceeded,1806			),1807			sponsor_approve_timeout => {},1808			owner_can_transfer => ensure!(1809				!limits.owner_can_transfer_instaled() ||1810				old_limit || !new_limit,1811				<Error<T>>::OwnerPermissionsCantBeReverted,1812			),1813			owner_can_destroy => ensure!(1814				old_limit || !new_limit,1815				<Error<T>>::OwnerPermissionsCantBeReverted,1816			),1817			transfers_enabled => {},1818		);1819		Ok(new_limit)1820	}18211822	/// Update collection permissions.1823	pub fn update_permissions(1824		user: &T::CrossAccountId,1825		collection: &mut CollectionHandle<T>,1826		new_permission: CollectionPermissions,1827	) -> DispatchResult {1828		collection.check_is_internal()?;1829		collection.check_is_owner_or_admin(user)?;1830		collection.permissions = Self::clamp_permissions(1831			collection.mode.clone(),1832			&collection.permissions,1833			new_permission,1834		)?;18351836		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1837		<PalletEvm<T>>::deposit_log(1838			erc::CollectionHelpersEvents::CollectionChanged {1839				collection_id: eth::collection_id_to_address(collection.id),1840			}1841			.to_log(T::ContractAddress::get()),1842		);18431844		collection.save()1845	}18461847	/// Merge set fields from `new_permission` to `old_permission`.1848	fn clamp_permissions(1849		_mode: CollectionMode,1850		old_permission: &CollectionPermissions,1851		mut new_permission: CollectionPermissions,1852	) -> Result<CollectionPermissions, DispatchError> {1853		limit_default_clone!(old_permission, new_permission,1854			access => {},1855			mint_mode => {},1856			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1857		);1858		Ok(new_permission)1859	}18601861	/// Repair possibly broken properties of a collection.1862	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1863		CollectionProperties::<T>::mutate(collection_id, |properties| {1864			properties.recompute_consumed_space();1865		});18661867		Ok(())1868	}1869}18701871/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1872#[macro_export]1873macro_rules! unsupported {1874	($runtime:path) => {1875		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1876	};1877}18781879/// Return weights for various worst-case operations.1880pub trait CommonWeightInfo<CrossAccountId> {1881	/// Weight of item creation.1882	fn create_item(data: &CreateItemData) -> Weight {1883		Self::create_multiple_items(from_ref(data))1884	}18851886	/// Weight of items creation.1887	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18881889	/// Weight of items creation.1890	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18911892	/// The weight of the burning item.1893	fn burn_item() -> Weight;18941895	/// Property setting weight.1896	///1897	/// * `amount`- The number of properties to set.1898	fn set_collection_properties(amount: u32) -> Weight;18991900	/// Collection property deletion weight.1901	///1902	/// * `amount`- The number of properties to set.1903	fn delete_collection_properties(amount: u32) -> Weight;19041905	/// Token property setting weight.1906	///1907	/// * `amount`- The number of properties to set.1908	fn set_token_properties(amount: u32) -> Weight;19091910	/// Token property deletion weight.1911	///1912	/// * `amount`- The number of properties to delete.1913	fn delete_token_properties(amount: u32) -> Weight;19141915	/// Token property permissions set weight.1916	///1917	/// * `amount`- The number of property permissions to set.1918	fn set_token_property_permissions(amount: u32) -> Weight;19191920	/// Transfer price of the token or its parts.1921	fn transfer() -> Weight;19221923	/// The price of setting the permission of the operation from another user.1924	fn approve() -> Weight;19251926	/// The price of setting the permission of the operation from another user for eth mirror.1927	fn approve_from() -> Weight;19281929	/// Transfer price from another user.1930	fn transfer_from() -> Weight;19311932	/// The price of burning a token from another user.1933	fn burn_from() -> Weight;19341935	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1936	/// whole users's balance.1937	///1938	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1939	fn burn_recursively_self_raw() -> Weight;19401941	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1942	///1943	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1944	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19451946	/// The price of recursive burning a token.1947	///1948	/// `max_selfs` - The maximum burning weight of the token itself.1949	/// `max_breadth` - The maximum number of nested tokens to burn.1950	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1951		Self::burn_recursively_self_raw()1952			.saturating_mul(max_selfs.max(1) as u64)1953			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1954	}19551956	/// The price of retrieving token owner1957	fn token_owner() -> Weight;19581959	/// The price of setting approval for all1960	fn set_allowance_for_all() -> Weight;19611962	/// The price of repairing an item.1963	fn force_repair_item() -> Weight;1964}19651966/// Weight info extension trait for refungible pallet.1967pub trait RefungibleExtensionsWeightInfo {1968	/// Weight of token repartition.1969	fn repartition() -> Weight;1970}19711972/// Common collection operations.1973///1974/// It wraps methods in Fungible, Nonfungible and Refungible pallets1975/// and adds weight info.1976pub trait CommonCollectionOperations<T: Config> {1977	/// Create token.1978	///1979	/// * `sender` - The user who mint the token and pays for the transaction.1980	/// * `to` - The user who will own the token.1981	/// * `data` - Token data.1982	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1983	fn create_item(1984		&self,1985		sender: T::CrossAccountId,1986		to: T::CrossAccountId,1987		data: CreateItemData,1988		nesting_budget: &dyn Budget,1989	) -> DispatchResultWithPostInfo;19901991	/// Create multiple tokens.1992	///1993	/// * `sender` - The user who mint the token and pays for the transaction.1994	/// * `to` - The user who will own the token.1995	/// * `data` - Token data.1996	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1997	fn create_multiple_items(1998		&self,1999		sender: T::CrossAccountId,2000		to: T::CrossAccountId,2001		data: Vec<CreateItemData>,2002		nesting_budget: &dyn Budget,2003	) -> DispatchResultWithPostInfo;20042005	/// Create multiple tokens.2006	///2007	/// * `sender` - The user who mint the token and pays for the transaction.2008	/// * `to` - The user who will own the token.2009	/// * `data` - Token data.2010	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2011	fn create_multiple_items_ex(2012		&self,2013		sender: T::CrossAccountId,2014		data: CreateItemExData<T::CrossAccountId>,2015		nesting_budget: &dyn Budget,2016	) -> DispatchResultWithPostInfo;20172018	/// Burn token.2019	///2020	/// * `sender` - The user who owns the token.2021	/// * `token` - Token id that will burned.2022	/// * `amount` - The number of parts of the token that will be burned.2023	fn burn_item(2024		&self,2025		sender: T::CrossAccountId,2026		token: TokenId,2027		amount: u128,2028	) -> DispatchResultWithPostInfo;20292030	/// Burn token and all nested tokens recursievly.2031	///2032	/// * `sender` - The user who owns the token.2033	/// * `token` - Token id that will burned.2034	/// * `self_budget` - The budget that can be spent on burning tokens.2035	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2036	fn burn_item_recursively(2037		&self,2038		sender: T::CrossAccountId,2039		token: TokenId,2040		self_budget: &dyn Budget,2041		breadth_budget: &dyn Budget,2042	) -> DispatchResultWithPostInfo;20432044	/// Set collection properties.2045	///2046	/// * `sender` - Must be either the owner of the collection or its admin.2047	/// * `properties` - Properties to be set.2048	fn set_collection_properties(2049		&self,2050		sender: T::CrossAccountId,2051		properties: Vec<Property>,2052	) -> DispatchResultWithPostInfo;20532054	/// Delete collection properties.2055	///2056	/// * `sender` - Must be either the owner of the collection or its admin.2057	/// * `properties` - The properties to be removed.2058	fn delete_collection_properties(2059		&self,2060		sender: &T::CrossAccountId,2061		property_keys: Vec<PropertyKey>,2062	) -> DispatchResultWithPostInfo;20632064	/// Set token properties.2065	///2066	/// The appropriate [`PropertyPermission`] for the token property2067	/// must be set with [`Self::set_token_property_permissions`].2068	///2069	/// * `sender` - Must be either the owner of the token or its admin.2070	/// * `token_id` - The token for which the properties are being set.2071	/// * `properties` - Properties to be set.2072	/// * `budget` - Budget for setting properties.2073	fn set_token_properties(2074		&self,2075		sender: T::CrossAccountId,2076		token_id: TokenId,2077		properties: Vec<Property>,2078		budget: &dyn Budget,2079	) -> DispatchResultWithPostInfo;20802081	/// Remove token properties.2082	///2083	/// The appropriate [`PropertyPermission`] for the token property2084	/// must be set with [`Self::set_token_property_permissions`].2085	///2086	/// * `sender` - Must be either the owner of the token or its admin.2087	/// * `token_id` - The token for which the properties are being remove.2088	/// * `property_keys` - Keys to remove corresponding properties.2089	/// * `budget` - Budget for removing properties.2090	fn delete_token_properties(2091		&self,2092		sender: T::CrossAccountId,2093		token_id: TokenId,2094		property_keys: Vec<PropertyKey>,2095		budget: &dyn Budget,2096	) -> DispatchResultWithPostInfo;20972098	/// Get token properties raw map.2099	///2100	/// * `token_id` - The token which properties are needed.2101	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;21022103	/// Set token properties raw map.2104	///2105	/// * `token_id` - The token for which the properties are being set.2106	/// * `map` - The raw map containing the token's properties.2107	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);21082109	/// Set token property permissions.2110	///2111	/// * `sender` - Must be either the owner of the token or its admin.2112	/// * `token_id` - The token for which the properties are being set.2113	/// * `property_permissions` - Property permissions to be set.2114	/// * `budget` - Budget for setting properties.2115	fn set_token_property_permissions(2116		&self,2117		sender: &T::CrossAccountId,2118		property_permissions: Vec<PropertyKeyPermission>,2119	) -> DispatchResultWithPostInfo;21202121	/// Transfer amount of token pieces.2122	///2123	/// * `sender` - Donor user.2124	/// * `to` - Recepient user.2125	/// * `token` - The token of which parts are being sent.2126	/// * `amount` - The number of parts of the token that will be transferred.2127	/// * `budget` - The maximum budget that can be spent on the transfer.2128	fn transfer(2129		&self,2130		sender: T::CrossAccountId,2131		to: T::CrossAccountId,2132		token: TokenId,2133		amount: u128,2134		budget: &dyn Budget,2135	) -> DispatchResultWithPostInfo;21362137	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2138	///2139	/// * `sender` - The user who grants access to the token.2140	/// * `spender` - The user to whom the rights are granted.2141	/// * `token` - The token to which access is granted.2142	/// * `amount` - The amount of pieces that another user can dispose of.2143	fn approve(2144		&self,2145		sender: T::CrossAccountId,2146		spender: T::CrossAccountId,2147		token: TokenId,2148		amount: u128,2149	) -> DispatchResultWithPostInfo;21502151	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2152	///2153	/// * `sender` - The user who grants access to the token.2154	/// * `from` - Spender's eth mirror.2155	/// * `to` - The user to whom the rights are granted.2156	/// * `token` - The token to which access is granted.2157	/// * `amount` - The amount of pieces that another user can dispose of.2158	fn approve_from(2159		&self,2160		sender: T::CrossAccountId,2161		from: T::CrossAccountId,2162		to: T::CrossAccountId,2163		token: TokenId,2164		amount: u128,2165	) -> DispatchResultWithPostInfo;21662167	/// Send parts of a token owned by another user.2168	///2169	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2170	///2171	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2172	/// * `from` - The user who owns the token.2173	/// * `to` - Recepient user.2174	/// * `token` - The token of which parts are being sent.2175	/// * `amount` - The number of parts of the token that will be transferred.2176	/// * `budget` - The maximum budget that can be spent on the transfer.2177	fn transfer_from(2178		&self,2179		sender: T::CrossAccountId,2180		from: T::CrossAccountId,2181		to: T::CrossAccountId,2182		token: TokenId,2183		amount: u128,2184		budget: &dyn Budget,2185	) -> DispatchResultWithPostInfo;21862187	/// Burn parts of a token owned by another user.2188	///2189	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2190	///2191	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2192	/// * `from` - The user who owns the token.2193	/// * `token` - The token of which parts are being sent.2194	/// * `amount` - The number of parts of the token that will be transferred.2195	/// * `budget` - The maximum budget that can be spent on the burn.2196	fn burn_from(2197		&self,2198		sender: T::CrossAccountId,2199		from: T::CrossAccountId,2200		token: TokenId,2201		amount: u128,2202		budget: &dyn Budget,2203	) -> DispatchResultWithPostInfo;22042205	/// Check permission to nest token.2206	///2207	/// * `sender` - The user who initiated the check.2208	/// * `from` - The token that is checked for embedding.2209	/// * `under` - Token under which to check.2210	/// * `budget` - The maximum budget that can be spent on the check.2211	fn check_nesting(2212		&self,2213		sender: T::CrossAccountId,2214		from: (CollectionId, TokenId),2215		under: TokenId,2216		budget: &dyn Budget,2217	) -> DispatchResult;22182219	/// Nest one token into another.2220	///2221	/// * `under` - Token holder.2222	/// * `to_nest` - Nested token.2223	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22242225	/// Unnest token.2226	///2227	/// * `under` - Token holder.2228	/// * `to_nest` - Token to unnest.2229	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22302231	/// Get all user tokens.2232	///2233	/// * `account` - Account for which you need to get tokens.2234	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22352236	/// Get all the tokens in the collection.2237	fn collection_tokens(&self) -> Vec<TokenId>;22382239	/// Check if the token exists.2240	///2241	/// * `token` - Id token to check.2242	fn token_exists(&self, token: TokenId) -> bool;22432244	/// Get the id of the last minted token.2245	fn last_token_id(&self) -> TokenId;22462247	/// Get the owner of the token.2248	///2249	/// * `token` - The token for which you need to find out the owner.2250	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22512252	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2253	///2254	/// * `token` - Id token to check.2255	/// * `maybe_owner` - The account to check.2256	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2257	fn check_token_indirect_owner(2258		&self,2259		token: TokenId,2260		maybe_owner: &T::CrossAccountId,2261		nesting_budget: &dyn Budget,2262	) -> Result<bool, DispatchError>;22632264	/// Returns 10 tokens owners in no particular order.2265	///2266	/// * `token` - The token for which you need to find out the owners.2267	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22682269	/// Get the value of the token property by key.2270	///2271	/// * `token` - Token with the property to get.2272	/// * `key` - Property name.2273	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22742275	/// Get a set of token properties by key vector.2276	///2277	/// * `token` - Token with the property to get.2278	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2279	/// then all properties are returned.2280	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22812282	/// Amount of unique collection tokens2283	fn total_supply(&self) -> u32;22842285	/// Amount of different tokens account has.2286	///2287	/// * `account` - The account for which need to get the balance.2288	fn account_balance(&self, account: T::CrossAccountId) -> u32;22892290	/// Amount of specific token account have.2291	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22922293	/// Amount of token pieces2294	fn total_pieces(&self, token: TokenId) -> Option<u128>;22952296	/// Get the number of parts of the token that a trusted user can manage.2297	///2298	/// * `sender` - Trusted user.2299	/// * `spender` - Owner of the token.2300	/// * `token` - The token for which to get the value.2301	fn allowance(2302		&self,2303		sender: T::CrossAccountId,2304		spender: T::CrossAccountId,2305		token: TokenId,2306	) -> u128;23072308	/// Get extension for RFT collection.2309	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23102311	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2312	/// * `owner` - Token owner2313	/// * `operator` - Operator2314	/// * `approve` - Should operator status be granted or revoked?2315	fn set_allowance_for_all(2316		&self,2317		owner: T::CrossAccountId,2318		operator: T::CrossAccountId,2319		approve: bool,2320	) -> DispatchResultWithPostInfo;23212322	/// Tells whether the given `owner` approves the `operator`.2323	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23242325	/// Repairs a possibly broken item.2326	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2327}23282329/// Extension for RFT collection.2330pub trait RefungibleExtensions<T>2331where2332	T: Config,2333{2334	/// Change the number of parts of the token.2335	///2336	/// When the value changes down, this function is equivalent to burning parts of the token.2337	///2338	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2339	/// * `token` - The token for which you want to change the number of parts.2340	/// * `amount` - The new value of the parts of the token.2341	fn repartition(2342		&self,2343		sender: &T::CrossAccountId,2344		token: TokenId,2345		amount: u128,2346	) -> DispatchResultWithPostInfo;2347}23482349/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2350///2351/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2352pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2353	let post_info = PostDispatchInfo {2354		actual_weight: Some(weight),2355		pays_fee: Pays::Yes,2356	};2357	match res {2358		Ok(()) => Ok(post_info),2359		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2360	}2361}23622363impl<T: Config> From<PropertiesError> for Error<T> {2364	fn from(error: PropertiesError) -> Self {2365		match error {2366			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2367			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2368			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2369			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2370			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2371		}2372	}2373}23742375/// A marker structure that enables the writer implementation2376/// to provide the interface to write properties to **newly created** tokens.2377pub struct NewTokenPropertyWriter;23782379/// A marker structure that enables the writer implementation2380/// to provide the interface to write properties to **already existing** tokens.2381pub struct ExistingTokenPropertyWriter;23822383/// The type-safe interface for writing properties (setting or deleting) to tokens.2384/// It has two distinct implementations for newly created tokens and existing ones.2385///2386/// This type utilizes the lazy evaluation to avoid repeating the computation2387/// of several performance-heavy or PoV-heavy tasks,2388/// such as checking the indirect ownership or reading the token property permissions.2389pub struct PropertyWriter<2390	'a,2391	T,2392	Handle,2393	WriterVariant,2394	FIsAdmin,2395	FPropertyPermissions,2396	FCheckTokenExist,2397	FGetProperties,2398> where2399	T: Config,2400	FIsAdmin: FnOnce() -> bool,2401	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2402{2403	collection: &'a Handle,2404	is_collection_admin: LazyValue<bool, FIsAdmin>,2405	property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,2406	check_token_exist: FCheckTokenExist,2407	get_properties: FGetProperties,2408	_phantom: PhantomData<(T, WriterVariant)>,2409}24102411impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2412	PropertyWriter<2413		'a,2414		T,2415		Handle,2416		NewTokenPropertyWriter,2417		FIsAdmin,2418		FPropertyPermissions,2419		FCheckTokenExist,2420		FGetProperties,2421	> where2422	T: Config,2423	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2424	FIsAdmin: FnOnce() -> bool,2425	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2426	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2427	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2428{2429	/// A function to write properties to a **newly created** token.2430	pub fn write_token_properties(2431		&mut self,2432		mint_target_is_sender: bool,2433		token_id: TokenId,2434		properties_updates: impl Iterator<Item = Property>,2435		log: evm_coder::ethereum::Log,2436	) -> DispatchResult {2437		self.internal_write_token_properties(2438			token_id,2439			properties_updates.map(|p| (p.key, Some(p.value))),2440			|_| Ok(mint_target_is_sender),2441			log,2442		)2443	}2444}24452446impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2447	PropertyWriter<2448		'a,2449		T,2450		Handle,2451		ExistingTokenPropertyWriter,2452		FIsAdmin,2453		FPropertyPermissions,2454		FCheckTokenExist,2455		FGetProperties,2456	> where2457	T: Config,2458	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2459	FIsAdmin: FnOnce() -> bool,2460	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2461	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2462	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2463{2464	/// A function to write properties to an **already existing** token.2465	pub fn write_token_properties(2466		&mut self,2467		sender: &T::CrossAccountId,2468		token_id: TokenId,2469		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2470		nesting_budget: &dyn Budget,2471		log: evm_coder::ethereum::Log,2472	) -> DispatchResult {2473		self.internal_write_token_properties(2474			token_id,2475			properties_updates,2476			|collection| collection.check_token_indirect_owner(token_id, sender, nesting_budget),2477			log,2478		)2479	}2480}24812482impl<2483		'a,2484		T,2485		Handle,2486		WriterVariant,2487		FIsAdmin,2488		FPropertyPermissions,2489		FCheckTokenExist,2490		FGetProperties,2491	>2492	PropertyWriter<2493		'a,2494		T,2495		Handle,2496		WriterVariant,2497		FIsAdmin,2498		FPropertyPermissions,2499		FCheckTokenExist,2500		FGetProperties,2501	> where2502	T: Config,2503	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2504	FIsAdmin: FnOnce() -> bool,2505	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2506	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2507	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2508{2509	fn internal_write_token_properties<FCheckTokenOwner>(2510		&mut self,2511		token_id: TokenId,2512		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2513		check_token_owner: FCheckTokenOwner,2514		log: evm_coder::ethereum::Log,2515	) -> DispatchResult2516	where2517		FCheckTokenOwner: FnOnce(&Handle) -> Result<bool, DispatchError>,2518	{2519		let get_properties = self.get_properties;2520		let mut stored_properties = LazyValue::new(move || get_properties(token_id));25212522		let mut is_token_owner = LazyValue::new(|| check_token_owner(self.collection));25232524		let check_token_exist = self.check_token_exist;2525		let mut is_token_exist = LazyValue::new(move || check_token_exist(token_id));25262527		for (key, value) in properties_updates {2528			let permission = self2529				.property_permissions2530				.value()2531				.get(&key)2532				.cloned()2533				.unwrap_or_else(PropertyPermission::none);25342535			match permission {2536				PropertyPermission { mutable: false, .. }2537					if stored_properties.value().get(&key).is_some() =>2538				{2539					return Err(<Error<T>>::NoPermission.into());2540				}25412542				PropertyPermission {2543					collection_admin,2544					token_owner,2545					..2546				} => check_token_permissions::<T, _, _, _>(2547					collection_admin,2548					token_owner,2549					&mut self.is_collection_admin,2550					&mut is_token_owner,2551					&mut is_token_exist,2552				)?,2553			}25542555			match value {2556				Some(value) => {2557					stored_properties2558						.value_mut()2559						.try_set(key.clone(), value)2560						.map_err(<Error<T>>::from)?;25612562					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2563						self.collection.id,2564						token_id,2565						key,2566					));2567				}2568				None => {2569					stored_properties2570						.value_mut()2571						.remove(&key)2572						.map_err(<Error<T>>::from)?;25732574					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2575						self.collection.id,2576						token_id,2577						key,2578					));2579				}2580			}2581		}25822583		let properties_changed = stored_properties.has_value();2584		if properties_changed {2585			<PalletEvm<T>>::deposit_log(log);25862587			self.collection2588				.set_token_properties_raw(token_id, stored_properties.into_inner());2589		}25902591		Ok(())2592	}2593}25942595/// Create a [`PropertyWriter`] for newly created tokens.2596pub fn property_writer_for_new_token<'a, T, Handle>(2597	collection: &'a Handle,2598	sender: &'a T::CrossAccountId,2599) -> PropertyWriter<2600	'a,2601	T,2602	Handle,2603	NewTokenPropertyWriter,2604	impl FnOnce() -> bool + 'a,2605	impl FnOnce() -> PropertiesPermissionMap + 'a,2606	impl Copy + FnOnce(TokenId) -> bool + 'a,2607	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2608>2609where2610	T: Config,2611	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2612{2613	PropertyWriter {2614		collection,2615		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2616		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2617		check_token_exist: |token_id| {2618			debug_assert!(collection.token_exists(token_id));2619			true2620		},2621		get_properties: |token_id| {2622			debug_assert!(collection.get_token_properties_raw(token_id).is_none());2623			TokenProperties::new()2624		},2625		_phantom: PhantomData,2626	}2627}26282629#[cfg(feature = "runtime-benchmarks")]2630/// Create a `PropertyWriter` with preloaded `is_collection_admin` and `property_permissions.2631/// Also:2632/// * it will return `true` for the token ownership check.2633/// * it will return empty stored properties without reading them from the storage.2634pub fn collection_info_loaded_property_writer<T, Handle>(2635	collection: &Handle,2636	is_collection_admin: bool,2637	property_permissions: PropertiesPermissionMap,2638) -> PropertyWriter<2639	T,2640	Handle,2641	NewTokenPropertyWriter,2642	impl FnOnce() -> bool,2643	impl FnOnce() -> PropertiesPermissionMap,2644	impl Copy + FnOnce(TokenId) -> bool,2645	impl Copy + FnOnce(TokenId) -> TokenProperties,2646>2647where2648	T: Config,2649	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2650{2651	PropertyWriter {2652		collection,2653		is_collection_admin: LazyValue::new(move || is_collection_admin),2654		property_permissions: LazyValue::new(move || property_permissions),2655		check_token_exist: |_token_id| true,2656		get_properties: |_token_id| TokenProperties::new(),2657		_phantom: PhantomData,2658	}2659}26602661/// Create a [`PropertyWriter`] for already existing tokens.2662pub fn property_writer_for_existing_token<'a, T, Handle>(2663	collection: &'a Handle,2664	sender: &'a T::CrossAccountId,2665) -> PropertyWriter<2666	'a,2667	T,2668	Handle,2669	ExistingTokenPropertyWriter,2670	impl FnOnce() -> bool + 'a,2671	impl FnOnce() -> PropertiesPermissionMap + 'a,2672	impl Copy + FnOnce(TokenId) -> bool + 'a,2673	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2674>2675where2676	T: Config,2677	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2678{2679	PropertyWriter {2680		collection,2681		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2682		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2683		check_token_exist: |token_id| collection.token_exists(token_id),2684		get_properties: |token_id| {2685			collection2686				.get_token_properties_raw(token_id)2687				.unwrap_or_default()2688		},2689		_phantom: PhantomData,2690	}2691}26922693/// Computes the weight delta for newly created tokens with properties.2694/// * `properties_nums` - The properties num of each created token.2695/// * `init_token_properties` - The function to obtain the weight from a token's properties num.2696pub fn init_token_properties_delta<T: Config, I: Fn(u32) -> Weight>(2697	properties_nums: impl Iterator<Item = u32>,2698	init_token_properties: I,2699) -> Weight {2700	let mut delta = properties_nums2701		.filter_map(|properties_num| {2702			if properties_num > 0 {2703				Some(init_token_properties(properties_num))2704			} else {2705				None2706			}2707		})2708		.fold(Weight::zero(), |a, b| a.saturating_add(b));27092710	// If at least once the `init_token_properties` was called,2711	// it means at least one newly created token has properties.2712	// Becuase of that, some common collection data also was loaded and we need to add this weight.2713	// However, these common data was loaded only once which is guaranteed by the `PropertyWriter`.2714	if !delta.is_zero() {2715		delta = delta.saturating_add(<SelfWeightOf<T>>::init_token_properties_common())2716	}27172718	delta2719}27202721#[cfg(any(feature = "tests", test))]2722#[allow(missing_docs)]2723pub mod tests {2724	use crate::{DispatchResult, DispatchError, LazyValue, Config};27252726	const fn to_bool(u: u8) -> bool {2727		u != 02728	}27292730	#[derive(Debug)]2731	pub struct TestCase {2732		pub collection_admin: bool,2733		pub is_collection_admin: bool,2734		pub token_owner: bool,2735		pub is_token_owner: bool,2736		pub no_permission: bool,2737	}27382739	impl TestCase {2740		const fn new(2741			collection_admin: u8,2742			is_collection_admin: u8,2743			token_owner: u8,2744			is_token_owner: u8,2745			no_permission: u8,2746		) -> Self {2747			Self {2748				collection_admin: to_bool(collection_admin),2749				is_collection_admin: to_bool(is_collection_admin),2750				token_owner: to_bool(token_owner),2751				is_token_owner: to_bool(is_token_owner),2752				no_permission: to_bool(no_permission),2753			}2754		}2755	}27562757	#[rustfmt::skip]2758	pub const TABLE: [TestCase; 16] = [2759		//                    ┌╴collection_admin2760		//                    │  ┌╴is_collection_admin2761		//                    │  │   ┌╴token_owner2762		//                    │  │   │  ┌╴is_token_ownership2763		//                    │  │   │  │   ┌╴no_permission2764		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2765		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2766		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2767		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2768		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2769		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2770		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2771		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2772		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2773		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2774		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2775		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2776		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2777		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2778		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2779		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2780	];27812782	pub fn check_token_permissions<T, FCA, FTO, FTE>(2783		collection_admin_permitted: bool,2784		token_owner_permitted: bool,2785		is_collection_admin: &mut LazyValue<bool, FCA>,2786		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2787		check_token_existence: &mut LazyValue<bool, FTE>,2788	) -> DispatchResult2789	where2790		T: Config,2791		FCA: FnOnce() -> bool,2792		FTO: FnOnce() -> Result<bool, DispatchError>,2793		FTE: FnOnce() -> bool,2794	{2795		crate::check_token_permissions::<T, FCA, FTO, FTE>(2796			collection_admin_permitted,2797			token_owner_permitted,2798			is_collection_admin,2799			check_token_ownership,2800			check_token_existence,2801		)2802	}2803}
after · pallets/common/src/lib.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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59	marker::PhantomData,60};61use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};62use sp_std::vec::Vec;63use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};64use evm_coder::ToLog;65use frame_support::{66	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},67	ensure,68	traits::{69		Get,70		fungible::{Balanced, Debt, Inspect},71		tokens::{Imbalance, Precision, Preservation},72	},73	dispatch::Pays,74	transactional, fail,75};76use up_data_structs::{77	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,78	CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,79	TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,80	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,81	CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,82	SponsoringRateLimit, budget::Budget, PhantomType, Property,83	CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,84	PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,85	PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,86};87use up_pov_estimate_rpc::PovInfo;8889pub use pallet::*;90use sp_core::H160;91use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9293#[cfg(feature = "runtime-benchmarks")]94pub mod benchmarking;95pub mod dispatch;96pub mod erc;97pub mod eth;98pub mod helpers;99#[allow(missing_docs)]100pub mod weights;101102use weights::WeightInfo;103104/// Weight info.105pub type SelfWeightOf<T> = <T as Config>::WeightInfo;106107/// Collection handle contains information about collection data and id.108/// Also provides functionality to count consumed gas.109///110/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).111/// It allows to perform common operations and queries on any collection type,112/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].113#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]114pub struct CollectionHandle<T: Config> {115	/// Collection id116	pub id: CollectionId,117	collection: Collection<T::AccountId>,118	/// Substrate recorder for counting consumed gas119	pub recorder: SubstrateRecorder<T>,120}121122impl<T: Config> WithRecorder<T> for CollectionHandle<T> {123	fn recorder(&self) -> &SubstrateRecorder<T> {124		&self.recorder125	}126	fn into_recorder(self) -> SubstrateRecorder<T> {127		self.recorder128	}129}130131impl<T: Config> CollectionHandle<T> {132	/// Same as [CollectionHandle::new] but with an explicit gas limit.133	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {134		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))135	}136137	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].138	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {139		<CollectionById<T>>::get(id).map(|collection| Self {140			id,141			collection,142			recorder,143		})144	}145146	/// Retrives collection data from storage and creates collection handle with default parameters.147	/// If collection not found return `None`148	pub fn new(id: CollectionId) -> Option<Self> {149		Self::new_with_gas_limit(id, u64::MAX)150	}151152	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.153	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {154		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)155	}156157	/// Consume gas for reading.158	pub fn consume_store_reads(159		&self,160		reads: u64,161	) -> pallet_evm_coder_substrate::execution::Result<()> {162		self.recorder().consume_store_reads(reads)163	}164165	/// Consume gas for writing.166	pub fn consume_store_writes(167		&self,168		writes: u64,169	) -> pallet_evm_coder_substrate::execution::Result<()> {170		self.recorder().consume_store_writes(writes)171	}172173	/// Consume gas for reading and writing.174	pub fn consume_store_reads_and_writes(175		&self,176		reads: u64,177		writes: u64,178	) -> pallet_evm_coder_substrate::execution::Result<()> {179		self.recorder()180			.consume_store_reads_and_writes(reads, writes)181	}182183	/// Save collection to storage.184	pub fn save(&self) -> DispatchResult {185		<CollectionById<T>>::insert(self.id, &self.collection);186		Ok(())187	}188189	/// Set collection sponsor.190	///191	/// Unique collections allows sponsoring for certain actions.192	/// This method allows you to set the sponsor of the collection.193	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].194	pub fn set_sponsor(195		&mut self,196		sender: &T::CrossAccountId,197		sponsor: T::AccountId,198	) -> DispatchResult {199		self.check_is_internal()?;200		self.check_is_owner_or_admin(sender)?;201202		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());203204		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));205		<PalletEvm<T>>::deposit_log(206			erc::CollectionHelpersEvents::CollectionChanged {207				collection_id: eth::collection_id_to_address(self.id),208			}209			.to_log(T::ContractAddress::get()),210		);211212		self.save()213	}214215	/// Force set `sponsor`.216	///217	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation218	/// from the `sponsor` is not required.219	///220	/// # Arguments221	///222	/// * `sponsor`: ID of the account of the sponsor-to-be.223	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {224		self.check_is_internal()?;225226		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());227228		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));229		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));230		<PalletEvm<T>>::deposit_log(231			erc::CollectionHelpersEvents::CollectionChanged {232				collection_id: eth::collection_id_to_address(self.id),233			}234			.to_log(T::ContractAddress::get()),235		);236237		self.save()238	}239240	/// Confirm sponsorship241	///242	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.243	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].244	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {245		self.check_is_internal()?;246		ensure!(247			self.collection.sponsorship.pending_sponsor() == Some(sender),248			Error::<T>::ConfirmSponsorshipFail249		);250251		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());252253		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));254		<PalletEvm<T>>::deposit_log(255			erc::CollectionHelpersEvents::CollectionChanged {256				collection_id: eth::collection_id_to_address(self.id),257			}258			.to_log(T::ContractAddress::get()),259		);260261		self.save()262	}263264	/// Remove collection sponsor.265	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {266		self.check_is_internal()?;267		self.check_is_owner_or_admin(sender)?;268269		self.collection.sponsorship = SponsorshipState::Disabled;270271		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));272		<PalletEvm<T>>::deposit_log(273			erc::CollectionHelpersEvents::CollectionChanged {274				collection_id: eth::collection_id_to_address(self.id),275			}276			.to_log(T::ContractAddress::get()),277		);278		self.save()279	}280281	/// Force remove `sponsor`.282	///283	/// Differs from `remove_sponsor` in that284	/// it doesn't require consent from the `owner` of the collection.285	pub fn force_remove_sponsor(&mut self) -> DispatchResult {286		self.check_is_internal()?;287288		self.collection.sponsorship = SponsorshipState::Disabled;289290		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));291		<PalletEvm<T>>::deposit_log(292			erc::CollectionHelpersEvents::CollectionChanged {293				collection_id: eth::collection_id_to_address(self.id),294			}295			.to_log(T::ContractAddress::get()),296		);297		self.save()298	}299300	/// Checks that the collection was created with, and must be operated upon through **Unique API**.301	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.302	pub fn check_is_internal(&self) -> DispatchResult {303		if self.flags.external {304			return Err(<Error<T>>::CollectionIsExternal)?;305		}306307		Ok(())308	}309310	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.311	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.312	pub fn check_is_external(&self) -> DispatchResult {313		if !self.flags.external {314			return Err(<Error<T>>::CollectionIsInternal)?;315		}316317		Ok(())318	}319}320321impl<T: Config> Deref for CollectionHandle<T> {322	type Target = Collection<T::AccountId>;323324	fn deref(&self) -> &Self::Target {325		&self.collection326	}327}328329impl<T: Config> DerefMut for CollectionHandle<T> {330	fn deref_mut(&mut self) -> &mut Self::Target {331		&mut self.collection332	}333}334335impl<T: Config> CollectionHandle<T> {336	/// Checks if the `user` is the owner of the collection.337	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {338		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);339		Ok(())340	}341342	/// Returns **true** if the `user` is the owner or administrator of the collection.343	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {344		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))345	}346347	/// Checks if the `user` is the owner or administrator of the collection.348	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {349		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);350		Ok(())351	}352353	/// Returns **true** if354	/// * the `user`is a collection owner or admin355	/// * the collection limits allow the owner/admins to transfer/burn any collection token356	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {357		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)358	}359360	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.361	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {362		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)363	}364365	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.366	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {367		ensure!(368			<Allowlist<T>>::get((self.id, user)),369			<Error<T>>::AddressNotInAllowlist370		);371		Ok(())372	}373374	/// Changes collection owner to another account375	/// #### Store read/writes376	/// 1 writes377	pub fn change_owner(378		&mut self,379		caller: T::CrossAccountId,380		new_owner: T::CrossAccountId,381	) -> DispatchResult {382		self.check_is_internal()?;383		self.check_is_owner(&caller)?;384		self.collection.owner = new_owner.as_sub().clone();385386		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(387			self.id,388			new_owner.as_sub().clone(),389		));390		<PalletEvm<T>>::deposit_log(391			erc::CollectionHelpersEvents::CollectionChanged {392				collection_id: eth::collection_id_to_address(self.id),393			}394			.to_log(T::ContractAddress::get()),395		);396397		self.save()398	}399}400401#[frame_support::pallet]402pub mod pallet {403404	use super::*;405	use dispatch::CollectionDispatch;406	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};407	use up_data_structs::{TokenId, mapping::TokenAddressMapping};408	use scale_info::TypeInfo;409	use weights::WeightInfo;410411	#[pallet::config]412	pub trait Config:413		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo414	{415		/// Weight information for functions of this pallet.416		type WeightInfo: WeightInfo;417418		/// Events compatible with [`frame_system::Config::Event`].419		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;420421		/// Handler of accounts and payment.422		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;423424		/// Set price to create a collection.425		#[pallet::constant]426		type CollectionCreationPrice: Get<427			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,428		>;429430		/// Dispatcher of operations on collections.431		type CollectionDispatch: CollectionDispatch<Self>;432433		/// Account which holds the chain's treasury.434		type TreasuryAccountId: Get<Self::AccountId>;435436		/// Address under which the CollectionHelper contract would be available.437		#[pallet::constant]438		type ContractAddress: Get<H160>;439440		/// Mapper for token addresses to Ethereum addresses.441		type EvmTokenAddressMapping: TokenAddressMapping<H160>;442443		/// Mapper for token addresses to [`CrossAccountId`].444		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;445	}446447	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);448	/// Collection id for native fungible collction.449	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);450451	#[pallet::pallet]452	#[pallet::storage_version(STORAGE_VERSION)]453	pub struct Pallet<T>(_);454455	#[pallet::extra_constants]456	impl<T: Config> Pallet<T> {457		/// Maximum admins per collection.458		pub fn collection_admins_limit() -> u32 {459			COLLECTION_ADMINS_LIMIT460		}461	}462463	#[pallet::genesis_config]464	pub struct GenesisConfig<T>(PhantomData<T>);465466	impl<T: Config> Default for GenesisConfig<T> {467		fn default() -> Self {468			Self(Default::default())469		}470	}471472	#[pallet::genesis_build]473	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {474		fn build(&self) {475			StorageVersion::new(1).put::<Pallet<T>>();476		}477	}478479	impl<T: Config> Pallet<T> {480		/// Helper function that handles deposit events481		pub fn deposit_event(event: Event<T>) {482			let event = <T as Config>::RuntimeEvent::from(event);483			let event = event.into();484			<frame_system::Pallet<T>>::deposit_event(event)485		}486	}487488	#[pallet::event]489	pub enum Event<T: Config> {490		/// New collection was created491		CollectionCreated(492			/// Globally unique identifier of newly created collection.493			CollectionId,494			/// [`CollectionMode`] converted into _u8_.495			u8,496			/// Collection owner.497			T::AccountId,498		),499500		/// New collection was destroyed501		CollectionDestroyed(502			/// Globally unique identifier of collection.503			CollectionId,504		),505506		/// New item was created.507		ItemCreated(508			/// Id of the collection where item was created.509			CollectionId,510			/// Id of an item. Unique within the collection.511			TokenId,512			/// Owner of newly created item513			T::CrossAccountId,514			/// Always 1 for NFT515			u128,516		),517518		/// Collection item was burned.519		ItemDestroyed(520			/// Id of the collection where item was destroyed.521			CollectionId,522			/// Identifier of burned NFT.523			TokenId,524			/// Which user has destroyed its tokens.525			T::CrossAccountId,526			/// Amount of token pieces destroed. Always 1 for NFT.527			u128,528		),529530		/// Item was transferred531		Transfer(532			/// Id of collection to which item is belong.533			CollectionId,534			/// Id of an item.535			TokenId,536			/// Original owner of item.537			T::CrossAccountId,538			/// New owner of item.539			T::CrossAccountId,540			/// Amount of token pieces transfered. Always 1 for NFT.541			u128,542		),543544		/// Amount pieces of token owned by `sender` was approved for `spender`.545		Approved(546			/// Id of collection to which item is belong.547			CollectionId,548			/// Id of an item.549			TokenId,550			/// Original owner of item.551			T::CrossAccountId,552			/// Id for which the approval was granted.553			T::CrossAccountId,554			/// Amount of token pieces transfered. Always 1 for NFT.555			u128,556		),557558		/// A `sender` approves operations on all owned tokens for `spender`.559		ApprovedForAll(560			/// Id of collection to which item is belong.561			CollectionId,562			/// Owner of a wallet.563			T::CrossAccountId,564			/// Id for which operator status was granted or rewoked.565			T::CrossAccountId,566			/// Is operator status granted or revoked?567			bool,568		),569570		/// The colletion property has been added or edited.571		CollectionPropertySet(572			/// Id of collection to which property has been set.573			CollectionId,574			/// The property that was set.575			PropertyKey,576		),577578		/// The property has been deleted.579		CollectionPropertyDeleted(580			/// Id of collection to which property has been deleted.581			CollectionId,582			/// The property that was deleted.583			PropertyKey,584		),585586		/// The token property has been added or edited.587		TokenPropertySet(588			/// Identifier of the collection whose token has the property set.589			CollectionId,590			/// The token for which the property was set.591			TokenId,592			/// The property that was set.593			PropertyKey,594		),595596		/// The token property has been deleted.597		TokenPropertyDeleted(598			/// Identifier of the collection whose token has the property deleted.599			CollectionId,600			/// The token for which the property was deleted.601			TokenId,602			/// The property that was deleted.603			PropertyKey,604		),605606		/// The token property permission of a collection has been set.607		PropertyPermissionSet(608			/// ID of collection to which property permission has been set.609			CollectionId,610			/// The property permission that was set.611			PropertyKey,612		),613614		/// Address was added to the allow list.615		AllowListAddressAdded(616			/// ID of the affected collection.617			CollectionId,618			/// Address of the added account.619			T::CrossAccountId,620		),621622		/// Address was removed from the allow list.623		AllowListAddressRemoved(624			/// ID of the affected collection.625			CollectionId,626			/// Address of the removed account.627			T::CrossAccountId,628		),629630		/// Collection admin was added.631		CollectionAdminAdded(632			/// ID of the affected collection.633			CollectionId,634			/// Admin address.635			T::CrossAccountId,636		),637638		/// Collection admin was removed.639		CollectionAdminRemoved(640			/// ID of the affected collection.641			CollectionId,642			/// Removed admin address.643			T::CrossAccountId,644		),645646		/// Collection limits were set.647		CollectionLimitSet(648			/// ID of the affected collection.649			CollectionId,650		),651652		/// Collection owned was changed.653		CollectionOwnerChanged(654			/// ID of the affected collection.655			CollectionId,656			/// New owner address.657			T::AccountId,658		),659660		/// Collection permissions were set.661		CollectionPermissionSet(662			/// ID of the affected collection.663			CollectionId,664		),665666		/// Collection sponsor was set.667		CollectionSponsorSet(668			/// ID of the affected collection.669			CollectionId,670			/// New sponsor address.671			T::AccountId,672		),673674		/// New sponsor was confirm.675		SponsorshipConfirmed(676			/// ID of the affected collection.677			CollectionId,678			/// New sponsor address.679			T::AccountId,680		),681682		/// Collection sponsor was removed.683		CollectionSponsorRemoved(684			/// ID of the affected collection.685			CollectionId,686		),687	}688689	#[pallet::error]690	pub enum Error<T> {691		/// This collection does not exist.692		CollectionNotFound,693		/// Sender parameter and item owner must be equal.694		MustBeTokenOwner,695		/// No permission to perform action696		NoPermission,697		/// Destroying only empty collections is allowed698		CantDestroyNotEmptyCollection,699		/// Collection is not in mint mode.700		PublicMintingNotAllowed,701		/// Address is not in allow list.702		AddressNotInAllowlist,703704		/// Collection name can not be longer than 63 char.705		CollectionNameLimitExceeded,706		/// Collection description can not be longer than 255 char.707		CollectionDescriptionLimitExceeded,708		/// Token prefix can not be longer than 15 char.709		CollectionTokenPrefixLimitExceeded,710		/// Total collections bound exceeded.711		TotalCollectionsLimitExceeded,712		/// Exceeded max admin count713		CollectionAdminCountExceeded,714		/// Collection limit bounds per collection exceeded715		CollectionLimitBoundsExceeded,716		/// Tried to enable permissions which are only permitted to be disabled717		OwnerPermissionsCantBeReverted,718		/// Collection settings not allowing items transferring719		TransferNotAllowed,720		/// Account token limit exceeded per collection721		AccountTokenLimitExceeded,722		/// Collection token limit exceeded723		CollectionTokenLimitExceeded,724		/// Metadata flag frozen725		MetadataFlagFrozen,726727		/// Item does not exist728		TokenNotFound,729		/// Item is balance not enough730		TokenValueTooLow,731		/// Requested value is more than the approved732		ApprovedValueTooLow,733		/// Tried to approve more than owned734		CantApproveMoreThanOwned,735		/// Only spending from eth mirror could be approved736		AddressIsNotEthMirror,737738		/// Can't transfer tokens to ethereum zero address739		AddressIsZero,740741		/// The operation is not supported742		UnsupportedOperation,743744		/// Insufficient funds to perform an action745		NotSufficientFounds,746747		/// User does not satisfy the nesting rule748		UserIsNotAllowedToNest,749		/// Only tokens from specific collections may nest tokens under this one750		SourceCollectionIsNotAllowedToNest,751752		/// Tried to store more data than allowed in collection field753		CollectionFieldSizeExceeded,754755		/// Tried to store more property data than allowed756		NoSpaceForProperty,757758		/// Tried to store more property keys than allowed759		PropertyLimitReached,760761		/// Property key is too long762		PropertyKeyIsTooLong,763764		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed765		InvalidCharacterInPropertyKey,766767		/// Empty property keys are forbidden768		EmptyPropertyKey,769770		/// Tried to access an external collection with an internal API771		CollectionIsExternal,772773		/// Tried to access an internal collection with an external API774		CollectionIsInternal,775776		/// This address is not set as sponsor, use setCollectionSponsor first.777		ConfirmSponsorshipFail,778779		/// The user is not an administrator.780		UserIsNotCollectionAdmin,781	}782783	/// Storage of the count of created collections. Essentially contains the last collection ID.784	#[pallet::storage]785	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;786787	/// Storage of the count of deleted collections.788	#[pallet::storage]789	pub type DestroyedCollectionCount<T> =790		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;791792	/// Storage of collection info.793	#[pallet::storage]794	pub type CollectionById<T> = StorageMap<795		Hasher = Blake2_128Concat,796		Key = CollectionId,797		Value = Collection<<T as frame_system::Config>::AccountId>,798		QueryKind = OptionQuery,799	>;800801	/// Storage of collection properties.802	#[pallet::storage]803	#[pallet::getter(fn collection_properties)]804	pub type CollectionProperties<T> = StorageMap<805		Hasher = Blake2_128Concat,806		Key = CollectionId,807		Value = CollectionPropertiesT,808		QueryKind = ValueQuery,809	>;810811	/// Storage of token property permissions of a collection.812	#[pallet::storage]813	#[pallet::getter(fn property_permissions)]814	pub type CollectionPropertyPermissions<T> = StorageMap<815		Hasher = Blake2_128Concat,816		Key = CollectionId,817		Value = PropertiesPermissionMap,818		QueryKind = ValueQuery,819	>;820821	/// Storage of the amount of collection admins.822	#[pallet::storage]823	pub type AdminAmount<T> = StorageMap<824		Hasher = Blake2_128Concat,825		Key = CollectionId,826		Value = u32,827		QueryKind = ValueQuery,828	>;829830	/// List of collection admins.831	#[pallet::storage]832	pub type IsAdmin<T: Config> = StorageNMap<833		Key = (834			Key<Blake2_128Concat, CollectionId>,835			Key<Blake2_128Concat, T::CrossAccountId>,836		),837		Value = bool,838		QueryKind = ValueQuery,839	>;840841	/// Allowlisted collection users.842	#[pallet::storage]843	pub type Allowlist<T: Config> = StorageNMap<844		Key = (845			Key<Blake2_128Concat, CollectionId>,846			Key<Blake2_128Concat, T::CrossAccountId>,847		),848		Value = bool,849		QueryKind = ValueQuery,850	>;851852	/// Not used by code, exists only to provide some types to metadata.853	#[pallet::storage]854	pub type DummyStorageValue<T: Config> = StorageValue<855		Value = (856			CollectionStats,857			CollectionId,858			TokenId,859			TokenChild,860			PhantomType<(861				TokenData<T::CrossAccountId>,862				RpcCollection<T::AccountId>,863				// PoV Estimate Info864				PovInfo,865			)>,866		),867		QueryKind = OptionQuery,868	>;869}870871/// Value representation with delayed initialization time.872pub struct LazyValue<T, F: FnOnce() -> T> {873	value: Option<T>,874	f: Option<F>,875}876877impl<T, F: FnOnce() -> T> LazyValue<T, F> {878	/// Create a new LazyValue.879	pub fn new(f: F) -> Self {880		Self {881			value: None,882			f: Some(f),883		}884	}885886	/// Get the value. If it is called the first time, the value will be initialized.887	pub fn value(&mut self) -> &T {888		self.compute_value_if_not_already();889		self.value.as_ref().unwrap()890	}891892	/// Get the value. If it is called the first time, the value will be initialized.893	pub fn value_mut(&mut self) -> &mut T {894		self.compute_value_if_not_already();895		self.value.as_mut().unwrap()896	}897898	fn into_inner(mut self) -> T {899		self.compute_value_if_not_already();900		self.value.unwrap()901	}902903	/// Is value initialized?904	pub fn has_value(&self) -> bool {905		self.value.is_some()906	}907908	fn compute_value_if_not_already(&mut self) {909		if self.value.is_none() {910			self.value = Some(self.f.take().unwrap()())911		}912	}913}914915fn check_token_permissions<T, FCA, FTO, FTE>(916	collection_admin_permitted: bool,917	token_owner_permitted: bool,918	is_collection_admin: &mut LazyValue<bool, FCA>,919	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,920	is_token_exist: &mut LazyValue<bool, FTE>,921) -> DispatchResult922where923	T: Config,924	FCA: FnOnce() -> bool,925	FTO: FnOnce() -> Result<bool, DispatchError>,926	FTE: FnOnce() -> bool,927{928	if !(collection_admin_permitted && *is_collection_admin.value()929		|| token_owner_permitted && (*is_token_owner.value())?)930	{931		fail!(<Error<T>>::NoPermission);932	}933934	let token_exist_due_to_owner_check_success =935		is_token_owner.has_value() && (*is_token_owner.value())?;936937	// If the token owner check has occurred and succeeded,938	// we know the token exists (otherwise, the owner check must fail).939	if !token_exist_due_to_owner_check_success {940		// If the token owner check didn't occur,941		// we must check the token's existence ourselves.942		if !is_token_exist.value() {943			fail!(<Error<T>>::TokenNotFound);944		}945	}946947	Ok(())948}949950impl<T: Config> Pallet<T> {951	/// Enshure that receiver address is correct.952	///953	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.954	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {955		ensure!(956			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,957			<Error<T>>::AddressIsZero958		);959		Ok(())960	}961962	/// Get a vector of collection admins.963	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {964		<IsAdmin<T>>::iter_prefix((collection,))965			.map(|(a, _)| a)966			.collect()967	}968969	/// Get a vector of users allowed to mint tokens.970	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {971		<Allowlist<T>>::iter_prefix((collection,))972			.map(|(a, _)| a)973			.collect()974	}975976	/// Is `user` allowed to mint token in `collection`.977	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {978		<Allowlist<T>>::get((collection, user))979	}980981	/// Get statistics of collections.982	pub fn collection_stats() -> CollectionStats {983		let created = <CreatedCollectionCount<T>>::get();984		let destroyed = <DestroyedCollectionCount<T>>::get();985		CollectionStats {986			created: created.0,987			destroyed: destroyed.0,988			alive: created.0 - destroyed.0,989		}990	}991992	/// Get the effective limits for the collection.993	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {994		let collection = <CollectionById<T>>::get(collection)?;995		let limits = collection.limits;996		let effective_limits = CollectionLimits {997			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),998			sponsored_data_size: Some(limits.sponsored_data_size()),999			sponsored_data_rate_limit: Some(1000				limits1001					.sponsored_data_rate_limit1002					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1003			),1004			token_limit: Some(limits.token_limit()),1005			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1006				match collection.mode {1007					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1008					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1009					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1010				},1011			)),1012			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1013			owner_can_transfer: Some(limits.owner_can_transfer()),1014			owner_can_destroy: Some(limits.owner_can_destroy()),1015			transfers_enabled: Some(limits.transfers_enabled()),1016		};10171018		Some(effective_limits)1019	}10201021	/// Returns information about the `collection` adapted for rpc.1022	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1023		let Collection {1024			name,1025			description,1026			owner,1027			mode,1028			token_prefix,1029			sponsorship,1030			limits,1031			permissions,1032			flags,1033		} = <CollectionById<T>>::get(collection)?;10341035		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1036			.into_iter()1037			.map(|(key, permission)| PropertyKeyPermission { key, permission })1038			.collect();10391040		let properties = <CollectionProperties<T>>::get(collection)1041			.into_iter()1042			.map(|(key, value)| Property { key, value })1043			.collect();10441045		let permissions = CollectionPermissions {1046			access: Some(permissions.access()),1047			mint_mode: Some(permissions.mint_mode()),1048			nesting: Some(permissions.nesting().clone()),1049		};10501051		Some(RpcCollection {1052			name: name.into_inner(),1053			description: description.into_inner(),1054			owner,1055			mode,1056			token_prefix: token_prefix.into_inner(),1057			sponsorship,1058			limits,1059			permissions,1060			token_property_permissions,1061			properties,1062			read_only: flags.external,10631064			flags: RpcCollectionFlags {1065				foreign: flags.foreign,1066				erc721metadata: flags.erc721metadata,1067			},1068		})1069	}1070}10711072macro_rules! limit_default {1073	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1074		$(1075			if let Some($new) = $new.$field {1076				let $old = $old.$field($($arg)?);1077				let _ = $new;1078				let _ = $old;1079				$check1080			} else {1081				$new.$field = $old.$field1082			}1083		)*1084	}};1085}1086macro_rules! limit_default_clone {1087	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1088		$(1089			if let Some($new) = $new.$field.clone() {1090				let $old = $old.$field($($arg)?);1091				let _ = $new;1092				let _ = $old;1093				$check1094			} else {1095				$new.$field = $old.$field.clone()1096			}1097		)*1098	}};1099}11001101impl<T: Config> Pallet<T> {1102	/// Create new collection.1103	///1104	/// * `owner` - The owner of the collection.1105	/// * `data` - Description of the created collection.1106	/// * `flags` - Extra flags to store.1107	pub fn init_collection(1108		owner: T::CrossAccountId,1109		payer: T::CrossAccountId,1110		data: CreateCollectionData<T::CrossAccountId>,1111	) -> Result<CollectionId, DispatchError> {1112		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1113		Self::init_collection_internal(owner, payer, data)1114	}11151116	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1117	pub fn init_foreign_collection(1118		owner: T::CrossAccountId,1119		payer: T::CrossAccountId,1120		mut data: CreateCollectionData<T::CrossAccountId>,1121	) -> Result<CollectionId, DispatchError> {1122		data.flags.foreign = true;1123		let id = Self::init_collection_internal(owner, payer, data)?;1124		Ok(id)1125	}11261127	fn init_collection_internal(1128		owner: T::CrossAccountId,1129		payer: T::CrossAccountId,1130		data: CreateCollectionData<T::CrossAccountId>,1131	) -> Result<CollectionId, DispatchError> {1132		{1133			ensure!(1134				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1135				Error::<T>::CollectionTokenPrefixLimitExceeded1136			);1137		}11381139		let created_count = <CreatedCollectionCount<T>>::get()1140			.01141			.checked_add(1)1142			.ok_or(ArithmeticError::Overflow)?;1143		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1144		let id = CollectionId(created_count);11451146		// bound Total number of collections1147		ensure!(1148			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1149			<Error<T>>::TotalCollectionsLimitExceeded1150		);11511152		// =========11531154		let collection = Collection {1155			owner: owner.as_sub().clone(),1156			name: data.name,1157			mode: data.mode.clone(),1158			description: data.description,1159			token_prefix: data.token_prefix,1160			sponsorship: data1161				.pending_sponsor1162				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1163				.unwrap_or_default(),1164			limits: data1165				.limits1166				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1167				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1168			permissions: data1169				.permissions1170				.map(|permissions| {1171					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1172				})1173				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1174			flags: data.flags,1175		};11761177		let mut collection_properties = CollectionPropertiesT::new();1178		collection_properties1179			.try_set_from_iter(data.properties.into_iter())1180			.map_err(<Error<T>>::from)?;11811182		CollectionProperties::<T>::insert(id, collection_properties);11831184		let mut token_props_permissions = PropertiesPermissionMap::new();1185		token_props_permissions1186			.try_set_from_iter(data.token_property_permissions.into_iter())1187			.map_err(<Error<T>>::from)?;11881189		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11901191		let mut admin_amount = 0u32;1192		for admin in data.admin_list.iter() {1193			if !<IsAdmin<T>>::get((id, admin)) {1194				<IsAdmin<T>>::insert((id, admin), true);1195				admin_amount = admin_amount1196					.checked_add(1)1197					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1198			}1199		}1200		ensure!(1201			admin_amount <= Self::collection_admins_limit(),1202			<Error<T>>::CollectionAdminCountExceeded,1203		);1204		<AdminAmount<T>>::insert(id, admin_amount);12051206		// Take a (non-refundable) deposit of collection creation1207		{1208			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1209			imbalance.subsume(<T as Config>::Currency::deposit(1210				&T::TreasuryAccountId::get(),1211				T::CollectionCreationPrice::get(),1212				Precision::Exact,1213			)?);1214			let credit =1215				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1216					.map_err(|_| Error::<T>::NotSufficientFounds)?;12171218			debug_assert!(credit.peek().is_zero())1219		}12201221		<CreatedCollectionCount<T>>::put(created_count);1222		<Pallet<T>>::deposit_event(Event::CollectionCreated(1223			id,1224			data.mode.id(),1225			owner.as_sub().clone(),1226		));1227		<PalletEvm<T>>::deposit_log(1228			erc::CollectionHelpersEvents::CollectionCreated {1229				owner: *owner.as_eth(),1230				collection_id: eth::collection_id_to_address(id),1231			}1232			.to_log(T::ContractAddress::get()),1233		);1234		<CollectionById<T>>::insert(id, collection);1235		Ok(id)1236	}12371238	/// Destroy collection.1239	///1240	/// * `collection` - Collection handler.1241	/// * `sender` - The owner or administrator of the collection.1242	pub fn destroy_collection(1243		collection: CollectionHandle<T>,1244		sender: &T::CrossAccountId,1245	) -> DispatchResult {1246		ensure!(1247			collection.limits.owner_can_destroy(),1248			<Error<T>>::NoPermission,1249		);1250		collection.check_is_owner(sender)?;12511252		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1253			.01254			.checked_add(1)1255			.ok_or(ArithmeticError::Overflow)?;12561257		// =========12581259		<DestroyedCollectionCount<T>>::put(destroyed_collections);1260		<CollectionById<T>>::remove(collection.id);1261		<AdminAmount<T>>::remove(collection.id);1262		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1263		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1264		<CollectionProperties<T>>::remove(collection.id);12651266		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12671268		<PalletEvm<T>>::deposit_log(1269			erc::CollectionHelpersEvents::CollectionDestroyed {1270				collection_id: eth::collection_id_to_address(collection.id),1271			}1272			.to_log(T::ContractAddress::get()),1273		);1274		Ok(())1275	}12761277	/// This function sets or removes a collection properties according to1278	/// `properties_updates` contents:1279	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1280	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1281	///1282	/// This function fires an event for each property change.1283	/// In case of an error, all the changes (including the events) will be reverted1284	/// since the function is transactional.1285	#[transactional]1286	fn modify_collection_properties(1287		collection: &CollectionHandle<T>,1288		sender: &T::CrossAccountId,1289		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1290	) -> DispatchResult {1291		collection.check_is_owner_or_admin(sender)?;12921293		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12941295		for (key, value) in properties_updates {1296			match value {1297				Some(value) => {1298					stored_properties1299						.try_set(key.clone(), value)1300						.map_err(<Error<T>>::from)?;13011302					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1303					<PalletEvm<T>>::deposit_log(1304						erc::CollectionHelpersEvents::CollectionChanged {1305							collection_id: eth::collection_id_to_address(collection.id),1306						}1307						.to_log(T::ContractAddress::get()),1308					);1309				}1310				None => {1311					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13121313					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1314					<PalletEvm<T>>::deposit_log(1315						erc::CollectionHelpersEvents::CollectionChanged {1316							collection_id: eth::collection_id_to_address(collection.id),1317						}1318						.to_log(T::ContractAddress::get()),1319					);1320				}1321			}1322		}13231324		<CollectionProperties<T>>::set(collection.id, stored_properties);13251326		Ok(())1327	}13281329	/// Sets or unsets the approval of a given operator.1330	///1331	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1332	/// - `owner`: Token owner1333	/// - `operator`: Operator1334	/// - `approve`: Should operator status be granted or revoked?1335	pub fn set_allowance_for_all(1336		collection: &CollectionHandle<T>,1337		owner: &T::CrossAccountId,1338		operator: &T::CrossAccountId,1339		approve: bool,1340		set_allowance: impl FnOnce(),1341		log: evm_coder::ethereum::Log,1342	) -> DispatchResult {1343		if collection.permissions.access() == AccessMode::AllowList {1344			collection.check_allowlist(owner)?;1345			collection.check_allowlist(operator)?;1346		}13471348		Self::ensure_correct_receiver(operator)?;13491350		set_allowance();13511352		<PalletEvm<T>>::deposit_log(log);1353		Self::deposit_event(Event::ApprovedForAll(1354			collection.id,1355			owner.clone(),1356			operator.clone(),1357			approve,1358		));1359		Ok(())1360	}13611362	/// Set collection property.1363	///1364	/// * `collection` - Collection handler.1365	/// * `sender` - The owner or administrator of the collection.1366	/// * `property` - The property to set.1367	pub fn set_collection_property(1368		collection: &CollectionHandle<T>,1369		sender: &T::CrossAccountId,1370		property: Property,1371	) -> DispatchResult {1372		Self::set_collection_properties(collection, sender, [property].into_iter())1373	}13741375	/// Set a scoped collection property, where the scope is a special prefix1376	/// prohibiting a user access to change the property directly.1377	///1378	/// * `collection_id` - ID of the collection for which the property is being set.1379	/// * `scope` - Property scope.1380	/// * `property` - The property to set.1381	pub fn set_scoped_collection_property(1382		collection_id: CollectionId,1383		scope: PropertyScope,1384		property: Property,1385	) -> DispatchResult {1386		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1387			properties.try_scoped_set(scope, property.key, property.value)1388		})1389		.map_err(<Error<T>>::from)?;13901391		Ok(())1392	}13931394	/// Set scoped collection properties, where the scope is a special prefix1395	/// prohibiting a user access to change the properties directly.1396	///1397	/// * `collection_id` - ID of the collection for which the properties is being set.1398	/// * `scope` - Property scope.1399	/// * `properties` - The properties to set.1400	pub fn set_scoped_collection_properties(1401		collection_id: CollectionId,1402		scope: PropertyScope,1403		properties: impl Iterator<Item = Property>,1404	) -> DispatchResult {1405		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1406			stored_properties.try_scoped_set_from_iter(scope, properties)1407		})1408		.map_err(<Error<T>>::from)?;14091410		Ok(())1411	}14121413	/// Set collection properties.1414	///1415	/// * `collection` - Collection handler.1416	/// * `sender` - The owner or administrator of the collection.1417	/// * `properties` - The properties to set.1418	pub fn set_collection_properties(1419		collection: &CollectionHandle<T>,1420		sender: &T::CrossAccountId,1421		properties: impl Iterator<Item = Property>,1422	) -> DispatchResult {1423		Self::modify_collection_properties(1424			collection,1425			sender,1426			properties.map(|property| (property.key, Some(property.value))),1427		)1428	}14291430	/// Delete collection property.1431	///1432	/// * `collection` - Collection handler.1433	/// * `sender` - The owner or administrator of the collection.1434	/// * `property` - The property to delete.1435	pub fn delete_collection_property(1436		collection: &CollectionHandle<T>,1437		sender: &T::CrossAccountId,1438		property_key: PropertyKey,1439	) -> DispatchResult {1440		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1441	}14421443	/// Delete collection properties.1444	///1445	/// * `collection` - Collection handler.1446	/// * `sender` - The owner or administrator of the collection.1447	/// * `properties` - The properties to delete.1448	pub fn delete_collection_properties(1449		collection: &CollectionHandle<T>,1450		sender: &T::CrossAccountId,1451		property_keys: impl Iterator<Item = PropertyKey>,1452	) -> DispatchResult {1453		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1454	}14551456	/// Set collection propetry permission without any checks.1457	///1458	/// Used for migrations.1459	///1460	/// * `collection` - Collection handler.1461	/// * `property_permissions` - Property permissions.1462	pub fn set_property_permission_unchecked(1463		collection: CollectionId,1464		property_permission: PropertyKeyPermission,1465	) -> DispatchResult {1466		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1467			permissions.try_set(property_permission.key, property_permission.permission)1468		})1469		.map_err(<Error<T>>::from)?;1470		Ok(())1471	}14721473	/// Set collection property permission.1474	///1475	/// * `collection` - Collection handler.1476	/// * `sender` - The owner or administrator of the collection.1477	/// * `property_permission` - Property permission.1478	pub fn set_property_permission(1479		collection: &CollectionHandle<T>,1480		sender: &T::CrossAccountId,1481		property_permission: PropertyKeyPermission,1482	) -> DispatchResult {1483		Self::set_scoped_property_permission(1484			collection,1485			sender,1486			PropertyScope::None,1487			property_permission,1488		)1489	}14901491	/// Set collection property permission with scope.1492	///1493	/// * `collection` - Collection handler.1494	/// * `sender` - The owner or administrator of the collection.1495	/// * `scope` - Property scope.1496	/// * `property_permission` - Property permission.1497	pub fn set_scoped_property_permission(1498		collection: &CollectionHandle<T>,1499		sender: &T::CrossAccountId,1500		scope: PropertyScope,1501		property_permission: PropertyKeyPermission,1502	) -> DispatchResult {1503		collection.check_is_owner_or_admin(sender)?;15041505		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1506		let current_permission = all_permissions.get(&property_permission.key);1507		if matches![1508			current_permission,1509			Some(PropertyPermission { mutable: false, .. })1510		] {1511			return Err(<Error<T>>::NoPermission.into());1512		}15131514		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1515			let property_permission = property_permission.clone();1516			permissions.try_scoped_set(1517				scope,1518				property_permission.key,1519				property_permission.permission,1520			)1521		})1522		.map_err(<Error<T>>::from)?;15231524		Self::deposit_event(Event::PropertyPermissionSet(1525			collection.id,1526			property_permission.key,1527		));1528		<PalletEvm<T>>::deposit_log(1529			erc::CollectionHelpersEvents::CollectionChanged {1530				collection_id: eth::collection_id_to_address(collection.id),1531			}1532			.to_log(T::ContractAddress::get()),1533		);15341535		Ok(())1536	}15371538	/// Set token property permission.1539	///1540	/// * `collection` - Collection handler.1541	/// * `sender` - The owner or administrator of the collection.1542	/// * `property_permissions` - Property permissions.1543	#[transactional]1544	pub fn set_token_property_permissions(1545		collection: &CollectionHandle<T>,1546		sender: &T::CrossAccountId,1547		property_permissions: Vec<PropertyKeyPermission>,1548	) -> DispatchResult {1549		Self::set_scoped_token_property_permissions(1550			collection,1551			sender,1552			PropertyScope::None,1553			property_permissions,1554		)1555	}15561557	/// Set token property permission with scope.1558	///1559	/// * `collection` - Collection handler.1560	/// * `sender` - The owner or administrator of the collection.1561	/// * `scope` - Property scope.1562	/// * `property_permissions` - Property permissions.1563	#[transactional]1564	pub fn set_scoped_token_property_permissions(1565		collection: &CollectionHandle<T>,1566		sender: &T::CrossAccountId,1567		scope: PropertyScope,1568		property_permissions: Vec<PropertyKeyPermission>,1569	) -> DispatchResult {1570		for prop_pemission in property_permissions {1571			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1572		}15731574		Ok(())1575	}15761577	/// Get collection property.1578	pub fn get_collection_property(1579		collection_id: CollectionId,1580		key: &PropertyKey,1581	) -> Option<PropertyValue> {1582		Self::collection_properties(collection_id).get(key).cloned()1583	}15841585	/// Convert byte vector to property key vector.1586	pub fn bytes_keys_to_property_keys(1587		keys: Vec<Vec<u8>>,1588	) -> Result<Vec<PropertyKey>, DispatchError> {1589		keys.into_iter()1590			.map(|key| -> Result<PropertyKey, DispatchError> {1591				key.try_into()1592					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1593			})1594			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1595	}15961597	/// Get properties according to given keys.1598	pub fn filter_collection_properties(1599		collection_id: CollectionId,1600		keys: Option<Vec<PropertyKey>>,1601	) -> Result<Vec<Property>, DispatchError> {1602		let properties = Self::collection_properties(collection_id);16031604		let properties = keys1605			.map(|keys| {1606				keys.into_iter()1607					.filter_map(|key| {1608						properties.get(&key).map(|value| Property {1609							key,1610							value: value.clone(),1611						})1612					})1613					.collect()1614			})1615			.unwrap_or_else(|| {1616				properties1617					.into_iter()1618					.map(|(key, value)| Property { key, value })1619					.collect()1620			});16211622		Ok(properties)1623	}16241625	/// Get property permissions according to given keys.1626	pub fn filter_property_permissions(1627		collection_id: CollectionId,1628		keys: Option<Vec<PropertyKey>>,1629	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1630		let permissions = Self::property_permissions(collection_id);16311632		let key_permissions = keys1633			.map(|keys| {1634				keys.into_iter()1635					.filter_map(|key| {1636						permissions1637							.get(&key)1638							.map(|permission| PropertyKeyPermission {1639								key,1640								permission: permission.clone(),1641							})1642					})1643					.collect()1644			})1645			.unwrap_or_else(|| {1646				permissions1647					.into_iter()1648					.map(|(key, permission)| PropertyKeyPermission { key, permission })1649					.collect()1650			});16511652		Ok(key_permissions)1653	}16541655	/// Toggle `user` participation in the `collection`'s allow list.1656	/// #### Store read/writes1657	/// 1 writes1658	pub fn toggle_allowlist(1659		collection: &CollectionHandle<T>,1660		sender: &T::CrossAccountId,1661		user: &T::CrossAccountId,1662		allowed: bool,1663	) -> DispatchResult {1664		collection.check_is_owner_or_admin(sender)?;16651666		// =========16671668		if allowed {1669			<Allowlist<T>>::insert((collection.id, user), true);1670			Self::deposit_event(Event::<T>::AllowListAddressAdded(1671				collection.id,1672				user.clone(),1673			));1674		} else {1675			<Allowlist<T>>::remove((collection.id, user));1676			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1677				collection.id,1678				user.clone(),1679			));1680		}16811682		<PalletEvm<T>>::deposit_log(1683			erc::CollectionHelpersEvents::CollectionChanged {1684				collection_id: eth::collection_id_to_address(collection.id),1685			}1686			.to_log(T::ContractAddress::get()),1687		);16881689		Ok(())1690	}16911692	/// Toggle `user` participation in the `collection`'s admin list.1693	/// #### Store read/writes1694	/// 2 reads, 2 writes1695	pub fn toggle_admin(1696		collection: &CollectionHandle<T>,1697		sender: &T::CrossAccountId,1698		user: &T::CrossAccountId,1699		admin: bool,1700	) -> DispatchResult {1701		collection.check_is_internal()?;1702		collection.check_is_owner(sender)?;17031704		let is_admin = <IsAdmin<T>>::get((collection.id, user));1705		if is_admin == admin {1706			if admin {1707				return Ok(());1708			} else {1709				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1710			}1711		}1712		let amount = <AdminAmount<T>>::get(collection.id);17131714		// =========17151716		if admin {1717			let amount = amount1718				.checked_add(1)1719				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1720			ensure!(1721				amount <= Self::collection_admins_limit(),1722				<Error<T>>::CollectionAdminCountExceeded,1723			);17241725			<AdminAmount<T>>::insert(collection.id, amount);1726			<IsAdmin<T>>::insert((collection.id, user), true);17271728			Self::deposit_event(Event::<T>::CollectionAdminAdded(1729				collection.id,1730				user.clone(),1731			));1732		} else {1733			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1734			<IsAdmin<T>>::remove((collection.id, user));17351736			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1737				collection.id,1738				user.clone(),1739			));1740		}17411742		<PalletEvm<T>>::deposit_log(1743			erc::CollectionHelpersEvents::CollectionChanged {1744				collection_id: eth::collection_id_to_address(collection.id),1745			}1746			.to_log(T::ContractAddress::get()),1747		);17481749		Ok(())1750	}17511752	/// Update collection limits.1753	pub fn update_limits(1754		user: &T::CrossAccountId,1755		collection: &mut CollectionHandle<T>,1756		new_limit: CollectionLimits,1757	) -> DispatchResult {1758		collection.check_is_internal()?;1759		collection.check_is_owner_or_admin(user)?;17601761		collection.limits =1762			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17631764		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1765		<PalletEvm<T>>::deposit_log(1766			erc::CollectionHelpersEvents::CollectionChanged {1767				collection_id: eth::collection_id_to_address(collection.id),1768			}1769			.to_log(T::ContractAddress::get()),1770		);17711772		collection.save()1773	}17741775	/// Merge set fields from `new_limit` to `old_limit`.1776	fn clamp_limits(1777		mode: CollectionMode,1778		old_limit: &CollectionLimits,1779		mut new_limit: CollectionLimits,1780	) -> Result<CollectionLimits, DispatchError> {1781		let limits = old_limit;1782		limit_default!(old_limit, new_limit,1783			account_token_ownership_limit => ensure!(1784				new_limit <= MAX_TOKEN_OWNERSHIP,1785				<Error<T>>::CollectionLimitBoundsExceeded,1786			),1787			sponsored_data_size => ensure!(1788				new_limit <= CUSTOM_DATA_LIMIT,1789				<Error<T>>::CollectionLimitBoundsExceeded,1790			),17911792			sponsored_data_rate_limit => {},1793			token_limit => ensure!(1794				old_limit >= new_limit && new_limit > 0,1795				<Error<T>>::CollectionTokenLimitExceeded1796			),17971798			sponsor_transfer_timeout(match mode {1799				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1800				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1801				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1802			}) => ensure!(1803				new_limit <= MAX_SPONSOR_TIMEOUT,1804				<Error<T>>::CollectionLimitBoundsExceeded,1805			),1806			sponsor_approve_timeout => {},1807			owner_can_transfer => ensure!(1808				!limits.owner_can_transfer_instaled() ||1809				old_limit || !new_limit,1810				<Error<T>>::OwnerPermissionsCantBeReverted,1811			),1812			owner_can_destroy => ensure!(1813				old_limit || !new_limit,1814				<Error<T>>::OwnerPermissionsCantBeReverted,1815			),1816			transfers_enabled => {},1817		);1818		Ok(new_limit)1819	}18201821	/// Update collection permissions.1822	pub fn update_permissions(1823		user: &T::CrossAccountId,1824		collection: &mut CollectionHandle<T>,1825		new_permission: CollectionPermissions,1826	) -> DispatchResult {1827		collection.check_is_internal()?;1828		collection.check_is_owner_or_admin(user)?;1829		collection.permissions = Self::clamp_permissions(1830			collection.mode.clone(),1831			&collection.permissions,1832			new_permission,1833		)?;18341835		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1836		<PalletEvm<T>>::deposit_log(1837			erc::CollectionHelpersEvents::CollectionChanged {1838				collection_id: eth::collection_id_to_address(collection.id),1839			}1840			.to_log(T::ContractAddress::get()),1841		);18421843		collection.save()1844	}18451846	/// Merge set fields from `new_permission` to `old_permission`.1847	fn clamp_permissions(1848		_mode: CollectionMode,1849		old_permission: &CollectionPermissions,1850		mut new_permission: CollectionPermissions,1851	) -> Result<CollectionPermissions, DispatchError> {1852		limit_default_clone!(old_permission, new_permission,1853			access => {},1854			mint_mode => {},1855			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1856		);1857		Ok(new_permission)1858	}18591860	/// Repair possibly broken properties of a collection.1861	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1862		CollectionProperties::<T>::mutate(collection_id, |properties| {1863			properties.recompute_consumed_space();1864		});18651866		Ok(())1867	}1868}18691870/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1871#[macro_export]1872macro_rules! unsupported {1873	($runtime:path) => {1874		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1875	};1876}18771878/// Return weights for various worst-case operations.1879pub trait CommonWeightInfo<CrossAccountId> {1880	/// Weight of item creation.1881	fn create_item(data: &CreateItemData) -> Weight {1882		Self::create_multiple_items(from_ref(data))1883	}18841885	/// Weight of items creation.1886	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18871888	/// Weight of items creation.1889	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18901891	/// The weight of the burning item.1892	fn burn_item() -> Weight;18931894	/// Property setting weight.1895	///1896	/// * `amount`- The number of properties to set.1897	fn set_collection_properties(amount: u32) -> Weight;18981899	/// Collection property deletion weight.1900	///1901	/// * `amount`- The number of properties to set.1902	fn delete_collection_properties(amount: u32) -> Weight;19031904	/// Token property setting weight.1905	///1906	/// * `amount`- The number of properties to set.1907	fn set_token_properties(amount: u32) -> Weight;19081909	/// Token property deletion weight.1910	///1911	/// * `amount`- The number of properties to delete.1912	fn delete_token_properties(amount: u32) -> Weight;19131914	/// Token property permissions set weight.1915	///1916	/// * `amount`- The number of property permissions to set.1917	fn set_token_property_permissions(amount: u32) -> Weight;19181919	/// Transfer price of the token or its parts.1920	fn transfer() -> Weight;19211922	/// The price of setting the permission of the operation from another user.1923	fn approve() -> Weight;19241925	/// The price of setting the permission of the operation from another user for eth mirror.1926	fn approve_from() -> Weight;19271928	/// Transfer price from another user.1929	fn transfer_from() -> Weight;19301931	/// The price of burning a token from another user.1932	fn burn_from() -> Weight;19331934	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1935	/// whole users's balance.1936	///1937	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1938	fn burn_recursively_self_raw() -> Weight;19391940	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1941	///1942	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1943	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19441945	/// The price of recursive burning a token.1946	///1947	/// `max_selfs` - The maximum burning weight of the token itself.1948	/// `max_breadth` - The maximum number of nested tokens to burn.1949	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1950		Self::burn_recursively_self_raw()1951			.saturating_mul(max_selfs.max(1) as u64)1952			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1953	}19541955	/// The price of retrieving token owner1956	fn token_owner() -> Weight;19571958	/// The price of setting approval for all1959	fn set_allowance_for_all() -> Weight;19601961	/// The price of repairing an item.1962	fn force_repair_item() -> Weight;1963}19641965/// Weight info extension trait for refungible pallet.1966pub trait RefungibleExtensionsWeightInfo {1967	/// Weight of token repartition.1968	fn repartition() -> Weight;1969}19701971/// Common collection operations.1972///1973/// It wraps methods in Fungible, Nonfungible and Refungible pallets1974/// and adds weight info.1975pub trait CommonCollectionOperations<T: Config> {1976	/// Create token.1977	///1978	/// * `sender` - The user who mint the token and pays for the transaction.1979	/// * `to` - The user who will own the token.1980	/// * `data` - Token data.1981	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1982	fn create_item(1983		&self,1984		sender: T::CrossAccountId,1985		to: T::CrossAccountId,1986		data: CreateItemData,1987		nesting_budget: &dyn Budget,1988	) -> DispatchResultWithPostInfo;19891990	/// Create multiple tokens.1991	///1992	/// * `sender` - The user who mint the token and pays for the transaction.1993	/// * `to` - The user who will own the token.1994	/// * `data` - Token data.1995	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1996	fn create_multiple_items(1997		&self,1998		sender: T::CrossAccountId,1999		to: T::CrossAccountId,2000		data: Vec<CreateItemData>,2001		nesting_budget: &dyn Budget,2002	) -> DispatchResultWithPostInfo;20032004	/// Create multiple tokens.2005	///2006	/// * `sender` - The user who mint the token and pays for the transaction.2007	/// * `to` - The user who will own the token.2008	/// * `data` - Token data.2009	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2010	fn create_multiple_items_ex(2011		&self,2012		sender: T::CrossAccountId,2013		data: CreateItemExData<T::CrossAccountId>,2014		nesting_budget: &dyn Budget,2015	) -> DispatchResultWithPostInfo;20162017	/// Burn token.2018	///2019	/// * `sender` - The user who owns the token.2020	/// * `token` - Token id that will burned.2021	/// * `amount` - The number of parts of the token that will be burned.2022	fn burn_item(2023		&self,2024		sender: T::CrossAccountId,2025		token: TokenId,2026		amount: u128,2027	) -> DispatchResultWithPostInfo;20282029	/// Burn token and all nested tokens recursievly.2030	///2031	/// * `sender` - The user who owns the token.2032	/// * `token` - Token id that will burned.2033	/// * `self_budget` - The budget that can be spent on burning tokens.2034	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2035	fn burn_item_recursively(2036		&self,2037		sender: T::CrossAccountId,2038		token: TokenId,2039		self_budget: &dyn Budget,2040		breadth_budget: &dyn Budget,2041	) -> DispatchResultWithPostInfo;20422043	/// Set collection properties.2044	///2045	/// * `sender` - Must be either the owner of the collection or its admin.2046	/// * `properties` - Properties to be set.2047	fn set_collection_properties(2048		&self,2049		sender: T::CrossAccountId,2050		properties: Vec<Property>,2051	) -> DispatchResultWithPostInfo;20522053	/// Delete collection properties.2054	///2055	/// * `sender` - Must be either the owner of the collection or its admin.2056	/// * `properties` - The properties to be removed.2057	fn delete_collection_properties(2058		&self,2059		sender: &T::CrossAccountId,2060		property_keys: Vec<PropertyKey>,2061	) -> DispatchResultWithPostInfo;20622063	/// Set token properties.2064	///2065	/// The appropriate [`PropertyPermission`] for the token property2066	/// must be set with [`Self::set_token_property_permissions`].2067	///2068	/// * `sender` - Must be either the owner of the token or its admin.2069	/// * `token_id` - The token for which the properties are being set.2070	/// * `properties` - Properties to be set.2071	/// * `budget` - Budget for setting properties.2072	fn set_token_properties(2073		&self,2074		sender: T::CrossAccountId,2075		token_id: TokenId,2076		properties: Vec<Property>,2077		budget: &dyn Budget,2078	) -> DispatchResultWithPostInfo;20792080	/// Remove token properties.2081	///2082	/// The appropriate [`PropertyPermission`] for the token property2083	/// must be set with [`Self::set_token_property_permissions`].2084	///2085	/// * `sender` - Must be either the owner of the token or its admin.2086	/// * `token_id` - The token for which the properties are being remove.2087	/// * `property_keys` - Keys to remove corresponding properties.2088	/// * `budget` - Budget for removing properties.2089	fn delete_token_properties(2090		&self,2091		sender: T::CrossAccountId,2092		token_id: TokenId,2093		property_keys: Vec<PropertyKey>,2094		budget: &dyn Budget,2095	) -> DispatchResultWithPostInfo;20962097	/// Get token properties raw map.2098	///2099	/// * `token_id` - The token which properties are needed.2100	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;21012102	/// Set token properties raw map.2103	///2104	/// * `token_id` - The token for which the properties are being set.2105	/// * `map` - The raw map containing the token's properties.2106	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);21072108	/// Set token property permissions.2109	///2110	/// * `sender` - Must be either the owner of the token or its admin.2111	/// * `token_id` - The token for which the properties are being set.2112	/// * `property_permissions` - Property permissions to be set.2113	/// * `budget` - Budget for setting properties.2114	fn set_token_property_permissions(2115		&self,2116		sender: &T::CrossAccountId,2117		property_permissions: Vec<PropertyKeyPermission>,2118	) -> DispatchResultWithPostInfo;21192120	/// Transfer amount of token pieces.2121	///2122	/// * `sender` - Donor user.2123	/// * `to` - Recepient user.2124	/// * `token` - The token of which parts are being sent.2125	/// * `amount` - The number of parts of the token that will be transferred.2126	/// * `budget` - The maximum budget that can be spent on the transfer.2127	fn transfer(2128		&self,2129		sender: T::CrossAccountId,2130		to: T::CrossAccountId,2131		token: TokenId,2132		amount: u128,2133		budget: &dyn Budget,2134	) -> DispatchResultWithPostInfo;21352136	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2137	///2138	/// * `sender` - The user who grants access to the token.2139	/// * `spender` - The user to whom the rights are granted.2140	/// * `token` - The token to which access is granted.2141	/// * `amount` - The amount of pieces that another user can dispose of.2142	fn approve(2143		&self,2144		sender: T::CrossAccountId,2145		spender: T::CrossAccountId,2146		token: TokenId,2147		amount: u128,2148	) -> DispatchResultWithPostInfo;21492150	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2151	///2152	/// * `sender` - The user who grants access to the token.2153	/// * `from` - Spender's eth mirror.2154	/// * `to` - The user to whom the rights are granted.2155	/// * `token` - The token to which access is granted.2156	/// * `amount` - The amount of pieces that another user can dispose of.2157	fn approve_from(2158		&self,2159		sender: T::CrossAccountId,2160		from: T::CrossAccountId,2161		to: T::CrossAccountId,2162		token: TokenId,2163		amount: u128,2164	) -> DispatchResultWithPostInfo;21652166	/// Send parts of a token owned by another user.2167	///2168	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2169	///2170	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2171	/// * `from` - The user who owns the token.2172	/// * `to` - Recepient user.2173	/// * `token` - The token of which parts are being sent.2174	/// * `amount` - The number of parts of the token that will be transferred.2175	/// * `budget` - The maximum budget that can be spent on the transfer.2176	fn transfer_from(2177		&self,2178		sender: T::CrossAccountId,2179		from: T::CrossAccountId,2180		to: T::CrossAccountId,2181		token: TokenId,2182		amount: u128,2183		budget: &dyn Budget,2184	) -> DispatchResultWithPostInfo;21852186	/// Burn parts of a token owned by another user.2187	///2188	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2189	///2190	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2191	/// * `from` - The user who owns the token.2192	/// * `token` - The token of which parts are being sent.2193	/// * `amount` - The number of parts of the token that will be transferred.2194	/// * `budget` - The maximum budget that can be spent on the burn.2195	fn burn_from(2196		&self,2197		sender: T::CrossAccountId,2198		from: T::CrossAccountId,2199		token: TokenId,2200		amount: u128,2201		budget: &dyn Budget,2202	) -> DispatchResultWithPostInfo;22032204	/// Check permission to nest token.2205	///2206	/// * `sender` - The user who initiated the check.2207	/// * `from` - The token that is checked for embedding.2208	/// * `under` - Token under which to check.2209	/// * `budget` - The maximum budget that can be spent on the check.2210	fn check_nesting(2211		&self,2212		sender: T::CrossAccountId,2213		from: (CollectionId, TokenId),2214		under: TokenId,2215		budget: &dyn Budget,2216	) -> DispatchResult;22172218	/// Nest one token into another.2219	///2220	/// * `under` - Token holder.2221	/// * `to_nest` - Nested token.2222	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22232224	/// Unnest token.2225	///2226	/// * `under` - Token holder.2227	/// * `to_nest` - Token to unnest.2228	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22292230	/// Get all user tokens.2231	///2232	/// * `account` - Account for which you need to get tokens.2233	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22342235	/// Get all the tokens in the collection.2236	fn collection_tokens(&self) -> Vec<TokenId>;22372238	/// Check if the token exists.2239	///2240	/// * `token` - Id token to check.2241	fn token_exists(&self, token: TokenId) -> bool;22422243	/// Get the id of the last minted token.2244	fn last_token_id(&self) -> TokenId;22452246	/// Get the owner of the token.2247	///2248	/// * `token` - The token for which you need to find out the owner.2249	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22502251	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2252	///2253	/// * `token` - Id token to check.2254	/// * `maybe_owner` - The account to check.2255	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2256	fn check_token_indirect_owner(2257		&self,2258		token: TokenId,2259		maybe_owner: &T::CrossAccountId,2260		nesting_budget: &dyn Budget,2261	) -> Result<bool, DispatchError>;22622263	/// Returns 10 tokens owners in no particular order.2264	///2265	/// * `token` - The token for which you need to find out the owners.2266	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22672268	/// Get the value of the token property by key.2269	///2270	/// * `token` - Token with the property to get.2271	/// * `key` - Property name.2272	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22732274	/// Get a set of token properties by key vector.2275	///2276	/// * `token` - Token with the property to get.2277	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2278	/// then all properties are returned.2279	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22802281	/// Amount of unique collection tokens2282	fn total_supply(&self) -> u32;22832284	/// Amount of different tokens account has.2285	///2286	/// * `account` - The account for which need to get the balance.2287	fn account_balance(&self, account: T::CrossAccountId) -> u32;22882289	/// Amount of specific token account have.2290	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22912292	/// Amount of token pieces2293	fn total_pieces(&self, token: TokenId) -> Option<u128>;22942295	/// Get the number of parts of the token that a trusted user can manage.2296	///2297	/// * `sender` - Trusted user.2298	/// * `spender` - Owner of the token.2299	/// * `token` - The token for which to get the value.2300	fn allowance(2301		&self,2302		sender: T::CrossAccountId,2303		spender: T::CrossAccountId,2304		token: TokenId,2305	) -> u128;23062307	/// Get extension for RFT collection.2308	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23092310	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2311	/// * `owner` - Token owner2312	/// * `operator` - Operator2313	/// * `approve` - Should operator status be granted or revoked?2314	fn set_allowance_for_all(2315		&self,2316		owner: T::CrossAccountId,2317		operator: T::CrossAccountId,2318		approve: bool,2319	) -> DispatchResultWithPostInfo;23202321	/// Tells whether the given `owner` approves the `operator`.2322	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23232324	/// Repairs a possibly broken item.2325	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2326}23272328/// Extension for RFT collection.2329pub trait RefungibleExtensions<T>2330where2331	T: Config,2332{2333	/// Change the number of parts of the token.2334	///2335	/// When the value changes down, this function is equivalent to burning parts of the token.2336	///2337	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2338	/// * `token` - The token for which you want to change the number of parts.2339	/// * `amount` - The new value of the parts of the token.2340	fn repartition(2341		&self,2342		sender: &T::CrossAccountId,2343		token: TokenId,2344		amount: u128,2345	) -> DispatchResultWithPostInfo;2346}23472348/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2349///2350/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2351pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2352	let post_info = PostDispatchInfo {2353		actual_weight: Some(weight),2354		pays_fee: Pays::Yes,2355	};2356	match res {2357		Ok(()) => Ok(post_info),2358		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2359	}2360}23612362impl<T: Config> From<PropertiesError> for Error<T> {2363	fn from(error: PropertiesError) -> Self {2364		match error {2365			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2366			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2367			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2368			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2369			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2370		}2371	}2372}23732374/// A marker structure that enables the writer implementation2375/// to provide the interface to write properties to **newly created** tokens.2376pub struct NewTokenPropertyWriter;23772378/// A marker structure that enables the writer implementation2379/// to provide the interface to write properties to **already existing** tokens.2380pub struct ExistingTokenPropertyWriter;23812382/// The type-safe interface for writing properties (setting or deleting) to tokens.2383/// It has two distinct implementations for newly created tokens and existing ones.2384///2385/// This type utilizes the lazy evaluation to avoid repeating the computation2386/// of several performance-heavy or PoV-heavy tasks,2387/// such as checking the indirect ownership or reading the token property permissions.2388pub struct PropertyWriter<2389	'a,2390	T,2391	Handle,2392	WriterVariant,2393	FIsAdmin,2394	FPropertyPermissions,2395	FCheckTokenExist,2396	FGetProperties,2397> where2398	T: Config,2399	FIsAdmin: FnOnce() -> bool,2400	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2401{2402	collection: &'a Handle,2403	is_collection_admin: LazyValue<bool, FIsAdmin>,2404	property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,2405	check_token_exist: FCheckTokenExist,2406	get_properties: FGetProperties,2407	_phantom: PhantomData<(T, WriterVariant)>,2408}24092410impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2411	PropertyWriter<2412		'a,2413		T,2414		Handle,2415		NewTokenPropertyWriter,2416		FIsAdmin,2417		FPropertyPermissions,2418		FCheckTokenExist,2419		FGetProperties,2420	> where2421	T: Config,2422	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2423	FIsAdmin: FnOnce() -> bool,2424	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2425	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2426	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2427{2428	/// A function to write properties to a **newly created** token.2429	pub fn write_token_properties(2430		&mut self,2431		mint_target_is_sender: bool,2432		token_id: TokenId,2433		properties_updates: impl Iterator<Item = Property>,2434		log: evm_coder::ethereum::Log,2435	) -> DispatchResult {2436		self.internal_write_token_properties(2437			token_id,2438			properties_updates.map(|p| (p.key, Some(p.value))),2439			|_| Ok(mint_target_is_sender),2440			log,2441		)2442	}2443}24442445impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2446	PropertyWriter<2447		'a,2448		T,2449		Handle,2450		ExistingTokenPropertyWriter,2451		FIsAdmin,2452		FPropertyPermissions,2453		FCheckTokenExist,2454		FGetProperties,2455	> where2456	T: Config,2457	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2458	FIsAdmin: FnOnce() -> bool,2459	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2460	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2461	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2462{2463	/// A function to write properties to an **already existing** token.2464	pub fn write_token_properties(2465		&mut self,2466		sender: &T::CrossAccountId,2467		token_id: TokenId,2468		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2469		nesting_budget: &dyn Budget,2470		log: evm_coder::ethereum::Log,2471	) -> DispatchResult {2472		self.internal_write_token_properties(2473			token_id,2474			properties_updates,2475			|collection| collection.check_token_indirect_owner(token_id, sender, nesting_budget),2476			log,2477		)2478	}2479}24802481impl<2482		'a,2483		T,2484		Handle,2485		WriterVariant,2486		FIsAdmin,2487		FPropertyPermissions,2488		FCheckTokenExist,2489		FGetProperties,2490	>2491	PropertyWriter<2492		'a,2493		T,2494		Handle,2495		WriterVariant,2496		FIsAdmin,2497		FPropertyPermissions,2498		FCheckTokenExist,2499		FGetProperties,2500	> where2501	T: Config,2502	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2503	FIsAdmin: FnOnce() -> bool,2504	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2505	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2506	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2507{2508	fn internal_write_token_properties<FCheckTokenOwner>(2509		&mut self,2510		token_id: TokenId,2511		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2512		check_token_owner: FCheckTokenOwner,2513		log: evm_coder::ethereum::Log,2514	) -> DispatchResult2515	where2516		FCheckTokenOwner: FnOnce(&Handle) -> Result<bool, DispatchError>,2517	{2518		let get_properties = self.get_properties;2519		let mut stored_properties = LazyValue::new(move || get_properties(token_id));25202521		let mut is_token_owner = LazyValue::new(|| check_token_owner(self.collection));25222523		let check_token_exist = self.check_token_exist;2524		let mut is_token_exist = LazyValue::new(move || check_token_exist(token_id));25252526		for (key, value) in properties_updates {2527			let permission = self2528				.property_permissions2529				.value()2530				.get(&key)2531				.cloned()2532				.unwrap_or_else(PropertyPermission::none);25332534			match permission {2535				PropertyPermission { mutable: false, .. }2536					if stored_properties.value().get(&key).is_some() =>2537				{2538					return Err(<Error<T>>::NoPermission.into());2539				}25402541				PropertyPermission {2542					collection_admin,2543					token_owner,2544					..2545				} => check_token_permissions::<T, _, _, _>(2546					collection_admin,2547					token_owner,2548					&mut self.is_collection_admin,2549					&mut is_token_owner,2550					&mut is_token_exist,2551				)?,2552			}25532554			match value {2555				Some(value) => {2556					stored_properties2557						.value_mut()2558						.try_set(key.clone(), value)2559						.map_err(<Error<T>>::from)?;25602561					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2562						self.collection.id,2563						token_id,2564						key,2565					));2566				}2567				None => {2568					stored_properties2569						.value_mut()2570						.remove(&key)2571						.map_err(<Error<T>>::from)?;25722573					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2574						self.collection.id,2575						token_id,2576						key,2577					));2578				}2579			}2580		}25812582		let properties_changed = stored_properties.has_value();2583		if properties_changed {2584			<PalletEvm<T>>::deposit_log(log);25852586			self.collection2587				.set_token_properties_raw(token_id, stored_properties.into_inner());2588		}25892590		Ok(())2591	}2592}25932594/// Create a [`PropertyWriter`] for newly created tokens.2595pub fn property_writer_for_new_token<'a, T, Handle>(2596	collection: &'a Handle,2597	sender: &'a T::CrossAccountId,2598) -> PropertyWriter<2599	'a,2600	T,2601	Handle,2602	NewTokenPropertyWriter,2603	impl FnOnce() -> bool + 'a,2604	impl FnOnce() -> PropertiesPermissionMap + 'a,2605	impl Copy + FnOnce(TokenId) -> bool + 'a,2606	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2607>2608where2609	T: Config,2610	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2611{2612	PropertyWriter {2613		collection,2614		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2615		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2616		check_token_exist: |token_id| {2617			debug_assert!(collection.token_exists(token_id));2618			true2619		},2620		get_properties: |token_id| {2621			debug_assert!(collection.get_token_properties_raw(token_id).is_none());2622			TokenProperties::new()2623		},2624		_phantom: PhantomData,2625	}2626}26272628#[cfg(feature = "runtime-benchmarks")]2629/// Create a `PropertyWriter` with preloaded `is_collection_admin` and `property_permissions.2630/// Also:2631/// * it will return `true` for the token ownership check.2632/// * it will return empty stored properties without reading them from the storage.2633pub fn collection_info_loaded_property_writer<T, Handle>(2634	collection: &Handle,2635	is_collection_admin: bool,2636	property_permissions: PropertiesPermissionMap,2637) -> PropertyWriter<2638	T,2639	Handle,2640	NewTokenPropertyWriter,2641	impl FnOnce() -> bool,2642	impl FnOnce() -> PropertiesPermissionMap,2643	impl Copy + FnOnce(TokenId) -> bool,2644	impl Copy + FnOnce(TokenId) -> TokenProperties,2645>2646where2647	T: Config,2648	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2649{2650	PropertyWriter {2651		collection,2652		is_collection_admin: LazyValue::new(move || is_collection_admin),2653		property_permissions: LazyValue::new(move || property_permissions),2654		check_token_exist: |_token_id| true,2655		get_properties: |_token_id| TokenProperties::new(),2656		_phantom: PhantomData,2657	}2658}26592660/// Create a [`PropertyWriter`] for already existing tokens.2661pub fn property_writer_for_existing_token<'a, T, Handle>(2662	collection: &'a Handle,2663	sender: &'a T::CrossAccountId,2664) -> PropertyWriter<2665	'a,2666	T,2667	Handle,2668	ExistingTokenPropertyWriter,2669	impl FnOnce() -> bool + 'a,2670	impl FnOnce() -> PropertiesPermissionMap + 'a,2671	impl Copy + FnOnce(TokenId) -> bool + 'a,2672	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2673>2674where2675	T: Config,2676	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2677{2678	PropertyWriter {2679		collection,2680		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2681		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2682		check_token_exist: |token_id| collection.token_exists(token_id),2683		get_properties: |token_id| {2684			collection2685				.get_token_properties_raw(token_id)2686				.unwrap_or_default()2687		},2688		_phantom: PhantomData,2689	}2690}26912692/// Computes the weight delta for newly created tokens with properties.2693/// * `properties_nums` - The properties num of each created token.2694/// * `init_token_properties` - The function to obtain the weight from a token's properties num.2695pub fn init_token_properties_delta<T: Config, I: Fn(u32) -> Weight>(2696	properties_nums: impl Iterator<Item = u32>,2697	init_token_properties: I,2698) -> Weight {2699	let mut delta = properties_nums2700		.filter_map(|properties_num| {2701			if properties_num > 0 {2702				Some(init_token_properties(properties_num))2703			} else {2704				None2705			}2706		})2707		.fold(Weight::zero(), |a, b| a.saturating_add(b));27082709	// If at least once the `init_token_properties` was called,2710	// it means at least one newly created token has properties.2711	// Becuase of that, some common collection data also was loaded and we need to add this weight.2712	// However, these common data was loaded only once which is guaranteed by the `PropertyWriter`.2713	if !delta.is_zero() {2714		delta = delta.saturating_add(<SelfWeightOf<T>>::init_token_properties_common())2715	}27162717	delta2718}27192720#[cfg(any(feature = "tests", test))]2721#[allow(missing_docs)]2722pub mod tests {2723	use crate::{DispatchResult, DispatchError, LazyValue, Config};27242725	const fn to_bool(u: u8) -> bool {2726		u != 02727	}27282729	#[derive(Debug)]2730	pub struct TestCase {2731		pub collection_admin: bool,2732		pub is_collection_admin: bool,2733		pub token_owner: bool,2734		pub is_token_owner: bool,2735		pub no_permission: bool,2736	}27372738	impl TestCase {2739		const fn new(2740			collection_admin: u8,2741			is_collection_admin: u8,2742			token_owner: u8,2743			is_token_owner: u8,2744			no_permission: u8,2745		) -> Self {2746			Self {2747				collection_admin: to_bool(collection_admin),2748				is_collection_admin: to_bool(is_collection_admin),2749				token_owner: to_bool(token_owner),2750				is_token_owner: to_bool(is_token_owner),2751				no_permission: to_bool(no_permission),2752			}2753		}2754	}27552756	#[rustfmt::skip]2757	pub const TABLE: [TestCase; 16] = [2758		//                    ┌╴collection_admin2759		//                    │  ┌╴is_collection_admin2760		//                    │  │   ┌╴token_owner2761		//                    │  │   │  ┌╴is_token_ownership2762		//                    │  │   │  │   ┌╴no_permission2763		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2764		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2765		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2766		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2767		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2768		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2769		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2770		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2771		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2772		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2773		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2774		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2775		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2776		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2777		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2778		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2779	];27802781	pub fn check_token_permissions<T, FCA, FTO, FTE>(2782		collection_admin_permitted: bool,2783		token_owner_permitted: bool,2784		is_collection_admin: &mut LazyValue<bool, FCA>,2785		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2786		check_token_existence: &mut LazyValue<bool, FTE>,2787	) -> DispatchResult2788	where2789		T: Config,2790		FCA: FnOnce() -> bool,2791		FTO: FnOnce() -> Result<bool, DispatchError>,2792		FTE: FnOnce() -> bool,2793	{2794		crate::check_token_permissions::<T, FCA, FTO, FTE>(2795			collection_admin_permitted,2796			token_owner_permitted,2797			is_collection_admin,2798			check_token_ownership,2799			check_token_existence,2800		)2801	}2802}
modifiedpallets/configuration/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/configuration/src/benchmarking.rs
+++ b/pallets/configuration/src/benchmarking.rs
@@ -52,7 +52,7 @@
 	}
 
 	set_app_promotion_configuration_override {
-		let configuration: AppPromotionConfiguration<T::BlockNumber> = Default::default();
+		let configuration: AppPromotionConfiguration<BlockNumberFor<T>> = Default::default();
 	}: {
 		assert_ok!(
 			<Pallet<T>>::set_app_promotion_configuration_override(RawOrigin::Root.into(), configuration)
@@ -82,7 +82,7 @@
 	}
 
 	set_collator_selection_kick_threshold {
-		let threshold: Option<T::BlockNumber> = Some(900u32.into());
+		let threshold: Option<BlockNumberFor<T>> = Some(900u32.into());
 	}: {
 		assert_ok!(
 			<Pallet<T>>::set_collator_selection_kick_threshold(RawOrigin::Root.into(), threshold)
modifiedpallets/configuration/src/lib.rsdiffbeforeafterboth
--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -80,14 +80,14 @@
 		#[pallet::constant]
 		type AppPromotionDailyRate: Get<Perbill>;
 		#[pallet::constant]
-		type DayRelayBlocks: Get<Self::BlockNumber>;
+		type DayRelayBlocks: Get<BlockNumberFor<Self>>;
 
 		#[pallet::constant]
 		type DefaultCollatorSelectionMaxCollators: Get<u32>;
 		#[pallet::constant]
 		type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;
 		#[pallet::constant]
-		type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;
+		type DefaultCollatorSelectionKickThreshold: Get<BlockNumberFor<Self>>;
 
 		/// The weight information of this pallet.
 		type WeightInfo: WeightInfo;
@@ -103,7 +103,7 @@
 			bond_cost: Option<T::Balance>,
 		},
 		NewCollatorKickThreshold {
-			length_in_blocks: Option<T::BlockNumber>,
+			length_in_blocks: Option<BlockNumberFor<T>>,
 		},
 	}
 
@@ -134,7 +134,6 @@
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T>(PhantomData<T>);
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self(Default::default())
@@ -142,7 +141,7 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
 			update_base_fee::<T>();
 		}
@@ -166,7 +165,7 @@
 
 	#[pallet::storage]
 	pub type AppPromomotionConfigurationOverride<T: Config> =
-		StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;
+		StorageValue<Value = AppPromotionConfiguration<BlockNumberFor<T>>, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
 	pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<
@@ -184,7 +183,7 @@
 
 	#[pallet::storage]
 	pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = ValueQuery,
 		OnEmpty = T::DefaultCollatorSelectionKickThreshold,
 	>;
@@ -228,7 +227,7 @@
 		#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]
 		pub fn set_app_promotion_configuration_override(
 			origin: OriginFor<T>,
-			mut configuration: AppPromotionConfiguration<T::BlockNumber>,
+			mut configuration: AppPromotionConfiguration<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 			if configuration.interval_income.is_some() {
@@ -287,7 +286,7 @@
 		#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]
 		pub fn set_collator_selection_kick_threshold(
 			origin: OriginFor<T>,
-			threshold: Option<T::BlockNumber>,
+			threshold: Option<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 			if let Some(threshold) = threshold {
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -422,7 +422,7 @@
 		{
 			return None;
 		}
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+		let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 
 		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {
 			let limit = <SponsoringRateLimit<T>>::get(contract_address);
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -53,7 +53,7 @@
 
 		/// In case of enabled sponsoring, but no sponsoring rate limit set,
 		/// this value will be used implicitly
-		type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;
+		type DefaultSponsoringRateLimit: Get<BlockNumberFor<Self>>;
 	}
 
 	#[pallet::error]
@@ -115,7 +115,7 @@
 	pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
 		Hasher = Twox128,
 		Key = H160,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = ValueQuery,
 		OnEmpty = T::DefaultSponsoringRateLimit,
 	>;
@@ -139,7 +139,7 @@
 		Key1 = H160,
 		Hasher2 = Twox128,
 		Key2 = H160,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
@@ -393,7 +393,7 @@
 		}
 
 		/// Set duration between two sponsored contract calls
-		pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: T::BlockNumber) {
+		pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: BlockNumberFor<T>) {
 			<SponsoringRateLimit<T>>::insert(contract, rate_limit);
 		}
 
modifiedpallets/evm-migration/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/benchmarking.rs
+++ b/pallets/evm-migration/src/benchmarking.rs
@@ -23,7 +23,7 @@
 use sp_std::{vec::Vec, vec};
 
 benchmarks! {
-	where_clause { where <T as Config>::RuntimeEvent: codec::Encode }
+	where_clause { where <T as Config>::RuntimeEvent: parity_scale_codec::Encode }
 
 	begin {
 	}: _(RawOrigin::Root, H160::default())
@@ -59,7 +59,7 @@
 
 	insert_events {
 		let b in 0..200;
-		use codec::Encode;
+		use parity_scale_codec::Encode;
 		let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();
 	}: _(RawOrigin::Root, logs)
 }
modifiedpallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -30,30 +30,30 @@
 
 impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
 	<T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
 {
-	type AssetId = AssetIds;
+	type AssetId = AssetId;
 	type Balance = BalanceOf<T>;
 
 	fn total_issuance(asset: Self::AssetId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
 					.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => return Zero::zero(),
@@ -71,38 +71,36 @@
 	fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
 					.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
-				AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))
-					.map(|x| x.minimal_balance)
-					.unwrap_or_else(Zero::zero)
-			}
+			AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
+				.map(|x| x.minimal_balance)
+				.unwrap_or_else(Zero::zero),
 		}
 	}
 
 	fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => return Zero::zero(),
@@ -133,7 +131,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
 					who,
 					preservation,
@@ -141,9 +139,9 @@
 				)
 				.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					preservation,
 					fortitude,
@@ -163,16 +161,16 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
 					who,
 					amount.into(),
 					provenance,
 				)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 					provenance,
@@ -219,7 +217,7 @@
 		};
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
 					Ok(val) => val,
 					Err(_) => {
@@ -240,7 +238,7 @@
 					_ => WithdrawConsequence::BalanceLow,
 				}
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
 					Ok(val) => val,
 					Err(_) => {
@@ -248,7 +246,7 @@
 					}
 				};
 				match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					parent_amount,
 				) {
@@ -269,17 +267,17 @@
 		}
 	}
 
-	fn asset_exists(asset: AssetIds) -> bool {
+	fn asset_exists(asset: AssetId) -> bool {
 		match asset {
-			AssetIds::NativeAssetId(_) => true,
-			AssetIds::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
+			AssetId::NativeAssetId(_) => true,
+			AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
 		}
 	}
 }
 
 impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
@@ -295,22 +293,22 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
 					who,
 					amount.into(),
 				)
 				.map(Into::into)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 				)
 				.map(Into::into)
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -349,7 +347,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
 					who,
 					amount.into(),
@@ -358,9 +356,9 @@
 				)
 				.map(Into::into)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 					precision,
@@ -368,7 +366,7 @@
 				)
 				.map(Into::into)
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -401,7 +399,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
 					source,
 					dest,
@@ -414,9 +412,9 @@
 					)),
 				}
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					source,
 					dest,
 					amount.into(),
@@ -426,7 +424,7 @@
 					Err(e) => Err(e),
 				}
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -479,7 +477,7 @@
 
 impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -79,8 +79,9 @@
 	Encode,
 	Decode,
 	TypeInfo,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub enum NativeCurrency {
 	Here = 0,
 	Parent = 1,
@@ -98,9 +99,10 @@
 	Encode,
 	Decode,
 	TypeInfo,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum AssetIds {
+pub enum AssetId {
 	ForeignAssetId(ForeignAssetId),
 	NativeAssetId(NativeCurrency),
 }
@@ -109,17 +111,17 @@
 	fn try_as_foreign(asset: T) -> Option<F>;
 }
 
-impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {
-	fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {
+impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
+	fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
 		match asset {
-			AssetIds::ForeignAssetId(id) => Some(id),
+			Self::ForeignAssetId(id) => Some(id),
 			_ => None,
 		}
 	}
 }
 
 pub type ForeignAssetId = u32;
-pub type CurrencyId = AssetIds;
+pub type CurrencyId = AssetId;
 
 mod impl_fungibles;
 pub mod weights;
@@ -151,7 +153,7 @@
 {
 	fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
 		log::trace!(target: "fassets::asset_metadatas", "call");
-		Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))
+		Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
 	}
 
 	fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
@@ -161,7 +163,7 @@
 
 	fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
 		log::trace!(target: "fassets::get_currency_id", "call");
-		Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
+		Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
 	}
 }
 
@@ -231,12 +233,12 @@
 		},
 		/// The asset registered.
 		AssetRegistered {
-			asset_id: AssetIds,
+			asset_id: AssetId,
 			metadata: AssetMetadata<BalanceOf<T>>,
 		},
 		/// The asset updated.
 		AssetUpdated {
-			asset_id: AssetIds,
+			asset_id: AssetId,
 			metadata: AssetMetadata<BalanceOf<T>>,
 		},
 	}
@@ -253,7 +255,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn foreign_asset_locations)]
 	pub type ForeignAssetLocations<T: Config> =
-		StorageMap<_, Twox64Concat, ForeignAssetId, xcm::v3::MultiLocation, OptionQuery>;
+		StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
 
 	/// The storages for CurrencyIds.
 	///
@@ -261,7 +263,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn location_to_currency_ids)]
 	pub type LocationToCurrencyIds<T: Config> =
-		StorageMap<_, Twox64Concat, xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
+		StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
 
 	/// The storages for AssetMetadatas.
 	///
@@ -269,7 +271,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn asset_metadatas)]
 	pub type AssetMetadatas<T: Config> =
-		StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;
+		StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
 
 	/// The storages for assets to fungible collection binding
 	///
@@ -381,7 +383,7 @@
 					*maybe_location = Some(*location);
 
 					AssetMetadatas::<T>::try_mutate(
-						AssetIds::ForeignAssetId(foreign_asset_id),
+						AssetId::ForeignAssetId(foreign_asset_id),
 						|maybe_asset_metadatas| -> DispatchResult {
 							ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
 							*maybe_asset_metadatas = Some(metadata.clone());
@@ -413,7 +415,7 @@
 					.ok_or(Error::<T>::AssetIdNotExists)?;
 
 				AssetMetadatas::<T>::try_mutate(
-					AssetIds::ForeignAssetId(foreign_asset_id),
+					AssetId::ForeignAssetId(foreign_asset_id),
 					|maybe_asset_metadatas| -> DispatchResult {
 						ensure!(
 							maybe_asset_metadatas.is_some(),
@@ -450,7 +452,7 @@
 	traits::{
 		fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,
 	},
-	weights::{WeightToFeePolynomial, WeightToFee},
+	weights::{WeightToFee, WeightToFeePolynomial},
 };
 
 pub struct FreeForAll<
@@ -477,7 +479,12 @@
 		Self(Weight::default(), Zero::zero(), PhantomData)
 	}
 
-	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+	fn buy_weight(
+		&mut self,
+		weight: Weight,
+		payment: Assets,
+		_xcm: &XcmContext,
+	) -> Result<Assets, XcmError> {
 		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
 		Ok(payment)
 	}
modifiedpallets/identity/src/tests.rsdiffbeforeafterboth
--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -54,14 +54,10 @@
 type Block = frame_system::mocking::MockBlock<Test>;
 
 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>},
-		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>},
+	pub enum Test {
+		System: frame_system,
+		Balances: pallet_balances,
+		Identity: pallet_identity,
 	}
 );
 
@@ -71,17 +67,16 @@
 }
 impl frame_system::Config for Test {
 	type BaseCallFilter = frame_support::traits::Everything;
+	type Block = Block;
 	type BlockWeights = ();
 	type BlockLength = ();
 	type RuntimeOrigin = RuntimeOrigin;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type RuntimeCall = RuntimeCall;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = RuntimeEvent;
 	type BlockHashCount = ConstU64<250>;
 	type DbWeight = ();
@@ -106,7 +101,7 @@
 	type MaxReserves = ();
 	type ReserveIdentifier = [u8; 8];
 	type WeightInfo = ();
-	type HoldIdentifier = ();
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type FreezeIdentifier = ();
 	type MaxHolds = ();
 	type MaxFreezes = ();
@@ -139,8 +134,8 @@
 }
 
 pub fn new_test_ext() -> sp_io::TestExternalities {
-	let mut t = frame_system::GenesisConfig::default()
-		.build_storage::<Test>()
+	let mut t = <frame_system::GenesisConfig<Test>>::default()
+		.build_storage()
 		.unwrap();
 	pallet_balances::GenesisConfig::<Test> {
 		balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -77,7 +77,9 @@
 }
 
 impl Decode for Data {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let b = input.read_byte()?;
 		Ok(match b {
 			0 => Data::None,
@@ -92,7 +94,7 @@
 			35 => Data::Sha256(<[u8; 32]>::decode(input)?),
 			36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
 			37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),
-			_ => return Err(codec::Error::from("invalid leading byte")),
+			_ => return Err(parity_scale_codec::Error::from("invalid leading byte")),
 		})
 	}
 }
@@ -114,7 +116,7 @@
 		}
 	}
 }
-impl codec::EncodeLike for Data {}
+impl parity_scale_codec::EncodeLike for Data {}
 
 /// Add a Raw variant with the given index and a fixed sized byte array
 macro_rules! data_raw_variants {
@@ -284,7 +286,9 @@
 	}
 }
 impl Decode for IdentityFields {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let field = u64::decode(input)?;
 		Ok(Self(
 			<BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
@@ -445,7 +449,9 @@
 		MaxAdditionalFields: Get<u32>,
 	> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>
 {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
 		Ok(Self {
 			judgements,
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -73,11 +73,11 @@
 		type TreasuryAccountId: Get<Self::AccountId>;
 
 		// The block number provider
-		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+		type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
 
 		/// Number of blocks that pass between treasury balance updates due to inflation
 		#[pallet::constant]
-		type InflationBlockInterval: Get<Self::BlockNumber>;
+		type InflationBlockInterval: Get<BlockNumberFor<Self>>;
 	}
 
 	#[pallet::pallet]
@@ -95,22 +95,23 @@
 	/// Next target (relay) block when inflation will be applied
 	#[pallet::storage]
 	pub type NextInflationBlock<T: Config> =
-		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	/// Next target (relay) block when inflation is recalculated
 	#[pallet::storage]
 	pub type NextRecalculationBlock<T: Config> =
-		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	/// Relay block when inflation has started
 	#[pallet::storage]
-	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+	pub type StartBlock<T: Config> =
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		fn on_initialize(_: T::BlockNumber) -> Weight
+		fn on_initialize(_: BlockNumberFor<T>) -> Weight
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			let mut consumed_weight = Weight::zero();
 			let mut add_weight = |reads, writes, weight| {
@@ -120,7 +121,7 @@
 
 			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
 			let current_relay_block = T::BlockNumberProvider::current_block_number();
-			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
+			let next_inflation: BlockNumberFor<T> = <NextInflationBlock<T>>::get();
 			add_weight(1, 0, Weight::from_parts(5_000_000, 0));
 
 			// Apply inflation every InflationBlockInterval blocks
@@ -129,7 +130,7 @@
 				// Recalculate inflation on the first block of the year (or if it is not initialized yet)
 				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"
 				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.
-				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();
+				let next_recalculation: BlockNumberFor<T> = <NextRecalculationBlock<T>>::get();
 				add_weight(1, 0, Weight::zero());
 				if current_relay_block >= next_recalculation {
 					Self::recalculate_inflation(next_recalculation);
@@ -169,10 +170,10 @@
 		#[pallet::weight(Weight::from_parts(0, 0))]
 		pub fn start_inflation(
 			origin: OriginFor<T>,
-			inflation_start_relay_block: T::BlockNumber,
+			inflation_start_relay_block: BlockNumberFor<T>,
 		) -> DispatchResult
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			ensure_root(origin)?;
 
@@ -200,9 +201,9 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
+	pub fn recalculate_inflation(recalculation_block: BlockNumberFor<T>) {
 		let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())
-			/ T::BlockNumber::from(YEAR))
+			/ BlockNumberFor::<T>::from(YEAR))
 		.try_into()
 		.unwrap_or(0);
 		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -57,21 +57,16 @@
 	type MaxLocks = MaxLocks;
 	type MaxReserves = ();
 	type ReserveIdentifier = ();
-	type HoldIdentifier = ();
 	type FreezeIdentifier = ();
 	type MaxHolds = ();
 	type MaxFreezes = ();
 }
 
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		Balances: pallet_balances::{Pallet, Call, Storage},
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Inflation: pallet_inflation::{Pallet, Call, Storage},
+	pub enum Test {
+		Balances: pallet_balances,
+		System: frame_system,
+		Inflation: pallet_inflation,
 	}
 );
 
@@ -89,13 +84,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = ();
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
@@ -112,11 +105,11 @@
 parameter_types! {
 	pub TreasuryAccountId: u64 = 1234;
 	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
-	pub static MockBlockNumberProvider: u64 = 0;
+	pub static MockBlockNumberProvider: u32 = 0;
 }
 
 impl BlockNumberProvider for MockBlockNumberProvider {
-	type BlockNumber = u64;
+	type BlockNumber = u32;
 
 	fn current_block_number() -> Self::BlockNumber {
 		Self::get()
@@ -131,8 +124,8 @@
 }
 
 pub fn new_test_ext() -> sp_io::TestExternalities {
-	frame_system::GenesisConfig::default()
-		.build_storage::<Test>()
+	<frame_system::GenesisConfig<Test>>::default()
+		.build_storage()
 		.unwrap()
 		.into()
 }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -90,37 +90,37 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
+use core::ops::Deref;
+
 use erc::ERC721Events;
 use evm_coder::ToLog;
 use frame_support::{
-	BoundedVec, ensure, fail, transactional,
+	dispatch::{Pays, PostDispatchInfo},
+	ensure, fail,
+	pallet_prelude::*,
 	storage::with_transaction,
-	pallet_prelude::DispatchResultWithPostInfo,
-	pallet_prelude::Weight,
-	dispatch::{PostDispatchInfo, Pays},
-};
-use up_data_structs::{
-	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
-	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
-	PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
-	TokenProperties as TokenPropertiesT,
+	transactional, BoundedVec,
 };
-use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
+pub use pallet::*;
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
 	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
 	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
 };
-use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
+use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_structure::{Error as StructureError, Pallet as PalletStructure};
+use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
+use scale_info::TypeInfo;
 use sp_core::{Get, H160};
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
-use core::ops::Deref;
-use codec::{Encode, Decode, MaxEncodedLen};
-use scale_info::TypeInfo;
-
-pub use pallet::*;
+use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
+use up_data_structs::{
+	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
+	PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+	TokenProperties as TokenPropertiesT,
+};
 use weights::WeightInfo;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
@@ -147,13 +147,13 @@
 
 #[frame_support::pallet]
 pub mod pallet {
-	use super::*;
 	use frame_support::{
-		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,
+		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat, Twox64Concat,
 	};
 	use up_data_structs::{CollectionId, TokenId};
-	use super::weights::WeightInfo;
 
+	use super::{weights::WeightInfo, *};
+
 	#[pallet::error]
 	pub enum Error<T> {
 		/// Not Nonfungible item data used to mint in Nonfungible collection.
@@ -285,7 +285,6 @@
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T>(PhantomData<T>);
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self(Default::default())
@@ -293,7 +292,7 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
 			StorageVersion::new(1).put::<Pallet<T>>();
 		}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -174,7 +174,7 @@
 	pub type CreateItemBasket<T: Config> = StorageMap<
 		Hasher = Blake2_128Concat,
 		Key = (CollectionId, T::AccountId),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), token id (controlled?2)
@@ -185,7 +185,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), owning user (real)
@@ -196,7 +196,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Twox64Concat,
 		Key2 = T::AccountId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), token id (controlled?2)
@@ -208,7 +208,7 @@
 			Key<Blake2_128Concat, TokenId>,
 			Key<Twox64Concat, T::AccountId>,
 		),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	//#endregion
@@ -221,7 +221,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
@@ -233,7 +233,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Last sponsoring of fungible tokens approval in a collection
@@ -244,7 +244,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Twox64Concat,
 		Key2 = T::AccountId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Last sponsoring of RFT approval in a collection
@@ -256,7 +256,7 @@
 			Key<Blake2_128Concat, TokenId>,
 			Key<Twox64Concat, T::AccountId>,
 		),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -28,14 +28,14 @@
 pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
 
 // These time units are defined in number of blocks.
-pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
-pub const HOURS: BlockNumber = MINUTES * 60;
-pub const DAYS: BlockNumber = HOURS * 24;
+pub const MINUTES: u32 = 60_000 / (MILLISECS_PER_BLOCK as u32);
+pub const HOURS: u32 = MINUTES * 60;
+pub const DAYS: u32 = HOURS * 24;
 
 // These time units are defined in number of relay blocks.
-pub const RELAY_MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_RELAY_BLOCK as BlockNumber);
-pub const RELAY_HOURS: BlockNumber = RELAY_MINUTES * 60;
-pub const RELAY_DAYS: BlockNumber = RELAY_HOURS * 24;
+pub const RELAY_MINUTES: u32 = 60_000 / (MILLISECS_PER_RELAY_BLOCK as u32);
+pub const RELAY_HOURS: u32 = RELAY_MINUTES * 60;
+pub const RELAY_DAYS: u32 = RELAY_HOURS * 24;
 
 pub const MICROUNIQUE: Balance = 1_000_000_000_000;
 pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;
modifiedprimitives/common/src/types.rsdiffbeforeafterboth
--- a/primitives/common/src/types.rs
+++ b/primitives/common/src/types.rs
@@ -37,10 +37,8 @@
 		Unknown(sp_std::vec::Vec<u8>),
 	}
 
-	/// Opaque block header type.
 	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
 
-	/// Opaque block type.
 	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 
 	pub trait RuntimeInstance {
@@ -71,7 +69,7 @@
 pub type Balance = u128;
 
 /// Index of a transaction in the chain.
-pub type Index = u32;
+pub type Nonce = u32;
 
 /// A hash of some data used by the chain.
 pub type Hash = sp_core::H256;
modifiedprimitives/data-structs/src/bondrewd_codec.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bondrewd_codec.rs
+++ b/primitives/data-structs/src/bondrewd_codec.rs
@@ -5,12 +5,14 @@
 macro_rules! bondrewd_codec {
 	($T:ty) => {
 		impl Encode for $T {
-			fn encode_to<O: codec::Output + ?Sized>(&self, dest: &mut O) {
+			fn encode_to<O: parity_scale_codec::Output + ?Sized>(&self, dest: &mut O) {
 				dest.write(&self.into_bytes())
 			}
 		}
-		impl codec::Decode for $T {
-			fn decode<I: codec::Input + ?Sized>(from: &mut I) -> Result<Self, codec::Error> {
+		impl parity_scale_codec::Decode for $T {
+			fn decode<I: parity_scale_codec::Input + ?Sized>(
+				from: &mut I,
+			) -> Result<Self, parity_scale_codec::Error> {
 				let mut bytes = [0; Self::BYTE_SIZE];
 				from.read(&mut bytes)?;
 				Ok(Self::from_bytes(bytes))
modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -26,13 +26,13 @@
 };
 
 /// [`serde`] implementations for [`BoundedVec`].
-#[cfg(feature = "serde1")]
 pub mod vec_serde {
 	use core::convert::TryFrom;
-	use frame_support::{BoundedVec, traits::Get};
+
+	use frame_support::{traits::Get, BoundedVec};
 	use serde::{
-		ser::{self, Serialize},
 		de::{self, Deserialize, Error},
+		ser::{self, Serialize},
 	};
 	use sp_std::vec::Vec;
 
@@ -66,17 +66,17 @@
 	(v as &Vec<V>).fmt(f)
 }
 
-#[cfg(feature = "serde1")]
 #[allow(dead_code)]
 /// [`serde`] implementations for [`BoundedBTreeMap`].
 pub mod map_serde {
 	use core::convert::TryFrom;
-	use sp_std::collections::btree_map::BTreeMap;
-	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};
+
+	use frame_support::{storage::bounded_btree_map::BoundedBTreeMap, traits::Get};
 	use serde::{
+		de::{self, Deserialize, Error},
 		ser::{self, Serialize},
-		de::{self, Deserialize, Error},
 	};
+	use sp_std::collections::btree_map::BTreeMap;
 	pub fn serialize<D, K, V, S>(
 		value: &BoundedBTreeMap<K, V, S>,
 		serializer: D,
@@ -117,17 +117,17 @@
 	(v as &BTreeMap<K, V>).fmt(f)
 }
 
-#[cfg(feature = "serde1")]
 #[allow(dead_code)]
 /// [`serde`] implementations for [`BoundedBTreeSet`].
 pub mod set_serde {
 	use core::convert::TryFrom;
-	use sp_std::collections::btree_set::BTreeSet;
-	use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};
+
+	use frame_support::{storage::bounded_btree_set::BoundedBTreeSet, traits::Get};
 	use serde::{
-		ser::{self, Serialize},
 		de::{self, Deserialize, Error},
+		ser::{self, Serialize},
 	};
+	use sp_std::collections::btree_set::BTreeSet;
 	pub fn serialize<D, K, S>(
 		value: &BoundedBTreeSet<K, S>,
 		serializer: D,
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -153,8 +153,9 @@
 	Default,
 	TypeInfo,
 	MaxEncodedLen,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionId(pub u32);
 impl EncodeLike<u32> for CollectionId {}
 impl EncodeLike<CollectionId> for u32 {}
@@ -187,8 +188,9 @@
 	Default,
 	TypeInfo,
 	MaxEncodedLen,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct TokenId(pub u32);
 impl EncodeLike<u32> for TokenId {}
 impl EncodeLike<TokenId> for u32 {}
@@ -221,8 +223,7 @@
 
 /// Token data.
 #[struct_versioning::versioned(version = 2, upper)]
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct TokenData<CrossAccountId> {
 	/// Properties of token.
 	pub properties: Vec<Property>,
@@ -251,8 +252,9 @@
 /// Collection can represent various types of tokens.
 /// Each collection can contain only one type of tokens at a time.
 /// This type helps to understand which tokens the collection contains.
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum CollectionMode {
 	/// Non fungible tokens.
 	NFT,
@@ -279,8 +281,19 @@
 }
 
 /// Access mode for some token operations.
-#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Eq,
+	Debug,
+	Clone,
+	Copy,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 pub enum AccessMode {
 	/// Access grant for owner and admins. Used as default.
 	Normal,
@@ -294,8 +307,9 @@
 }
 
 // TODO: remove in future.
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SchemaVersion {
 	ImageURL,
 	Unique,
@@ -307,16 +321,16 @@
 }
 
 // TODO: unused type
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct Ownership<AccountId> {
 	pub owner: AccountId,
 	pub fraction: u128,
 }
 
 /// The state of collection sponsorship.
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SponsorshipState<AccountId> {
 	/// The fees are applied to the transaction sender.
 	Disabled,
@@ -444,8 +458,7 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
-#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct RpcCollectionFlags {
 	/// Is collection is foreign.
 	pub foreign: bool,
@@ -455,8 +468,7 @@
 
 /// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
 #[struct_versioning::versioned(version = 2, upper)]
-#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct RpcCollection<AccountId> {
 	/// Collection owner account.
 	pub owner: AccountId,
@@ -538,8 +550,10 @@
 
 pub struct RawEncoded(Vec<u8>);
 
-impl codec::Decode for RawEncoded {
-	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
+impl parity_scale_codec::Decode for RawEncoded {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> Result<Self, parity_scale_codec::Error> {
 		let mut out = Vec::new();
 		while let Ok(v) = input.read_byte() {
 			out.push(v);
@@ -612,8 +626,18 @@
 ///
 /// Update with `pallet_common::Pallet::clamp_limits`.
 // IMPORTANT: When adding/removing fields from this struct - don't forget to also
-#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Debug,
+	Default,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 // When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.
 // TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.
 // TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.
@@ -769,8 +793,18 @@
 /// Some fields are wrapped in [`Option`], where `None` means chain default.
 ///
 /// Update with `pallet_common::Pallet::clamp_permissions`.
-#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Debug,
+	Default,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 // When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.
 // TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.
 pub struct CollectionPermissions {
@@ -821,11 +855,12 @@
 type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;
 
 /// Wraper for collections set allowing nest.
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
+)]
 #[derivative(Debug)]
 pub struct OwnerRestrictedSet(
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]
+	#[serde(with = "bounded::set_serde")]
 	#[derivative(Debug(format_with = "bounded::set_debug"))]
 	pub OwnerRestrictedSetInner,
 );
@@ -862,8 +897,9 @@
 }
 
 /// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
+)]
 #[derivative(Debug)]
 pub struct NestingPermissions {
 	/// Owner of token can nest tokens under it.
@@ -881,8 +917,9 @@
 /// Enum denominating how often can sponsoring occur if it is enabled.
 ///
 /// Used for [`collection limits`](CollectionLimits).
-#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SponsoringRateLimit {
 	/// Sponsoring is disabled, and the collection sponsor will not pay for transactions
 	SponsoringDisabled,
@@ -891,42 +928,73 @@
 }
 
 /// Data used to describe an NFT at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	PartialEq,
+	Clone,
+	Derivative,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 #[derivative(Debug)]
 pub struct CreateNftData {
 	/// Key-value pairs used to describe the token as metadata
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
 	/// Properties that wil be assignet to created item.
 	pub properties: CollectionPropertiesVec,
 }
 
 /// Data used to describe a Fungible token at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	Debug,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 pub struct CreateFungibleData {
 	/// Number of fungible coins minted
 	pub value: u128,
 }
 
 /// Data used to describe a Refungible token at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	PartialEq,
+	Clone,
+	Derivative,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 #[derivative(Debug)]
 pub struct CreateReFungibleData {
 	/// Number of pieces the RFT is split into
 	pub pieces: u128,
 
 	/// Key-value pairs used to describe the token as metadata
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
 	pub properties: CollectionPropertiesVec,
 }
 
 // TODO: remove this.
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum MetaUpdatePermission {
 	ItemOwner,
 	Admin,
@@ -935,8 +1003,9 @@
 
 /// Enum holding data used for creation of all three item types.
 /// Unified data for create item.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 pub enum CreateItemData {
 	/// Data for create NFT.
 	NFT(CreateNftData),
@@ -1025,8 +1094,9 @@
 }
 
 /// Token's address, dictated by its collection and token IDs.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 // todo possibly rename to be used generally as an address pair
 pub struct TokenChild {
 	/// Token id.
@@ -1037,8 +1107,9 @@
 }
 
 /// Collection statistics.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 pub struct CollectionStats {
 	/// Number of created items.
 	pub created: u32,
@@ -1060,10 +1131,9 @@
 
 	fn type_info() -> scale_info::Type {
 		use scale_info::{
-			Type, Path,
 			build::{FieldsBuilder, UnnamedFields},
 			form::MetaForm,
-			type_params,
+			type_params, Path, Type,
 		};
 		Type::builder()
 			.path(Path::new("up_data_structs", "PhantomType"))
@@ -1092,8 +1162,18 @@
 pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
 
 /// Property permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	TypeInfo,
+	Debug,
+	MaxEncodedLen,
+	PartialEq,
+	Clone,
+	Default,
+	Serialize,
+	Deserialize,
+)]
 pub struct PropertyPermission {
 	/// Permission to change the property and property permission.
 	///
@@ -1119,15 +1199,16 @@
 }
 
 /// Property is simpl key-value record.
-#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub struct Property {
 	/// Property key.
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	pub key: PropertyKey,
 
 	/// Property value.
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	pub value: PropertyValue,
 }
 
@@ -1138,8 +1219,9 @@
 }
 
 /// Record for proprty key permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Serialize, Deserialize,
+)]
 pub struct PropertyKeyPermission {
 	/// Key.
 	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
@@ -1362,7 +1444,7 @@
 	scoped_slice_size(PropertyScope::None, data)
 }
 fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {
-	use codec::Compact;
+	use parity_scale_codec::Compact;
 	let prefix = scope.prefix();
 	<Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u32
 		+ data.len() as u32
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -82,7 +82,7 @@
 			collection: CollectionId,
 			token_id: TokenId,
 			keys: Option<Vec<Vec<u8>>>
-		) -> Result<TokenDataVersion1<CrossAccountId>>;
+		) -> Result<up_data_structs::TokenDataVersion1<CrossAccountId>>;
 
 		/// Total number of tokens in collection.
 		fn total_supply(collection: CollectionId) -> Result<u32>;
@@ -117,7 +117,7 @@
 		fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
 
 		#[changed_in(3)]
-		fn collection_by_id(collection: CollectionId) -> Result<Option<RawEncoded>>;
+		fn collection_by_id(collection: CollectionId) -> Result<Option<up_data_structs::RawEncoded>>;
 
 		/// Get collection stats.
 		fn collection_stats() -> Result<CollectionStats>;
modifiedruntime/common/config/pallets/collator_selection.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/collator_selection.rs
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -107,6 +107,7 @@
 
 impl pallet_collator_selection::Config for Runtime {
 	type RuntimeEvent = RuntimeEvent;
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type Currency = Balances;
 	// We allow root only to execute privileged collator selection operations.
 
@@ -128,7 +129,6 @@
 	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
 	type ValidatorRegistration = Session;
 	type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
-	type LicenceBondIdentifier = LicenceBondIdentifier;
 	type DesiredCollators = DesiredCollators;
 	type LicenseBond = LicenseBond;
 	type KickThreshold = KickThreshold;
modifiedruntime/common/config/substrate.rsdiffbeforeafterboth
--- a/runtime/common/config/substrate.rs
+++ b/runtime/common/config/substrate.rs
@@ -76,10 +76,10 @@
 	type BaseCallFilter = Everything;
 	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
 	type BlockHashCount = BlockHashCount;
+	/// The block type.
+	type Block = Block;
 	/// The maximum length of a block (in bytes).
 	type BlockLength = RuntimeBlockLength;
-	/// The index type for blocks.
-	type BlockNumber = BlockNumber;
 	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.
 	type BlockWeights = RuntimeBlockWeights;
 	/// The aggregated dispatch type that is available for extrinsics.
@@ -92,10 +92,8 @@
 	type Hash = Hash;
 	/// The hashing algorithm used.
 	type Hashing = BlakeTwo256;
-	/// The header type.
-	type Header = generic::Header<BlockNumber, BlakeTwo256>;
 	/// The index type for storing how many extrinsics an account has signed.
-	type Index = Index;
+	type Nonce = Nonce;
 	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
 	type Lookup = AccountIdLookup<AccountId, ()>;
 	/// What to do if an account is fully reaped from the system.
@@ -171,7 +169,7 @@
 	type ExistentialDeposit = ExistentialDeposit;
 	type AccountStore = System;
 	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
-	type HoldIdentifier = [u8; 16];
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type FreezeIdentifier = [u8; 16];
 	type MaxHolds = MaxHolds;
 	type MaxFreezes = MaxFreezes;
@@ -247,6 +245,7 @@
 	type AuthorityId = AuraId;
 	type DisabledValidators = ();
 	type MaxAuthorities = MaxAuthorities;
+	type AllowMultipleBlocksPerSlot = ConstBool<true>;
 }
 
 impl pallet_utility::Config for Runtime {
modifiedruntime/common/config/xcm/foreignassets.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -36,17 +36,11 @@
 	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
 }
 
-pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
-	ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
-where
-	AssetId: Borrow<AssetId>,
-	AssetId: TryAsForeign<AssetId, ForeignAssetId>,
-	AssetIds: Borrow<AssetId>,
+pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
+impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
+	for AsInnerId<ConvertAssetId>
 {
-	fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
-		let id = id.borrow();
-
+	fn convert(id: &MultiLocation) -> Option<AssetId> {
 		log::trace!(
 			target: "xcm::AsInnerId::Convert",
 			"AsInnerId {:?}",
@@ -58,52 +52,46 @@
 		let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
 
 		if *id == parent {
-			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));
+			return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
 		}
 
 		if *id == here || *id == self_location {
-			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
+			return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
 		}
 
 		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
-			Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
-				ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
+			Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
+				ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
 			}
-			_ => Err(()),
+			_ => None,
 		}
 	}
 
-	fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {
+	fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
 		log::trace!(
 			target: "xcm::AsInnerId::Reverse",
 			"AsInnerId",
 		);
-
-		let asset_id = what.borrow();
 
 		let parent_id =
-			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();
+			ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
 		let here_id =
-			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();
+			ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
 
 		if asset_id.clone() == parent_id {
-			return Ok(MultiLocation::parent());
+			return Some(MultiLocation::parent());
 		}
 
 		if asset_id.clone() == here_id {
-			return Ok(MultiLocation::new(
+			return Some(MultiLocation::new(
 				1,
 				X1(Parachain(ParachainInfo::get().into())),
 			));
 		}
 
-		match <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone()) {
-			Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {
-				Some(location) => Ok(location),
-				None => Err(()),
-			},
-			None => Err(()),
-		}
+		let fid =
+			<AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone())?;
+		XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
 	}
 }
 
@@ -112,7 +100,7 @@
 	// Use this fungibles implementation:
 	ForeignAssets,
 	// Use this currency when it is a fungible asset matching the given location or name:
-	ConvertedConcreteId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,
+	ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
 	// Convert an XCM MultiLocation into a local account id:
 	LocationToAccountId,
 	// Our chain's account ID type (we can't get away without mentioning it explicitly):
@@ -154,7 +142,7 @@
 		what: &MultiAsset,
 		who: &MultiLocation,
 		maybe_context: Option<&XcmContext>,
-	) -> Result<xcm_executor::Assets, XcmError> {
+	) -> Result<staging_xcm_executor::Assets, XcmError> {
 		FungiblesTransactor::withdraw_asset(what, who, maybe_context)
 	}
 
@@ -163,7 +151,7 @@
 		from: &MultiLocation,
 		to: &MultiLocation,
 		context: &XcmContext,
-	) -> Result<xcm_executor::Assets, XcmError> {
+	) -> Result<staging_xcm_executor::Assets, XcmError> {
 		FungiblesTransactor::internal_transfer_asset(what, from, to, context)
 	}
 }
@@ -179,15 +167,15 @@
 >;
 
 pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
-	fn convert(id: AssetIds) -> Option<MultiLocation> {
+impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
+	fn convert(id: AssetId) -> Option<MultiLocation> {
 		match id {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+			AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
 				1,
 				X1(Parachain(ParachainInfo::get().into())),
 			)),
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
-			AssetIds::ForeignAssetId(foreign_asset_id) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
+			AssetId::ForeignAssetId(foreign_asset_id) => {
 				XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
 			}
 		}
@@ -199,11 +187,11 @@
 		if location == MultiLocation::here()
 			|| location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
 		{
-			return Some(AssetIds::NativeAssetId(NativeCurrency::Here));
+			return Some(AssetId::NativeAssetId(NativeCurrency::Here));
 		}
 
 		if location == MultiLocation::parent() {
-			return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
+			return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
 		}
 
 		if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
modifiedruntime/common/config/xcm/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/mod.rs
+++ b/runtime/common/config/xcm/mod.rs
@@ -153,10 +153,10 @@
 		origin: &MultiLocation,
 		message: &mut [Instruction<Call>],
 		max_weight: Weight,
-		weight_credit: &mut Weight,
+		properties: &mut Properties,
 	) -> Result<(), ProcessMessageError> {
 		Deny::try_pass(origin, message)?;
-		Allow::should_execute(origin, message, max_weight, weight_credit)
+		Allow::should_execute(origin, message, max_weight, properties)
 	}
 }
 
@@ -211,7 +211,7 @@
 }
 
 pub struct XcmExecutorConfig<T>(PhantomData<T>);
-impl<T> xcm_executor::Config for XcmExecutorConfig<T>
+impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
 where
 	T: pallet_configuration::Config,
 {
@@ -240,6 +240,7 @@
 	type UniversalAliases = Nothing;
 	type CallDispatcher = RuntimeCall;
 	type SafeCallFilter = XcmCallFilter;
+	type Aliasers = Nothing;
 }
 
 #[cfg(feature = "runtime-benchmarks")]
modifiedruntime/common/config/xcm/nativeassets.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/nativeassets.rs
+++ b/runtime/common/config/xcm/nativeassets.rs
@@ -106,7 +106,12 @@
 		Self(Weight::from_parts(0, 0), Zero::zero(), PhantomData)
 	}
 
-	fn buy_weight(&mut self, _weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+	fn buy_weight(
+		&mut self,
+		_weight: Weight,
+		payment: Assets,
+		_xcm: &XcmContext,
+	) -> Result<Assets, XcmError> {
 		Ok(payment)
 	}
 }
modifiedruntime/common/construct_runtime.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -19,11 +19,7 @@
 	() => {
 		frame_support::construct_runtime! {
 
-			pub enum Runtime where
-				Block = Block,
-				NodeBlock = opaque::Block,
-				UncheckedExtrinsic = UncheckedExtrinsic
-			{
+			pub enum Runtime {
 				System: frame_system = 0,
 				StateTrieMigration: pallet_state_trie_migration = 1,
 
modifiedruntime/common/mod.rsdiffbeforeafterboth
--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -63,12 +63,15 @@
 
 /// The address format for describing accounts.
 pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
-/// Block header type as expected by this runtime.
-pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
-/// Block type as expected by this runtime.
-pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 /// A Block signed with a Justification
 pub type SignedBlock = generic::SignedBlock<Block>;
+/// Frontier wrapped extrinsic
+pub type UncheckedExtrinsic =
+	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
+/// Header type.
+pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
+/// Block type.
+pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 /// BlockId type as expected by this runtime.
 pub type BlockId = generic::BlockId<Block>;
 
@@ -102,14 +105,6 @@
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 	pallet_ethereum::FakeTransactionFinalizer<Runtime>,
 );
-
-/// Unchecked extrinsic type as expected by this runtime.
-pub type UncheckedExtrinsic =
-	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
-
-/// Extrinsic type that has already been checked.
-pub type CheckedExtrinsic =
-	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
 
 /// Executive: handles dispatch to the various modules.
 pub type Executive = frame_executive::Executive<
modifiedruntime/common/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -79,7 +79,7 @@
 		return None;
 	}
 
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection.limits.sponsored_data_rate_limit()?;
 
 	if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {
@@ -123,7 +123,7 @@
 	}
 
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection
 		.limits
 		.sponsor_transfer_timeout(match collection.mode {
@@ -169,7 +169,7 @@
 	properties: &CreateItemData,
 ) -> Option<()> {
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection
 		.limits
 		.sponsor_transfer_timeout(match properties {
@@ -195,7 +195,7 @@
 	item_id: &TokenId,
 ) -> Option<()> {
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection.limits.sponsor_approve_timeout();
 
 	let last_tx_block = match collection.mode {
@@ -307,7 +307,7 @@
 pub trait SponsorshipPredict<T: Config> {
 	fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>
 	where
-		u64: From<<T as frame_system::Config>::BlockNumber>;
+		u64: From<BlockNumberFor<T>>;
 }
 
 pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);
@@ -315,13 +315,13 @@
 impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {
 	fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>
 	where
-		u64: From<<T as frame_system::Config>::BlockNumber>,
+		u64: From<BlockNumberFor<T>>,
 	{
 		let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;
 		let _ = collection.sponsorship.sponsor()?;
 
 		// sponsor timeout
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+		let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 		let limit = collection
 			.limits
 			.sponsor_transfer_timeout(match collection.mode {
modifiedruntime/common/tests/mod.rsdiffbeforeafterboth
--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -51,8 +51,8 @@
 fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
 	let mut storage = make_basic_storage();
 
-	pallet_balances::GenesisConfig::<Runtime> { balances }
-		.assimilate_storage(&mut storage)
+	pallet_balances::BuildGenesisConfig::<Runtime> { balances }
+		.build_storage(&mut storage)
 		.unwrap();
 
 	let mut ext = sp_io::TestExternalities::new(storage);
@@ -94,13 +94,14 @@
 		.map(|acc| get_account_id_from_seed::<sr25519::Public>(acc))
 		.collect::<Vec<_>>();
 
-	let cfg = GenesisConfig {
+	let cfg = BuildGenesisConfig {
 		collator_selection: CollatorSelectionConfig { invulnerables },
 		session: SessionConfig { keys },
 		parachain_info: ParachainInfoConfig {
 			parachain_id: PARA_ID.into(),
+			..Default::default()
 		},
-		..GenesisConfig::default()
+		..Default::default()
 	};
 
 	cfg.build_storage().unwrap()
@@ -110,7 +111,7 @@
 fn make_basic_storage() -> Storage {
 	use crate::AuraConfig;
 
-	let cfg = GenesisConfig {
+	let cfg = BuildGenesisConfig {
 		aura: AuraConfig {
 			authorities: vec![
 				get_from_seed::<AuraId>("Alice"),
@@ -119,8 +120,9 @@
 		},
 		parachain_info: ParachainInfoConfig {
 			parachain_id: PARA_ID.into(),
+			..Default::default()
 		},
-		..GenesisConfig::default()
+		..Default::default()
 	};
 
 	cfg.build_storage().unwrap().into()
modifiedruntime/tests/src/lib.rsdiffbeforeafterboth
--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -57,23 +57,19 @@
 
 // Configure a mock runtime to test the pallet.
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
+	pub enum Test {
 		System: frame_system,
 		Timestamp: pallet_timestamp,
-		Unique: pallet_unique::{Pallet, Call, Storage},
-		Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},
-		Common: pallet_common::{Pallet, Storage, Event<T>},
-		Fungible: pallet_fungible::{Pallet, Storage},
-		Refungible: pallet_refungible::{Pallet, Storage},
-		Nonfungible: pallet_nonfungible::{Pallet, Storage},
-		Structure: pallet_structure::{Pallet, Storage, Event<T>},
-		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>},
-		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin},
-		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},
+		Unique: pallet_unique,
+		Balances: pallet_balances,
+		Common: pallet_common,
+		Fungible: pallet_fungible,
+		Refungible: pallet_refungible,
+		Nonfungible: pallet_nonfungible,
+		Structure: pallet_structure,
+		TransactionPayment: pallet_transaction_payment,
+		Ethereum: pallet_ethereum,
+		EVM: pallet_evm,
 	}
 );
 
@@ -90,13 +86,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
 	type PalletInfo = PalletInfo;
@@ -127,7 +121,6 @@
 	type MaxFreezes = MaxLocks;
 	type FreezeIdentifier = [u8; 8];
 	type MaxHolds = MaxLocks;
-	type HoldIdentifier = [u8; 8];
 }
 
 parameter_types! {
@@ -242,7 +235,6 @@
 	type OnChargeTransaction = ();
 	type FindAuthor = ();
 	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
-	type TransactionValidityHack = ();
 	type Timestamp = Timestamp;
 	type GasLimitPovSizeRatio = ConstU64<0>;
 }