git.delta.rocks / unique-network / refs/commits / 0ee16a462778

difftreelog

feat add PoV estimate

Daniel Shiposha2022-11-21parent: #83762c9.patch.diff
in: master

19 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5362,6 +5362,7 @@
  "substrate-wasm-builder",
  "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
  "up-sponsorship",
  "xcm",
@@ -5806,6 +5807,7 @@
  "sp-runtime",
  "sp-std",
  "up-data-structs",
+ "up-pov-estimate-rpc",
 ]
 
 [[package]]
@@ -8917,6 +8919,7 @@
  "substrate-wasm-builder",
  "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
  "up-sponsorship",
  "xcm",
@@ -12824,18 +12827,31 @@
 dependencies = [
  "anyhow",
  "app-promotion-rpc",
+ "frame-benchmarking",
  "jsonrpsee",
+ "opal-runtime",
  "pallet-common",
  "pallet-evm",
  "parity-scale-codec 3.2.1",
+ "quartz-runtime",
  "rmrk-rpc",
+ "sc-client-api",
+ "sc-executor",
+ "sc-rpc-api",
+ "sc-service",
  "sp-api",
  "sp-blockchain",
  "sp-core",
+ "sp-externalities",
  "sp-rpc",
  "sp-runtime",
+ "sp-state-machine",
+ "unique-runtime",
+ "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
+ "zstd",
 ]
 
 [[package]]
@@ -12978,10 +12994,12 @@
  "substrate-prometheus-endpoint",
  "tokio",
  "try-runtime-cli",
+ "uc-rpc",
  "unique-rpc",
  "unique-runtime",
  "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
 ]
 
@@ -13032,6 +13050,7 @@
  "uc-rpc",
  "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
 ]
 
@@ -13125,6 +13144,7 @@
  "substrate-wasm-builder",
  "up-common",
  "up-data-structs",
+ "up-pov-estimate-rpc",
  "up-rpc",
  "up-sponsorship",
  "xcm",
@@ -13194,6 +13214,19 @@
 ]
 
 [[package]]
+name = "up-pov-estimate-rpc"
+version = "0.1.0"
+dependencies = [
+ "parity-scale-codec 3.2.1",
+ "scale-info",
+ "serde",
+ "sp-api",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
 name = "up-rpc"
 version = "0.1.3"
 dependencies = [
modifiedclient/rpc/Cargo.tomldiffbeforeafterboth
--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -7,16 +7,40 @@
 [dependencies]
 pallet-common = { default-features = false, path = '../../pallets/common' }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
+up-common = { default-features = false, path = '../../primitives/common' }
 up-rpc = { path = "../../primitives/rpc" }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc" }
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc", optional = true }
 codec = { package = "parity-scale-codec", version = "3.1.2" }
 jsonrpsee = { version = "0.16.2", features = ["server", "macros"] }
 anyhow = "1.0.57"
+zstd = { version = "0.11.2", default-features = false }
 
+sc-rpc-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sc-service = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-externalities = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 sp-blockchain = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 sp-rpc = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
 pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
+
+frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+
+sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+
+unique-runtime = { path = '../../runtime/unique', optional = true }
+quartz-runtime = { path = '../../runtime/quartz', optional = true }
+opal-runtime = { path = '../../runtime/opal' }
+
+[features]
+pov-estimate = [
+    'up-pov-estimate-rpc',
+    'unique-runtime?/pov-estimate',
+    'quartz-runtime?/pov-estimate',
+    'opal-runtime/pov-estimate',
+]
modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -42,6 +42,9 @@
 pub use app_promotion_unique_rpc::AppPromotionApiServer;
 pub use rmrk_unique_rpc::RmrkApiServer;
 
+#[cfg(feature = "pov-estimate")]
+pub mod pov_estimate;
+
 #[rpc(server)]
 #[async_trait]
 pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {
@@ -420,17 +423,18 @@
 	}
 }
 
+#[macro_export]
 macro_rules! define_struct_for_server_api {
-	($name:ident) => {
-		pub struct $name<C, P> {
-			client: Arc<C>,
-			_marker: std::marker::PhantomData<P>,
+	($name:ident { $($arg:ident: $arg_ty:ty),+ $(,)? }) => {
+		pub struct $name<Client, Block: BlockT> {
+			$($arg: $arg_ty),+,
+			_marker: std::marker::PhantomData<Block>,
 		}
 
-		impl<C, P> $name<C, P> {
-			pub fn new(client: Arc<C>) -> Self {
+		impl<Client, Block: BlockT> $name<Client, Block> {
+			pub fn new($($arg: $arg_ty),+) -> Self {
 				Self {
-					client,
+					$($arg),+,
 					_marker: Default::default(),
 				}
 			}
@@ -438,9 +442,23 @@
 	};
 }
 
-define_struct_for_server_api!(Unique);
-define_struct_for_server_api!(AppPromotion);
-define_struct_for_server_api!(Rmrk);
+define_struct_for_server_api! {
+	Unique {
+		client: Arc<Client>
+	}
+}
+
+define_struct_for_server_api! {
+	AppPromotion {
+		client: Arc<Client>
+	}
+}
+
+define_struct_for_server_api! {
+	Rmrk {
+		client: Arc<Client>
+	}
+}
 
 macro_rules! pass_method {
 	(
addedclient/rpc/src/pov_estimate.rsdiffbeforeafterboth
--- /dev/null
+++ b/client/rpc/src/pov_estimate.rs
@@ -0,0 +1,205 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use std::sync::Arc;
+
+use codec::Encode;
+
+use up_pov_estimate_rpc::{PovEstimateApi as PovEstimateRuntimeApi};
+use up_common::types::opaque::RuntimeId;
+
+use sc_service::{NativeExecutionDispatch, config::ExecutionStrategy};
+use sp_state_machine::{StateMachine, TrieBackendBuilder};
+
+use jsonrpsee::{
+	core::RpcResult as Result,
+	proc_macros::rpc,
+};
+use anyhow::anyhow;
+
+use sc_client_api::backend::Backend;
+use sp_blockchain::HeaderBackend;
+use sp_api::{AsTrieBackend, BlockId, BlockT, ProvideRuntimeApi};
+
+use sc_executor::NativeElseWasmExecutor;
+use sc_rpc_api::DenyUnsafe;
+
+use sp_runtime::traits::Header;
+
+use up_pov_estimate_rpc::PovInfo;
+
+use crate::define_struct_for_server_api;
+
+type HasherOf<Block> = <<Block as BlockT>::Header as Header>::Hashing;
+type StateOf<Block> = <sc_service::TFullBackend<Block> as Backend<Block>>::State;
+
+pub struct ExecutorParams {
+	pub wasm_method: sc_service::config::WasmExecutionMethod,
+	pub default_heap_pages: Option<u64>,
+	pub max_runtime_instances: usize,
+	pub runtime_cache_size: u8,
+}
+
+#[cfg(feature = "unique-runtime")]
+pub struct UniqueRuntimeExecutor;
+
+#[cfg(feature = "quartz-runtime")]
+pub struct QuartzRuntimeExecutor;
+
+pub struct OpalRuntimeExecutor;
+
+#[cfg(feature = "unique-runtime")]
+impl NativeExecutionDispatch for UniqueRuntimeExecutor {
+	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+
+	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
+		unique_runtime::api::dispatch(method, data)
+	}
+
+	fn native_version() -> sc_executor::NativeVersion {
+		unique_runtime::native_version()
+	}
+}
+
+#[cfg(feature = "quartz-runtime")]
+impl NativeExecutionDispatch for QuartzRuntimeExecutor {
+	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+
+	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
+		quartz_runtime::api::dispatch(method, data)
+	}
+
+	fn native_version() -> sc_executor::NativeVersion {
+		quartz_runtime::native_version()
+	}
+}
+
+impl NativeExecutionDispatch for OpalRuntimeExecutor {
+	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+
+	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
+		opal_runtime::api::dispatch(method, data)
+	}
+
+	fn native_version() -> sc_executor::NativeVersion {
+		opal_runtime::native_version()
+	}
+}
+
+#[cfg(feature = "pov-estimate")]
+define_struct_for_server_api! {
+	PovEstimate {
+		client: Arc<Client>,
+		backend: Arc<sc_service::TFullBackend<Block>>,
+		deny_unsafe: DenyUnsafe,
+		exec_params: ExecutorParams,
+		runtime_id: RuntimeId,
+	}
+}
+
+#[rpc(server)]
+#[async_trait]
+pub trait PovEstimateApi<BlockHash> {
+    #[method(name = "unique_povEstimate")]
+    fn pov_estimate(&self, encoded_xt: Vec<u8>, at: Option<BlockHash>) -> Result<PovInfo>;
+}
+
+#[allow(deprecated)]
+#[cfg(feature = "pov-estimate")]
+impl<C, Block>
+	PovEstimateApiServer<<Block as BlockT>::Hash> for PovEstimate<C, Block>
+where
+	Block: BlockT,
+	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
+	C::Api: PovEstimateRuntimeApi<Block>,
+{
+	fn pov_estimate(&self, encoded_xt: Vec<u8>, at: Option<<Block as BlockT>::Hash>,) -> Result<PovInfo> {
+        self.deny_unsafe.check_if_safe()?;
+
+		let at = BlockId::<Block>::hash(at.unwrap_or_else(|| self.client.info().best_hash));
+		let state = self.backend.state_at(at).map_err(|_| anyhow!("unable to fetch the state at {at:?}"))?;
+        match &self.runtime_id {
+            #[cfg(feature = "unique-runtime")]
+            RuntimeId::Unique => execute_extrinsic_in_sandbox::<Block, UniqueRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+
+            #[cfg(feature = "quartz-runtime")]
+            RuntimeId::Quartz => execute_extrinsic_in_sandbox::<Block, QuartzRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+
+            RuntimeId::Opal => execute_extrinsic_in_sandbox::<Block, OpalRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+
+            runtime_id => Err(anyhow!("unknown runtime id {:?}", runtime_id).into()),
+        }
+	}
+}
+
+fn execute_extrinsic_in_sandbox<Block, D>(state: StateOf<Block>, exec_params: &ExecutorParams, encoded_xt: Vec<u8>) -> Result<PovInfo>
+where
+    Block: BlockT,
+    D: NativeExecutionDispatch + 'static,
+{
+    let backend = state.as_trie_backend().clone();
+    let mut changes = Default::default();
+    let runtime_code_backend = sp_state_machine::backend::BackendRuntimeCode::new(backend);
+
+    let proving_backend =
+        TrieBackendBuilder::wrap(&backend).with_recorder(Default::default()).build();
+
+    let runtime_code = runtime_code_backend.runtime_code()
+        .map_err(|_| anyhow!("runtime code backend creation failed"))?;
+
+    let pre_root = *backend.root();
+
+    let executor = NativeElseWasmExecutor::<D>::new(
+        exec_params.wasm_method,
+        exec_params.default_heap_pages,
+        exec_params.max_runtime_instances,
+        exec_params.runtime_cache_size,
+    );
+    let execution = ExecutionStrategy::NativeElseWasm;
+
+    StateMachine::new(
+        &proving_backend,
+        &mut changes,
+        &executor,
+        "PovEstimateApi_pov_estimate",
+        encoded_xt.as_slice(),
+        sp_externalities::Extensions::default(),
+        &runtime_code,
+        sp_core::testing::TaskExecutor::new(),
+    )
+    .execute(execution.into())
+    .map_err(|e| anyhow!("failed to execute the extrinsic {:?}", e))?;
+
+    let proof = proving_backend
+        .extract_proof()
+        .expect("A recorder was set and thus, a storage proof can be extracted; qed");
+    let proof_size = proof.encoded_size();
+    let compact_proof = proof
+        .clone()
+        .into_compact_proof::<HasherOf<Block>>(pre_root)
+        .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
+    let compact_proof_size = compact_proof.encoded_size();
+
+    let compressed_proof = zstd::stream::encode_all(&compact_proof.encode()[..], 0)
+            .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
+    let compressed_proof_size = compressed_proof.len();
+
+    Ok(PovInfo {
+        proof_size: proof_size as u64,
+        compact_proof_size: compact_proof_size as u64,
+        compressed_proof_size: compressed_proof_size as u64,
+    })
+}
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -319,8 +319,10 @@
 pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
 
 unique-rpc = { default-features = false, path = "../rpc" }
+uc-rpc = { default-features = false, path = "../../client/rpc" }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc", default-features = false }
 
 [features]
 default = ["opal-runtime"]
@@ -339,3 +341,10 @@
     'try-runtime-cli/try-runtime',
 ]
 sapphire-runtime = ['opal-runtime', 'opal-runtime/become-sapphire']
+pov-estimate = [
+    'unique-runtime?/pov-estimate',
+    'quartz-runtime?/pov-estimate',
+    'opal-runtime/pov-estimate',
+    'uc-rpc/pov-estimate',
+    'unique-rpc/pov-estimate',
+]
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -54,17 +54,6 @@
 #[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
 pub type DefaultChainSpec = OpalChainSpec;
 
-pub enum RuntimeId {
-	#[cfg(feature = "unique-runtime")]
-	Unique,
-
-	#[cfg(feature = "quartz-runtime")]
-	Quartz,
-
-	Opal,
-	Unknown(String),
-}
-
 #[cfg(not(feature = "unique-runtime"))]
 /// PARA_ID for Opal/Sapphire/Quartz
 const PARA_ID: u32 = 2095;
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -33,7 +33,7 @@
 // limitations under the License.
 
 use crate::{
-	chain_spec::{self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification},
+	chain_spec::{self, RuntimeIdentification, ServiceId, ServiceIdentification},
 	cli::{Cli, RelayChainCli, Subcommand},
 	service::{new_partial, start_node, start_dev_node},
 };
@@ -66,13 +66,13 @@
 use sp_runtime::traits::{AccountIdConversion, Block as BlockT};
 use std::{net::SocketAddr, time::Duration};
 
-use up_common::types::opaque::Block;
+use up_common::types::opaque::{Block, RuntimeId};
 
 macro_rules! no_runtime_err {
-	($chain_name:expr) => {
+	($runtime_id:expr) => {
 		format!(
-			"No runtime valid runtime was found for chain {}",
-			$chain_name
+			"No runtime valid runtime was found for chain {:#?}",
+			$runtime_id
 		)
 	};
 }
@@ -94,7 +94,7 @@
 				RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),
 
 				RuntimeId::Opal => chain_spec,
-				RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),
+				runtime_id => return Err(no_runtime_err!(runtime_id)),
 			}
 		}
 	})
@@ -147,7 +147,7 @@
 			RuntimeId::Quartz => &quartz_runtime::VERSION,
 
 			RuntimeId::Opal => &opal_runtime::VERSION,
-			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),
+			runtime_id => panic!("{}", no_runtime_err!(runtime_id)),
 		}
 	}
 }
@@ -235,7 +235,7 @@
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
-			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())
+			runtime_id => Err(no_runtime_err!(runtime_id).into())
 		}
 	}}
 }
@@ -274,7 +274,7 @@
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
-			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())
+			runtime_id => Err(no_runtime_err!(runtime_id).into())
 		}
 	}}
 }
@@ -302,7 +302,7 @@
 				OpalRuntimeExecutor,
 			>($config $(, $($args),+)?) $($code)*,
 
-			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),
+			runtime_id => Err(no_runtime_err!(runtime_id).into()),
 		}
 	};
 }
@@ -445,7 +445,7 @@
 							sp_io::SubstrateHostFunctions,
 							<OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
 						>>()),
-						RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),
+						runtime_id => return Err(no_runtime_err!(runtime_id).into()),
 					},
 					task_manager,
 				))
modifiednode/cli/src/service.rsdiffbeforeafterboth
--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -66,9 +66,8 @@
 use fc_rpc_core::types::FilterPool;
 use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};
 
-use up_common::types::opaque::{
-	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,
-};
+use up_common::types::opaque::*;
+use crate::chain_spec::RuntimeIdentification;
 
 // RMRK
 use up_data_structs::{
@@ -412,7 +411,8 @@
 			RmrkBaseInfo<AccountId>,
 			RmrkPartType,
 			RmrkTheme,
-		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+		> + 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>,
@@ -517,9 +517,25 @@
 		.for_each(|()| futures::future::ready(())),
 	);
 
+	let rpc_backend = backend.clone();
+	let runtime_id = parachain_config.chain_spec.runtime_id();
 	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {
 		let full_deps = unique_rpc::FullDeps {
-			backend: rpc_frontier_backend.clone(),
+			#[cfg(feature = "pov-estimate")]
+			runtime_id: runtime_id.clone(),
+
+			#[cfg(feature = "pov-estimate")]
+			exec_params: uc_rpc::pov_estimate::ExecutorParams {
+				wasm_method: parachain_config.wasm_method,
+				default_heap_pages: parachain_config.default_heap_pages,
+				max_runtime_instances: parachain_config.max_runtime_instances,
+				runtime_cache_size: parachain_config.runtime_cache_size,
+			},
+
+			#[cfg(feature = "pov-estimate")]
+			backend: rpc_backend.clone(),
+
+			eth_backend: rpc_frontier_backend.clone(),
 			deny_unsafe,
 			client: rpc_client.clone(),
 			pool: rpc_pool.clone(),
@@ -720,7 +736,8 @@
 			RmrkBaseInfo<AccountId>,
 			RmrkPartType,
 			RmrkTheme,
-		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+		> + 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>
@@ -869,7 +886,8 @@
 			RmrkBaseInfo<AccountId>,
 			RmrkPartType,
 			RmrkTheme,
-		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+		> + 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>
@@ -1040,9 +1058,24 @@
 	let rpc_pool = transaction_pool.clone();
 	let rpc_network = network.clone();
 	let rpc_frontier_backend = frontier_backend.clone();
+	let rpc_backend = backend.clone();
+	let runtime_id = config.chain_spec.runtime_id();
 	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {
 		let full_deps = unique_rpc::FullDeps {
-			backend: rpc_frontier_backend.clone(),
+			#[cfg(feature = "pov-estimate")]
+			runtime_id: runtime_id.clone(),
+
+			#[cfg(feature = "pov-estimate")]
+			exec_params: uc_rpc::pov_estimate::ExecutorParams {
+				wasm_method: config.wasm_method,
+				default_heap_pages: config.default_heap_pages,
+				max_runtime_instances: config.max_runtime_instances,
+				runtime_cache_size: config.runtime_cache_size,
+			},
+
+			#[cfg(feature = "pov-estimate")]
+			backend: rpc_backend.clone(),
+			eth_backend: rpc_frontier_backend.clone(),
 			deny_unsafe,
 			client: rpc_client.clone(),
 			pool: rpc_pool.clone(),
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -55,6 +55,7 @@
 up-rpc = { path = "../../primitives/rpc" }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc" }
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc" }
 up-data-structs = { default-features = false, path = "../../primitives/data-structs" }
 
 [dependencies.serde]
@@ -65,3 +66,4 @@
 default = []
 std = []
 unique-runtime = []
+pov-estimate = ['uc-rpc/pov-estimate']
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -40,7 +40,7 @@
 use sc_service::TransactionPool;
 use std::{collections::BTreeMap, sync::Arc};
 
-use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};
+use up_common::types::opaque::*;
 
 // RMRK
 use up_data_structs::{
@@ -48,6 +48,8 @@
 	RmrkPartType, RmrkTheme,
 };
 
+type FullBackend = sc_service::TFullBackend<Block>;
+
 /// Extra dependencies for GRANDPA
 pub struct GrandpaDeps<B> {
 	/// Voting round info.
@@ -82,8 +84,18 @@
 	pub deny_unsafe: DenyUnsafe,
 	/// EthFilterApi pool.
 	pub filter_pool: Option<FilterPool>,
-	/// Backend.
-	pub backend: Arc<fc_db::Backend<Block>>,
+	
+	#[cfg(feature = "pov-estimate")]
+	pub runtime_id: RuntimeId,
+	/// Executor params for PoV estimating
+	#[cfg(feature = "pov-estimate")]
+	pub exec_params: uc_rpc::pov_estimate::ExecutorParams,
+	/// Substrate Backend.
+	#[cfg(feature = "pov-estimate")]
+	pub backend: Arc<FullBackend>,
+
+	/// Ethereum Backend.
+	pub eth_backend: Arc<fc_db::Backend<Block>>,
 	/// Maximum number of logs in a query.
 	pub max_past_logs: u32,
 	/// Maximum fee history cache size.
@@ -162,6 +174,7 @@
 		RmrkPartType,
 		RmrkTheme,
 	>,
+	C::Api: up_pov_estimate_rpc::PovEstimateApi<Block>,
 	B: sc_client_api::Backend<Block> + Send + Sync + 'static,
 	B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
 	P: TransactionPool<Block = Block> + 'static,
@@ -182,6 +195,9 @@
 	#[cfg(not(feature = "unique-runtime"))]
 	use uc_rpc::{RmrkApiServer, Rmrk};
 
+	#[cfg(feature = "pov-estimate")]
+	use uc_rpc::pov_estimate::{PovEstimateApiServer, PovEstimate};
+
 	// use pallet_contracts_rpc::{Contracts, ContractsApi};
 	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
 	use substrate_frame_rpc_system::{System, SystemApiServer};
@@ -200,7 +216,17 @@
 		network,
 		deny_unsafe,
 		filter_pool,
+
+		#[cfg(feature = "pov-estimate")]
+		runtime_id,
+
+		#[cfg(feature = "pov-estimate")]
+		exec_params,
+
+		#[cfg(feature = "pov-estimate")]
 		backend,
+
+		eth_backend,
 		max_past_logs,
 	} = deps;
 
@@ -226,7 +252,7 @@
 			network.clone(),
 			signers,
 			overrides.clone(),
-			backend.clone(),
+			eth_backend.clone(),
 			is_authority,
 			block_data_cache.clone(),
 			fee_history_cache,
@@ -244,11 +270,14 @@
 	#[cfg(not(feature = "unique-runtime"))]
 	io.merge(Rmrk::new(client.clone()).into_rpc())?;
 
+	#[cfg(feature = "pov-estimate")]
+	io.merge(PovEstimate::new(client.clone(), backend, deny_unsafe, exec_params, runtime_id).into_rpc())?;
+
 	if let Some(filter_pool) = filter_pool {
 		io.merge(
 			EthFilter::new(
 				client.clone(),
-				backend,
+				eth_backend,
 				filter_pool,
 				500_usize, // max stored filters
 				max_past_logs,
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -23,6 +23,7 @@
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
 ethereum = { version = "0.14.0", default-features = false }
 pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
+up-pov-estimate-rpc = { default-features = false, path = "../../primitives/pov-estimate-rpc" }
 
 serde = { version = "1.0.130", default-features = false }
 scale-info = { version = "2.0.1", default-features = false, features = [
@@ -39,6 +40,7 @@
     "fp-evm-mapping/std",
     "up-data-structs/std",
     "pallet-evm/std",
+    "up-pov-estimate-rpc/std",
 ]
 runtime-benchmarks = [
     "frame-benchmarking/runtime-benchmarks",
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::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			)))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			)))204	}205206	/// Consume gas for reading and writing.207	pub fn consume_store_reads_and_writes(208		&self,209		reads: u64,210		writes: u64,211	) -> evm_coder::execution::Result<()> {212		let weight = <T as frame_system::Config>::DbWeight::get();213		let reads = weight.read.saturating_mul(reads);214		let writes = weight.read.saturating_mul(writes);215		self.recorder216			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217				reads.saturating_add(writes),218			)))219	}220221	/// Save collection to storage.222	pub fn save(&self) -> DispatchResult {223		<CollectionById<T>>::insert(self.id, &self.collection);224		Ok(())225	}226227	/// Set collection sponsor.228	///229	/// Unique collections allows sponsoring for certain actions.230	/// This method allows you to set the sponsor of the collection.231	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232	pub fn set_sponsor(233		&mut self,234		sender: &T::CrossAccountId,235		sponsor: T::AccountId,236	) -> DispatchResult {237		self.check_is_internal()?;238		self.check_is_owner_or_admin(sender)?;239240		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());241242		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));243		<PalletEvm<T>>::deposit_log(244			erc::CollectionHelpersEvents::CollectionChanged {245				collection_id: eth::collection_id_to_address(self.id),246			}247			.to_log(T::ContractAddress::get()),248		);249250		self.save()251	}252253	/// Force set `sponsor`.254	///255	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation256	/// from the `sponsor` is not required.257	///258	/// # Arguments259	///260	/// * `sender`: Caller's account.261	/// * `sponsor`: ID of the account of the sponsor-to-be.262	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {263		self.check_is_internal()?;264265		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());266267		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));268		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));269		<PalletEvm<T>>::deposit_log(270			erc::CollectionHelpersEvents::CollectionChanged {271				collection_id: eth::collection_id_to_address(self.id),272			}273			.to_log(T::ContractAddress::get()),274		);275276		self.save()277	}278279	/// Confirm sponsorship280	///281	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.282	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].283	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {284		self.check_is_internal()?;285		ensure!(286			self.collection.sponsorship.pending_sponsor() == Some(sender),287			Error::<T>::ConfirmSponsorshipFail288		);289290		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());291292		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));293		<PalletEvm<T>>::deposit_log(294			erc::CollectionHelpersEvents::CollectionChanged {295				collection_id: eth::collection_id_to_address(self.id),296			}297			.to_log(T::ContractAddress::get()),298		);299300		self.save()301	}302303	/// Remove collection sponsor.304	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {305		self.check_is_internal()?;306		self.check_is_owner_or_admin(sender)?;307308		self.collection.sponsorship = SponsorshipState::Disabled;309310		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));311		<PalletEvm<T>>::deposit_log(312			erc::CollectionHelpersEvents::CollectionChanged {313				collection_id: eth::collection_id_to_address(self.id),314			}315			.to_log(T::ContractAddress::get()),316		);317		self.save()318	}319320	/// Force remove `sponsor`.321	///322	/// Differs from `remove_sponsor` in that323	/// it doesn't require consent from the `owner` of the collection.324	pub fn force_remove_sponsor(&mut self) -> DispatchResult {325		self.check_is_internal()?;326327		self.collection.sponsorship = SponsorshipState::Disabled;328329		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));330		<PalletEvm<T>>::deposit_log(331			erc::CollectionHelpersEvents::CollectionChanged {332				collection_id: eth::collection_id_to_address(self.id),333			}334			.to_log(T::ContractAddress::get()),335		);336		self.save()337	}338339	/// Checks that the collection was created with, and must be operated upon through **Unique API**.340	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.341	pub fn check_is_internal(&self) -> DispatchResult {342		if self.flags.external {343			return Err(<Error<T>>::CollectionIsExternal)?;344		}345346		Ok(())347	}348349	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.350	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.351	pub fn check_is_external(&self) -> DispatchResult {352		if !self.flags.external {353			return Err(<Error<T>>::CollectionIsInternal)?;354		}355356		Ok(())357	}358}359360impl<T: Config> Deref for CollectionHandle<T> {361	type Target = Collection<T::AccountId>;362363	fn deref(&self) -> &Self::Target {364		&self.collection365	}366}367368impl<T: Config> DerefMut for CollectionHandle<T> {369	fn deref_mut(&mut self) -> &mut Self::Target {370		&mut self.collection371	}372}373374impl<T: Config> CollectionHandle<T> {375	/// Checks if the `user` is the owner of the collection.376	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {377		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);378		Ok(())379	}380381	/// Returns **true** if the `user` is the owner or administrator of the collection.382	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {383		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))384	}385386	/// Checks if the `user` is the owner or administrator of the collection.387	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {388		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);389		Ok(())390	}391392	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.393	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {394		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)395	}396397	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.398	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {399		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)400	}401402	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.403	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {404		ensure!(405			<Allowlist<T>>::get((self.id, user)),406			<Error<T>>::AddressNotInAllowlist407		);408		Ok(())409	}410411	/// Changes collection owner to another account412	/// #### Store read/writes413	/// 1 writes414	pub fn change_owner(415		&mut self,416		caller: T::CrossAccountId,417		new_owner: T::CrossAccountId,418	) -> DispatchResult {419		self.check_is_internal()?;420		self.check_is_owner(&caller)?;421		self.collection.owner = new_owner.as_sub().clone();422423		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(424			self.id,425			new_owner.as_sub().clone(),426		));427		<PalletEvm<T>>::deposit_log(428			erc::CollectionHelpersEvents::CollectionChanged {429				collection_id: eth::collection_id_to_address(self.id),430			}431			.to_log(T::ContractAddress::get()),432		);433434		self.save()435	}436}437438#[frame_support::pallet]439pub mod pallet {440	use super::*;441	use dispatch::CollectionDispatch;442	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};443	use frame_system::pallet_prelude::*;444	use frame_support::traits::Currency;445	use up_data_structs::{TokenId, mapping::TokenAddressMapping};446	use scale_info::TypeInfo;447	use weights::WeightInfo;448449	#[pallet::config]450	pub trait Config:451		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo452	{453		/// Weight information for functions of this pallet.454		type WeightInfo: WeightInfo;455456		/// Events compatible with [`frame_system::Config::Event`].457		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;458459		/// Handler of accounts and payment.460		type Currency: Currency<Self::AccountId>;461462		/// Set price to create a collection.463		#[pallet::constant]464		type CollectionCreationPrice: Get<465			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,466		>;467468		/// Dispatcher of operations on collections.469		type CollectionDispatch: CollectionDispatch<Self>;470471		/// Account which holds the chain's treasury.472		type TreasuryAccountId: Get<Self::AccountId>;473474		/// Address under which the CollectionHelper contract would be available.475		#[pallet::constant]476		type ContractAddress: Get<H160>;477478		/// Mapper for token addresses to Ethereum addresses.479		type EvmTokenAddressMapping: TokenAddressMapping<H160>;480481		/// Mapper for token addresses to [`CrossAccountId`].482		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;483	}484485	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);486487	#[pallet::pallet]488	#[pallet::storage_version(STORAGE_VERSION)]489	#[pallet::generate_store(pub(super) trait Store)]490	pub struct Pallet<T>(_);491492	#[pallet::extra_constants]493	impl<T: Config> Pallet<T> {494		/// Maximum admins per collection.495		pub fn collection_admins_limit() -> u32 {496			COLLECTION_ADMINS_LIMIT497		}498	}499500	#[pallet::event]501	#[pallet::generate_deposit(pub fn deposit_event)]502	pub enum Event<T: Config> {503		/// New collection was created504		CollectionCreated(505			/// Globally unique identifier of newly created collection.506			CollectionId,507			/// [`CollectionMode`] converted into _u8_.508			u8,509			/// Collection owner.510			T::AccountId,511		),512513		/// New collection was destroyed514		CollectionDestroyed(515			/// Globally unique identifier of collection.516			CollectionId,517		),518519		/// New item was created.520		ItemCreated(521			/// Id of the collection where item was created.522			CollectionId,523			/// Id of an item. Unique within the collection.524			TokenId,525			/// Owner of newly created item526			T::CrossAccountId,527			/// Always 1 for NFT528			u128,529		),530531		/// Collection item was burned.532		ItemDestroyed(533			/// Id of the collection where item was destroyed.534			CollectionId,535			/// Identifier of burned NFT.536			TokenId,537			/// Which user has destroyed its tokens.538			T::CrossAccountId,539			/// Amount of token pieces destroed. Always 1 for NFT.540			u128,541		),542543		/// Item was transferred544		Transfer(545			/// Id of collection to which item is belong.546			CollectionId,547			/// Id of an item.548			TokenId,549			/// Original owner of item.550			T::CrossAccountId,551			/// New owner of item.552			T::CrossAccountId,553			/// Amount of token pieces transfered. Always 1 for NFT.554			u128,555		),556557		/// Amount pieces of token owned by `sender` was approved for `spender`.558		Approved(559			/// Id of collection to which item is belong.560			CollectionId,561			/// Id of an item.562			TokenId,563			/// Original owner of item.564			T::CrossAccountId,565			/// Id for which the approval was granted.566			T::CrossAccountId,567			/// Amount of token pieces transfered. Always 1 for NFT.568			u128,569		),570571		/// A `sender` approves operations on all owned tokens for `spender`.572		ApprovedForAll(573			/// Id of collection to which item is belong.574			CollectionId,575			/// Owner of a wallet.576			T::CrossAccountId,577			/// Id for which operator status was granted or rewoked.578			T::CrossAccountId,579			/// Is operator status granted or revoked?580			bool,581		),582583		/// The colletion property has been added or edited.584		CollectionPropertySet(585			/// Id of collection to which property has been set.586			CollectionId,587			/// The property that was set.588			PropertyKey,589		),590591		/// The property has been deleted.592		CollectionPropertyDeleted(593			/// Id of collection to which property has been deleted.594			CollectionId,595			/// The property that was deleted.596			PropertyKey,597		),598599		/// The token property has been added or edited.600		TokenPropertySet(601			/// Identifier of the collection whose token has the property set.602			CollectionId,603			/// The token for which the property was set.604			TokenId,605			/// The property that was set.606			PropertyKey,607		),608609		/// The token property has been deleted.610		TokenPropertyDeleted(611			/// Identifier of the collection whose token has the property deleted.612			CollectionId,613			/// The token for which the property was deleted.614			TokenId,615			/// The property that was deleted.616			PropertyKey,617		),618619		/// The token property permission of a collection has been set.620		PropertyPermissionSet(621			/// ID of collection to which property permission has been set.622			CollectionId,623			/// The property permission that was set.624			PropertyKey,625		),626627		/// Address was added to the allow list.628		AllowListAddressAdded(629			/// ID of the affected collection.630			CollectionId,631			/// Address of the added account.632			T::CrossAccountId,633		),634635		/// Address was removed from the allow list.636		AllowListAddressRemoved(637			/// ID of the affected collection.638			CollectionId,639			/// Address of the removed account.640			T::CrossAccountId,641		),642643		/// Collection admin was added.644		CollectionAdminAdded(645			/// ID of the affected collection.646			CollectionId,647			/// Admin address.648			T::CrossAccountId,649		),650651		/// Collection admin was removed.652		CollectionAdminRemoved(653			/// ID of the affected collection.654			CollectionId,655			/// Removed admin address.656			T::CrossAccountId,657		),658659		/// Collection limits were set.660		CollectionLimitSet(661			/// ID of the affected collection.662			CollectionId,663		),664665		/// Collection owned was changed.666		CollectionOwnerChanged(667			/// ID of the affected collection.668			CollectionId,669			/// New owner address.670			T::AccountId,671		),672673		/// Collection permissions were set.674		CollectionPermissionSet(675			/// ID of the affected collection.676			CollectionId,677		),678679		/// Collection sponsor was set.680		CollectionSponsorSet(681			/// ID of the affected collection.682			CollectionId,683			/// New sponsor address.684			T::AccountId,685		),686687		/// New sponsor was confirm.688		SponsorshipConfirmed(689			/// ID of the affected collection.690			CollectionId,691			/// New sponsor address.692			T::AccountId,693		),694695		/// Collection sponsor was removed.696		CollectionSponsorRemoved(697			/// ID of the affected collection.698			CollectionId,699		),700	}701702	#[pallet::error]703	pub enum Error<T> {704		/// This collection does not exist.705		CollectionNotFound,706		/// Sender parameter and item owner must be equal.707		MustBeTokenOwner,708		/// No permission to perform action709		NoPermission,710		/// Destroying only empty collections is allowed711		CantDestroyNotEmptyCollection,712		/// Collection is not in mint mode.713		PublicMintingNotAllowed,714		/// Address is not in allow list.715		AddressNotInAllowlist,716717		/// Collection name can not be longer than 63 char.718		CollectionNameLimitExceeded,719		/// Collection description can not be longer than 255 char.720		CollectionDescriptionLimitExceeded,721		/// Token prefix can not be longer than 15 char.722		CollectionTokenPrefixLimitExceeded,723		/// Total collections bound exceeded.724		TotalCollectionsLimitExceeded,725		/// Exceeded max admin count726		CollectionAdminCountExceeded,727		/// Collection limit bounds per collection exceeded728		CollectionLimitBoundsExceeded,729		/// Tried to enable permissions which are only permitted to be disabled730		OwnerPermissionsCantBeReverted,731		/// Collection settings not allowing items transferring732		TransferNotAllowed,733		/// Account token limit exceeded per collection734		AccountTokenLimitExceeded,735		/// Collection token limit exceeded736		CollectionTokenLimitExceeded,737		/// Metadata flag frozen738		MetadataFlagFrozen,739740		/// Item does not exist741		TokenNotFound,742		/// Item is balance not enough743		TokenValueTooLow,744		/// Requested value is more than the approved745		ApprovedValueTooLow,746		/// Tried to approve more than owned747		CantApproveMoreThanOwned,748749		/// Can't transfer tokens to ethereum zero address750		AddressIsZero,751752		/// The operation is not supported753		UnsupportedOperation,754755		/// Insufficient funds to perform an action756		NotSufficientFounds,757758		/// User does not satisfy the nesting rule759		UserIsNotAllowedToNest,760		/// Only tokens from specific collections may nest tokens under this one761		SourceCollectionIsNotAllowedToNest,762763		/// Tried to store more data than allowed in collection field764		CollectionFieldSizeExceeded,765766		/// Tried to store more property data than allowed767		NoSpaceForProperty,768769		/// Tried to store more property keys than allowed770		PropertyLimitReached,771772		/// Property key is too long773		PropertyKeyIsTooLong,774775		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed776		InvalidCharacterInPropertyKey,777778		/// Empty property keys are forbidden779		EmptyPropertyKey,780781		/// Tried to access an external collection with an internal API782		CollectionIsExternal,783784		/// Tried to access an internal collection with an external API785		CollectionIsInternal,786787		/// This address is not set as sponsor, use setCollectionSponsor first.788		ConfirmSponsorshipFail,789790		/// The user is not an administrator.791		UserIsNotCollectionAdmin,792	}793794	/// Storage of the count of created collections. Essentially contains the last collection ID.795	#[pallet::storage]796	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;797798	/// Storage of the count of deleted collections.799	#[pallet::storage]800	pub type DestroyedCollectionCount<T> =801		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;802803	/// Storage of collection info.804	#[pallet::storage]805	pub type CollectionById<T> = StorageMap<806		Hasher = Blake2_128Concat,807		Key = CollectionId,808		Value = Collection<<T as frame_system::Config>::AccountId>,809		QueryKind = OptionQuery,810	>;811812	/// Storage of collection properties.813	#[pallet::storage]814	#[pallet::getter(fn collection_properties)]815	pub type CollectionProperties<T> = StorageMap<816		Hasher = Blake2_128Concat,817		Key = CollectionId,818		Value = Properties,819		QueryKind = ValueQuery,820		OnEmpty = up_data_structs::CollectionProperties,821	>;822823	/// Storage of token property permissions of a collection.824	#[pallet::storage]825	#[pallet::getter(fn property_permissions)]826	pub type CollectionPropertyPermissions<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = PropertiesPermissionMap,830		QueryKind = ValueQuery,831	>;832833	/// Storage of the amount of collection admins.834	#[pallet::storage]835	pub type AdminAmount<T> = StorageMap<836		Hasher = Blake2_128Concat,837		Key = CollectionId,838		Value = u32,839		QueryKind = ValueQuery,840	>;841842	/// List of collection admins.843	#[pallet::storage]844	pub type IsAdmin<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	/// Allowlisted collection users.854	#[pallet::storage]855	pub type Allowlist<T: Config> = StorageNMap<856		Key = (857			Key<Blake2_128Concat, CollectionId>,858			Key<Blake2_128Concat, T::CrossAccountId>,859		),860		Value = bool,861		QueryKind = ValueQuery,862	>;863864	/// Not used by code, exists only to provide some types to metadata.865	#[pallet::storage]866	pub type DummyStorageValue<T: Config> = StorageValue<867		Value = (868			CollectionStats,869			CollectionId,870			TokenId,871			TokenChild,872			PhantomType<(873				TokenData<T::CrossAccountId>,874				RpcCollection<T::AccountId>,875				// RMRK876				RmrkCollectionInfo<T::AccountId>,877				RmrkInstanceInfo<T::AccountId>,878				RmrkResourceInfo,879				RmrkPropertyInfo,880				RmrkBaseInfo<T::AccountId>,881				RmrkPartType,882				RmrkBoundedTheme,883				RmrkNftChild,884			)>,885		),886		QueryKind = OptionQuery,887	>;888889	#[pallet::hooks]890	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {891		fn on_runtime_upgrade() -> Weight {892			StorageVersion::new(1).put::<Pallet<T>>();893894			Weight::zero()895		}896	}897}898899impl<T: Config> Pallet<T> {900	/// Enshure that receiver address is correct.901	///902	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.903	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {904		ensure!(905			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,906			<Error<T>>::AddressIsZero907		);908		Ok(())909	}910911	/// Get a vector of collection admins.912	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {913		<IsAdmin<T>>::iter_prefix((collection,))914			.map(|(a, _)| a)915			.collect()916	}917918	/// Get a vector of users allowed to mint tokens.919	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {920		<Allowlist<T>>::iter_prefix((collection,))921			.map(|(a, _)| a)922			.collect()923	}924925	/// Is `user` allowed to mint token in `collection`.926	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {927		<Allowlist<T>>::get((collection, user))928	}929930	/// Get statistics of collections.931	pub fn collection_stats() -> CollectionStats {932		let created = <CreatedCollectionCount<T>>::get();933		let destroyed = <DestroyedCollectionCount<T>>::get();934		CollectionStats {935			created: created.0,936			destroyed: destroyed.0,937			alive: created.0 - destroyed.0,938		}939	}940941	/// Get the effective limits for the collection.942	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {943		let collection = <CollectionById<T>>::get(collection)?;944		let limits = collection.limits;945		let effective_limits = CollectionLimits {946			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),947			sponsored_data_size: Some(limits.sponsored_data_size()),948			sponsored_data_rate_limit: Some(949				limits950					.sponsored_data_rate_limit951					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),952			),953			token_limit: Some(limits.token_limit()),954			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(955				match collection.mode {956					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,957					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,958					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,959				},960			)),961			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),962			owner_can_transfer: Some(limits.owner_can_transfer()),963			owner_can_destroy: Some(limits.owner_can_destroy()),964			transfers_enabled: Some(limits.transfers_enabled()),965		};966967		Some(effective_limits)968	}969970	/// Returns information about the `collection` adapted for rpc.971	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {972		let Collection {973			name,974			description,975			owner,976			mode,977			token_prefix,978			sponsorship,979			limits,980			permissions,981			flags,982		} = <CollectionById<T>>::get(collection)?;983984		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)985			.into_iter()986			.map(|(key, permission)| PropertyKeyPermission { key, permission })987			.collect();988989		let properties = <CollectionProperties<T>>::get(collection)990			.into_iter()991			.map(|(key, value)| Property { key, value })992			.collect();993994		let permissions = CollectionPermissions {995			access: Some(permissions.access()),996			mint_mode: Some(permissions.mint_mode()),997			nesting: Some(permissions.nesting().clone()),998		};9991000		Some(RpcCollection {1001			name: name.into_inner(),1002			description: description.into_inner(),1003			owner,1004			mode,1005			token_prefix: token_prefix.into_inner(),1006			sponsorship,1007			limits,1008			permissions,1009			token_property_permissions,1010			properties,1011			read_only: flags.external,10121013			flags: RpcCollectionFlags {1014				foreign: flags.foreign,1015				erc721metadata: flags.erc721metadata,1016			},1017		})1018	}1019}10201021macro_rules! limit_default {1022	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1023		$(1024			if let Some($new) = $new.$field {1025				let $old = $old.$field($($arg)?);1026				let _ = $new;1027				let _ = $old;1028				$check1029			} else {1030				$new.$field = $old.$field1031			}1032		)*1033	}};1034}1035macro_rules! limit_default_clone {1036	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1037		$(1038			if let Some($new) = $new.$field.clone() {1039				let $old = $old.$field($($arg)?);1040				let _ = $new;1041				let _ = $old;1042				$check1043			} else {1044				$new.$field = $old.$field.clone()1045			}1046		)*1047	}};1048}10491050impl<T: Config> Pallet<T> {1051	/// Create new collection.1052	///1053	/// * `owner` - The owner of the collection.1054	/// * `data` - Description of the created collection.1055	/// * `flags` - Extra flags to store.1056	pub fn init_collection(1057		owner: T::CrossAccountId,1058		payer: T::CrossAccountId,1059		data: CreateCollectionData<T::AccountId>,1060		flags: CollectionFlags,1061	) -> Result<CollectionId, DispatchError> {1062		{1063			ensure!(1064				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1065				Error::<T>::CollectionTokenPrefixLimitExceeded1066			);1067		}10681069		let created_count = <CreatedCollectionCount<T>>::get()1070			.01071			.checked_add(1)1072			.ok_or(ArithmeticError::Overflow)?;1073		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1074		let id = CollectionId(created_count);10751076		// bound Total number of collections1077		ensure!(1078			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1079			<Error<T>>::TotalCollectionsLimitExceeded1080		);10811082		// =========10831084		let collection = Collection {1085			owner: owner.as_sub().clone(),1086			name: data.name,1087			mode: data.mode.clone(),1088			description: data.description,1089			token_prefix: data.token_prefix,1090			sponsorship: data1091				.pending_sponsor1092				.map(SponsorshipState::Unconfirmed)1093				.unwrap_or_default(),1094			limits: data1095				.limits1096				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1097				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1098			permissions: data1099				.permissions1100				.map(|permissions| {1101					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1102				})1103				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1104			flags,1105		};11061107		let mut collection_properties = up_data_structs::CollectionProperties::get();1108		collection_properties1109			.try_set_from_iter(data.properties.into_iter())1110			.map_err(<Error<T>>::from)?;11111112		CollectionProperties::<T>::insert(id, collection_properties);11131114		let mut token_props_permissions = PropertiesPermissionMap::new();1115		token_props_permissions1116			.try_set_from_iter(data.token_property_permissions.into_iter())1117			.map_err(<Error<T>>::from)?;11181119		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11201121		// Take a (non-refundable) deposit of collection creation1122		{1123			let mut imbalance =1124				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1125			imbalance.subsume(1126				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1127					&T::TreasuryAccountId::get(),1128					T::CollectionCreationPrice::get(),1129				),1130			);1131			<T as Config>::Currency::settle(1132				payer.as_sub(),1133				imbalance,1134				WithdrawReasons::TRANSFER,1135				ExistenceRequirement::KeepAlive,1136			)1137			.map_err(|_| Error::<T>::NotSufficientFounds)?;1138		}11391140		<CreatedCollectionCount<T>>::put(created_count);1141		<Pallet<T>>::deposit_event(Event::CollectionCreated(1142			id,1143			data.mode.id(),1144			owner.as_sub().clone(),1145		));1146		<PalletEvm<T>>::deposit_log(1147			erc::CollectionHelpersEvents::CollectionCreated {1148				owner: *owner.as_eth(),1149				collection_id: eth::collection_id_to_address(id),1150			}1151			.to_log(T::ContractAddress::get()),1152		);1153		<CollectionById<T>>::insert(id, collection);1154		Ok(id)1155	}11561157	/// Destroy collection.1158	///1159	/// * `collection` - Collection handler.1160	/// * `sender` - The owner or administrator of the collection.1161	pub fn destroy_collection(1162		collection: CollectionHandle<T>,1163		sender: &T::CrossAccountId,1164	) -> DispatchResult {1165		ensure!(1166			collection.limits.owner_can_destroy(),1167			<Error<T>>::NoPermission,1168		);1169		collection.check_is_owner(sender)?;11701171		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1172			.01173			.checked_add(1)1174			.ok_or(ArithmeticError::Overflow)?;11751176		// =========11771178		<DestroyedCollectionCount<T>>::put(destroyed_collections);1179		<CollectionById<T>>::remove(collection.id);1180		<AdminAmount<T>>::remove(collection.id);1181		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1182		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1183		<CollectionProperties<T>>::remove(collection.id);11841185		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11861187		<PalletEvm<T>>::deposit_log(1188			erc::CollectionHelpersEvents::CollectionDestroyed {1189				collection_id: eth::collection_id_to_address(collection.id),1190			}1191			.to_log(T::ContractAddress::get()),1192		);1193		Ok(())1194	}11951196	/// Set collection property.1197	///1198	/// * `collection` - Collection handler.1199	/// * `sender` - The owner or administrator of the collection.1200	/// * `property` - The property to set.1201	pub fn set_collection_property(1202		collection: &CollectionHandle<T>,1203		sender: &T::CrossAccountId,1204		property: Property,1205	) -> DispatchResult {1206		collection.check_is_owner_or_admin(sender)?;12071208		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1209			let property = property.clone();1210			properties.try_set(property.key, property.value)1211		})1212		.map_err(<Error<T>>::from)?;12131214		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1215		<PalletEvm<T>>::deposit_log(1216			erc::CollectionHelpersEvents::CollectionChanged {1217				collection_id: eth::collection_id_to_address(collection.id),1218			}1219			.to_log(T::ContractAddress::get()),1220		);12211222		Ok(())1223	}12241225	/// Set a scoped collection property, where the scope is a special prefix1226	/// prohibiting a user access to change the property directly.1227	///1228	/// * `collection_id` - ID of the collection for which the property is being set.1229	/// * `scope` - Property scope.1230	/// * `property` - The property to set.1231	pub fn set_scoped_collection_property(1232		collection_id: CollectionId,1233		scope: PropertyScope,1234		property: Property,1235	) -> DispatchResult {1236		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1237			properties.try_scoped_set(scope, property.key, property.value)1238		})1239		.map_err(<Error<T>>::from)?;12401241		Ok(())1242	}12431244	/// Set scoped collection properties, where the scope is a special prefix1245	/// prohibiting a user access to change the properties directly.1246	///1247	/// * `collection_id` - ID of the collection for which the properties is being set.1248	/// * `scope` - Property scope.1249	/// * `properties` - The properties to set.1250	pub fn set_scoped_collection_properties(1251		collection_id: CollectionId,1252		scope: PropertyScope,1253		properties: impl Iterator<Item = Property>,1254	) -> DispatchResult {1255		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1256			stored_properties.try_scoped_set_from_iter(scope, properties)1257		})1258		.map_err(<Error<T>>::from)?;12591260		Ok(())1261	}12621263	/// Set collection properties.1264	///1265	/// * `collection` - Collection handler.1266	/// * `sender` - The owner or administrator of the collection.1267	/// * `properties` - The properties to set.1268	#[transactional]1269	pub fn set_collection_properties(1270		collection: &CollectionHandle<T>,1271		sender: &T::CrossAccountId,1272		properties: Vec<Property>,1273	) -> DispatchResult {1274		for property in properties {1275			Self::set_collection_property(collection, sender, property)?;1276		}12771278		Ok(())1279	}12801281	/// Delete collection property.1282	///1283	/// * `collection` - Collection handler.1284	/// * `sender` - The owner or administrator of the collection.1285	/// * `property` - The property to delete.1286	pub fn delete_collection_property(1287		collection: &CollectionHandle<T>,1288		sender: &T::CrossAccountId,1289		property_key: PropertyKey,1290	) -> DispatchResult {1291		collection.check_is_owner_or_admin(sender)?;12921293		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1294			properties.remove(&property_key)1295		})1296		.map_err(<Error<T>>::from)?;12971298		Self::deposit_event(Event::CollectionPropertyDeleted(1299			collection.id,1300			property_key,1301		));1302		<PalletEvm<T>>::deposit_log(1303			erc::CollectionHelpersEvents::CollectionChanged {1304				collection_id: eth::collection_id_to_address(collection.id),1305			}1306			.to_log(T::ContractAddress::get()),1307		);13081309		Ok(())1310	}13111312	/// Delete collection properties.1313	///1314	/// * `collection` - Collection handler.1315	/// * `sender` - The owner or administrator of the collection.1316	/// * `properties` - The properties to delete.1317	#[transactional]1318	pub fn delete_collection_properties(1319		collection: &CollectionHandle<T>,1320		sender: &T::CrossAccountId,1321		property_keys: Vec<PropertyKey>,1322	) -> DispatchResult {1323		for key in property_keys {1324			Self::delete_collection_property(collection, sender, key)?;1325		}13261327		Ok(())1328	}13291330	/// Set collection propetry permission without any checks.1331	///1332	/// Used for migrations.1333	///1334	/// * `collection` - Collection handler.1335	/// * `property_permissions` - Property permissions.1336	pub fn set_property_permission_unchecked(1337		collection: CollectionId,1338		property_permission: PropertyKeyPermission,1339	) -> DispatchResult {1340		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1341			permissions.try_set(property_permission.key, property_permission.permission)1342		})1343		.map_err(<Error<T>>::from)?;1344		Ok(())1345	}13461347	/// Set collection property permission.1348	///1349	/// * `collection` - Collection handler.1350	/// * `sender` - The owner or administrator of the collection.1351	/// * `property_permission` - Property permission.1352	pub fn set_property_permission(1353		collection: &CollectionHandle<T>,1354		sender: &T::CrossAccountId,1355		property_permission: PropertyKeyPermission,1356	) -> DispatchResult {1357		Self::set_scoped_property_permission(1358			collection,1359			sender,1360			PropertyScope::None,1361			property_permission,1362		)1363	}13641365	/// Set collection property permission with scope.1366	///1367	/// * `collection` - Collection handler.1368	/// * `sender` - The owner or administrator of the collection.1369	/// * `scope` - Property scope.1370	/// * `property_permission` - Property permission.1371	pub fn set_scoped_property_permission(1372		collection: &CollectionHandle<T>,1373		sender: &T::CrossAccountId,1374		scope: PropertyScope,1375		property_permission: PropertyKeyPermission,1376	) -> DispatchResult {1377		collection.check_is_owner_or_admin(sender)?;13781379		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1380		let current_permission = all_permissions.get(&property_permission.key);1381		if matches![1382			current_permission,1383			Some(PropertyPermission { mutable: false, .. })1384		] {1385			return Err(<Error<T>>::NoPermission.into());1386		}13871388		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1389			let property_permission = property_permission.clone();1390			permissions.try_scoped_set(1391				scope,1392				property_permission.key,1393				property_permission.permission,1394			)1395		})1396		.map_err(<Error<T>>::from)?;13971398		Self::deposit_event(Event::PropertyPermissionSet(1399			collection.id,1400			property_permission.key,1401		));1402		<PalletEvm<T>>::deposit_log(1403			erc::CollectionHelpersEvents::CollectionChanged {1404				collection_id: eth::collection_id_to_address(collection.id),1405			}1406			.to_log(T::ContractAddress::get()),1407		);14081409		Ok(())1410	}14111412	/// Set token property permission.1413	///1414	/// * `collection` - Collection handler.1415	/// * `sender` - The owner or administrator of the collection.1416	/// * `property_permissions` - Property permissions.1417	#[transactional]1418	pub fn set_token_property_permissions(1419		collection: &CollectionHandle<T>,1420		sender: &T::CrossAccountId,1421		property_permissions: Vec<PropertyKeyPermission>,1422	) -> DispatchResult {1423		Self::set_scoped_token_property_permissions(1424			collection,1425			sender,1426			PropertyScope::None,1427			property_permissions,1428		)1429	}14301431	/// Set token property permission with scope.1432	///1433	/// * `collection` - Collection handler.1434	/// * `sender` - The owner or administrator of the collection.1435	/// * `scope` - Property scope.1436	/// * `property_permissions` - Property permissions.1437	#[transactional]1438	pub fn set_scoped_token_property_permissions(1439		collection: &CollectionHandle<T>,1440		sender: &T::CrossAccountId,1441		scope: PropertyScope,1442		property_permissions: Vec<PropertyKeyPermission>,1443	) -> DispatchResult {1444		for prop_pemission in property_permissions {1445			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1446		}14471448		Ok(())1449	}14501451	/// Get collection property.1452	pub fn get_collection_property(1453		collection_id: CollectionId,1454		key: &PropertyKey,1455	) -> Option<PropertyValue> {1456		Self::collection_properties(collection_id).get(key).cloned()1457	}14581459	/// Convert byte vector to property key vector.1460	pub fn bytes_keys_to_property_keys(1461		keys: Vec<Vec<u8>>,1462	) -> Result<Vec<PropertyKey>, DispatchError> {1463		keys.into_iter()1464			.map(|key| -> Result<PropertyKey, DispatchError> {1465				key.try_into()1466					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1467			})1468			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1469	}14701471	/// Get properties according to given keys.1472	pub fn filter_collection_properties(1473		collection_id: CollectionId,1474		keys: Option<Vec<PropertyKey>>,1475	) -> Result<Vec<Property>, DispatchError> {1476		let properties = Self::collection_properties(collection_id);14771478		let properties = keys1479			.map(|keys| {1480				keys.into_iter()1481					.filter_map(|key| {1482						properties.get(&key).map(|value| Property {1483							key,1484							value: value.clone(),1485						})1486					})1487					.collect()1488			})1489			.unwrap_or_else(|| {1490				properties1491					.into_iter()1492					.map(|(key, value)| Property { key, value })1493					.collect()1494			});14951496		Ok(properties)1497	}14981499	/// Get property permissions according to given keys.1500	pub fn filter_property_permissions(1501		collection_id: CollectionId,1502		keys: Option<Vec<PropertyKey>>,1503	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1504		let permissions = Self::property_permissions(collection_id);15051506		let key_permissions = keys1507			.map(|keys| {1508				keys.into_iter()1509					.filter_map(|key| {1510						permissions1511							.get(&key)1512							.map(|permission| PropertyKeyPermission {1513								key,1514								permission: permission.clone(),1515							})1516					})1517					.collect()1518			})1519			.unwrap_or_else(|| {1520				permissions1521					.into_iter()1522					.map(|(key, permission)| PropertyKeyPermission { key, permission })1523					.collect()1524			});15251526		Ok(key_permissions)1527	}15281529	/// Toggle `user` participation in the `collection`'s allow list.1530	/// #### Store read/writes1531	/// 1 writes1532	pub fn toggle_allowlist(1533		collection: &CollectionHandle<T>,1534		sender: &T::CrossAccountId,1535		user: &T::CrossAccountId,1536		allowed: bool,1537	) -> DispatchResult {1538		collection.check_is_owner_or_admin(sender)?;15391540		// =========15411542		if allowed {1543			<Allowlist<T>>::insert((collection.id, user), true);1544			Self::deposit_event(Event::<T>::AllowListAddressAdded(1545				collection.id,1546				user.clone(),1547			));1548		} else {1549			<Allowlist<T>>::remove((collection.id, user));1550			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1551				collection.id,1552				user.clone(),1553			));1554		}15551556		<PalletEvm<T>>::deposit_log(1557			erc::CollectionHelpersEvents::CollectionChanged {1558				collection_id: eth::collection_id_to_address(collection.id),1559			}1560			.to_log(T::ContractAddress::get()),1561		);15621563		Ok(())1564	}15651566	/// Toggle `user` participation in the `collection`'s admin list.1567	/// #### Store read/writes1568	/// 2 reads, 2 writes1569	pub fn toggle_admin(1570		collection: &CollectionHandle<T>,1571		sender: &T::CrossAccountId,1572		user: &T::CrossAccountId,1573		admin: bool,1574	) -> DispatchResult {1575		collection.check_is_internal()?;1576		collection.check_is_owner(sender)?;15771578		let is_admin = <IsAdmin<T>>::get((collection.id, user));1579		if is_admin == admin {1580			if admin {1581				return Ok(());1582			} else {1583				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1584			}1585		}1586		let amount = <AdminAmount<T>>::get(collection.id);15871588		// =========15891590		if admin {1591			let amount = amount1592				.checked_add(1)1593				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1594			ensure!(1595				amount <= Self::collection_admins_limit(),1596				<Error<T>>::CollectionAdminCountExceeded,1597			);15981599			<AdminAmount<T>>::insert(collection.id, amount);1600			<IsAdmin<T>>::insert((collection.id, user), true);16011602			Self::deposit_event(Event::<T>::CollectionAdminAdded(1603				collection.id,1604				user.clone(),1605			));1606		} else {1607			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1608			<IsAdmin<T>>::remove((collection.id, user));16091610			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1611				collection.id,1612				user.clone(),1613			));1614		}16151616		<PalletEvm<T>>::deposit_log(1617			erc::CollectionHelpersEvents::CollectionChanged {1618				collection_id: eth::collection_id_to_address(collection.id),1619			}1620			.to_log(T::ContractAddress::get()),1621		);16221623		Ok(())1624	}16251626	/// Update collection limits.1627	pub fn update_limits(1628		user: &T::CrossAccountId,1629		collection: &mut CollectionHandle<T>,1630		new_limit: CollectionLimits,1631	) -> DispatchResult {1632		collection.check_is_internal()?;1633		collection.check_is_owner_or_admin(user)?;16341635		collection.limits =1636			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16371638		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1639		<PalletEvm<T>>::deposit_log(1640			erc::CollectionHelpersEvents::CollectionChanged {1641				collection_id: eth::collection_id_to_address(collection.id),1642			}1643			.to_log(T::ContractAddress::get()),1644		);16451646		collection.save()1647	}16481649	/// Merge set fields from `new_limit` to `old_limit`.1650	fn clamp_limits(1651		mode: CollectionMode,1652		old_limit: &CollectionLimits,1653		mut new_limit: CollectionLimits,1654	) -> Result<CollectionLimits, DispatchError> {1655		let limits = old_limit;1656		limit_default!(old_limit, new_limit,1657			account_token_ownership_limit => ensure!(1658				new_limit <= MAX_TOKEN_OWNERSHIP,1659				<Error<T>>::CollectionLimitBoundsExceeded,1660			),1661			sponsored_data_size => ensure!(1662				new_limit <= CUSTOM_DATA_LIMIT,1663				<Error<T>>::CollectionLimitBoundsExceeded,1664			),16651666			sponsored_data_rate_limit => {},1667			token_limit => ensure!(1668				old_limit >= new_limit && new_limit > 0,1669				<Error<T>>::CollectionTokenLimitExceeded1670			),16711672			sponsor_transfer_timeout(match mode {1673				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1674				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1675				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1676			}) => ensure!(1677				new_limit <= MAX_SPONSOR_TIMEOUT,1678				<Error<T>>::CollectionLimitBoundsExceeded,1679			),1680			sponsor_approve_timeout => {},1681			owner_can_transfer => ensure!(1682				!limits.owner_can_transfer_instaled() ||1683				old_limit || !new_limit,1684				<Error<T>>::OwnerPermissionsCantBeReverted,1685			),1686			owner_can_destroy => ensure!(1687				old_limit || !new_limit,1688				<Error<T>>::OwnerPermissionsCantBeReverted,1689			),1690			transfers_enabled => {},1691		);1692		Ok(new_limit)1693	}16941695	/// Update collection permissions.1696	pub fn update_permissions(1697		user: &T::CrossAccountId,1698		collection: &mut CollectionHandle<T>,1699		new_permission: CollectionPermissions,1700	) -> DispatchResult {1701		collection.check_is_internal()?;1702		collection.check_is_owner_or_admin(user)?;1703		collection.permissions = Self::clamp_permissions(1704			collection.mode.clone(),1705			&collection.permissions,1706			new_permission,1707		)?;17081709		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1710		<PalletEvm<T>>::deposit_log(1711			erc::CollectionHelpersEvents::CollectionChanged {1712				collection_id: eth::collection_id_to_address(collection.id),1713			}1714			.to_log(T::ContractAddress::get()),1715		);17161717		collection.save()1718	}17191720	/// Merge set fields from `new_permission` to `old_permission`.1721	fn clamp_permissions(1722		_mode: CollectionMode,1723		old_permission: &CollectionPermissions,1724		mut new_permission: CollectionPermissions,1725	) -> Result<CollectionPermissions, DispatchError> {1726		limit_default_clone!(old_permission, new_permission,1727			access => {},1728			mint_mode => {},1729			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1730		);1731		Ok(new_permission)1732	}17331734	/// Repair possibly broken properties of a collection.1735	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1736		CollectionProperties::<T>::mutate(collection_id, |properties| {1737			properties.recompute_consumed_space();1738		});17391740		Ok(())1741	}1742}17431744/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1745#[macro_export]1746macro_rules! unsupported {1747	($runtime:path) => {1748		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1749	};1750}17511752/// Return weights for various worst-case operations.1753pub trait CommonWeightInfo<CrossAccountId> {1754	/// Weight of item creation.1755	fn create_item() -> Weight;17561757	/// Weight of items creation.1758	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17591760	/// Weight of items creation.1761	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17621763	/// The weight of the burning item.1764	fn burn_item() -> Weight;17651766	/// Property setting weight.1767	///1768	/// * `amount`- The number of properties to set.1769	fn set_collection_properties(amount: u32) -> Weight;17701771	/// Collection property deletion weight.1772	///1773	/// * `amount`- The number of properties to set.1774	fn delete_collection_properties(amount: u32) -> Weight;17751776	/// Token property setting weight.1777	///1778	/// * `amount`- The number of properties to set.1779	fn set_token_properties(amount: u32) -> Weight;17801781	/// Token property deletion weight.1782	///1783	/// * `amount`- The number of properties to delete.1784	fn delete_token_properties(amount: u32) -> Weight;17851786	/// Token property permissions set weight.1787	///1788	/// * `amount`- The number of property permissions to set.1789	fn set_token_property_permissions(amount: u32) -> Weight;17901791	/// Transfer price of the token or its parts.1792	fn transfer() -> Weight;17931794	/// The price of setting the permission of the operation from another user.1795	fn approve() -> Weight;17961797	/// Transfer price from another user.1798	fn transfer_from() -> Weight;17991800	/// The price of burning a token from another user.1801	fn burn_from() -> Weight;18021803	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1804	/// whole users's balance.1805	///1806	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1807	fn burn_recursively_self_raw() -> Weight;18081809	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1810	///1811	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1812	fn burn_recursively_breadth_raw(amount: u32) -> Weight;18131814	/// The price of recursive burning a token.1815	///1816	/// `max_selfs` - The maximum burning weight of the token itself.1817	/// `max_breadth` - The maximum number of nested tokens to burn.1818	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1819		Self::burn_recursively_self_raw()1820			.saturating_mul(max_selfs.max(1) as u64)1821			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1822	}18231824	/// The price of retrieving token owner1825	fn token_owner() -> Weight;18261827	/// The price of setting approval for all1828	fn set_allowance_for_all() -> Weight;18291830	/// The price of repairing an item.1831	fn force_repair_item() -> Weight;1832}18331834/// Weight info extension trait for refungible pallet.1835pub trait RefungibleExtensionsWeightInfo {1836	/// Weight of token repartition.1837	fn repartition() -> Weight;1838}18391840/// Common collection operations.1841///1842/// It wraps methods in Fungible, Nonfungible and Refungible pallets1843/// and adds weight info.1844pub trait CommonCollectionOperations<T: Config> {1845	/// Create token.1846	///1847	/// * `sender` - The user who mint the token and pays for the transaction.1848	/// * `to` - The user who will own the token.1849	/// * `data` - Token data.1850	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1851	fn create_item(1852		&self,1853		sender: T::CrossAccountId,1854		to: T::CrossAccountId,1855		data: CreateItemData,1856		nesting_budget: &dyn Budget,1857	) -> DispatchResultWithPostInfo;18581859	/// Create multiple tokens.1860	///1861	/// * `sender` - The user who mint the token and pays for the transaction.1862	/// * `to` - The user who will own the token.1863	/// * `data` - Token data.1864	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1865	fn create_multiple_items(1866		&self,1867		sender: T::CrossAccountId,1868		to: T::CrossAccountId,1869		data: Vec<CreateItemData>,1870		nesting_budget: &dyn Budget,1871	) -> DispatchResultWithPostInfo;18721873	/// Create multiple tokens.1874	///1875	/// * `sender` - The user who mint the token and pays for the transaction.1876	/// * `to` - The user who will own the token.1877	/// * `data` - Token data.1878	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1879	fn create_multiple_items_ex(1880		&self,1881		sender: T::CrossAccountId,1882		data: CreateItemExData<T::CrossAccountId>,1883		nesting_budget: &dyn Budget,1884	) -> DispatchResultWithPostInfo;18851886	/// Burn token.1887	///1888	/// * `sender` - The user who owns the token.1889	/// * `token` - Token id that will burned.1890	/// * `amount` - The number of parts of the token that will be burned.1891	fn burn_item(1892		&self,1893		sender: T::CrossAccountId,1894		token: TokenId,1895		amount: u128,1896	) -> DispatchResultWithPostInfo;18971898	/// Burn token and all nested tokens recursievly.1899	///1900	/// * `sender` - The user who owns the token.1901	/// * `token` - Token id that will burned.1902	/// * `self_budget` - The budget that can be spent on burning tokens.1903	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1904	fn burn_item_recursively(1905		&self,1906		sender: T::CrossAccountId,1907		token: TokenId,1908		self_budget: &dyn Budget,1909		breadth_budget: &dyn Budget,1910	) -> DispatchResultWithPostInfo;19111912	/// Set collection properties.1913	///1914	/// * `sender` - Must be either the owner of the collection or its admin.1915	/// * `properties` - Properties to be set.1916	fn set_collection_properties(1917		&self,1918		sender: T::CrossAccountId,1919		properties: Vec<Property>,1920	) -> DispatchResultWithPostInfo;19211922	/// Delete collection properties.1923	///1924	/// * `sender` - Must be either the owner of the collection or its admin.1925	/// * `properties` - The properties to be removed.1926	fn delete_collection_properties(1927		&self,1928		sender: &T::CrossAccountId,1929		property_keys: Vec<PropertyKey>,1930	) -> DispatchResultWithPostInfo;19311932	/// Set token properties.1933	///1934	/// The appropriate [`PropertyPermission`] for the token property1935	/// must be set with [`Self::set_token_property_permissions`].1936	///1937	/// * `sender` - Must be either the owner of the token or its admin.1938	/// * `token_id` - The token for which the properties are being set.1939	/// * `properties` - Properties to be set.1940	/// * `budget` - Budget for setting properties.1941	fn set_token_properties(1942		&self,1943		sender: T::CrossAccountId,1944		token_id: TokenId,1945		properties: Vec<Property>,1946		budget: &dyn Budget,1947	) -> DispatchResultWithPostInfo;19481949	/// Remove token properties.1950	///1951	/// The appropriate [`PropertyPermission`] for the token property1952	/// must be set with [`Self::set_token_property_permissions`].1953	///1954	/// * `sender` - Must be either the owner of the token or its admin.1955	/// * `token_id` - The token for which the properties are being remove.1956	/// * `property_keys` - Keys to remove corresponding properties.1957	/// * `budget` - Budget for removing properties.1958	fn delete_token_properties(1959		&self,1960		sender: T::CrossAccountId,1961		token_id: TokenId,1962		property_keys: Vec<PropertyKey>,1963		budget: &dyn Budget,1964	) -> DispatchResultWithPostInfo;19651966	/// Set token property permissions.1967	///1968	/// * `sender` - Must be either the owner of the token or its admin.1969	/// * `token_id` - The token for which the properties are being set.1970	/// * `property_permissions` - Property permissions to be set.1971	/// * `budget` - Budget for setting properties.1972	fn set_token_property_permissions(1973		&self,1974		sender: &T::CrossAccountId,1975		property_permissions: Vec<PropertyKeyPermission>,1976	) -> DispatchResultWithPostInfo;19771978	/// Transfer amount of token pieces.1979	///1980	/// * `sender` - Donor user.1981	/// * `to` - Recepient user.1982	/// * `token` - The token of which parts are being sent.1983	/// * `amount` - The number of parts of the token that will be transferred.1984	/// * `budget` - The maximum budget that can be spent on the transfer.1985	fn transfer(1986		&self,1987		sender: T::CrossAccountId,1988		to: T::CrossAccountId,1989		token: TokenId,1990		amount: u128,1991		budget: &dyn Budget,1992	) -> DispatchResultWithPostInfo;19931994	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1995	///1996	/// * `sender` - The user who grants access to the token.1997	/// * `spender` - The user to whom the rights are granted.1998	/// * `token` - The token to which access is granted.1999	/// * `amount` - The amount of pieces that another user can dispose of.2000	fn approve(2001		&self,2002		sender: T::CrossAccountId,2003		spender: T::CrossAccountId,2004		token: TokenId,2005		amount: u128,2006	) -> DispatchResultWithPostInfo;20072008	/// Send parts of a token owned by another user.2009	///2010	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2011	///2012	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2013	/// * `from` - The user who owns the token.2014	/// * `to` - Recepient user.2015	/// * `token` - The token of which parts are being sent.2016	/// * `amount` - The number of parts of the token that will be transferred.2017	/// * `budget` - The maximum budget that can be spent on the transfer.2018	fn transfer_from(2019		&self,2020		sender: T::CrossAccountId,2021		from: T::CrossAccountId,2022		to: T::CrossAccountId,2023		token: TokenId,2024		amount: u128,2025		budget: &dyn Budget,2026	) -> DispatchResultWithPostInfo;20272028	/// Burn parts of a token owned by another user.2029	///2030	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2031	///2032	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2033	/// * `from` - The user who owns the token.2034	/// * `token` - The token of which parts are being sent.2035	/// * `amount` - The number of parts of the token that will be transferred.2036	/// * `budget` - The maximum budget that can be spent on the burn.2037	fn burn_from(2038		&self,2039		sender: T::CrossAccountId,2040		from: T::CrossAccountId,2041		token: TokenId,2042		amount: u128,2043		budget: &dyn Budget,2044	) -> DispatchResultWithPostInfo;20452046	/// Check permission to nest token.2047	///2048	/// * `sender` - The user who initiated the check.2049	/// * `from` - The token that is checked for embedding.2050	/// * `under` - Token under which to check.2051	/// * `budget` - The maximum budget that can be spent on the check.2052	fn check_nesting(2053		&self,2054		sender: T::CrossAccountId,2055		from: (CollectionId, TokenId),2056		under: TokenId,2057		budget: &dyn Budget,2058	) -> DispatchResult;20592060	/// Nest one token into another.2061	///2062	/// * `under` - Token holder.2063	/// * `to_nest` - Nested token.2064	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20652066	/// Unnest token.2067	///2068	/// * `under` - Token holder.2069	/// * `to_nest` - Token to unnest.2070	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20712072	/// Get all user tokens.2073	///2074	/// * `account` - Account for which you need to get tokens.2075	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20762077	/// Get all the tokens in the collection.2078	fn collection_tokens(&self) -> Vec<TokenId>;20792080	/// Check if the token exists.2081	///2082	/// * `token` - Id token to check.2083	fn token_exists(&self, token: TokenId) -> bool;20842085	/// Get the id of the last minted token.2086	fn last_token_id(&self) -> TokenId;20872088	/// Get the owner of the token.2089	///2090	/// * `token` - The token for which you need to find out the owner.2091	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20922093	/// Returns 10 tokens owners in no particular order.2094	///2095	/// * `token` - The token for which you need to find out the owners.2096	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;20972098	/// Get the value of the token property by key.2099	///2100	/// * `token` - Token with the property to get.2101	/// * `key` - Property name.2102	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21032104	/// Get a set of token properties by key vector.2105	///2106	/// * `token` - Token with the property to get.2107	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2108	/// then all properties are returned.2109	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21102111	/// Amount of unique collection tokens2112	fn total_supply(&self) -> u32;21132114	/// Amount of different tokens account has.2115	///2116	/// * `account` - The account for which need to get the balance.2117	fn account_balance(&self, account: T::CrossAccountId) -> u32;21182119	/// Amount of specific token account have.2120	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21212122	/// Amount of token pieces2123	fn total_pieces(&self, token: TokenId) -> Option<u128>;21242125	/// Get the number of parts of the token that a trusted user can manage.2126	///2127	/// * `sender` - Trusted user.2128	/// * `spender` - Owner of the token.2129	/// * `token` - The token for which to get the value.2130	fn allowance(2131		&self,2132		sender: T::CrossAccountId,2133		spender: T::CrossAccountId,2134		token: TokenId,2135	) -> u128;21362137	/// Get extension for RFT collection.2138	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21392140	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2141	/// * `owner` - Token owner2142	/// * `operator` - Operator2143	/// * `approve` - Should operator status be granted or revoked?2144	fn set_allowance_for_all(2145		&self,2146		owner: T::CrossAccountId,2147		operator: T::CrossAccountId,2148		approve: bool,2149	) -> DispatchResultWithPostInfo;21502151	/// Tells whether the given `owner` approves the `operator`.2152	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21532154	/// Repairs a possibly broken item.2155	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2156}21572158/// Extension for RFT collection.2159pub trait RefungibleExtensions<T>2160where2161	T: Config,2162{2163	/// Change the number of parts of the token.2164	///2165	/// When the value changes down, this function is equivalent to burning parts of the token.2166	///2167	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2168	/// * `token` - The token for which you want to change the number of parts.2169	/// * `amount` - The new value of the parts of the token.2170	fn repartition(2171		&self,2172		sender: &T::CrossAccountId,2173		token: TokenId,2174		amount: u128,2175	) -> DispatchResultWithPostInfo;2176}21772178/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2179///2180/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2181pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2182	let post_info = PostDispatchInfo {2183		actual_weight: Some(weight),2184		pays_fee: Pays::Yes,2185	};2186	match res {2187		Ok(()) => Ok(post_info),2188		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2189	}2190}21912192impl<T: Config> From<PropertiesError> for Error<T> {2193	fn from(error: PropertiesError) -> Self {2194		match error {2195			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2196			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2197			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2198			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2199			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2200		}2201	}2202}
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::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118use up_pov_estimate_rpc::PovInfo;119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135///136/// CollectionHandle is used as a generic wrapper for collections of all types.137/// It allows to perform common operations and queries on any collection type,138/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].139#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]140pub struct CollectionHandle<T: Config> {141	/// Collection id142	pub id: CollectionId,143	collection: Collection<T::AccountId>,144	/// Substrate recorder for counting consumed gas145	pub recorder: SubstrateRecorder<T>,146}147148impl<T: Config> WithRecorder<T> for CollectionHandle<T> {149	fn recorder(&self) -> &SubstrateRecorder<T> {150		&self.recorder151	}152	fn into_recorder(self) -> SubstrateRecorder<T> {153		self.recorder154	}155}156157impl<T: Config> CollectionHandle<T> {158	/// Same as [CollectionHandle::new] but with an explicit gas limit.159	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {160		<CollectionById<T>>::get(id).map(|collection| Self {161			id,162			collection,163			recorder: SubstrateRecorder::new(gas_limit),164		})165	}166167	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].168	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {169		<CollectionById<T>>::get(id).map(|collection| Self {170			id,171			collection,172			recorder,173		})174	}175176	/// Retrives collection data from storage and creates collection handle with default parameters.177	/// If collection not found return `None`178	pub fn new(id: CollectionId) -> Option<Self> {179		Self::new_with_gas_limit(id, u64::MAX)180	}181182	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.183	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {184		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)185	}186187	/// Consume gas for reading.188	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {189		self.recorder190			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191				<T as frame_system::Config>::DbWeight::get()192					.read193					.saturating_mul(reads),194			)))195	}196197	/// Consume gas for writing.198	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199		self.recorder200			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(201				<T as frame_system::Config>::DbWeight::get()202					.write203					.saturating_mul(writes),204			)))205	}206207	/// Consume gas for reading and writing.208	pub fn consume_store_reads_and_writes(209		&self,210		reads: u64,211		writes: u64,212	) -> evm_coder::execution::Result<()> {213		let weight = <T as frame_system::Config>::DbWeight::get();214		let reads = weight.read.saturating_mul(reads);215		let writes = weight.read.saturating_mul(writes);216		self.recorder217			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(218				reads.saturating_add(writes),219			)))220	}221222	/// Save collection to storage.223	pub fn save(&self) -> DispatchResult {224		<CollectionById<T>>::insert(self.id, &self.collection);225		Ok(())226	}227228	/// Set collection sponsor.229	///230	/// Unique collections allows sponsoring for certain actions.231	/// This method allows you to set the sponsor of the collection.232	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].233	pub fn set_sponsor(234		&mut self,235		sender: &T::CrossAccountId,236		sponsor: T::AccountId,237	) -> DispatchResult {238		self.check_is_internal()?;239		self.check_is_owner_or_admin(sender)?;240241		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());242243		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));244		<PalletEvm<T>>::deposit_log(245			erc::CollectionHelpersEvents::CollectionChanged {246				collection_id: eth::collection_id_to_address(self.id),247			}248			.to_log(T::ContractAddress::get()),249		);250251		self.save()252	}253254	/// Force set `sponsor`.255	///256	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation257	/// from the `sponsor` is not required.258	///259	/// # Arguments260	///261	/// * `sender`: Caller's account.262	/// * `sponsor`: ID of the account of the sponsor-to-be.263	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {264		self.check_is_internal()?;265266		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());267268		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));269		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));270		<PalletEvm<T>>::deposit_log(271			erc::CollectionHelpersEvents::CollectionChanged {272				collection_id: eth::collection_id_to_address(self.id),273			}274			.to_log(T::ContractAddress::get()),275		);276277		self.save()278	}279280	/// Confirm sponsorship281	///282	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.283	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].284	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {285		self.check_is_internal()?;286		ensure!(287			self.collection.sponsorship.pending_sponsor() == Some(sender),288			Error::<T>::ConfirmSponsorshipFail289		);290291		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());292293		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));294		<PalletEvm<T>>::deposit_log(295			erc::CollectionHelpersEvents::CollectionChanged {296				collection_id: eth::collection_id_to_address(self.id),297			}298			.to_log(T::ContractAddress::get()),299		);300301		self.save()302	}303304	/// Remove collection sponsor.305	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {306		self.check_is_internal()?;307		self.check_is_owner_or_admin(sender)?;308309		self.collection.sponsorship = SponsorshipState::Disabled;310311		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));312		<PalletEvm<T>>::deposit_log(313			erc::CollectionHelpersEvents::CollectionChanged {314				collection_id: eth::collection_id_to_address(self.id),315			}316			.to_log(T::ContractAddress::get()),317		);318		self.save()319	}320321	/// Force remove `sponsor`.322	///323	/// Differs from `remove_sponsor` in that324	/// it doesn't require consent from the `owner` of the collection.325	pub fn force_remove_sponsor(&mut self) -> DispatchResult {326		self.check_is_internal()?;327328		self.collection.sponsorship = SponsorshipState::Disabled;329330		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));331		<PalletEvm<T>>::deposit_log(332			erc::CollectionHelpersEvents::CollectionChanged {333				collection_id: eth::collection_id_to_address(self.id),334			}335			.to_log(T::ContractAddress::get()),336		);337		self.save()338	}339340	/// Checks that the collection was created with, and must be operated upon through **Unique API**.341	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.342	pub fn check_is_internal(&self) -> DispatchResult {343		if self.flags.external {344			return Err(<Error<T>>::CollectionIsExternal)?;345		}346347		Ok(())348	}349350	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.351	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.352	pub fn check_is_external(&self) -> DispatchResult {353		if !self.flags.external {354			return Err(<Error<T>>::CollectionIsInternal)?;355		}356357		Ok(())358	}359}360361impl<T: Config> Deref for CollectionHandle<T> {362	type Target = Collection<T::AccountId>;363364	fn deref(&self) -> &Self::Target {365		&self.collection366	}367}368369impl<T: Config> DerefMut for CollectionHandle<T> {370	fn deref_mut(&mut self) -> &mut Self::Target {371		&mut self.collection372	}373}374375impl<T: Config> CollectionHandle<T> {376	/// Checks if the `user` is the owner of the collection.377	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {378		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);379		Ok(())380	}381382	/// Returns **true** if the `user` is the owner or administrator of the collection.383	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {384		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))385	}386387	/// Checks if the `user` is the owner or administrator of the collection.388	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {389		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);390		Ok(())391	}392393	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.394	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {395		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)396	}397398	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.399	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {400		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)401	}402403	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.404	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {405		ensure!(406			<Allowlist<T>>::get((self.id, user)),407			<Error<T>>::AddressNotInAllowlist408		);409		Ok(())410	}411412	/// Changes collection owner to another account413	/// #### Store read/writes414	/// 1 writes415	pub fn change_owner(416		&mut self,417		caller: T::CrossAccountId,418		new_owner: T::CrossAccountId,419	) -> DispatchResult {420		self.check_is_internal()?;421		self.check_is_owner(&caller)?;422		self.collection.owner = new_owner.as_sub().clone();423424		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(425			self.id,426			new_owner.as_sub().clone(),427		));428		<PalletEvm<T>>::deposit_log(429			erc::CollectionHelpersEvents::CollectionChanged {430				collection_id: eth::collection_id_to_address(self.id),431			}432			.to_log(T::ContractAddress::get()),433		);434435		self.save()436	}437}438439#[frame_support::pallet]440pub mod pallet {441	use super::*;442	use dispatch::CollectionDispatch;443	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};444	use frame_system::pallet_prelude::*;445	use frame_support::traits::Currency;446	use up_data_structs::{TokenId, mapping::TokenAddressMapping};447	use scale_info::TypeInfo;448	use weights::WeightInfo;449450	#[pallet::config]451	pub trait Config:452		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo453	{454		/// Weight information for functions of this pallet.455		type WeightInfo: WeightInfo;456457		/// Events compatible with [`frame_system::Config::Event`].458		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;459460		/// Handler of accounts and payment.461		type Currency: Currency<Self::AccountId>;462463		/// Set price to create a collection.464		#[pallet::constant]465		type CollectionCreationPrice: Get<466			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,467		>;468469		/// Dispatcher of operations on collections.470		type CollectionDispatch: CollectionDispatch<Self>;471472		/// Account which holds the chain's treasury.473		type TreasuryAccountId: Get<Self::AccountId>;474475		/// Address under which the CollectionHelper contract would be available.476		#[pallet::constant]477		type ContractAddress: Get<H160>;478479		/// Mapper for token addresses to Ethereum addresses.480		type EvmTokenAddressMapping: TokenAddressMapping<H160>;481482		/// Mapper for token addresses to [`CrossAccountId`].483		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;484	}485486	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);487488	#[pallet::pallet]489	#[pallet::storage_version(STORAGE_VERSION)]490	#[pallet::generate_store(pub(super) trait Store)]491	pub struct Pallet<T>(_);492493	#[pallet::extra_constants]494	impl<T: Config> Pallet<T> {495		/// Maximum admins per collection.496		pub fn collection_admins_limit() -> u32 {497			COLLECTION_ADMINS_LIMIT498		}499	}500501	#[pallet::event]502	#[pallet::generate_deposit(pub fn deposit_event)]503	pub enum Event<T: Config> {504		/// New collection was created505		CollectionCreated(506			/// Globally unique identifier of newly created collection.507			CollectionId,508			/// [`CollectionMode`] converted into _u8_.509			u8,510			/// Collection owner.511			T::AccountId,512		),513514		/// New collection was destroyed515		CollectionDestroyed(516			/// Globally unique identifier of collection.517			CollectionId,518		),519520		/// New item was created.521		ItemCreated(522			/// Id of the collection where item was created.523			CollectionId,524			/// Id of an item. Unique within the collection.525			TokenId,526			/// Owner of newly created item527			T::CrossAccountId,528			/// Always 1 for NFT529			u128,530		),531532		/// Collection item was burned.533		ItemDestroyed(534			/// Id of the collection where item was destroyed.535			CollectionId,536			/// Identifier of burned NFT.537			TokenId,538			/// Which user has destroyed its tokens.539			T::CrossAccountId,540			/// Amount of token pieces destroed. Always 1 for NFT.541			u128,542		),543544		/// Item was transferred545		Transfer(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			/// New owner of item.553			T::CrossAccountId,554			/// Amount of token pieces transfered. Always 1 for NFT.555			u128,556		),557558		/// Amount pieces of token owned by `sender` was approved for `spender`.559		Approved(560			/// Id of collection to which item is belong.561			CollectionId,562			/// Id of an item.563			TokenId,564			/// Original owner of item.565			T::CrossAccountId,566			/// Id for which the approval was granted.567			T::CrossAccountId,568			/// Amount of token pieces transfered. Always 1 for NFT.569			u128,570		),571572		/// A `sender` approves operations on all owned tokens for `spender`.573		ApprovedForAll(574			/// Id of collection to which item is belong.575			CollectionId,576			/// Owner of a wallet.577			T::CrossAccountId,578			/// Id for which operator status was granted or rewoked.579			T::CrossAccountId,580			/// Is operator status granted or revoked?581			bool,582		),583584		/// The colletion property has been added or edited.585		CollectionPropertySet(586			/// Id of collection to which property has been set.587			CollectionId,588			/// The property that was set.589			PropertyKey,590		),591592		/// The property has been deleted.593		CollectionPropertyDeleted(594			/// Id of collection to which property has been deleted.595			CollectionId,596			/// The property that was deleted.597			PropertyKey,598		),599600		/// The token property has been added or edited.601		TokenPropertySet(602			/// Identifier of the collection whose token has the property set.603			CollectionId,604			/// The token for which the property was set.605			TokenId,606			/// The property that was set.607			PropertyKey,608		),609610		/// The token property has been deleted.611		TokenPropertyDeleted(612			/// Identifier of the collection whose token has the property deleted.613			CollectionId,614			/// The token for which the property was deleted.615			TokenId,616			/// The property that was deleted.617			PropertyKey,618		),619620		/// The token property permission of a collection has been set.621		PropertyPermissionSet(622			/// ID of collection to which property permission has been set.623			CollectionId,624			/// The property permission that was set.625			PropertyKey,626		),627628		/// Address was added to the allow list.629		AllowListAddressAdded(630			/// ID of the affected collection.631			CollectionId,632			/// Address of the added account.633			T::CrossAccountId,634		),635636		/// Address was removed from the allow list.637		AllowListAddressRemoved(638			/// ID of the affected collection.639			CollectionId,640			/// Address of the removed account.641			T::CrossAccountId,642		),643644		/// Collection admin was added.645		CollectionAdminAdded(646			/// ID of the affected collection.647			CollectionId,648			/// Admin address.649			T::CrossAccountId,650		),651652		/// Collection admin was removed.653		CollectionAdminRemoved(654			/// ID of the affected collection.655			CollectionId,656			/// Removed admin address.657			T::CrossAccountId,658		),659660		/// Collection limits were set.661		CollectionLimitSet(662			/// ID of the affected collection.663			CollectionId,664		),665666		/// Collection owned was changed.667		CollectionOwnerChanged(668			/// ID of the affected collection.669			CollectionId,670			/// New owner address.671			T::AccountId,672		),673674		/// Collection permissions were set.675		CollectionPermissionSet(676			/// ID of the affected collection.677			CollectionId,678		),679680		/// Collection sponsor was set.681		CollectionSponsorSet(682			/// ID of the affected collection.683			CollectionId,684			/// New sponsor address.685			T::AccountId,686		),687688		/// New sponsor was confirm.689		SponsorshipConfirmed(690			/// ID of the affected collection.691			CollectionId,692			/// New sponsor address.693			T::AccountId,694		),695696		/// Collection sponsor was removed.697		CollectionSponsorRemoved(698			/// ID of the affected collection.699			CollectionId,700		),701	}702703	#[pallet::error]704	pub enum Error<T> {705		/// This collection does not exist.706		CollectionNotFound,707		/// Sender parameter and item owner must be equal.708		MustBeTokenOwner,709		/// No permission to perform action710		NoPermission,711		/// Destroying only empty collections is allowed712		CantDestroyNotEmptyCollection,713		/// Collection is not in mint mode.714		PublicMintingNotAllowed,715		/// Address is not in allow list.716		AddressNotInAllowlist,717718		/// Collection name can not be longer than 63 char.719		CollectionNameLimitExceeded,720		/// Collection description can not be longer than 255 char.721		CollectionDescriptionLimitExceeded,722		/// Token prefix can not be longer than 15 char.723		CollectionTokenPrefixLimitExceeded,724		/// Total collections bound exceeded.725		TotalCollectionsLimitExceeded,726		/// Exceeded max admin count727		CollectionAdminCountExceeded,728		/// Collection limit bounds per collection exceeded729		CollectionLimitBoundsExceeded,730		/// Tried to enable permissions which are only permitted to be disabled731		OwnerPermissionsCantBeReverted,732		/// Collection settings not allowing items transferring733		TransferNotAllowed,734		/// Account token limit exceeded per collection735		AccountTokenLimitExceeded,736		/// Collection token limit exceeded737		CollectionTokenLimitExceeded,738		/// Metadata flag frozen739		MetadataFlagFrozen,740741		/// Item does not exist742		TokenNotFound,743		/// Item is balance not enough744		TokenValueTooLow,745		/// Requested value is more than the approved746		ApprovedValueTooLow,747		/// Tried to approve more than owned748		CantApproveMoreThanOwned,749750		/// Can't transfer tokens to ethereum zero address751		AddressIsZero,752753		/// The operation is not supported754		UnsupportedOperation,755756		/// Insufficient funds to perform an action757		NotSufficientFounds,758759		/// User does not satisfy the nesting rule760		UserIsNotAllowedToNest,761		/// Only tokens from specific collections may nest tokens under this one762		SourceCollectionIsNotAllowedToNest,763764		/// Tried to store more data than allowed in collection field765		CollectionFieldSizeExceeded,766767		/// Tried to store more property data than allowed768		NoSpaceForProperty,769770		/// Tried to store more property keys than allowed771		PropertyLimitReached,772773		/// Property key is too long774		PropertyKeyIsTooLong,775776		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed777		InvalidCharacterInPropertyKey,778779		/// Empty property keys are forbidden780		EmptyPropertyKey,781782		/// Tried to access an external collection with an internal API783		CollectionIsExternal,784785		/// Tried to access an internal collection with an external API786		CollectionIsInternal,787788		/// This address is not set as sponsor, use setCollectionSponsor first.789		ConfirmSponsorshipFail,790791		/// The user is not an administrator.792		UserIsNotCollectionAdmin,793	}794795	/// Storage of the count of created collections. Essentially contains the last collection ID.796	#[pallet::storage]797	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799	/// Storage of the count of deleted collections.800	#[pallet::storage]801	pub type DestroyedCollectionCount<T> =802		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804	/// Storage of collection info.805	#[pallet::storage]806	pub type CollectionById<T> = StorageMap<807		Hasher = Blake2_128Concat,808		Key = CollectionId,809		Value = Collection<<T as frame_system::Config>::AccountId>,810		QueryKind = OptionQuery,811	>;812813	/// Storage of collection properties.814	#[pallet::storage]815	#[pallet::getter(fn collection_properties)]816	pub type CollectionProperties<T> = StorageMap<817		Hasher = Blake2_128Concat,818		Key = CollectionId,819		Value = Properties,820		QueryKind = ValueQuery,821		OnEmpty = up_data_structs::CollectionProperties,822	>;823824	/// Storage of token property permissions of a collection.825	#[pallet::storage]826	#[pallet::getter(fn property_permissions)]827	pub type CollectionPropertyPermissions<T> = StorageMap<828		Hasher = Blake2_128Concat,829		Key = CollectionId,830		Value = PropertiesPermissionMap,831		QueryKind = ValueQuery,832	>;833834	/// Storage of the amount of collection admins.835	#[pallet::storage]836	pub type AdminAmount<T> = StorageMap<837		Hasher = Blake2_128Concat,838		Key = CollectionId,839		Value = u32,840		QueryKind = ValueQuery,841	>;842843	/// List of collection admins.844	#[pallet::storage]845	pub type IsAdmin<T: Config> = StorageNMap<846		Key = (847			Key<Blake2_128Concat, CollectionId>,848			Key<Blake2_128Concat, T::CrossAccountId>,849		),850		Value = bool,851		QueryKind = ValueQuery,852	>;853854	/// Allowlisted collection users.855	#[pallet::storage]856	pub type Allowlist<T: Config> = StorageNMap<857		Key = (858			Key<Blake2_128Concat, CollectionId>,859			Key<Blake2_128Concat, T::CrossAccountId>,860		),861		Value = bool,862		QueryKind = ValueQuery,863	>;864865	/// Not used by code, exists only to provide some types to metadata.866	#[pallet::storage]867	pub type DummyStorageValue<T: Config> = StorageValue<868		Value = (869			CollectionStats,870			CollectionId,871			TokenId,872			TokenChild,873			PhantomType<(874				TokenData<T::CrossAccountId>,875				RpcCollection<T::AccountId>,876				// RMRK877				RmrkCollectionInfo<T::AccountId>,878				RmrkInstanceInfo<T::AccountId>,879				RmrkResourceInfo,880				RmrkPropertyInfo,881				RmrkBaseInfo<T::AccountId>,882				RmrkPartType,883				RmrkBoundedTheme,884				RmrkNftChild,885				// PoV Estimate Info886				PovInfo,887			)>,888		),889		QueryKind = OptionQuery,890	>;891892	#[pallet::hooks]893	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {894		fn on_runtime_upgrade() -> Weight {895			StorageVersion::new(1).put::<Pallet<T>>();896897			Weight::zero()898		}899	}900}901902impl<T: Config> Pallet<T> {903	/// Enshure that receiver address is correct.904	///905	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.906	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {907		ensure!(908			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,909			<Error<T>>::AddressIsZero910		);911		Ok(())912	}913914	/// Get a vector of collection admins.915	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {916		<IsAdmin<T>>::iter_prefix((collection,))917			.map(|(a, _)| a)918			.collect()919	}920921	/// Get a vector of users allowed to mint tokens.922	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {923		<Allowlist<T>>::iter_prefix((collection,))924			.map(|(a, _)| a)925			.collect()926	}927928	/// Is `user` allowed to mint token in `collection`.929	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {930		<Allowlist<T>>::get((collection, user))931	}932933	/// Get statistics of collections.934	pub fn collection_stats() -> CollectionStats {935		let created = <CreatedCollectionCount<T>>::get();936		let destroyed = <DestroyedCollectionCount<T>>::get();937		CollectionStats {938			created: created.0,939			destroyed: destroyed.0,940			alive: created.0 - destroyed.0,941		}942	}943944	/// Get the effective limits for the collection.945	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {946		let collection = <CollectionById<T>>::get(collection)?;947		let limits = collection.limits;948		let effective_limits = CollectionLimits {949			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),950			sponsored_data_size: Some(limits.sponsored_data_size()),951			sponsored_data_rate_limit: Some(952				limits953					.sponsored_data_rate_limit954					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),955			),956			token_limit: Some(limits.token_limit()),957			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(958				match collection.mode {959					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,960					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,961					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,962				},963			)),964			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),965			owner_can_transfer: Some(limits.owner_can_transfer()),966			owner_can_destroy: Some(limits.owner_can_destroy()),967			transfers_enabled: Some(limits.transfers_enabled()),968		};969970		Some(effective_limits)971	}972973	/// Returns information about the `collection` adapted for rpc.974	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {975		let Collection {976			name,977			description,978			owner,979			mode,980			token_prefix,981			sponsorship,982			limits,983			permissions,984			flags,985		} = <CollectionById<T>>::get(collection)?;986987		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)988			.into_iter()989			.map(|(key, permission)| PropertyKeyPermission { key, permission })990			.collect();991992		let properties = <CollectionProperties<T>>::get(collection)993			.into_iter()994			.map(|(key, value)| Property { key, value })995			.collect();996997		let permissions = CollectionPermissions {998			access: Some(permissions.access()),999			mint_mode: Some(permissions.mint_mode()),1000			nesting: Some(permissions.nesting().clone()),1001		};10021003		Some(RpcCollection {1004			name: name.into_inner(),1005			description: description.into_inner(),1006			owner,1007			mode,1008			token_prefix: token_prefix.into_inner(),1009			sponsorship,1010			limits,1011			permissions,1012			token_property_permissions,1013			properties,1014			read_only: flags.external,10151016			flags: RpcCollectionFlags {1017				foreign: flags.foreign,1018				erc721metadata: flags.erc721metadata,1019			},1020		})1021	}1022}10231024macro_rules! limit_default {1025	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1026		$(1027			if let Some($new) = $new.$field {1028				let $old = $old.$field($($arg)?);1029				let _ = $new;1030				let _ = $old;1031				$check1032			} else {1033				$new.$field = $old.$field1034			}1035		)*1036	}};1037}1038macro_rules! limit_default_clone {1039	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1040		$(1041			if let Some($new) = $new.$field.clone() {1042				let $old = $old.$field($($arg)?);1043				let _ = $new;1044				let _ = $old;1045				$check1046			} else {1047				$new.$field = $old.$field.clone()1048			}1049		)*1050	}};1051}10521053impl<T: Config> Pallet<T> {1054	/// Create new collection.1055	///1056	/// * `owner` - The owner of the collection.1057	/// * `data` - Description of the created collection.1058	/// * `flags` - Extra flags to store.1059	pub fn init_collection(1060		owner: T::CrossAccountId,1061		payer: T::CrossAccountId,1062		data: CreateCollectionData<T::AccountId>,1063		flags: CollectionFlags,1064	) -> Result<CollectionId, DispatchError> {1065		{1066			ensure!(1067				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1068				Error::<T>::CollectionTokenPrefixLimitExceeded1069			);1070		}10711072		let created_count = <CreatedCollectionCount<T>>::get()1073			.01074			.checked_add(1)1075			.ok_or(ArithmeticError::Overflow)?;1076		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1077		let id = CollectionId(created_count);10781079		// bound Total number of collections1080		ensure!(1081			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1082			<Error<T>>::TotalCollectionsLimitExceeded1083		);10841085		// =========10861087		let collection = Collection {1088			owner: owner.as_sub().clone(),1089			name: data.name,1090			mode: data.mode.clone(),1091			description: data.description,1092			token_prefix: data.token_prefix,1093			sponsorship: data1094				.pending_sponsor1095				.map(SponsorshipState::Unconfirmed)1096				.unwrap_or_default(),1097			limits: data1098				.limits1099				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1100				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1101			permissions: data1102				.permissions1103				.map(|permissions| {1104					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1105				})1106				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1107			flags,1108		};11091110		let mut collection_properties = up_data_structs::CollectionProperties::get();1111		collection_properties1112			.try_set_from_iter(data.properties.into_iter())1113			.map_err(<Error<T>>::from)?;11141115		CollectionProperties::<T>::insert(id, collection_properties);11161117		let mut token_props_permissions = PropertiesPermissionMap::new();1118		token_props_permissions1119			.try_set_from_iter(data.token_property_permissions.into_iter())1120			.map_err(<Error<T>>::from)?;11211122		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11231124		// Take a (non-refundable) deposit of collection creation1125		{1126			let mut imbalance =1127				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1128			imbalance.subsume(1129				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1130					&T::TreasuryAccountId::get(),1131					T::CollectionCreationPrice::get(),1132				),1133			);1134			<T as Config>::Currency::settle(1135				payer.as_sub(),1136				imbalance,1137				WithdrawReasons::TRANSFER,1138				ExistenceRequirement::KeepAlive,1139			)1140			.map_err(|_| Error::<T>::NotSufficientFounds)?;1141		}11421143		<CreatedCollectionCount<T>>::put(created_count);1144		<Pallet<T>>::deposit_event(Event::CollectionCreated(1145			id,1146			data.mode.id(),1147			owner.as_sub().clone(),1148		));1149		<PalletEvm<T>>::deposit_log(1150			erc::CollectionHelpersEvents::CollectionCreated {1151				owner: *owner.as_eth(),1152				collection_id: eth::collection_id_to_address(id),1153			}1154			.to_log(T::ContractAddress::get()),1155		);1156		<CollectionById<T>>::insert(id, collection);1157		Ok(id)1158	}11591160	/// Destroy collection.1161	///1162	/// * `collection` - Collection handler.1163	/// * `sender` - The owner or administrator of the collection.1164	pub fn destroy_collection(1165		collection: CollectionHandle<T>,1166		sender: &T::CrossAccountId,1167	) -> DispatchResult {1168		ensure!(1169			collection.limits.owner_can_destroy(),1170			<Error<T>>::NoPermission,1171		);1172		collection.check_is_owner(sender)?;11731174		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1175			.01176			.checked_add(1)1177			.ok_or(ArithmeticError::Overflow)?;11781179		// =========11801181		<DestroyedCollectionCount<T>>::put(destroyed_collections);1182		<CollectionById<T>>::remove(collection.id);1183		<AdminAmount<T>>::remove(collection.id);1184		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1185		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1186		<CollectionProperties<T>>::remove(collection.id);11871188		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11891190		<PalletEvm<T>>::deposit_log(1191			erc::CollectionHelpersEvents::CollectionDestroyed {1192				collection_id: eth::collection_id_to_address(collection.id),1193			}1194			.to_log(T::ContractAddress::get()),1195		);1196		Ok(())1197	}11981199	/// Set collection property.1200	///1201	/// * `collection` - Collection handler.1202	/// * `sender` - The owner or administrator of the collection.1203	/// * `property` - The property to set.1204	pub fn set_collection_property(1205		collection: &CollectionHandle<T>,1206		sender: &T::CrossAccountId,1207		property: Property,1208	) -> DispatchResult {1209		collection.check_is_owner_or_admin(sender)?;12101211		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1212			let property = property.clone();1213			properties.try_set(property.key, property.value)1214		})1215		.map_err(<Error<T>>::from)?;12161217		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1218		<PalletEvm<T>>::deposit_log(1219			erc::CollectionHelpersEvents::CollectionChanged {1220				collection_id: eth::collection_id_to_address(collection.id),1221			}1222			.to_log(T::ContractAddress::get()),1223		);12241225		Ok(())1226	}12271228	/// Set a scoped collection property, where the scope is a special prefix1229	/// prohibiting a user access to change the property directly.1230	///1231	/// * `collection_id` - ID of the collection for which the property is being set.1232	/// * `scope` - Property scope.1233	/// * `property` - The property to set.1234	pub fn set_scoped_collection_property(1235		collection_id: CollectionId,1236		scope: PropertyScope,1237		property: Property,1238	) -> DispatchResult {1239		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1240			properties.try_scoped_set(scope, property.key, property.value)1241		})1242		.map_err(<Error<T>>::from)?;12431244		Ok(())1245	}12461247	/// Set scoped collection properties, where the scope is a special prefix1248	/// prohibiting a user access to change the properties directly.1249	///1250	/// * `collection_id` - ID of the collection for which the properties is being set.1251	/// * `scope` - Property scope.1252	/// * `properties` - The properties to set.1253	pub fn set_scoped_collection_properties(1254		collection_id: CollectionId,1255		scope: PropertyScope,1256		properties: impl Iterator<Item = Property>,1257	) -> DispatchResult {1258		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1259			stored_properties.try_scoped_set_from_iter(scope, properties)1260		})1261		.map_err(<Error<T>>::from)?;12621263		Ok(())1264	}12651266	/// Set collection properties.1267	///1268	/// * `collection` - Collection handler.1269	/// * `sender` - The owner or administrator of the collection.1270	/// * `properties` - The properties to set.1271	#[transactional]1272	pub fn set_collection_properties(1273		collection: &CollectionHandle<T>,1274		sender: &T::CrossAccountId,1275		properties: Vec<Property>,1276	) -> DispatchResult {1277		for property in properties {1278			Self::set_collection_property(collection, sender, property)?;1279		}12801281		Ok(())1282	}12831284	/// Delete collection property.1285	///1286	/// * `collection` - Collection handler.1287	/// * `sender` - The owner or administrator of the collection.1288	/// * `property` - The property to delete.1289	pub fn delete_collection_property(1290		collection: &CollectionHandle<T>,1291		sender: &T::CrossAccountId,1292		property_key: PropertyKey,1293	) -> DispatchResult {1294		collection.check_is_owner_or_admin(sender)?;12951296		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1297			properties.remove(&property_key)1298		})1299		.map_err(<Error<T>>::from)?;13001301		Self::deposit_event(Event::CollectionPropertyDeleted(1302			collection.id,1303			property_key,1304		));1305		<PalletEvm<T>>::deposit_log(1306			erc::CollectionHelpersEvents::CollectionChanged {1307				collection_id: eth::collection_id_to_address(collection.id),1308			}1309			.to_log(T::ContractAddress::get()),1310		);13111312		Ok(())1313	}13141315	/// Delete collection properties.1316	///1317	/// * `collection` - Collection handler.1318	/// * `sender` - The owner or administrator of the collection.1319	/// * `properties` - The properties to delete.1320	#[transactional]1321	pub fn delete_collection_properties(1322		collection: &CollectionHandle<T>,1323		sender: &T::CrossAccountId,1324		property_keys: Vec<PropertyKey>,1325	) -> DispatchResult {1326		for key in property_keys {1327			Self::delete_collection_property(collection, sender, key)?;1328		}13291330		Ok(())1331	}13321333	/// Set collection propetry permission without any checks.1334	///1335	/// Used for migrations.1336	///1337	/// * `collection` - Collection handler.1338	/// * `property_permissions` - Property permissions.1339	pub fn set_property_permission_unchecked(1340		collection: CollectionId,1341		property_permission: PropertyKeyPermission,1342	) -> DispatchResult {1343		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1344			permissions.try_set(property_permission.key, property_permission.permission)1345		})1346		.map_err(<Error<T>>::from)?;1347		Ok(())1348	}13491350	/// Set collection property permission.1351	///1352	/// * `collection` - Collection handler.1353	/// * `sender` - The owner or administrator of the collection.1354	/// * `property_permission` - Property permission.1355	pub fn set_property_permission(1356		collection: &CollectionHandle<T>,1357		sender: &T::CrossAccountId,1358		property_permission: PropertyKeyPermission,1359	) -> DispatchResult {1360		Self::set_scoped_property_permission(1361			collection,1362			sender,1363			PropertyScope::None,1364			property_permission,1365		)1366	}13671368	/// Set collection property permission with scope.1369	///1370	/// * `collection` - Collection handler.1371	/// * `sender` - The owner or administrator of the collection.1372	/// * `scope` - Property scope.1373	/// * `property_permission` - Property permission.1374	pub fn set_scoped_property_permission(1375		collection: &CollectionHandle<T>,1376		sender: &T::CrossAccountId,1377		scope: PropertyScope,1378		property_permission: PropertyKeyPermission,1379	) -> DispatchResult {1380		collection.check_is_owner_or_admin(sender)?;13811382		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1383		let current_permission = all_permissions.get(&property_permission.key);1384		if matches![1385			current_permission,1386			Some(PropertyPermission { mutable: false, .. })1387		] {1388			return Err(<Error<T>>::NoPermission.into());1389		}13901391		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1392			let property_permission = property_permission.clone();1393			permissions.try_scoped_set(1394				scope,1395				property_permission.key,1396				property_permission.permission,1397			)1398		})1399		.map_err(<Error<T>>::from)?;14001401		Self::deposit_event(Event::PropertyPermissionSet(1402			collection.id,1403			property_permission.key,1404		));1405		<PalletEvm<T>>::deposit_log(1406			erc::CollectionHelpersEvents::CollectionChanged {1407				collection_id: eth::collection_id_to_address(collection.id),1408			}1409			.to_log(T::ContractAddress::get()),1410		);14111412		Ok(())1413	}14141415	/// Set token property permission.1416	///1417	/// * `collection` - Collection handler.1418	/// * `sender` - The owner or administrator of the collection.1419	/// * `property_permissions` - Property permissions.1420	#[transactional]1421	pub fn set_token_property_permissions(1422		collection: &CollectionHandle<T>,1423		sender: &T::CrossAccountId,1424		property_permissions: Vec<PropertyKeyPermission>,1425	) -> DispatchResult {1426		Self::set_scoped_token_property_permissions(1427			collection,1428			sender,1429			PropertyScope::None,1430			property_permissions,1431		)1432	}14331434	/// Set token property permission with scope.1435	///1436	/// * `collection` - Collection handler.1437	/// * `sender` - The owner or administrator of the collection.1438	/// * `scope` - Property scope.1439	/// * `property_permissions` - Property permissions.1440	#[transactional]1441	pub fn set_scoped_token_property_permissions(1442		collection: &CollectionHandle<T>,1443		sender: &T::CrossAccountId,1444		scope: PropertyScope,1445		property_permissions: Vec<PropertyKeyPermission>,1446	) -> DispatchResult {1447		for prop_pemission in property_permissions {1448			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1449		}14501451		Ok(())1452	}14531454	/// Get collection property.1455	pub fn get_collection_property(1456		collection_id: CollectionId,1457		key: &PropertyKey,1458	) -> Option<PropertyValue> {1459		Self::collection_properties(collection_id).get(key).cloned()1460	}14611462	/// Convert byte vector to property key vector.1463	pub fn bytes_keys_to_property_keys(1464		keys: Vec<Vec<u8>>,1465	) -> Result<Vec<PropertyKey>, DispatchError> {1466		keys.into_iter()1467			.map(|key| -> Result<PropertyKey, DispatchError> {1468				key.try_into()1469					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1470			})1471			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1472	}14731474	/// Get properties according to given keys.1475	pub fn filter_collection_properties(1476		collection_id: CollectionId,1477		keys: Option<Vec<PropertyKey>>,1478	) -> Result<Vec<Property>, DispatchError> {1479		let properties = Self::collection_properties(collection_id);14801481		let properties = keys1482			.map(|keys| {1483				keys.into_iter()1484					.filter_map(|key| {1485						properties.get(&key).map(|value| Property {1486							key,1487							value: value.clone(),1488						})1489					})1490					.collect()1491			})1492			.unwrap_or_else(|| {1493				properties1494					.into_iter()1495					.map(|(key, value)| Property { key, value })1496					.collect()1497			});14981499		Ok(properties)1500	}15011502	/// Get property permissions according to given keys.1503	pub fn filter_property_permissions(1504		collection_id: CollectionId,1505		keys: Option<Vec<PropertyKey>>,1506	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1507		let permissions = Self::property_permissions(collection_id);15081509		let key_permissions = keys1510			.map(|keys| {1511				keys.into_iter()1512					.filter_map(|key| {1513						permissions1514							.get(&key)1515							.map(|permission| PropertyKeyPermission {1516								key,1517								permission: permission.clone(),1518							})1519					})1520					.collect()1521			})1522			.unwrap_or_else(|| {1523				permissions1524					.into_iter()1525					.map(|(key, permission)| PropertyKeyPermission { key, permission })1526					.collect()1527			});15281529		Ok(key_permissions)1530	}15311532	/// Toggle `user` participation in the `collection`'s allow list.1533	/// #### Store read/writes1534	/// 1 writes1535	pub fn toggle_allowlist(1536		collection: &CollectionHandle<T>,1537		sender: &T::CrossAccountId,1538		user: &T::CrossAccountId,1539		allowed: bool,1540	) -> DispatchResult {1541		collection.check_is_owner_or_admin(sender)?;15421543		// =========15441545		if allowed {1546			<Allowlist<T>>::insert((collection.id, user), true);1547			Self::deposit_event(Event::<T>::AllowListAddressAdded(1548				collection.id,1549				user.clone(),1550			));1551		} else {1552			<Allowlist<T>>::remove((collection.id, user));1553			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1554				collection.id,1555				user.clone(),1556			));1557		}15581559		<PalletEvm<T>>::deposit_log(1560			erc::CollectionHelpersEvents::CollectionChanged {1561				collection_id: eth::collection_id_to_address(collection.id),1562			}1563			.to_log(T::ContractAddress::get()),1564		);15651566		Ok(())1567	}15681569	/// Toggle `user` participation in the `collection`'s admin list.1570	/// #### Store read/writes1571	/// 2 reads, 2 writes1572	pub fn toggle_admin(1573		collection: &CollectionHandle<T>,1574		sender: &T::CrossAccountId,1575		user: &T::CrossAccountId,1576		admin: bool,1577	) -> DispatchResult {1578		collection.check_is_internal()?;1579		collection.check_is_owner(sender)?;15801581		let is_admin = <IsAdmin<T>>::get((collection.id, user));1582		if is_admin == admin {1583			if admin {1584				return Ok(());1585			} else {1586				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1587			}1588		}1589		let amount = <AdminAmount<T>>::get(collection.id);15901591		// =========15921593		if admin {1594			let amount = amount1595				.checked_add(1)1596				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1597			ensure!(1598				amount <= Self::collection_admins_limit(),1599				<Error<T>>::CollectionAdminCountExceeded,1600			);16011602			<AdminAmount<T>>::insert(collection.id, amount);1603			<IsAdmin<T>>::insert((collection.id, user), true);16041605			Self::deposit_event(Event::<T>::CollectionAdminAdded(1606				collection.id,1607				user.clone(),1608			));1609		} else {1610			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1611			<IsAdmin<T>>::remove((collection.id, user));16121613			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1614				collection.id,1615				user.clone(),1616			));1617		}16181619		<PalletEvm<T>>::deposit_log(1620			erc::CollectionHelpersEvents::CollectionChanged {1621				collection_id: eth::collection_id_to_address(collection.id),1622			}1623			.to_log(T::ContractAddress::get()),1624		);16251626		Ok(())1627	}16281629	/// Update collection limits.1630	pub fn update_limits(1631		user: &T::CrossAccountId,1632		collection: &mut CollectionHandle<T>,1633		new_limit: CollectionLimits,1634	) -> DispatchResult {1635		collection.check_is_internal()?;1636		collection.check_is_owner_or_admin(user)?;16371638		collection.limits =1639			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16401641		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1642		<PalletEvm<T>>::deposit_log(1643			erc::CollectionHelpersEvents::CollectionChanged {1644				collection_id: eth::collection_id_to_address(collection.id),1645			}1646			.to_log(T::ContractAddress::get()),1647		);16481649		collection.save()1650	}16511652	/// Merge set fields from `new_limit` to `old_limit`.1653	fn clamp_limits(1654		mode: CollectionMode,1655		old_limit: &CollectionLimits,1656		mut new_limit: CollectionLimits,1657	) -> Result<CollectionLimits, DispatchError> {1658		let limits = old_limit;1659		limit_default!(old_limit, new_limit,1660			account_token_ownership_limit => ensure!(1661				new_limit <= MAX_TOKEN_OWNERSHIP,1662				<Error<T>>::CollectionLimitBoundsExceeded,1663			),1664			sponsored_data_size => ensure!(1665				new_limit <= CUSTOM_DATA_LIMIT,1666				<Error<T>>::CollectionLimitBoundsExceeded,1667			),16681669			sponsored_data_rate_limit => {},1670			token_limit => ensure!(1671				old_limit >= new_limit && new_limit > 0,1672				<Error<T>>::CollectionTokenLimitExceeded1673			),16741675			sponsor_transfer_timeout(match mode {1676				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1677				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1678				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1679			}) => ensure!(1680				new_limit <= MAX_SPONSOR_TIMEOUT,1681				<Error<T>>::CollectionLimitBoundsExceeded,1682			),1683			sponsor_approve_timeout => {},1684			owner_can_transfer => ensure!(1685				!limits.owner_can_transfer_instaled() ||1686				old_limit || !new_limit,1687				<Error<T>>::OwnerPermissionsCantBeReverted,1688			),1689			owner_can_destroy => ensure!(1690				old_limit || !new_limit,1691				<Error<T>>::OwnerPermissionsCantBeReverted,1692			),1693			transfers_enabled => {},1694		);1695		Ok(new_limit)1696	}16971698	/// Update collection permissions.1699	pub fn update_permissions(1700		user: &T::CrossAccountId,1701		collection: &mut CollectionHandle<T>,1702		new_permission: CollectionPermissions,1703	) -> DispatchResult {1704		collection.check_is_internal()?;1705		collection.check_is_owner_or_admin(user)?;1706		collection.permissions = Self::clamp_permissions(1707			collection.mode.clone(),1708			&collection.permissions,1709			new_permission,1710		)?;17111712		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1713		<PalletEvm<T>>::deposit_log(1714			erc::CollectionHelpersEvents::CollectionChanged {1715				collection_id: eth::collection_id_to_address(collection.id),1716			}1717			.to_log(T::ContractAddress::get()),1718		);17191720		collection.save()1721	}17221723	/// Merge set fields from `new_permission` to `old_permission`.1724	fn clamp_permissions(1725		_mode: CollectionMode,1726		old_permission: &CollectionPermissions,1727		mut new_permission: CollectionPermissions,1728	) -> Result<CollectionPermissions, DispatchError> {1729		limit_default_clone!(old_permission, new_permission,1730			access => {},1731			mint_mode => {},1732			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1733		);1734		Ok(new_permission)1735	}17361737	/// Repair possibly broken properties of a collection.1738	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1739		CollectionProperties::<T>::mutate(collection_id, |properties| {1740			properties.recompute_consumed_space();1741		});17421743		Ok(())1744	}1745}17461747/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1748#[macro_export]1749macro_rules! unsupported {1750	($runtime:path) => {1751		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1752	};1753}17541755/// Return weights for various worst-case operations.1756pub trait CommonWeightInfo<CrossAccountId> {1757	/// Weight of item creation.1758	fn create_item() -> Weight;17591760	/// Weight of items creation.1761	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17621763	/// Weight of items creation.1764	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17651766	/// The weight of the burning item.1767	fn burn_item() -> Weight;17681769	/// Property setting weight.1770	///1771	/// * `amount`- The number of properties to set.1772	fn set_collection_properties(amount: u32) -> Weight;17731774	/// Collection property deletion weight.1775	///1776	/// * `amount`- The number of properties to set.1777	fn delete_collection_properties(amount: u32) -> Weight;17781779	/// Token property setting weight.1780	///1781	/// * `amount`- The number of properties to set.1782	fn set_token_properties(amount: u32) -> Weight;17831784	/// Token property deletion weight.1785	///1786	/// * `amount`- The number of properties to delete.1787	fn delete_token_properties(amount: u32) -> Weight;17881789	/// Token property permissions set weight.1790	///1791	/// * `amount`- The number of property permissions to set.1792	fn set_token_property_permissions(amount: u32) -> Weight;17931794	/// Transfer price of the token or its parts.1795	fn transfer() -> Weight;17961797	/// The price of setting the permission of the operation from another user.1798	fn approve() -> Weight;17991800	/// Transfer price from another user.1801	fn transfer_from() -> Weight;18021803	/// The price of burning a token from another user.1804	fn burn_from() -> Weight;18051806	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1807	/// whole users's balance.1808	///1809	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1810	fn burn_recursively_self_raw() -> Weight;18111812	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1813	///1814	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1815	fn burn_recursively_breadth_raw(amount: u32) -> Weight;18161817	/// The price of recursive burning a token.1818	///1819	/// `max_selfs` - The maximum burning weight of the token itself.1820	/// `max_breadth` - The maximum number of nested tokens to burn.1821	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1822		Self::burn_recursively_self_raw()1823			.saturating_mul(max_selfs.max(1) as u64)1824			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1825	}18261827	/// The price of retrieving token owner1828	fn token_owner() -> Weight;18291830	/// The price of setting approval for all1831	fn set_allowance_for_all() -> Weight;18321833	/// The price of repairing an item.1834	fn force_repair_item() -> Weight;1835}18361837/// Weight info extension trait for refungible pallet.1838pub trait RefungibleExtensionsWeightInfo {1839	/// Weight of token repartition.1840	fn repartition() -> Weight;1841}18421843/// Common collection operations.1844///1845/// It wraps methods in Fungible, Nonfungible and Refungible pallets1846/// and adds weight info.1847pub trait CommonCollectionOperations<T: Config> {1848	/// Create token.1849	///1850	/// * `sender` - The user who mint the token and pays for the transaction.1851	/// * `to` - The user who will own the token.1852	/// * `data` - Token data.1853	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1854	fn create_item(1855		&self,1856		sender: T::CrossAccountId,1857		to: T::CrossAccountId,1858		data: CreateItemData,1859		nesting_budget: &dyn Budget,1860	) -> DispatchResultWithPostInfo;18611862	/// Create multiple tokens.1863	///1864	/// * `sender` - The user who mint the token and pays for the transaction.1865	/// * `to` - The user who will own the token.1866	/// * `data` - Token data.1867	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1868	fn create_multiple_items(1869		&self,1870		sender: T::CrossAccountId,1871		to: T::CrossAccountId,1872		data: Vec<CreateItemData>,1873		nesting_budget: &dyn Budget,1874	) -> DispatchResultWithPostInfo;18751876	/// Create multiple tokens.1877	///1878	/// * `sender` - The user who mint the token and pays for the transaction.1879	/// * `to` - The user who will own the token.1880	/// * `data` - Token data.1881	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1882	fn create_multiple_items_ex(1883		&self,1884		sender: T::CrossAccountId,1885		data: CreateItemExData<T::CrossAccountId>,1886		nesting_budget: &dyn Budget,1887	) -> DispatchResultWithPostInfo;18881889	/// Burn token.1890	///1891	/// * `sender` - The user who owns the token.1892	/// * `token` - Token id that will burned.1893	/// * `amount` - The number of parts of the token that will be burned.1894	fn burn_item(1895		&self,1896		sender: T::CrossAccountId,1897		token: TokenId,1898		amount: u128,1899	) -> DispatchResultWithPostInfo;19001901	/// Burn token and all nested tokens recursievly.1902	///1903	/// * `sender` - The user who owns the token.1904	/// * `token` - Token id that will burned.1905	/// * `self_budget` - The budget that can be spent on burning tokens.1906	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1907	fn burn_item_recursively(1908		&self,1909		sender: T::CrossAccountId,1910		token: TokenId,1911		self_budget: &dyn Budget,1912		breadth_budget: &dyn Budget,1913	) -> DispatchResultWithPostInfo;19141915	/// Set collection properties.1916	///1917	/// * `sender` - Must be either the owner of the collection or its admin.1918	/// * `properties` - Properties to be set.1919	fn set_collection_properties(1920		&self,1921		sender: T::CrossAccountId,1922		properties: Vec<Property>,1923	) -> DispatchResultWithPostInfo;19241925	/// Delete collection properties.1926	///1927	/// * `sender` - Must be either the owner of the collection or its admin.1928	/// * `properties` - The properties to be removed.1929	fn delete_collection_properties(1930		&self,1931		sender: &T::CrossAccountId,1932		property_keys: Vec<PropertyKey>,1933	) -> DispatchResultWithPostInfo;19341935	/// Set token properties.1936	///1937	/// The appropriate [`PropertyPermission`] for the token property1938	/// must be set with [`Self::set_token_property_permissions`].1939	///1940	/// * `sender` - Must be either the owner of the token or its admin.1941	/// * `token_id` - The token for which the properties are being set.1942	/// * `properties` - Properties to be set.1943	/// * `budget` - Budget for setting properties.1944	fn set_token_properties(1945		&self,1946		sender: T::CrossAccountId,1947		token_id: TokenId,1948		properties: Vec<Property>,1949		budget: &dyn Budget,1950	) -> DispatchResultWithPostInfo;19511952	/// Remove token properties.1953	///1954	/// The appropriate [`PropertyPermission`] for the token property1955	/// must be set with [`Self::set_token_property_permissions`].1956	///1957	/// * `sender` - Must be either the owner of the token or its admin.1958	/// * `token_id` - The token for which the properties are being remove.1959	/// * `property_keys` - Keys to remove corresponding properties.1960	/// * `budget` - Budget for removing properties.1961	fn delete_token_properties(1962		&self,1963		sender: T::CrossAccountId,1964		token_id: TokenId,1965		property_keys: Vec<PropertyKey>,1966		budget: &dyn Budget,1967	) -> DispatchResultWithPostInfo;19681969	/// Set token property permissions.1970	///1971	/// * `sender` - Must be either the owner of the token or its admin.1972	/// * `token_id` - The token for which the properties are being set.1973	/// * `property_permissions` - Property permissions to be set.1974	/// * `budget` - Budget for setting properties.1975	fn set_token_property_permissions(1976		&self,1977		sender: &T::CrossAccountId,1978		property_permissions: Vec<PropertyKeyPermission>,1979	) -> DispatchResultWithPostInfo;19801981	/// Transfer amount of token pieces.1982	///1983	/// * `sender` - Donor user.1984	/// * `to` - Recepient user.1985	/// * `token` - The token of which parts are being sent.1986	/// * `amount` - The number of parts of the token that will be transferred.1987	/// * `budget` - The maximum budget that can be spent on the transfer.1988	fn transfer(1989		&self,1990		sender: T::CrossAccountId,1991		to: T::CrossAccountId,1992		token: TokenId,1993		amount: u128,1994		budget: &dyn Budget,1995	) -> DispatchResultWithPostInfo;19961997	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1998	///1999	/// * `sender` - The user who grants access to the token.2000	/// * `spender` - The user to whom the rights are granted.2001	/// * `token` - The token to which access is granted.2002	/// * `amount` - The amount of pieces that another user can dispose of.2003	fn approve(2004		&self,2005		sender: T::CrossAccountId,2006		spender: T::CrossAccountId,2007		token: TokenId,2008		amount: u128,2009	) -> DispatchResultWithPostInfo;20102011	/// Send parts of a token owned by another user.2012	///2013	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2014	///2015	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2016	/// * `from` - The user who owns the token.2017	/// * `to` - Recepient user.2018	/// * `token` - The token of which parts are being sent.2019	/// * `amount` - The number of parts of the token that will be transferred.2020	/// * `budget` - The maximum budget that can be spent on the transfer.2021	fn transfer_from(2022		&self,2023		sender: T::CrossAccountId,2024		from: T::CrossAccountId,2025		to: T::CrossAccountId,2026		token: TokenId,2027		amount: u128,2028		budget: &dyn Budget,2029	) -> DispatchResultWithPostInfo;20302031	/// Burn parts of a token owned by another user.2032	///2033	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2034	///2035	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2036	/// * `from` - The user who owns the token.2037	/// * `token` - The token of which parts are being sent.2038	/// * `amount` - The number of parts of the token that will be transferred.2039	/// * `budget` - The maximum budget that can be spent on the burn.2040	fn burn_from(2041		&self,2042		sender: T::CrossAccountId,2043		from: T::CrossAccountId,2044		token: TokenId,2045		amount: u128,2046		budget: &dyn Budget,2047	) -> DispatchResultWithPostInfo;20482049	/// Check permission to nest token.2050	///2051	/// * `sender` - The user who initiated the check.2052	/// * `from` - The token that is checked for embedding.2053	/// * `under` - Token under which to check.2054	/// * `budget` - The maximum budget that can be spent on the check.2055	fn check_nesting(2056		&self,2057		sender: T::CrossAccountId,2058		from: (CollectionId, TokenId),2059		under: TokenId,2060		budget: &dyn Budget,2061	) -> DispatchResult;20622063	/// Nest one token into another.2064	///2065	/// * `under` - Token holder.2066	/// * `to_nest` - Nested token.2067	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20682069	/// Unnest token.2070	///2071	/// * `under` - Token holder.2072	/// * `to_nest` - Token to unnest.2073	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20742075	/// Get all user tokens.2076	///2077	/// * `account` - Account for which you need to get tokens.2078	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20792080	/// Get all the tokens in the collection.2081	fn collection_tokens(&self) -> Vec<TokenId>;20822083	/// Check if the token exists.2084	///2085	/// * `token` - Id token to check.2086	fn token_exists(&self, token: TokenId) -> bool;20872088	/// Get the id of the last minted token.2089	fn last_token_id(&self) -> TokenId;20902091	/// Get the owner of the token.2092	///2093	/// * `token` - The token for which you need to find out the owner.2094	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20952096	/// Returns 10 tokens owners in no particular order.2097	///2098	/// * `token` - The token for which you need to find out the owners.2099	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21002101	/// Get the value of the token property by key.2102	///2103	/// * `token` - Token with the property to get.2104	/// * `key` - Property name.2105	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21062107	/// Get a set of token properties by key vector.2108	///2109	/// * `token` - Token with the property to get.2110	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2111	/// then all properties are returned.2112	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21132114	/// Amount of unique collection tokens2115	fn total_supply(&self) -> u32;21162117	/// Amount of different tokens account has.2118	///2119	/// * `account` - The account for which need to get the balance.2120	fn account_balance(&self, account: T::CrossAccountId) -> u32;21212122	/// Amount of specific token account have.2123	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21242125	/// Amount of token pieces2126	fn total_pieces(&self, token: TokenId) -> Option<u128>;21272128	/// Get the number of parts of the token that a trusted user can manage.2129	///2130	/// * `sender` - Trusted user.2131	/// * `spender` - Owner of the token.2132	/// * `token` - The token for which to get the value.2133	fn allowance(2134		&self,2135		sender: T::CrossAccountId,2136		spender: T::CrossAccountId,2137		token: TokenId,2138	) -> u128;21392140	/// Get extension for RFT collection.2141	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21422143	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2144	/// * `owner` - Token owner2145	/// * `operator` - Operator2146	/// * `approve` - Should operator status be granted or revoked?2147	fn set_allowance_for_all(2148		&self,2149		owner: T::CrossAccountId,2150		operator: T::CrossAccountId,2151		approve: bool,2152	) -> DispatchResultWithPostInfo;21532154	/// Tells whether the given `owner` approves the `operator`.2155	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21562157	/// Repairs a possibly broken item.2158	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2159}21602161/// Extension for RFT collection.2162pub trait RefungibleExtensions<T>2163where2164	T: Config,2165{2166	/// Change the number of parts of the token.2167	///2168	/// When the value changes down, this function is equivalent to burning parts of the token.2169	///2170	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2171	/// * `token` - The token for which you want to change the number of parts.2172	/// * `amount` - The new value of the parts of the token.2173	fn repartition(2174		&self,2175		sender: &T::CrossAccountId,2176		token: TokenId,2177		amount: u128,2178	) -> DispatchResultWithPostInfo;2179}21802181/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2182///2183/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2184pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2185	let post_info = PostDispatchInfo {2186		actual_weight: Some(weight),2187		pays_fee: Pays::Yes,2188	};2189	match res {2190		Ok(()) => Ok(post_info),2191		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2192	}2193}21942195impl<T: Config> From<PropertiesError> for Error<T> {2196	fn from(error: PropertiesError) -> Self {2197		match error {2198			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2199			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2200			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2201			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2202			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2203		}2204	}2205}
modifiedprimitives/common/src/types.rsdiffbeforeafterboth
--- a/primitives/common/src/types.rs
+++ b/primitives/common/src/types.rs
@@ -29,6 +29,14 @@
 
 	pub use super::{BlockNumber, Signature, AccountId, Balance, Index, Hash, AuraId};
 
+	#[derive(Debug, Clone)]
+	pub enum RuntimeId {
+		Unique,
+		Quartz,
+		Opal,
+		Unknown(sp_std::vec::Vec<u8>),
+	}
+
 	/// Opaque block header type.
 	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
 
addedprimitives/pov-estimate-rpc/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/pov-estimate-rpc/Cargo.toml
@@ -0,0 +1,28 @@
+[package]
+name = "up-pov-estimate-rpc"
+version = "0.1.0"
+license = "GPLv3"
+edition = "2021"
+
+[dependencies]
+codec = { package = "parity-scale-codec", version = "3.1.2", default-features = false, features = [
+	"derive",
+] }
+serde = { version = "1.0.130", features = ["derive"], default-features = false, optional = true }
+scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+
+[features]
+default = ["std"]
+std = [
+	"codec/std",
+	"serde/std",
+	"scale-info/std",
+	"sp-core/std",
+	"sp-std/std",
+	"sp-api/std",
+	"sp-runtime/std",
+]
addedprimitives/pov-estimate-rpc/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/pov-estimate-rpc/src/lib.rs
@@ -0,0 +1,39 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use codec::{Decode, Encode, MaxEncodedLen};
+use scale_info::TypeInfo;
+
+#[cfg(feature = "std")]
+use serde::Serialize;
+
+use sp_runtime::ApplyExtrinsicResult;
+
+#[cfg_attr(feature = "std", derive(Serialize))]
+#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
+pub struct PovInfo {
+    pub proof_size: u64,
+    pub compact_proof_size: u64,
+    pub compressed_proof_size: u64,
+}
+
+sp_api::decl_runtime_apis! {
+    pub trait PovEstimateApi {
+        fn pov_estimate(uxt: Block::Extrinsic) -> ApplyExtrinsicResult;
+    }
+}
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -39,7 +39,7 @@
         use sp_runtime::{
             Permill,
             traits::Block as BlockT,
-            transaction_validity::{TransactionSource, TransactionValidity},
+            transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError, InvalidTransaction},
             ApplyExtrinsicResult, DispatchError,
         };
         use fp_rpc::TransactionStatus;
@@ -778,6 +778,17 @@
                 }
             }
 
+            impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {
+                #[allow(unused_variables)]
+                fn pov_estimate(uxt: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
+                    #[cfg(feature = "pov-estimate")]
+                    return Executive::apply_extrinsic(uxt);
+
+                    #[cfg(not(feature = "pov-estimate"))]
+                    return Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
+                }
+            }
+
             #[cfg(feature = "try-runtime")]
             impl frame_try_runtime::TryRuntime<Block> for Runtime {
                 fn on_runtime_upgrade(checks: bool) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -127,6 +127,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'up-pov-estimate-rpc/std',
     'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
@@ -184,6 +185,7 @@
     'pallet-test-utils',
 ]
 become-sapphire = []
+pov-estimate = []
 
 refungible = []
 scheduler = []
@@ -468,6 +470,7 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc", default-features = false }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
 rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
 fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -122,6 +122,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'up-pov-estimate-rpc/std',
     'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
@@ -169,6 +170,7 @@
 ]
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
 quartz-runtime = ['refungible', 'app-promotion', 'foreign-assets']
+pov-estimate = []
 
 refungible = []
 scheduler = []
@@ -461,6 +463,7 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc", default-features = false }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
 fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -123,6 +123,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'up-pov-estimate-rpc/std',
     'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
@@ -170,6 +171,7 @@
 ]
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
 unique-runtime = ['foreign-assets']
+pov-estimate = []
 stubgen = ["evm-coder/stubgen"]
 
 refungible = []
@@ -454,6 +456,7 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+up-pov-estimate-rpc = { path = "../../primitives/pov-estimate-rpc", default-features = false }
 app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
 rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }