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

difftreelog

Merge branch 'develop' into tests/generalization

Max Andreev2023-01-17parents: #f37b77a #2991c90.patch.diff
in: master

41 files changed

modified.docker/Dockerfile-chain-devdiffbeforeafterboth
--- a/.docker/Dockerfile-chain-dev
+++ b/.docker/Dockerfile-chain-dev
@@ -1,4 +1,4 @@
-FROM ubuntu:20.04
+FROM uniquenetwork/services:latest
 
 ARG RUST_TOOLCHAIN
 ARG NETWORK
@@ -10,10 +10,6 @@
 ENV PATH="/cargo-home/bin:$PATH"
 
 RUN echo "$NETWORK\n" && echo "$RUST_TOOLCHAIN\n"
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake protobuf-compiler
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth
--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -1,14 +1,8 @@
-FROM ubuntu:20.04
+FROM uniquenetwork/services:latest
 
 ENV DEBIAN_FRONTEND=noninteractive
-ENV TZ=Etc/UTC
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake protobuf-compiler
-
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 ARG RUST_TOOLCHAIN
 ARG NETWORK
modified.docker/Dockerfile-parachaindiffbeforeafterboth
--- a/.docker/Dockerfile-parachain
+++ b/.docker/Dockerfile-parachain
@@ -2,24 +2,13 @@
 FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
 
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
 ARG RUST_TOOLCHAIN=
 ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
 
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
     rustup default $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-parachain-node-onlydiffbeforeafterboth
--- a/.docker/Dockerfile-parachain-node-only
+++ b/.docker/Dockerfile-parachain-node-only
@@ -2,24 +2,13 @@
 FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
 
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
 
 ARG RUST_TOOLCHAIN=
-
 ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
     rustup default $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-parachain-upgradediffbeforeafterboth
--- a/.docker/Dockerfile-parachain-upgrade
+++ b/.docker/Dockerfile-parachain-upgrade
@@ -2,8 +2,7 @@
 FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
 
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
 
 ARG RUST_TOOLCHAIN=
 
@@ -11,15 +10,6 @@
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
     rustup default $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-parachain-upgrade-datadiffbeforeafterboth
--- a/.docker/Dockerfile-parachain-upgrade-data
+++ b/.docker/Dockerfile-parachain-upgrade-data
@@ -2,23 +2,13 @@
 FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
 
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
 ARG RUST_TOOLCHAIN=
 
 ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-testnet.j2diffbeforeafterboth
--- a/.docker/Dockerfile-testnet.j2
+++ b/.docker/Dockerfile-testnet.j2
@@ -1,18 +1,11 @@
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
+ARG RUST_TOOLCHAIN=
 
+ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang llvm libudev-dev protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install {{ RUST_TOOLCHAIN }} && \
modified.docker/Dockerfile-try-runtimediffbeforeafterboth
--- a/.docker/Dockerfile-try-runtime
+++ b/.docker/Dockerfile-try-runtime
@@ -1,6 +1,5 @@
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
 
 ARG RUST_TOOLCHAIN
 
@@ -8,15 +7,6 @@
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install $RUST_TOOLCHAIN && \
modified.docker/Dockerfile-xcm.j2diffbeforeafterboth
--- a/.docker/Dockerfile-xcm.j2
+++ b/.docker/Dockerfile-xcm.j2
@@ -1,18 +1,8 @@
 # ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
 ENV CARGO_HOME="/cargo-home"
 ENV PATH="/cargo-home/bin:$PATH"
 ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
-    apt-get install -y curl cmake pkg-config libssl-dev git clang llvm libudev-dev protobuf-compiler && \
-    apt-get clean && \
-    rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
 
 RUN rustup toolchain uninstall $(rustup toolchain list) && \
     rustup toolchain install {{ RUST_TOOLCHAIN }} && \
modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2340,7 +2340,7 @@
 
 [[package]]
 name = "evm-coder-procedural"
-version = "0.2.2"
+version = "0.2.3"
 dependencies = [
  "Inflector",
  "hex",
@@ -2467,7 +2467,7 @@
 [[package]]
 name = "fc-consensus"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "async-trait",
  "fc-db",
@@ -2486,7 +2486,7 @@
 [[package]]
 name = "fc-db"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "fp-storage",
  "kvdb-rocksdb",
@@ -2505,7 +2505,7 @@
 [[package]]
 name = "fc-mapping-sync"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "fc-db",
  "fp-consensus",
@@ -2522,7 +2522,7 @@
 [[package]]
 name = "fc-rpc"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2565,7 +2565,7 @@
 [[package]]
 name = "fc-rpc-core"
 version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2730,7 +2730,7 @@
 [[package]]
 name = "fp-consensus"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "parity-scale-codec 3.2.1",
@@ -2742,7 +2742,7 @@
 [[package]]
 name = "fp-ethereum"
 version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2757,7 +2757,7 @@
 [[package]]
 name = "fp-evm"
 version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "evm",
  "frame-support",
@@ -2771,7 +2771,7 @@
 [[package]]
 name = "fp-evm-mapping"
 version = "0.1.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "frame-support",
  "sp-core",
@@ -2780,7 +2780,7 @@
 [[package]]
 name = "fp-rpc"
 version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2797,7 +2797,7 @@
 [[package]]
 name = "fp-self-contained"
 version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "frame-support",
@@ -2810,7 +2810,7 @@
 [[package]]
 name = "fp-storage"
 version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "parity-scale-codec 3.2.1",
  "serde",
@@ -5687,7 +5687,7 @@
 [[package]]
 name = "pallet-base-fee"
 version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "fp-evm",
  "frame-support",
@@ -5952,7 +5952,7 @@
 [[package]]
 name = "pallet-ethereum"
 version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -5980,7 +5980,7 @@
 [[package]]
 name = "pallet-evm"
 version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "environmental",
  "evm",
@@ -6066,7 +6066,7 @@
 [[package]]
 name = "pallet-evm-precompile-simple"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
 dependencies = [
  "fp-evm",
  "ripemd",
modifiedcrates/evm-coder/procedural/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder/procedural/Cargo.toml
+++ b/crates/evm-coder/procedural/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "evm-coder-procedural"
-version = "0.2.2"
+version = "0.2.3"
 license = "GPLv3"
 edition = "2021"
 
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -811,6 +811,13 @@
 	let list = generics_list(gen);
 	quote! { <#list> }
 }
+fn generics_stub(gen: &Generics) -> proc_macro2::TokenStream {
+	if gen.params.is_empty() {
+		return quote! {};
+	}
+	let params = (0..gen.params.len()).map(|_| quote! {()});
+	quote! {<#(#params,)*>}
+}
 fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {
 	let list = generics_list(gen);
 	if gen.params.len() == 1 {
@@ -866,6 +873,7 @@
 		let generics = self.generics;
 		let gen_ref = generics_reference(&generics);
 		let gen_data = generics_data(&generics);
+		let gen_stub = generics_stub(&generics);
 		let gen_where = &generics.where_clause;
 
 		let call_sub = self
@@ -936,6 +944,12 @@
 		let solidity_events_idents = self.info.events.0.iter().map(|is| is.name.clone());
 		let docs = &self.docs;
 
+		let expect_selector = self.info.expect_selector.map(|s| {
+            quote! {
+                const _: () = assert!(#s == u32::from_be_bytes(<#call_name #gen_stub>::interface_id()), "selector mismatch, review contained function selectors");
+            }
+        });
+
 		quote! {
 			#(
 				const _: ::core::marker::PhantomData<#solidity_events_idents> = ::core::marker::PhantomData;
@@ -952,12 +966,15 @@
 					#call_sub,
 				)*
 			}
+
+			#expect_selector
+
 			impl #gen_ref #call_name #gen_ref {
 				#(
 					#consts
 				)*
 				/// Return this call ERC165 selector
-				pub fn interface_id() -> ::evm_coder::types::bytes4 {
+				pub const fn interface_id() -> ::evm_coder::types::bytes4 {
 					let mut interface_id = 0;
 					#(#interface_id)*
 					#(#inline_interface_id)*
modifiedcrates/evm-coder/procedural/src/to_log.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/to_log.rs
+++ b/crates/evm-coder/procedural/src/to_log.rs
@@ -16,7 +16,6 @@
 
 use inflector::cases;
 use syn::{Data, DeriveInput, Field, Fields, Ident, Variant, spanned::Spanned};
-use std::fmt::Write;
 use quote::quote;
 
 use crate::{parse_ident_from_path, parse_ident_from_type, snake_ident_to_screaming};
@@ -61,13 +60,13 @@
 	name: Ident,
 	name_screaming: Ident,
 	fields: Vec<EventField>,
-	selector: [u8; 32],
-	selector_str: String,
+	selector: proc_macro2::TokenStream,
 }
 
 impl Event {
 	fn try_from(variant: &Variant) -> syn::Result<Self> {
 		let name = &variant.ident;
+		let name_lit = proc_macro2::Literal::string(name.to_string().as_str());
 		let name_screaming = snake_ident_to_screaming(name);
 
 		let named = match &variant.fields {
@@ -89,22 +88,40 @@
 				"events can have at most 4 indexed fields (1 indexed field is reserved for event signature)"
 			));
 		}
-		let mut selector_str = format!("{}(", name);
-		for (i, arg) in fields.iter().enumerate() {
-			if i != 0 {
-				write!(selector_str, ",").unwrap();
+
+		let args = fields.iter().map(|f| {
+			let ty = &f.ty;
+			quote! {nameof(<#ty as ::evm_coder::abi::AbiType>::SIGNATURE) fixed(",")}
+		});
+		// Remove trailing comma
+		let shift = (!fields.is_empty()).then(|| quote! {shift_left(1)});
+
+		let signature = quote! { ::evm_coder::make_signature!(new fixed(#name_lit) fixed("(") #(#args)* #shift fixed(")")) };
+		let selector = quote! {
+			{
+				let signature = #signature;
+				let mut sum = ::evm_coder::sha3_const::Keccak256::new();
+				let mut pos = 0;
+				while pos < signature.len {
+					sum = sum.update(&[signature.data[pos]; 1]);
+					pos += 1;
+				}
+				let a = sum.finalize();
+				let mut selector_bytes = [0; 32];
+				let mut i = 0;
+				while i != 32 {
+					selector_bytes[i] = a[i];
+					i += 1;
+				}
+				selector_bytes
 			}
-			write!(selector_str, "{}", arg.ty).unwrap();
-		}
-		selector_str.push(')');
-		let selector = crate::event_selector_str(&selector_str);
+		};
 
 		Ok(Self {
 			name: name.to_owned(),
 			name_screaming,
 			fields,
 			selector,
-			selector_str,
 		})
 	}
 
@@ -133,14 +150,10 @@
 
 	fn expand_consts(&self) -> proc_macro2::TokenStream {
 		let name_screaming = &self.name_screaming;
-		let selector_str = &self.selector_str;
 		let selector = &self.selector;
 
 		quote! {
-			#[doc = #selector_str]
-			const #name_screaming: [u8; 32] = [#(
-				#selector,
-			)*];
+			const #name_screaming: [u8; 32] = #selector;
 		}
 	}
 
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -143,7 +143,7 @@
 	AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
 }
 
-#[cfg(feature = "quartz-runtime")]
+#[cfg(not(feature = "unique-runtime"))]
 macro_rules! testnet_genesis {
 	(
 		$runtime:path,
@@ -207,7 +207,7 @@
 	}};
 }
 
-#[cfg(not(feature = "quartz-runtime"))]
+#[cfg(feature = "unique-runtime")]
 macro_rules! testnet_genesis {
 	(
 		$runtime:path,
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -176,7 +176,7 @@
 			key: property_key(p as usize),
 			value: property_value(),
 		}).collect::<Vec<_>>();
-	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props)?}
+	}: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}
 
 	delete_collection_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -188,7 +188,7 @@
 			key: property_key(p as usize),
 			value: property_value(),
 		}).collect::<Vec<_>>();
-		<Pallet<T>>::set_collection_properties(&collection, &owner, props)?;
+		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
 		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
-	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete)?}
+	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}
 }
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -125,7 +125,7 @@
 			.map(eth::Property::try_into)
 			.collect::<Result<Vec<_>>>()?;
 
-		<Pallet<T>>::set_collection_properties(self, &caller, properties)
+		<Pallet<T>>::set_collection_properties(self, &caller, properties.into_iter())
 			.map_err(dispatch_to_evm::<T>)
 	}
 
@@ -158,7 +158,8 @@
 			})
 			.collect::<Result<Vec<_>>>()?;
 
-		<Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)
+		<Pallet<T>>::delete_collection_properties(self, &caller, keys.into_iter())
+			.map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Get collection property.
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -390,8 +390,10 @@
 		Ok(())
 	}
 
-	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.
-	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {
+	/// Returns **true** if
+	/// * the `user`is a collection owner or admin
+	/// * the collection limits allow the owner/admins to transfer/burn any collection token
+	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {
 		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)
 	}
 
@@ -1198,6 +1200,58 @@
 		Ok(())
 	}
 
+	/// This function sets or removes a collection properties according to
+	/// `properties_updates` contents:
+	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
+	///
+	/// This function fires an event for each property change.
+	/// In case of an error, all the changes (including the events) will be reverted
+	/// since the function is transactional.
+	#[transactional]
+	fn modify_collection_properties(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+	) -> DispatchResult {
+		collection.check_is_owner_or_admin(sender)?;
+
+		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);
+
+		for (key, value) in properties_updates {
+			match value {
+				Some(value) => {
+					stored_properties
+						.try_set(key.clone(), value)
+						.map_err(<Error<T>>::from)?;
+
+					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));
+					<PalletEvm<T>>::deposit_log(
+						erc::CollectionHelpersEvents::CollectionChanged {
+							collection_id: eth::collection_id_to_address(collection.id),
+						}
+						.to_log(T::ContractAddress::get()),
+					);
+				}
+				None => {
+					stored_properties.remove(&key).map_err(<Error<T>>::from)?;
+
+					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));
+					<PalletEvm<T>>::deposit_log(
+						erc::CollectionHelpersEvents::CollectionChanged {
+							collection_id: eth::collection_id_to_address(collection.id),
+						}
+						.to_log(T::ContractAddress::get()),
+					);
+				}
+			}
+		}
+
+		<CollectionProperties<T>>::set(collection.id, stored_properties);
+
+		Ok(())
+	}
+
 	/// Set collection property.
 	///
 	/// * `collection` - Collection handler.
@@ -1208,23 +1262,7 @@
 		sender: &T::CrossAccountId,
 		property: Property,
 	) -> DispatchResult {
-		collection.check_is_owner_or_admin(sender)?;
-
-		CollectionProperties::<T>::try_mutate(collection.id, |properties| {
-			let property = property.clone();
-			properties.try_set(property.key, property.value)
-		})
-		.map_err(<Error<T>>::from)?;
-
-		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));
-		<PalletEvm<T>>::deposit_log(
-			erc::CollectionHelpersEvents::CollectionChanged {
-				collection_id: eth::collection_id_to_address(collection.id),
-			}
-			.to_log(T::ContractAddress::get()),
-		);
-
-		Ok(())
+		Self::set_collection_properties(collection, sender, [property].into_iter())
 	}
 
 	/// Set a scoped collection property, where the scope is a special prefix
@@ -1270,17 +1308,16 @@
 	/// * `collection` - Collection handler.
 	/// * `sender` - The owner or administrator of the collection.
 	/// * `properties` - The properties to set.
-	#[transactional]
 	pub fn set_collection_properties(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
-		properties: Vec<Property>,
+		properties: impl Iterator<Item = Property>,
 	) -> DispatchResult {
-		for property in properties {
-			Self::set_collection_property(collection, sender, property)?;
-		}
-
-		Ok(())
+		Self::modify_collection_properties(
+			collection,
+			sender,
+			properties.map(|property| (property.key, Some(property.value))),
+		)
 	}
 
 	/// Delete collection property.
@@ -1293,25 +1330,7 @@
 		sender: &T::CrossAccountId,
 		property_key: PropertyKey,
 	) -> DispatchResult {
-		collection.check_is_owner_or_admin(sender)?;
-
-		CollectionProperties::<T>::try_mutate(collection.id, |properties| {
-			properties.remove(&property_key)
-		})
-		.map_err(<Error<T>>::from)?;
-
-		Self::deposit_event(Event::CollectionPropertyDeleted(
-			collection.id,
-			property_key,
-		));
-		<PalletEvm<T>>::deposit_log(
-			erc::CollectionHelpersEvents::CollectionChanged {
-				collection_id: eth::collection_id_to_address(collection.id),
-			}
-			.to_log(T::ContractAddress::get()),
-		);
-
-		Ok(())
+		Self::delete_collection_properties(collection, sender, [property_key].into_iter())
 	}
 
 	/// Delete collection properties.
@@ -1319,17 +1338,12 @@
 	/// * `collection` - Collection handler.
 	/// * `sender` - The owner or administrator of the collection.
 	/// * `properties` - The properties to delete.
-	#[transactional]
 	pub fn delete_collection_properties(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
-		property_keys: Vec<PropertyKey>,
+		property_keys: impl Iterator<Item = PropertyKey>,
 	) -> DispatchResult {
-		for key in property_keys {
-			Self::delete_collection_property(collection, sender, key)?;
-		}
-
-		Ok(())
+		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))
 	}
 
 	/// Set collection propetry permission without any checks.
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -266,7 +266,7 @@
 		sender: &T::CrossAccountId,
 		properties: Vec<Property>,
 	) -> DispatchResult {
-		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())
 	}
 
 	/// Delete properties of the collection, associated with the provided keys.
@@ -275,7 +275,11 @@
 		sender: &T::CrossAccountId,
 		property_keys: Vec<PropertyKey>,
 	) -> DispatchResult {
-		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+		<PalletCommon<T>>::delete_collection_properties(
+			collection,
+			sender,
+			property_keys.into_iter(),
+		)
 	}
 
 	/// Checks if collection has tokens. Return `true` if it has.
@@ -673,8 +677,14 @@
 			// `from`, `to` checked in [`transfer`]
 			collection.check_allowlist(spender)?;
 		}
+
+		if collection.ignores_token_restrictions(spender) {
+			return Ok(Self::compute_allowance_decrease(
+				collection, from, spender, amount,
+			));
+		}
+
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
-			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
 				<PalletStructure<T>>::check_indirectly_owned(
 					spender.clone(),
@@ -687,17 +697,24 @@
 			);
 			return Ok(None);
 		}
-		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
-		if allowance.is_none() {
-			ensure!(
-				collection.ignores_allowance(spender),
-				<CommonError<T>>::ApprovedValueTooLow
-			);
-		}
 
+		let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);
+		ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);
+
 		Ok(allowance)
 	}
 
+	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+	/// Otherwise, it returns `None`.
+	fn compute_allowance_decrease(
+		collection: &FungibleHandle<T>,
+		from: &T::CrossAccountId,
+		spender: &T::CrossAccountId,
+		amount: u128,
+	) -> Option<u128> {
+		<Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)
+	}
+
 	/// Transfer fungible tokens from one account to another.
 	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
 	/// The owner should set allowance for the spender to transfer pieces.
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -524,11 +524,6 @@
 
 		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))
 	}
-
-	/// @notice Returns collection helper contract address
-	fn collection_helper_address(&self) -> Result<address> {
-		Ok(T::ContractAddress::get())
-	}
 }
 
 /// @title ERC721 Token that can be irreversibly burned (destroyed).
@@ -1058,6 +1053,11 @@
 
 		Ok(token_id.into())
 	}
+
+	/// @notice Returns collection helper contract address
+	fn collection_helper_address(&self) -> Result<address> {
+		Ok(T::ContractAddress::get())
+	}
 }
 
 #[solidity_interface(
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -577,20 +577,29 @@
 		})
 	}
 
-	/// Batch operation to add, edit or remove properties for the token
-	///
-	/// All affected properties should have mutable permission and sender should have
-	/// permission to edit those properties.
+	/// A batch operation to add, edit or remove properties for a token.
+	/// It sets or removes a token's properties according to
+	/// `properties_updates` contents:
+	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
 	///
-	/// - `nesting_budget`: Limit for searching parents in depth to check ownership.
+	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
 	/// - `is_token_create`: Indicates that method is called during token initialization.
 	///   Allows to bypass ownership check.
+	///
+	/// All affected properties should have `mutable` permission
+	/// to be **deleted** or to be **set more than once**,
+	/// and the sender should have permission to edit those properties.
+	///
+	/// This function fires an event for each property change.
+	/// In case of an error, all the changes (including the events) will be reverted
+	/// since the function is transactional.
 	#[transactional]
 	fn modify_token_properties(
 		collection: &NonfungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
-		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
 		is_token_create: bool,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
@@ -614,15 +623,16 @@
 			})
 		};
 
-		for (key, value) in properties {
-			let permission = <PalletCommon<T>>::property_permissions(collection.id)
+		let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
+		let permissions = <PalletCommon<T>>::property_permissions(collection.id);
+
+		for (key, value) in properties_updates {
+			let permission = permissions
 				.get(&key)
 				.cloned()
 				.unwrap_or_else(PropertyPermission::none);
 
-			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
-				.get(&key)
-				.is_some();
+			let is_property_exists = stored_properties.get(&key).is_some();
 
 			match permission {
 				PropertyPermission { mutable: false, .. } if is_property_exists => {
@@ -649,10 +659,9 @@
 
 			match value {
 				Some(value) => {
-					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
-						properties.try_set(key.clone(), value)
-					})
-					.map_err(<CommonError<T>>::from)?;
+					stored_properties
+						.try_set(key.clone(), value)
+						.map_err(<CommonError<T>>::from)?;
 
 					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
 						collection.id,
@@ -661,10 +670,9 @@
 					));
 				}
 				None => {
-					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
-						properties.remove(&key)
-					})
-					.map_err(<CommonError<T>>::from)?;
+					stored_properties
+						.remove(&key)
+						.map_err(<CommonError<T>>::from)?;
 
 					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
 						collection.id,
@@ -683,6 +691,8 @@
 			);
 		}
 
+		<TokenProperties<T>>::set((collection.id, token_id), stored_properties);
+
 		Ok(())
 	}
 
@@ -784,7 +794,7 @@
 		sender: &T::CrossAccountId,
 		properties: Vec<Property>,
 	) -> DispatchResult {
-		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())
 	}
 
 	/// Remove properties from the collection
@@ -793,7 +803,11 @@
 		sender: &T::CrossAccountId,
 		property_keys: Vec<PropertyKey>,
 	) -> DispatchResult {
-		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+		<PalletCommon<T>>::delete_collection_properties(
+			collection,
+			sender,
+			property_keys.into_iter(),
+		)
 	}
 
 	/// Set property permissions for the token.
@@ -1232,7 +1246,7 @@
 			collection.check_allowlist(spender)?;
 		}
 
-		if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {
+		if collection.ignores_token_restrictions(spender) {
 			return Ok(());
 		}
 
@@ -1255,11 +1269,8 @@
 		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
 			return Ok(());
 		}
-		ensure!(
-			collection.ignores_allowance(spender),
-			<CommonError<T>>::ApprovedValueTooLow
-		);
-		Ok(())
+
+		Err(<CommonError<T>>::ApprovedValueTooLow.into())
 	}
 
 	/// Transfer NFT token from one account to another.
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -785,7 +785,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e48fdb4
+/// @dev the ERC-165 identifier for this interface is 0x16de3152
 contract ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -986,6 +986,15 @@
 		dummy = 0;
 		return 0;
 	}
+
+	/// @notice Returns collection helper contract address
+	/// @dev EVM selector for this function is: 0x1896cce6,
+	///  or in textual repr: collectionHelperAddress()
+	function collectionHelperAddress() public view returns (address) {
+		require(false, stub_error);
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
 }
 
 /// @dev anonymous struct
@@ -1043,7 +1052,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard
 /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x983a942b
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
 contract ERC721 is Dummy, ERC165, ERC721Events {
 	/// @notice Count all NFTs assigned to an owner
 	/// @dev NFTs assigned to the zero address are considered invalid, and this
@@ -1175,15 +1184,6 @@
 		operator;
 		dummy;
 		return false;
-	}
-
-	/// @notice Returns collection helper contract address
-	/// @dev EVM selector for this function is: 0x1896cce6,
-	///  or in textual repr: collectionHelperAddress()
-	function collectionHelperAddress() public view returns (address) {
-		require(false, stub_error);
-		dummy;
-		return 0x0000000000000000000000000000000000000000;
 	}
 }
 
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -184,21 +184,21 @@
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_361_000 as u64)
-			// Standard Error: 5_349_868
-			.saturating_add(Weight::from_ref_time(637_246_356 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(31_850_484 as u64)
+			// Standard Error: 9_618
+			.saturating_add(Weight::from_ref_time(4_721_947 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_489_000 as u64)
-			// Standard Error: 5_738_954
-			.saturating_add(Weight::from_ref_time(689_912_822 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(13_795_000 as u64)
+			// Standard Error: 28_239
+			.saturating_add(Weight::from_ref_time(12_840_446 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
@@ -354,21 +354,21 @@
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_361_000 as u64)
-			// Standard Error: 5_349_868
-			.saturating_add(Weight::from_ref_time(637_246_356 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(31_850_484 as u64)
+			// Standard Error: 9_618
+			.saturating_add(Weight::from_ref_time(4_721_947 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_489_000 as u64)
-			// Standard Error: 5_738_954
-			.saturating_add(Weight::from_ref_time(689_912_822 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(13_795_000 as u64)
+			// Standard Error: 28_239
+			.saturating_add(Weight::from_ref_time(12_840_446 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -295,7 +295,9 @@
 	MintingFinished {},
 }
 
-#[solidity_interface(name = ERC721Metadata)]
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
 impl<T: Config> RefungibleHandle<T>
 where
 	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
@@ -364,7 +366,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 /// @dev See https://eips.ethereum.org/EIPS/eip-721
-#[solidity_interface(name = ERC721Enumerable)]
+#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]
 impl<T: Config> RefungibleHandle<T> {
 	/// @notice Enumerate valid RFTs
 	/// @param index A counter less than `totalSupply()`
@@ -391,7 +393,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard
 /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-#[solidity_interface(name = ERC721, events(ERC721Events))]
+#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]
 impl<T: Config> RefungibleHandle<T> {
 	/// @notice Count all RFTs assigned to an owner
 	/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -422,6 +424,7 @@
 	}
 
 	/// @dev Not implemented
+	#[solidity(rename_selector = "safeTransferFrom")]
 	fn safe_transfer_from_with_data(
 		&mut self,
 		_from: address,
@@ -434,6 +437,7 @@
 	}
 
 	/// @dev Not implemented
+	#[solidity(rename_selector = "safeTransferFrom")]
 	fn safe_transfer_from(
 		&mut self,
 		_from: address,
@@ -517,11 +521,6 @@
 
 		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))
 	}
-
-	/// @notice Returns collection helper contract address
-	fn collection_helper_address(&self) -> Result<address> {
-		Ok(T::ContractAddress::get())
-	}
 }
 
 /// Returns amount of pieces of `token` that `owner` have
@@ -1116,6 +1115,11 @@
 			token.try_into().map_err(|_| "token id overflow")?,
 		))
 	}
+
+	/// @notice Returns collection helper contract address
+	fn collection_helper_address(&self) -> Result<address> {
+		Ok(T::ContractAddress::get())
+	}
 }
 
 #[solidity_interface(
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100	Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109	PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,110	TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122	CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127	use super::*;128	use frame_support::{129		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130		traits::StorageVersion,131	};132	use up_data_structs::{CollectionId, TokenId};133	use super::weights::WeightInfo;134135	#[pallet::error]136	pub enum Error<T> {137		/// Not Refungible item data used to mint in Refungible collection.138		NotRefungibleDataUsedToMintFungibleCollectionToken,139		/// Maximum refungibility exceeded.140		WrongRefungiblePieces,141		/// Refungible token can't be repartitioned by user who isn't owns all pieces.142		RepartitionWhileNotOwningAllPieces,143		/// Refungible token can't nest other tokens.144		RefungibleDisallowsNesting,145		/// Setting item properties is not allowed.146		SettingPropertiesNotAllowed,147	}148149	#[pallet::config]150	pub trait Config:151		frame_system::Config + pallet_common::Config + pallet_structure::Config152	{153		type WeightInfo: WeightInfo;154	}155156	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158	#[pallet::pallet]159	#[pallet::storage_version(STORAGE_VERSION)]160	#[pallet::generate_store(pub(super) trait Store)]161	pub struct Pallet<T>(_);162163	/// Total amount of minted tokens in a collection.164	#[pallet::storage]165	pub type TokensMinted<T: Config> =166		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168	/// Amount of tokens burnt in a collection.169	#[pallet::storage]170	pub type TokensBurnt<T: Config> =171		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173	/// Amount of pieces a refungible token is split into.174	#[pallet::storage]175	#[pallet::getter(fn token_properties)]176	pub type TokenProperties<T: Config> = StorageNMap<177		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178		Value = up_data_structs::Properties,179		QueryKind = ValueQuery,180		OnEmpty = up_data_structs::TokenProperties,181	>;182183	/// Total amount of pieces for token184	#[pallet::storage]185	pub type TotalSupply<T: Config> = StorageNMap<186		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187		Value = u128,188		QueryKind = ValueQuery,189	>;190191	/// Used to enumerate tokens owned by account.192	#[pallet::storage]193	pub type Owned<T: Config> = StorageNMap<194		Key = (195			Key<Twox64Concat, CollectionId>,196			Key<Blake2_128Concat, T::CrossAccountId>,197			Key<Twox64Concat, TokenId>,198		),199		Value = bool,200		QueryKind = ValueQuery,201	>;202203	/// Amount of tokens (not pieces) partially owned by an account within a collection.204	#[pallet::storage]205	pub type AccountBalance<T: Config> = StorageNMap<206		Key = (207			Key<Twox64Concat, CollectionId>,208			// Owner209			Key<Blake2_128Concat, T::CrossAccountId>,210		),211		Value = u32,212		QueryKind = ValueQuery,213	>;214215	/// Amount of token pieces owned by account.216	#[pallet::storage]217	pub type Balance<T: Config> = StorageNMap<218		Key = (219			Key<Twox64Concat, CollectionId>,220			Key<Twox64Concat, TokenId>,221			// Owner222			Key<Blake2_128Concat, T::CrossAccountId>,223		),224		Value = u128,225		QueryKind = ValueQuery,226	>;227228	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229	#[pallet::storage]230	pub type Allowance<T: Config> = StorageNMap<231		Key = (232			Key<Twox64Concat, CollectionId>,233			Key<Twox64Concat, TokenId>,234			// Owner235			Key<Blake2_128, T::CrossAccountId>,236			// Spender237			Key<Blake2_128Concat, T::CrossAccountId>,238		),239		Value = u128,240		QueryKind = ValueQuery,241	>;242243	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.244	#[pallet::storage]245	pub type CollectionAllowance<T: Config> = StorageNMap<246		Key = (247			Key<Twox64Concat, CollectionId>,248			Key<Blake2_128Concat, T::CrossAccountId>,249			Key<Blake2_128Concat, T::CrossAccountId>,250		),251		Value = bool,252		QueryKind = ValueQuery,253	>;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259		Self(inner)260	}261	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262		self.0263	}264	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265		&mut self.0266	}267}268269impl<T: Config> Deref for RefungibleHandle<T> {270	type Target = pallet_common::CollectionHandle<T>;271272	fn deref(&self) -> &Self::Target {273		&self.0274	}275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279		self.0.recorder()280	}281	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282		self.0.into_recorder()283	}284}285286impl<T: Config> Pallet<T> {287	/// Get number of RFT tokens in collection288	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290	}291292	/// Check that RFT token exists293	///294	/// - `token`: Token ID.295	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296		<TotalSupply<T>>::contains_key((collection.id, token))297	}298299	pub fn set_scoped_token_property(300		collection_id: CollectionId,301		token_id: TokenId,302		scope: PropertyScope,303		property: Property,304	) -> DispatchResult {305		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306			properties.try_scoped_set(scope, property.key, property.value)307		})308		.map_err(<CommonError<T>>::from)?;309310		Ok(())311	}312313	pub fn set_scoped_token_properties(314		collection_id: CollectionId,315		token_id: TokenId,316		scope: PropertyScope,317		properties: impl Iterator<Item = Property>,318	) -> DispatchResult {319		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320			stored_properties.try_scoped_set_from_iter(scope, properties)321		})322		.map_err(<CommonError<T>>::from)?;323324		Ok(())325	}326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330	/// Create RFT collection331	///332	/// `init_collection` will take non-refundable deposit for collection creation.333	///334	/// - `data`: Contains settings for collection limits and permissions.335	pub fn init_collection(336		owner: T::CrossAccountId,337		payer: T::CrossAccountId,338		data: CreateCollectionData<T::AccountId>,339		flags: CollectionFlags,340	) -> Result<CollectionId, DispatchError> {341		<PalletCommon<T>>::init_collection(owner, payer, data, flags)342	}343344	/// Destroy RFT collection345	///346	/// `destroy_collection` will throw error if collection contains any tokens.347	/// Only owner can destroy collection.348	pub fn destroy_collection(349		collection: RefungibleHandle<T>,350		sender: &T::CrossAccountId,351	) -> DispatchResult {352		let id = collection.id;353354		if Self::collection_has_tokens(id) {355			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356		}357358		// =========359360		PalletCommon::destroy_collection(collection.0, sender)?;361362		<TokensMinted<T>>::remove(id);363		<TokensBurnt<T>>::remove(id);364		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369		Ok(())370	}371372	fn collection_has_tokens(collection_id: CollectionId) -> bool {373		<TotalSupply<T>>::iter_prefix((collection_id,))374			.next()375			.is_some()376	}377378	pub fn burn_token_unchecked(379		collection: &RefungibleHandle<T>,380		owner: &T::CrossAccountId,381		token_id: TokenId,382	) -> DispatchResult {383		let burnt = <TokensBurnt<T>>::get(collection.id)384			.checked_add(1)385			.ok_or(ArithmeticError::Overflow)?;386387		<TokensBurnt<T>>::insert(collection.id, burnt);388		<TokenProperties<T>>::remove((collection.id, token_id));389		<TotalSupply<T>>::remove((collection.id, token_id));390		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392		<PalletEvm<T>>::deposit_log(393			ERC721Events::Transfer {394				from: *owner.as_eth(),395				to: H160::default(),396				token_id: token_id.into(),397			}398			.to_log(collection_id_to_address(collection.id)),399		);400		Ok(())401	}402403	/// Burn RFT token pieces404	///405	/// `burn` will decrease total amount of token pieces and amount owned by sender.406	/// `burn` can be called even if there are multiple owners of the RFT token.407	/// If sender wouldn't have any pieces left after `burn` than she will stop being408	/// one of the owners of the token. If there is no account that owns any pieces of409	/// the token than token will be burned too.410	///411	/// - `amount`: Amount of token pieces to burn.412	/// - `token`: Token who's pieces should be burned413	/// - `collection`: Collection that contains the token414	pub fn burn(415		collection: &RefungibleHandle<T>,416		owner: &T::CrossAccountId,417		token: TokenId,418		amount: u128,419	) -> DispatchResult {420		if <Balance<T>>::get((collection.id, token, owner)) == 0 {421			return Err(<CommonError<T>>::TokenValueTooLow.into());422		}423424		let total_supply = <TotalSupply<T>>::get((collection.id, token))425			.checked_sub(amount)426			.ok_or(<CommonError<T>>::TokenValueTooLow)?;427428		// This was probally last owner of this token?429		if total_supply == 0 {430			// Ensure user actually owns this amount431			ensure!(432				<Balance<T>>::get((collection.id, token, owner)) == amount,433				<CommonError<T>>::TokenValueTooLow434			);435			let account_balance = <AccountBalance<T>>::get((collection.id, owner))436				.checked_sub(1)437				// Should not occur438				.ok_or(ArithmeticError::Underflow)?;439440			// =========441442			<Owned<T>>::remove((collection.id, owner, token));443			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444			<AccountBalance<T>>::insert((collection.id, owner), account_balance);445			Self::burn_token_unchecked(collection, owner, token)?;446			<PalletEvm<T>>::deposit_log(447				ERC20Events::Transfer {448					from: *owner.as_eth(),449					to: H160::default(),450					value: amount.into(),451				}452				.to_log(collection_id_to_address(collection.id)),453			);454			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455				collection.id,456				token,457				owner.clone(),458				amount,459			));460			return Ok(());461		}462463		let balance = <Balance<T>>::get((collection.id, token, owner))464			.checked_sub(amount)465			.ok_or(<CommonError<T>>::TokenValueTooLow)?;466		let account_balance = if balance == 0 {467			<AccountBalance<T>>::get((collection.id, owner))468				.checked_sub(1)469				// Should not occur470				.ok_or(ArithmeticError::Underflow)?471		} else {472			0473		};474475		// =========476477		if balance == 0 {478			<Owned<T>>::remove((collection.id, owner, token));479			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480			<Balance<T>>::remove((collection.id, token, owner));481			<AccountBalance<T>>::insert((collection.id, owner), account_balance);482483			if let Some(user) = Self::token_owner(collection.id, token) {484				<PalletEvm<T>>::deposit_log(485					ERC721Events::Transfer {486						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487						to: *user.as_eth(),488						token_id: token.into(),489					}490					.to_log(collection_id_to_address(collection.id)),491				);492			}493		} else {494			<Balance<T>>::insert((collection.id, token, owner), balance);495		}496		<TotalSupply<T>>::insert((collection.id, token), total_supply);497498		<PalletEvm<T>>::deposit_log(499			ERC20Events::Transfer {500				from: *owner.as_eth(),501				to: H160::default(),502				value: amount.into(),503			}504			.to_log(T::EvmTokenAddressMapping::token_to_address(505				collection.id,506				token,507			)),508		);509		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510			collection.id,511			token,512			owner.clone(),513			amount,514		));515		Ok(())516	}517518	#[transactional]519	fn modify_token_properties(520		collection: &RefungibleHandle<T>,521		sender: &T::CrossAccountId,522		token_id: TokenId,523		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524		is_token_create: bool,525		nesting_budget: &dyn Budget,526	) -> DispatchResult {527		let is_collection_admin = || collection.is_owner_or_admin(sender);528		let is_token_owner = || -> Result<bool, DispatchError> {529			let balance = collection.balance(sender.clone(), token_id);530			let total_pieces: u128 =531				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532			if balance != total_pieces {533				return Ok(false);534			}535536			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537				sender.clone(),538				collection.id,539				token_id,540				None,541				nesting_budget,542			)?;543544			Ok(is_bundle_owner)545		};546547		for (key, value) in properties {548			let permission = <PalletCommon<T>>::property_permissions(collection.id)549				.get(&key)550				.cloned()551				.unwrap_or_else(PropertyPermission::none);552553			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554				.get(&key)555				.is_some();556557			match permission {558				PropertyPermission { mutable: false, .. } if is_property_exists => {559					return Err(<CommonError<T>>::NoPermission.into());560				}561562				PropertyPermission {563					collection_admin,564					token_owner,565					..566				} => {567					//TODO: investigate threats during public minting.568					let is_token_create =569						is_token_create && (collection_admin || token_owner) && value.is_some();570					if !(is_token_create571						|| (collection_admin && is_collection_admin())572						|| (token_owner && is_token_owner()?))573					{574						fail!(<CommonError<T>>::NoPermission);575					}576				}577			}578579			match value {580				Some(value) => {581					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582						properties.try_set(key.clone(), value)583					})584					.map_err(<CommonError<T>>::from)?;585586					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587						collection.id,588						token_id,589						key,590					));591				}592				None => {593					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594						properties.remove(&key)595					})596					.map_err(<CommonError<T>>::from)?;597598					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599						collection.id,600						token_id,601						key,602					));603				}604			}605606			<PalletEvm<T>>::deposit_log(607				CollectionHelpersEvents::TokenChanged {608					collection_id: collection_id_to_address(collection.id),609					token_id: token_id.into(),610				}611				.to_log(T::ContractAddress::get()),612			);613		}614615		Ok(())616	}617618	pub fn set_token_properties(619		collection: &RefungibleHandle<T>,620		sender: &T::CrossAccountId,621		token_id: TokenId,622		properties: impl Iterator<Item = Property>,623		is_token_create: bool,624		nesting_budget: &dyn Budget,625	) -> DispatchResult {626		Self::modify_token_properties(627			collection,628			sender,629			token_id,630			properties.map(|p| (p.key, Some(p.value))),631			is_token_create,632			nesting_budget,633		)634	}635636	pub fn set_token_property(637		collection: &RefungibleHandle<T>,638		sender: &T::CrossAccountId,639		token_id: TokenId,640		property: Property,641		nesting_budget: &dyn Budget,642	) -> DispatchResult {643		let is_token_create = false;644645		Self::set_token_properties(646			collection,647			sender,648			token_id,649			[property].into_iter(),650			is_token_create,651			nesting_budget,652		)653	}654655	pub fn delete_token_properties(656		collection: &RefungibleHandle<T>,657		sender: &T::CrossAccountId,658		token_id: TokenId,659		property_keys: impl Iterator<Item = PropertyKey>,660		nesting_budget: &dyn Budget,661	) -> DispatchResult {662		let is_token_create = false;663664		Self::modify_token_properties(665			collection,666			sender,667			token_id,668			property_keys.into_iter().map(|key| (key, None)),669			is_token_create,670			nesting_budget,671		)672	}673674	pub fn delete_token_property(675		collection: &RefungibleHandle<T>,676		sender: &T::CrossAccountId,677		token_id: TokenId,678		property_key: PropertyKey,679		nesting_budget: &dyn Budget,680	) -> DispatchResult {681		Self::delete_token_properties(682			collection,683			sender,684			token_id,685			[property_key].into_iter(),686			nesting_budget,687		)688	}689690	/// Transfer RFT token pieces from one account to another.691	///692	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.693	///694	/// - `from`: Owner of token pieces to transfer.695	/// - `to`: Recepient of transfered token pieces.696	/// - `amount`: Amount of token pieces to transfer.697	/// - `token`: Token whos pieces should be transfered698	/// - `collection`: Collection that contains the token699	pub fn transfer(700		collection: &RefungibleHandle<T>,701		from: &T::CrossAccountId,702		to: &T::CrossAccountId,703		token: TokenId,704		amount: u128,705		nesting_budget: &dyn Budget,706	) -> DispatchResult {707		ensure!(708			collection.limits.transfers_enabled(),709			<CommonError<T>>::TransferNotAllowed710		);711712		if collection.permissions.access() == AccessMode::AllowList {713			collection.check_allowlist(from)?;714			collection.check_allowlist(to)?;715		}716		<PalletCommon<T>>::ensure_correct_receiver(to)?;717718		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));719720		if initial_balance_from == 0 {721			return Err(<CommonError<T>>::TokenValueTooLow.into());722		}723724		let updated_balance_from = initial_balance_from725			.checked_sub(amount)726			.ok_or(<CommonError<T>>::TokenValueTooLow)?;727		let mut create_target = false;728		let from_to_differ = from != to;729		let updated_balance_to = if from != to && amount != 0 {730			let old_balance = <Balance<T>>::get((collection.id, token, to));731			if old_balance == 0 {732				create_target = true;733			}734			Some(735				old_balance736					.checked_add(amount)737					.ok_or(ArithmeticError::Overflow)?,738			)739		} else {740			None741		};742743		let account_balance_from = if updated_balance_from == 0 {744			Some(745				<AccountBalance<T>>::get((collection.id, from))746					.checked_sub(1)747					// Should not occur748					.ok_or(ArithmeticError::Underflow)?,749			)750		} else {751			None752		};753		// Account data is created in token, AccountBalance should be increased754		// But only if from != to as we shouldn't check overflow in this case755		let account_balance_to = if create_target && from_to_differ {756			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))757				.checked_add(1)758				.ok_or(ArithmeticError::Overflow)?;759			ensure!(760				account_balance_to < collection.limits.account_token_ownership_limit(),761				<CommonError<T>>::AccountTokenLimitExceeded,762			);763764			Some(account_balance_to)765		} else {766			None767		};768769		// =========770771		if let Some(updated_balance_to) = updated_balance_to {772			// from != to && amount != 0773774			<PalletStructure<T>>::nest_if_sent_to_token(775				from.clone(),776				to,777				collection.id,778				token,779				nesting_budget,780			)?;781782			if updated_balance_from == 0 {783				<Balance<T>>::remove((collection.id, token, from));784				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);785			} else {786				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);787			}788			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);789			if let Some(account_balance_from) = account_balance_from {790				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);791				<Owned<T>>::remove((collection.id, from, token));792			}793			if let Some(account_balance_to) = account_balance_to {794				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);795				<Owned<T>>::insert((collection.id, to, token), true);796			}797		}798799		<PalletEvm<T>>::deposit_log(800			ERC20Events::Transfer {801				from: *from.as_eth(),802				to: *to.as_eth(),803				value: amount.into(),804			}805			.to_log(T::EvmTokenAddressMapping::token_to_address(806				collection.id,807				token,808			)),809		);810811		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(812			collection.id,813			token,814			from.clone(),815			to.clone(),816			amount,817		));818819		let total_supply = <TotalSupply<T>>::get((collection.id, token));820821		if amount == total_supply {822			// if token was fully owned by `from` and will be fully owned by `to` after transfer823			<PalletEvm<T>>::deposit_log(824				ERC721Events::Transfer {825					from: *from.as_eth(),826					to: *to.as_eth(),827					token_id: token.into(),828				}829				.to_log(collection_id_to_address(collection.id)),830			);831		} else if let Some(updated_balance_to) = updated_balance_to {832			// if `from` not equals `to`. This condition is needed to avoid sending event833			// when `from` fully owns token and sends part of token pieces to itself.834			if initial_balance_from == total_supply {835				// if token was fully owned by `from` and will be only partially owned by `to`836				// and `from` after transfer837				<PalletEvm<T>>::deposit_log(838					ERC721Events::Transfer {839						from: *from.as_eth(),840						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,841						token_id: token.into(),842					}843					.to_log(collection_id_to_address(collection.id)),844				);845			} else if updated_balance_to == total_supply {846				// if token was partially owned by `from` and will be fully owned by `to` after transfer847				<PalletEvm<T>>::deposit_log(848					ERC721Events::Transfer {849						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,850						to: *to.as_eth(),851						token_id: token.into(),852					}853					.to_log(collection_id_to_address(collection.id)),854				);855			}856		}857858		Ok(())859	}860861	/// Batched operation to create multiple RFT tokens.862	///863	/// Same as `create_item` but creates multiple tokens.864	///865	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.866	pub fn create_multiple_items(867		collection: &RefungibleHandle<T>,868		sender: &T::CrossAccountId,869		data: Vec<CreateItemData<T>>,870		nesting_budget: &dyn Budget,871	) -> DispatchResult {872		if !collection.is_owner_or_admin(sender) {873			ensure!(874				collection.permissions.mint_mode(),875				<CommonError<T>>::PublicMintingNotAllowed876			);877			collection.check_allowlist(sender)?;878879			for item in data.iter() {880				for user in item.users.keys() {881					collection.check_allowlist(user)?;882				}883			}884		}885886		for item in data.iter() {887			for (owner, _) in item.users.iter() {888				<PalletCommon<T>>::ensure_correct_receiver(owner)?;889			}890		}891892		// Total pieces per tokens893		let totals = data894			.iter()895			.map(|data| {896				Ok(data897					.users898					.iter()899					.map(|u| u.1)900					.try_fold(0u128, |acc, v| acc.checked_add(*v))901					.ok_or(ArithmeticError::Overflow)?)902			})903			.collect::<Result<Vec<_>, DispatchError>>()?;904		for total in &totals {905			ensure!(906				*total <= MAX_REFUNGIBLE_PIECES,907				<Error<T>>::WrongRefungiblePieces908			);909		}910911		let first_token_id = <TokensMinted<T>>::get(collection.id);912		let tokens_minted = first_token_id913			.checked_add(data.len() as u32)914			.ok_or(ArithmeticError::Overflow)?;915		ensure!(916			tokens_minted < collection.limits.token_limit(),917			<CommonError<T>>::CollectionTokenLimitExceeded918		);919920		let mut balances = BTreeMap::new();921		for data in &data {922			for owner in data.users.keys() {923				let balance = balances924					.entry(owner)925					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));926				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;927928				ensure!(929					*balance <= collection.limits.account_token_ownership_limit(),930					<CommonError<T>>::AccountTokenLimitExceeded,931				);932			}933		}934935		for (i, token) in data.iter().enumerate() {936			let token_id = TokenId(first_token_id + i as u32 + 1);937			for (to, _) in token.users.iter() {938				<PalletStructure<T>>::check_nesting(939					sender.clone(),940					to,941					collection.id,942					token_id,943					nesting_budget,944				)?;945			}946		}947948		// =========949950		with_transaction(|| {951			for (i, data) in data.iter().enumerate() {952				let token_id = first_token_id + i as u32 + 1;953				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);954955				for (user, amount) in data.users.iter() {956					if *amount == 0 {957						continue;958					}959					<Balance<T>>::insert((collection.id, token_id, &user), amount);960					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);961					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(962						user,963						collection.id,964						TokenId(token_id),965					);966				}967968				if let Err(e) = Self::set_token_properties(969					collection,970					sender,971					TokenId(token_id),972					data.properties.clone().into_iter(),973					true,974					nesting_budget,975				) {976					return TransactionOutcome::Rollback(Err(e));977				}978			}979			TransactionOutcome::Commit(Ok(()))980		})?;981982		<TokensMinted<T>>::insert(collection.id, tokens_minted);983984		for (account, balance) in balances {985			<AccountBalance<T>>::insert((collection.id, account), balance);986		}987988		for (i, token) in data.into_iter().enumerate() {989			let token_id = first_token_id + i as u32 + 1;990991			let receivers = token992				.users993				.into_iter()994				.filter(|(_, amount)| *amount > 0)995				.collect::<Vec<_>>();996997			if let [(user, _)] = receivers.as_slice() {998				// if there is exactly one receiver999				<PalletEvm<T>>::deposit_log(1000					ERC721Events::Transfer {1001						from: H160::default(),1002						to: *user.as_eth(),1003						token_id: token_id.into(),1004					}1005					.to_log(collection_id_to_address(collection.id)),1006				);1007			} else if let [_, ..] = receivers.as_slice() {1008				// if there is more than one receiver1009				<PalletEvm<T>>::deposit_log(1010					ERC721Events::Transfer {1011						from: H160::default(),1012						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1013						token_id: token_id.into(),1014					}1015					.to_log(collection_id_to_address(collection.id)),1016				);1017			}10181019			for (user, amount) in receivers.into_iter() {1020				<PalletEvm<T>>::deposit_log(1021					ERC20Events::Transfer {1022						from: H160::default(),1023						to: *user.as_eth(),1024						value: amount.into(),1025					}1026					.to_log(T::EvmTokenAddressMapping::token_to_address(1027						collection.id,1028						TokenId(token_id),1029					)),1030				);1031				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1032					collection.id,1033					TokenId(token_id),1034					user,1035					amount,1036				));1037			}1038		}1039		Ok(())1040	}10411042	pub fn set_allowance_unchecked(1043		collection: &RefungibleHandle<T>,1044		sender: &T::CrossAccountId,1045		spender: &T::CrossAccountId,1046		token: TokenId,1047		amount: u128,1048	) {1049		if amount == 0 {1050			<Allowance<T>>::remove((collection.id, token, sender, spender));1051		} else {1052			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1053		}10541055		<PalletEvm<T>>::deposit_log(1056			ERC20Events::Approval {1057				owner: *sender.as_eth(),1058				spender: *spender.as_eth(),1059				value: amount.into(),1060			}1061			.to_log(T::EvmTokenAddressMapping::token_to_address(1062				collection.id,1063				token,1064			)),1065		);1066		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1067			collection.id,1068			token,1069			sender.clone(),1070			spender.clone(),1071			amount,1072		))1073	}10741075	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1076	///1077	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1078	pub fn set_allowance(1079		collection: &RefungibleHandle<T>,1080		sender: &T::CrossAccountId,1081		spender: &T::CrossAccountId,1082		token: TokenId,1083		amount: u128,1084	) -> DispatchResult {1085		if collection.permissions.access() == AccessMode::AllowList {1086			collection.check_allowlist(sender)?;1087			collection.check_allowlist(spender)?;1088		}10891090		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10911092		if <Balance<T>>::get((collection.id, token, sender)) < amount {1093			ensure!(1094				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1095				<CommonError<T>>::CantApproveMoreThanOwned1096			);1097		}10981099		// =========11001101		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1102		Ok(())1103	}11041105	/// Set allowance to spend from sender's eth mirror1106	///1107	/// - `from`: Address of sender's eth mirror.1108	/// - `to`: Adress of spender.1109	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1110	pub fn set_allowance_from(1111		collection: &RefungibleHandle<T>,1112		sender: &T::CrossAccountId,1113		from: &T::CrossAccountId,1114		to: &T::CrossAccountId,1115		token_id: TokenId,1116		amount: u128,1117	) -> DispatchResult {1118		if collection.permissions.access() == AccessMode::AllowList {1119			collection.check_allowlist(sender)?;1120			collection.check_allowlist(from)?;1121			collection.check_allowlist(to)?;1122		}11231124		<PalletCommon<T>>::ensure_correct_receiver(to)?;11251126		ensure!(1127			sender.conv_eq(from),1128			<CommonError<T>>::AddressIsNotEthMirror1129		);11301131		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1132			ensure!(1133				collection.limits.owner_can_transfer()1134					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1135					&& Self::token_exists(collection, token_id),1136				<CommonError<T>>::CantApproveMoreThanOwned1137			);1138		}11391140		// =========11411142		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1143		Ok(())1144	}11451146	/// Returns allowance, which should be set after transaction1147	fn check_allowed(1148		collection: &RefungibleHandle<T>,1149		spender: &T::CrossAccountId,1150		from: &T::CrossAccountId,1151		token: TokenId,1152		amount: u128,1153		nesting_budget: &dyn Budget,1154	) -> Result<Option<u128>, DispatchError> {1155		if spender.conv_eq(from) {1156			return Ok(None);1157		}1158		if collection.permissions.access() == AccessMode::AllowList {1159			// `from`, `to` checked in [`transfer`]1160			collection.check_allowlist(spender)?;1161		}1162		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1163			// TODO: should collection owner be allowed to perform this transfer?1164			ensure!(1165				<PalletStructure<T>>::check_indirectly_owned(1166					spender.clone(),1167					source.0,1168					source.1,1169					None,1170					nesting_budget1171				)?,1172				<CommonError<T>>::ApprovedValueTooLow,1173			);1174			return Ok(None);1175		}1176		let allowance =1177			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11781179		// Allowance (if any) would be reduced if spender is also wallet operator1180		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1181			return Ok(allowance);1182		}11831184		if allowance.is_none() {1185			ensure!(1186				collection.ignores_allowance(spender),1187				<CommonError<T>>::ApprovedValueTooLow1188			);1189		}1190		Ok(allowance)1191	}11921193	/// Transfer RFT token pieces from one account to another.1194	///1195	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1196	/// The owner should set allowance for the spender to transfer pieces.1197	///1198	/// [`transfer`]: struct.Pallet.html#method.transfer1199	pub fn transfer_from(1200		collection: &RefungibleHandle<T>,1201		spender: &T::CrossAccountId,1202		from: &T::CrossAccountId,1203		to: &T::CrossAccountId,1204		token: TokenId,1205		amount: u128,1206		nesting_budget: &dyn Budget,1207	) -> DispatchResult {1208		let allowance =1209			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12101211		// =========12121213		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1214		if let Some(allowance) = allowance {1215			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1216		}1217		Ok(())1218	}12191220	/// Burn RFT token pieces from the account.1221	///1222	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1223	/// set allowance for the spender to burn pieces1224	///1225	/// [`burn`]: struct.Pallet.html#method.burn1226	pub fn burn_from(1227		collection: &RefungibleHandle<T>,1228		spender: &T::CrossAccountId,1229		from: &T::CrossAccountId,1230		token: TokenId,1231		amount: u128,1232		nesting_budget: &dyn Budget,1233	) -> DispatchResult {1234		let allowance =1235			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12361237		// =========12381239		Self::burn(collection, from, token, amount)?;1240		if let Some(allowance) = allowance {1241			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1242		}1243		Ok(())1244	}12451246	/// Create RFT token.1247	///1248	/// The sender should be the owner/admin of the collection or collection should be configured1249	/// to allow public minting.1250	///1251	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1252	///   of token pieces they will receive.1253	pub fn create_item(1254		collection: &RefungibleHandle<T>,1255		sender: &T::CrossAccountId,1256		data: CreateItemData<T>,1257		nesting_budget: &dyn Budget,1258	) -> DispatchResult {1259		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1260	}12611262	/// Repartition RFT token.1263	///1264	/// `repartition` will set token balance of the sender and total amount of token pieces.1265	/// Sender should own all of the token pieces. `repartition' could be done even if some1266	/// token pieces were burned before.1267	///1268	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1269	pub fn repartition(1270		collection: &RefungibleHandle<T>,1271		owner: &T::CrossAccountId,1272		token: TokenId,1273		amount: u128,1274	) -> DispatchResult {1275		ensure!(1276			amount <= MAX_REFUNGIBLE_PIECES,1277			<Error<T>>::WrongRefungiblePieces1278		);1279		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1280		// Ensure user owns all pieces1281		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1282		let balance = <Balance<T>>::get((collection.id, token, owner));1283		ensure!(1284			total_pieces == balance,1285			<Error<T>>::RepartitionWhileNotOwningAllPieces1286		);12871288		<Balance<T>>::insert((collection.id, token, owner), amount);1289		<TotalSupply<T>>::insert((collection.id, token), amount);12901291		if amount > total_pieces {1292			let mint_amount = amount - total_pieces;1293			<PalletEvm<T>>::deposit_log(1294				ERC20Events::Transfer {1295					from: H160::default(),1296					to: *owner.as_eth(),1297					value: mint_amount.into(),1298				}1299				.to_log(T::EvmTokenAddressMapping::token_to_address(1300					collection.id,1301					token,1302				)),1303			);1304			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1305				collection.id,1306				token,1307				owner.clone(),1308				mint_amount,1309			));1310		} else if total_pieces > amount {1311			let burn_amount = total_pieces - amount;1312			<PalletEvm<T>>::deposit_log(1313				ERC20Events::Transfer {1314					from: *owner.as_eth(),1315					to: H160::default(),1316					value: burn_amount.into(),1317				}1318				.to_log(T::EvmTokenAddressMapping::token_to_address(1319					collection.id,1320					token,1321				)),1322			);1323			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1324				collection.id,1325				token,1326				owner.clone(),1327				burn_amount,1328			));1329		}13301331		Ok(())1332	}13331334	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1335		let mut owner = None;1336		let mut count = 0;1337		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1338			count += 1;1339			if count > 1 {1340				return None;1341			}1342			owner = Some(key);1343		}1344		owner1345	}13461347	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1348		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1349	}13501351	pub fn set_collection_properties(1352		collection: &RefungibleHandle<T>,1353		sender: &T::CrossAccountId,1354		properties: Vec<Property>,1355	) -> DispatchResult {1356		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1357	}13581359	pub fn delete_collection_properties(1360		collection: &RefungibleHandle<T>,1361		sender: &T::CrossAccountId,1362		property_keys: Vec<PropertyKey>,1363	) -> DispatchResult {1364		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1365	}13661367	pub fn set_token_property_permissions(1368		collection: &RefungibleHandle<T>,1369		sender: &T::CrossAccountId,1370		property_permissions: Vec<PropertyKeyPermission>,1371	) -> DispatchResult {1372		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1373	}13741375	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1376		<PalletCommon<T>>::property_permissions(collection_id)1377	}13781379	pub fn set_scoped_token_property_permissions(1380		collection: &RefungibleHandle<T>,1381		sender: &T::CrossAccountId,1382		scope: PropertyScope,1383		property_permissions: Vec<PropertyKeyPermission>,1384	) -> DispatchResult {1385		<PalletCommon<T>>::set_scoped_token_property_permissions(1386			collection,1387			sender,1388			scope,1389			property_permissions,1390		)1391	}13921393	/// Returns 10 token in no particular order.1394	///1395	/// There is no direct way to get token holders in ascending order,1396	/// since `iter_prefix` returns values in no particular order.1397	/// Therefore, getting the 10 largest holders with a large value of holders1398	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1399	pub fn token_owners(1400		collection_id: CollectionId,1401		token: TokenId,1402	) -> Option<Vec<T::CrossAccountId>> {1403		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1404			.map(|(owner, _amount)| owner)1405			.take(10)1406			.collect();14071408		if res.is_empty() {1409			None1410		} else {1411			Some(res)1412		}1413	}14141415	/// Sets or unsets the approval of a given operator.1416	///1417	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1418	/// - `owner`: Token owner1419	/// - `operator`: Operator1420	/// - `approve`: Should operator status be granted or revoked?1421	pub fn set_allowance_for_all(1422		collection: &RefungibleHandle<T>,1423		owner: &T::CrossAccountId,1424		operator: &T::CrossAccountId,1425		approve: bool,1426	) -> DispatchResult {1427		if collection.permissions.access() == AccessMode::AllowList {1428			collection.check_allowlist(owner)?;1429			collection.check_allowlist(operator)?;1430		}14311432		<PalletCommon<T>>::ensure_correct_receiver(operator)?;14331434		// =========14351436		<CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1437		<PalletEvm<T>>::deposit_log(1438			ERC721Events::ApprovalForAll {1439				owner: *owner.as_eth(),1440				operator: *operator.as_eth(),1441				approved: approve,1442			}1443			.to_log(collection_id_to_address(collection.id)),1444		);1445		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1446			collection.id,1447			owner.clone(),1448			operator.clone(),1449			approve,1450		));1451		Ok(())1452	}14531454	/// Tells whether the given `owner` approves the `operator`.1455	pub fn allowance_for_all(1456		collection: &RefungibleHandle<T>,1457		owner: &T::CrossAccountId,1458		operator: &T::CrossAccountId,1459	) -> bool {1460		<CollectionAllowance<T>>::get((collection.id, owner, operator))1461	}14621463	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1464		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1465			properties.recompute_consumed_space();1466		});14671468		Ok(())1469	}1470}
after · pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100	Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109	PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,110	TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122	CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127	use super::*;128	use frame_support::{129		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130		traits::StorageVersion,131	};132	use up_data_structs::{CollectionId, TokenId};133	use super::weights::WeightInfo;134135	#[pallet::error]136	pub enum Error<T> {137		/// Not Refungible item data used to mint in Refungible collection.138		NotRefungibleDataUsedToMintFungibleCollectionToken,139		/// Maximum refungibility exceeded.140		WrongRefungiblePieces,141		/// Refungible token can't be repartitioned by user who isn't owns all pieces.142		RepartitionWhileNotOwningAllPieces,143		/// Refungible token can't nest other tokens.144		RefungibleDisallowsNesting,145		/// Setting item properties is not allowed.146		SettingPropertiesNotAllowed,147	}148149	#[pallet::config]150	pub trait Config:151		frame_system::Config + pallet_common::Config + pallet_structure::Config152	{153		type WeightInfo: WeightInfo;154	}155156	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158	#[pallet::pallet]159	#[pallet::storage_version(STORAGE_VERSION)]160	#[pallet::generate_store(pub(super) trait Store)]161	pub struct Pallet<T>(_);162163	/// Total amount of minted tokens in a collection.164	#[pallet::storage]165	pub type TokensMinted<T: Config> =166		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168	/// Amount of tokens burnt in a collection.169	#[pallet::storage]170	pub type TokensBurnt<T: Config> =171		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173	/// Amount of pieces a refungible token is split into.174	#[pallet::storage]175	#[pallet::getter(fn token_properties)]176	pub type TokenProperties<T: Config> = StorageNMap<177		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178		Value = up_data_structs::Properties,179		QueryKind = ValueQuery,180		OnEmpty = up_data_structs::TokenProperties,181	>;182183	/// Total amount of pieces for token184	#[pallet::storage]185	pub type TotalSupply<T: Config> = StorageNMap<186		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187		Value = u128,188		QueryKind = ValueQuery,189	>;190191	/// Used to enumerate tokens owned by account.192	#[pallet::storage]193	pub type Owned<T: Config> = StorageNMap<194		Key = (195			Key<Twox64Concat, CollectionId>,196			Key<Blake2_128Concat, T::CrossAccountId>,197			Key<Twox64Concat, TokenId>,198		),199		Value = bool,200		QueryKind = ValueQuery,201	>;202203	/// Amount of tokens (not pieces) partially owned by an account within a collection.204	#[pallet::storage]205	pub type AccountBalance<T: Config> = StorageNMap<206		Key = (207			Key<Twox64Concat, CollectionId>,208			// Owner209			Key<Blake2_128Concat, T::CrossAccountId>,210		),211		Value = u32,212		QueryKind = ValueQuery,213	>;214215	/// Amount of token pieces owned by account.216	#[pallet::storage]217	pub type Balance<T: Config> = StorageNMap<218		Key = (219			Key<Twox64Concat, CollectionId>,220			Key<Twox64Concat, TokenId>,221			// Owner222			Key<Blake2_128Concat, T::CrossAccountId>,223		),224		Value = u128,225		QueryKind = ValueQuery,226	>;227228	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229	#[pallet::storage]230	pub type Allowance<T: Config> = StorageNMap<231		Key = (232			Key<Twox64Concat, CollectionId>,233			Key<Twox64Concat, TokenId>,234			// Owner235			Key<Blake2_128, T::CrossAccountId>,236			// Spender237			Key<Blake2_128Concat, T::CrossAccountId>,238		),239		Value = u128,240		QueryKind = ValueQuery,241	>;242243	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.244	#[pallet::storage]245	pub type CollectionAllowance<T: Config> = StorageNMap<246		Key = (247			Key<Twox64Concat, CollectionId>,248			Key<Blake2_128Concat, T::CrossAccountId>,249			Key<Blake2_128Concat, T::CrossAccountId>,250		),251		Value = bool,252		QueryKind = ValueQuery,253	>;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259		Self(inner)260	}261	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262		self.0263	}264	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265		&mut self.0266	}267}268269impl<T: Config> Deref for RefungibleHandle<T> {270	type Target = pallet_common::CollectionHandle<T>;271272	fn deref(&self) -> &Self::Target {273		&self.0274	}275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279		self.0.recorder()280	}281	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282		self.0.into_recorder()283	}284}285286impl<T: Config> Pallet<T> {287	/// Get number of RFT tokens in collection288	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290	}291292	/// Check that RFT token exists293	///294	/// - `token`: Token ID.295	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296		<TotalSupply<T>>::contains_key((collection.id, token))297	}298299	pub fn set_scoped_token_property(300		collection_id: CollectionId,301		token_id: TokenId,302		scope: PropertyScope,303		property: Property,304	) -> DispatchResult {305		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306			properties.try_scoped_set(scope, property.key, property.value)307		})308		.map_err(<CommonError<T>>::from)?;309310		Ok(())311	}312313	pub fn set_scoped_token_properties(314		collection_id: CollectionId,315		token_id: TokenId,316		scope: PropertyScope,317		properties: impl Iterator<Item = Property>,318	) -> DispatchResult {319		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320			stored_properties.try_scoped_set_from_iter(scope, properties)321		})322		.map_err(<CommonError<T>>::from)?;323324		Ok(())325	}326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330	/// Create RFT collection331	///332	/// `init_collection` will take non-refundable deposit for collection creation.333	///334	/// - `data`: Contains settings for collection limits and permissions.335	pub fn init_collection(336		owner: T::CrossAccountId,337		payer: T::CrossAccountId,338		data: CreateCollectionData<T::AccountId>,339		flags: CollectionFlags,340	) -> Result<CollectionId, DispatchError> {341		<PalletCommon<T>>::init_collection(owner, payer, data, flags)342	}343344	/// Destroy RFT collection345	///346	/// `destroy_collection` will throw error if collection contains any tokens.347	/// Only owner can destroy collection.348	pub fn destroy_collection(349		collection: RefungibleHandle<T>,350		sender: &T::CrossAccountId,351	) -> DispatchResult {352		let id = collection.id;353354		if Self::collection_has_tokens(id) {355			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356		}357358		// =========359360		PalletCommon::destroy_collection(collection.0, sender)?;361362		<TokensMinted<T>>::remove(id);363		<TokensBurnt<T>>::remove(id);364		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369		Ok(())370	}371372	fn collection_has_tokens(collection_id: CollectionId) -> bool {373		<TotalSupply<T>>::iter_prefix((collection_id,))374			.next()375			.is_some()376	}377378	pub fn burn_token_unchecked(379		collection: &RefungibleHandle<T>,380		owner: &T::CrossAccountId,381		token_id: TokenId,382	) -> DispatchResult {383		let burnt = <TokensBurnt<T>>::get(collection.id)384			.checked_add(1)385			.ok_or(ArithmeticError::Overflow)?;386387		<TokensBurnt<T>>::insert(collection.id, burnt);388		<TokenProperties<T>>::remove((collection.id, token_id));389		<TotalSupply<T>>::remove((collection.id, token_id));390		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392		<PalletEvm<T>>::deposit_log(393			ERC721Events::Transfer {394				from: *owner.as_eth(),395				to: H160::default(),396				token_id: token_id.into(),397			}398			.to_log(collection_id_to_address(collection.id)),399		);400		Ok(())401	}402403	/// Burn RFT token pieces404	///405	/// `burn` will decrease total amount of token pieces and amount owned by sender.406	/// `burn` can be called even if there are multiple owners of the RFT token.407	/// If sender wouldn't have any pieces left after `burn` than she will stop being408	/// one of the owners of the token. If there is no account that owns any pieces of409	/// the token than token will be burned too.410	///411	/// - `amount`: Amount of token pieces to burn.412	/// - `token`: Token who's pieces should be burned413	/// - `collection`: Collection that contains the token414	pub fn burn(415		collection: &RefungibleHandle<T>,416		owner: &T::CrossAccountId,417		token: TokenId,418		amount: u128,419	) -> DispatchResult {420		if <Balance<T>>::get((collection.id, token, owner)) == 0 {421			return Err(<CommonError<T>>::TokenValueTooLow.into());422		}423424		let total_supply = <TotalSupply<T>>::get((collection.id, token))425			.checked_sub(amount)426			.ok_or(<CommonError<T>>::TokenValueTooLow)?;427428		// This was probally last owner of this token?429		if total_supply == 0 {430			// Ensure user actually owns this amount431			ensure!(432				<Balance<T>>::get((collection.id, token, owner)) == amount,433				<CommonError<T>>::TokenValueTooLow434			);435			let account_balance = <AccountBalance<T>>::get((collection.id, owner))436				.checked_sub(1)437				// Should not occur438				.ok_or(ArithmeticError::Underflow)?;439440			// =========441442			<Owned<T>>::remove((collection.id, owner, token));443			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444			<AccountBalance<T>>::insert((collection.id, owner), account_balance);445			Self::burn_token_unchecked(collection, owner, token)?;446			<PalletEvm<T>>::deposit_log(447				ERC20Events::Transfer {448					from: *owner.as_eth(),449					to: H160::default(),450					value: amount.into(),451				}452				.to_log(collection_id_to_address(collection.id)),453			);454			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455				collection.id,456				token,457				owner.clone(),458				amount,459			));460			return Ok(());461		}462463		let balance = <Balance<T>>::get((collection.id, token, owner))464			.checked_sub(amount)465			.ok_or(<CommonError<T>>::TokenValueTooLow)?;466		let account_balance = if balance == 0 {467			<AccountBalance<T>>::get((collection.id, owner))468				.checked_sub(1)469				// Should not occur470				.ok_or(ArithmeticError::Underflow)?471		} else {472			0473		};474475		// =========476477		if balance == 0 {478			<Owned<T>>::remove((collection.id, owner, token));479			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480			<Balance<T>>::remove((collection.id, token, owner));481			<AccountBalance<T>>::insert((collection.id, owner), account_balance);482483			if let Some(user) = Self::token_owner(collection.id, token) {484				<PalletEvm<T>>::deposit_log(485					ERC721Events::Transfer {486						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487						to: *user.as_eth(),488						token_id: token.into(),489					}490					.to_log(collection_id_to_address(collection.id)),491				);492			}493		} else {494			<Balance<T>>::insert((collection.id, token, owner), balance);495		}496		<TotalSupply<T>>::insert((collection.id, token), total_supply);497498		<PalletEvm<T>>::deposit_log(499			ERC20Events::Transfer {500				from: *owner.as_eth(),501				to: H160::default(),502				value: amount.into(),503			}504			.to_log(T::EvmTokenAddressMapping::token_to_address(505				collection.id,506				token,507			)),508		);509		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510			collection.id,511			token,512			owner.clone(),513			amount,514		));515		Ok(())516	}517518	/// A batch operation to add, edit or remove properties for a token.519	/// It sets or removes a token's properties according to520	/// `properties_updates` contents:521	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`522	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.523	///524	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.525	/// - `is_token_create`: Indicates that method is called during token initialization.526	///   Allows to bypass ownership check.527	///528	/// All affected properties should have `mutable` permission529	/// to be **deleted** or to be **set more than once**,530	/// and the sender should have permission to edit those properties.531	///532	/// This function fires an event for each property change.533	/// In case of an error, all the changes (including the events) will be reverted534	/// since the function is transactional.535	#[transactional]536	fn modify_token_properties(537		collection: &RefungibleHandle<T>,538		sender: &T::CrossAccountId,539		token_id: TokenId,540		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541		is_token_create: bool,542		nesting_budget: &dyn Budget,543	) -> DispatchResult {544		let is_collection_admin = || collection.is_owner_or_admin(sender);545		let is_token_owner = || -> Result<bool, DispatchError> {546			let balance = collection.balance(sender.clone(), token_id);547			let total_pieces: u128 =548				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);549			if balance != total_pieces {550				return Ok(false);551			}552553			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(554				sender.clone(),555				collection.id,556				token_id,557				None,558				nesting_budget,559			)?;560561			Ok(is_bundle_owner)562		};563564		let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));565		let permissions = <PalletCommon<T>>::property_permissions(collection.id);566567		for (key, value) in properties_updates {568			let permission = permissions569				.get(&key)570				.cloned()571				.unwrap_or_else(PropertyPermission::none);572573			let is_property_exists = stored_properties.get(&key).is_some();574575			match permission {576				PropertyPermission { mutable: false, .. } if is_property_exists => {577					return Err(<CommonError<T>>::NoPermission.into());578				}579580				PropertyPermission {581					collection_admin,582					token_owner,583					..584				} => {585					//TODO: investigate threats during public minting.586					let is_token_create =587						is_token_create && (collection_admin || token_owner) && value.is_some();588					if !(is_token_create589						|| (collection_admin && is_collection_admin())590						|| (token_owner && is_token_owner()?))591					{592						fail!(<CommonError<T>>::NoPermission);593					}594				}595			}596597			match value {598				Some(value) => {599					stored_properties600						.try_set(key.clone(), value)601						.map_err(<CommonError<T>>::from)?;602603					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(604						collection.id,605						token_id,606						key,607					));608				}609				None => {610					stored_properties611						.remove(&key)612						.map_err(<CommonError<T>>::from)?;613614					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(615						collection.id,616						token_id,617						key,618					));619				}620			}621622			<PalletEvm<T>>::deposit_log(623				CollectionHelpersEvents::TokenChanged {624					collection_id: collection_id_to_address(collection.id),625					token_id: token_id.into(),626				}627				.to_log(T::ContractAddress::get()),628			);629		}630631		<TokenProperties<T>>::set((collection.id, token_id), stored_properties);632633		Ok(())634	}635636	pub fn set_token_properties(637		collection: &RefungibleHandle<T>,638		sender: &T::CrossAccountId,639		token_id: TokenId,640		properties: impl Iterator<Item = Property>,641		is_token_create: bool,642		nesting_budget: &dyn Budget,643	) -> DispatchResult {644		Self::modify_token_properties(645			collection,646			sender,647			token_id,648			properties.map(|p| (p.key, Some(p.value))),649			is_token_create,650			nesting_budget,651		)652	}653654	pub fn set_token_property(655		collection: &RefungibleHandle<T>,656		sender: &T::CrossAccountId,657		token_id: TokenId,658		property: Property,659		nesting_budget: &dyn Budget,660	) -> DispatchResult {661		let is_token_create = false;662663		Self::set_token_properties(664			collection,665			sender,666			token_id,667			[property].into_iter(),668			is_token_create,669			nesting_budget,670		)671	}672673	pub fn delete_token_properties(674		collection: &RefungibleHandle<T>,675		sender: &T::CrossAccountId,676		token_id: TokenId,677		property_keys: impl Iterator<Item = PropertyKey>,678		nesting_budget: &dyn Budget,679	) -> DispatchResult {680		let is_token_create = false;681682		Self::modify_token_properties(683			collection,684			sender,685			token_id,686			property_keys.into_iter().map(|key| (key, None)),687			is_token_create,688			nesting_budget,689		)690	}691692	pub fn delete_token_property(693		collection: &RefungibleHandle<T>,694		sender: &T::CrossAccountId,695		token_id: TokenId,696		property_key: PropertyKey,697		nesting_budget: &dyn Budget,698	) -> DispatchResult {699		Self::delete_token_properties(700			collection,701			sender,702			token_id,703			[property_key].into_iter(),704			nesting_budget,705		)706	}707708	/// Transfer RFT token pieces from one account to another.709	///710	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.711	///712	/// - `from`: Owner of token pieces to transfer.713	/// - `to`: Recepient of transfered token pieces.714	/// - `amount`: Amount of token pieces to transfer.715	/// - `token`: Token whos pieces should be transfered716	/// - `collection`: Collection that contains the token717	pub fn transfer(718		collection: &RefungibleHandle<T>,719		from: &T::CrossAccountId,720		to: &T::CrossAccountId,721		token: TokenId,722		amount: u128,723		nesting_budget: &dyn Budget,724	) -> DispatchResult {725		ensure!(726			collection.limits.transfers_enabled(),727			<CommonError<T>>::TransferNotAllowed728		);729730		if collection.permissions.access() == AccessMode::AllowList {731			collection.check_allowlist(from)?;732			collection.check_allowlist(to)?;733		}734		<PalletCommon<T>>::ensure_correct_receiver(to)?;735736		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));737738		if initial_balance_from == 0 {739			return Err(<CommonError<T>>::TokenValueTooLow.into());740		}741742		let updated_balance_from = initial_balance_from743			.checked_sub(amount)744			.ok_or(<CommonError<T>>::TokenValueTooLow)?;745		let mut create_target = false;746		let from_to_differ = from != to;747		let updated_balance_to = if from != to && amount != 0 {748			let old_balance = <Balance<T>>::get((collection.id, token, to));749			if old_balance == 0 {750				create_target = true;751			}752			Some(753				old_balance754					.checked_add(amount)755					.ok_or(ArithmeticError::Overflow)?,756			)757		} else {758			None759		};760761		let account_balance_from = if updated_balance_from == 0 {762			Some(763				<AccountBalance<T>>::get((collection.id, from))764					.checked_sub(1)765					// Should not occur766					.ok_or(ArithmeticError::Underflow)?,767			)768		} else {769			None770		};771		// Account data is created in token, AccountBalance should be increased772		// But only if from != to as we shouldn't check overflow in this case773		let account_balance_to = if create_target && from_to_differ {774			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))775				.checked_add(1)776				.ok_or(ArithmeticError::Overflow)?;777			ensure!(778				account_balance_to < collection.limits.account_token_ownership_limit(),779				<CommonError<T>>::AccountTokenLimitExceeded,780			);781782			Some(account_balance_to)783		} else {784			None785		};786787		// =========788789		if let Some(updated_balance_to) = updated_balance_to {790			// from != to && amount != 0791792			<PalletStructure<T>>::nest_if_sent_to_token(793				from.clone(),794				to,795				collection.id,796				token,797				nesting_budget,798			)?;799800			if updated_balance_from == 0 {801				<Balance<T>>::remove((collection.id, token, from));802				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);803			} else {804				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);805			}806			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);807			if let Some(account_balance_from) = account_balance_from {808				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);809				<Owned<T>>::remove((collection.id, from, token));810			}811			if let Some(account_balance_to) = account_balance_to {812				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);813				<Owned<T>>::insert((collection.id, to, token), true);814			}815		}816817		<PalletEvm<T>>::deposit_log(818			ERC20Events::Transfer {819				from: *from.as_eth(),820				to: *to.as_eth(),821				value: amount.into(),822			}823			.to_log(T::EvmTokenAddressMapping::token_to_address(824				collection.id,825				token,826			)),827		);828829		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(830			collection.id,831			token,832			from.clone(),833			to.clone(),834			amount,835		));836837		let total_supply = <TotalSupply<T>>::get((collection.id, token));838839		if amount == total_supply {840			// if token was fully owned by `from` and will be fully owned by `to` after transfer841			<PalletEvm<T>>::deposit_log(842				ERC721Events::Transfer {843					from: *from.as_eth(),844					to: *to.as_eth(),845					token_id: token.into(),846				}847				.to_log(collection_id_to_address(collection.id)),848			);849		} else if let Some(updated_balance_to) = updated_balance_to {850			// if `from` not equals `to`. This condition is needed to avoid sending event851			// when `from` fully owns token and sends part of token pieces to itself.852			if initial_balance_from == total_supply {853				// if token was fully owned by `from` and will be only partially owned by `to`854				// and `from` after transfer855				<PalletEvm<T>>::deposit_log(856					ERC721Events::Transfer {857						from: *from.as_eth(),858						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,859						token_id: token.into(),860					}861					.to_log(collection_id_to_address(collection.id)),862				);863			} else if updated_balance_to == total_supply {864				// if token was partially owned by `from` and will be fully owned by `to` after transfer865				<PalletEvm<T>>::deposit_log(866					ERC721Events::Transfer {867						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,868						to: *to.as_eth(),869						token_id: token.into(),870					}871					.to_log(collection_id_to_address(collection.id)),872				);873			}874		}875876		Ok(())877	}878879	/// Batched operation to create multiple RFT tokens.880	///881	/// Same as `create_item` but creates multiple tokens.882	///883	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.884	pub fn create_multiple_items(885		collection: &RefungibleHandle<T>,886		sender: &T::CrossAccountId,887		data: Vec<CreateItemData<T>>,888		nesting_budget: &dyn Budget,889	) -> DispatchResult {890		if !collection.is_owner_or_admin(sender) {891			ensure!(892				collection.permissions.mint_mode(),893				<CommonError<T>>::PublicMintingNotAllowed894			);895			collection.check_allowlist(sender)?;896897			for item in data.iter() {898				for user in item.users.keys() {899					collection.check_allowlist(user)?;900				}901			}902		}903904		for item in data.iter() {905			for (owner, _) in item.users.iter() {906				<PalletCommon<T>>::ensure_correct_receiver(owner)?;907			}908		}909910		// Total pieces per tokens911		let totals = data912			.iter()913			.map(|data| {914				Ok(data915					.users916					.iter()917					.map(|u| u.1)918					.try_fold(0u128, |acc, v| acc.checked_add(*v))919					.ok_or(ArithmeticError::Overflow)?)920			})921			.collect::<Result<Vec<_>, DispatchError>>()?;922		for total in &totals {923			ensure!(924				*total <= MAX_REFUNGIBLE_PIECES,925				<Error<T>>::WrongRefungiblePieces926			);927		}928929		let first_token_id = <TokensMinted<T>>::get(collection.id);930		let tokens_minted = first_token_id931			.checked_add(data.len() as u32)932			.ok_or(ArithmeticError::Overflow)?;933		ensure!(934			tokens_minted < collection.limits.token_limit(),935			<CommonError<T>>::CollectionTokenLimitExceeded936		);937938		let mut balances = BTreeMap::new();939		for data in &data {940			for owner in data.users.keys() {941				let balance = balances942					.entry(owner)943					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));944				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;945946				ensure!(947					*balance <= collection.limits.account_token_ownership_limit(),948					<CommonError<T>>::AccountTokenLimitExceeded,949				);950			}951		}952953		for (i, token) in data.iter().enumerate() {954			let token_id = TokenId(first_token_id + i as u32 + 1);955			for (to, _) in token.users.iter() {956				<PalletStructure<T>>::check_nesting(957					sender.clone(),958					to,959					collection.id,960					token_id,961					nesting_budget,962				)?;963			}964		}965966		// =========967968		with_transaction(|| {969			for (i, data) in data.iter().enumerate() {970				let token_id = first_token_id + i as u32 + 1;971				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);972973				for (user, amount) in data.users.iter() {974					if *amount == 0 {975						continue;976					}977					<Balance<T>>::insert((collection.id, token_id, &user), amount);978					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);979					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(980						user,981						collection.id,982						TokenId(token_id),983					);984				}985986				if let Err(e) = Self::set_token_properties(987					collection,988					sender,989					TokenId(token_id),990					data.properties.clone().into_iter(),991					true,992					nesting_budget,993				) {994					return TransactionOutcome::Rollback(Err(e));995				}996			}997			TransactionOutcome::Commit(Ok(()))998		})?;9991000		<TokensMinted<T>>::insert(collection.id, tokens_minted);10011002		for (account, balance) in balances {1003			<AccountBalance<T>>::insert((collection.id, account), balance);1004		}10051006		for (i, token) in data.into_iter().enumerate() {1007			let token_id = first_token_id + i as u32 + 1;10081009			let receivers = token1010				.users1011				.into_iter()1012				.filter(|(_, amount)| *amount > 0)1013				.collect::<Vec<_>>();10141015			if let [(user, _)] = receivers.as_slice() {1016				// if there is exactly one receiver1017				<PalletEvm<T>>::deposit_log(1018					ERC721Events::Transfer {1019						from: H160::default(),1020						to: *user.as_eth(),1021						token_id: token_id.into(),1022					}1023					.to_log(collection_id_to_address(collection.id)),1024				);1025			} else if let [_, ..] = receivers.as_slice() {1026				// if there is more than one receiver1027				<PalletEvm<T>>::deposit_log(1028					ERC721Events::Transfer {1029						from: H160::default(),1030						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1031						token_id: token_id.into(),1032					}1033					.to_log(collection_id_to_address(collection.id)),1034				);1035			}10361037			for (user, amount) in receivers.into_iter() {1038				<PalletEvm<T>>::deposit_log(1039					ERC20Events::Transfer {1040						from: H160::default(),1041						to: *user.as_eth(),1042						value: amount.into(),1043					}1044					.to_log(T::EvmTokenAddressMapping::token_to_address(1045						collection.id,1046						TokenId(token_id),1047					)),1048				);1049				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1050					collection.id,1051					TokenId(token_id),1052					user,1053					amount,1054				));1055			}1056		}1057		Ok(())1058	}10591060	pub fn set_allowance_unchecked(1061		collection: &RefungibleHandle<T>,1062		sender: &T::CrossAccountId,1063		spender: &T::CrossAccountId,1064		token: TokenId,1065		amount: u128,1066	) {1067		if amount == 0 {1068			<Allowance<T>>::remove((collection.id, token, sender, spender));1069		} else {1070			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1071		}10721073		<PalletEvm<T>>::deposit_log(1074			ERC20Events::Approval {1075				owner: *sender.as_eth(),1076				spender: *spender.as_eth(),1077				value: amount.into(),1078			}1079			.to_log(T::EvmTokenAddressMapping::token_to_address(1080				collection.id,1081				token,1082			)),1083		);1084		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1085			collection.id,1086			token,1087			sender.clone(),1088			spender.clone(),1089			amount,1090		))1091	}10921093	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1094	///1095	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1096	pub fn set_allowance(1097		collection: &RefungibleHandle<T>,1098		sender: &T::CrossAccountId,1099		spender: &T::CrossAccountId,1100		token: TokenId,1101		amount: u128,1102	) -> DispatchResult {1103		if collection.permissions.access() == AccessMode::AllowList {1104			collection.check_allowlist(sender)?;1105			collection.check_allowlist(spender)?;1106		}11071108		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11091110		if <Balance<T>>::get((collection.id, token, sender)) < amount {1111			ensure!(1112				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1113				<CommonError<T>>::CantApproveMoreThanOwned1114			);1115		}11161117		// =========11181119		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1120		Ok(())1121	}11221123	/// Set allowance to spend from sender's eth mirror1124	///1125	/// - `from`: Address of sender's eth mirror.1126	/// - `to`: Adress of spender.1127	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1128	pub fn set_allowance_from(1129		collection: &RefungibleHandle<T>,1130		sender: &T::CrossAccountId,1131		from: &T::CrossAccountId,1132		to: &T::CrossAccountId,1133		token_id: TokenId,1134		amount: u128,1135	) -> DispatchResult {1136		if collection.permissions.access() == AccessMode::AllowList {1137			collection.check_allowlist(sender)?;1138			collection.check_allowlist(from)?;1139			collection.check_allowlist(to)?;1140		}11411142		<PalletCommon<T>>::ensure_correct_receiver(to)?;11431144		ensure!(1145			sender.conv_eq(from),1146			<CommonError<T>>::AddressIsNotEthMirror1147		);11481149		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1150			ensure!(1151				collection.limits.owner_can_transfer()1152					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1153					&& Self::token_exists(collection, token_id),1154				<CommonError<T>>::CantApproveMoreThanOwned1155			);1156		}11571158		// =========11591160		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1161		Ok(())1162	}11631164	/// Returns allowance, which should be set after transaction1165	fn check_allowed(1166		collection: &RefungibleHandle<T>,1167		spender: &T::CrossAccountId,1168		from: &T::CrossAccountId,1169		token: TokenId,1170		amount: u128,1171		nesting_budget: &dyn Budget,1172	) -> Result<Option<u128>, DispatchError> {1173		if spender.conv_eq(from) {1174			return Ok(None);1175		}1176		if collection.permissions.access() == AccessMode::AllowList {1177			// `from`, `to` checked in [`transfer`]1178			collection.check_allowlist(spender)?;1179		}11801181		if collection.ignores_token_restrictions(spender) {1182			return Ok(Self::compute_allowance_decrease(1183				collection, token, from, &spender, amount,1184			));1185		}11861187		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1188			// TODO: should collection owner be allowed to perform this transfer?1189			ensure!(1190				<PalletStructure<T>>::check_indirectly_owned(1191					spender.clone(),1192					source.0,1193					source.1,1194					None,1195					nesting_budget1196				)?,1197				<CommonError<T>>::ApprovedValueTooLow,1198			);1199			return Ok(None);1200		}12011202		let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1203		if allowance.is_some() {1204			return Ok(allowance);1205		}12061207		// Allowance (if any) would be reduced if spender is also wallet operator1208		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1209			return Ok(allowance);1210		}12111212		Err(<CommonError<T>>::ApprovedValueTooLow.into())1213	}12141215	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1216	/// Otherwise, it returns `None`.1217	fn compute_allowance_decrease(1218		collection: &RefungibleHandle<T>,1219		token: TokenId,1220		from: &T::CrossAccountId,1221		spender: &T::CrossAccountId,1222		amount: u128,1223	) -> Option<u128> {1224		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1225	}12261227	/// Transfer RFT token pieces from one account to another.1228	///1229	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1230	/// The owner should set allowance for the spender to transfer pieces.1231	///1232	/// [`transfer`]: struct.Pallet.html#method.transfer1233	pub fn transfer_from(1234		collection: &RefungibleHandle<T>,1235		spender: &T::CrossAccountId,1236		from: &T::CrossAccountId,1237		to: &T::CrossAccountId,1238		token: TokenId,1239		amount: u128,1240		nesting_budget: &dyn Budget,1241	) -> DispatchResult {1242		let allowance =1243			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12441245		// =========12461247		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1248		if let Some(allowance) = allowance {1249			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1250		}1251		Ok(())1252	}12531254	/// Burn RFT token pieces from the account.1255	///1256	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1257	/// set allowance for the spender to burn pieces1258	///1259	/// [`burn`]: struct.Pallet.html#method.burn1260	pub fn burn_from(1261		collection: &RefungibleHandle<T>,1262		spender: &T::CrossAccountId,1263		from: &T::CrossAccountId,1264		token: TokenId,1265		amount: u128,1266		nesting_budget: &dyn Budget,1267	) -> DispatchResult {1268		let allowance =1269			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12701271		// =========12721273		Self::burn(collection, from, token, amount)?;1274		if let Some(allowance) = allowance {1275			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1276		}1277		Ok(())1278	}12791280	/// Create RFT token.1281	///1282	/// The sender should be the owner/admin of the collection or collection should be configured1283	/// to allow public minting.1284	///1285	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1286	///   of token pieces they will receive.1287	pub fn create_item(1288		collection: &RefungibleHandle<T>,1289		sender: &T::CrossAccountId,1290		data: CreateItemData<T>,1291		nesting_budget: &dyn Budget,1292	) -> DispatchResult {1293		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1294	}12951296	/// Repartition RFT token.1297	///1298	/// `repartition` will set token balance of the sender and total amount of token pieces.1299	/// Sender should own all of the token pieces. `repartition' could be done even if some1300	/// token pieces were burned before.1301	///1302	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1303	pub fn repartition(1304		collection: &RefungibleHandle<T>,1305		owner: &T::CrossAccountId,1306		token: TokenId,1307		amount: u128,1308	) -> DispatchResult {1309		ensure!(1310			amount <= MAX_REFUNGIBLE_PIECES,1311			<Error<T>>::WrongRefungiblePieces1312		);1313		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1314		// Ensure user owns all pieces1315		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1316		let balance = <Balance<T>>::get((collection.id, token, owner));1317		ensure!(1318			total_pieces == balance,1319			<Error<T>>::RepartitionWhileNotOwningAllPieces1320		);13211322		<Balance<T>>::insert((collection.id, token, owner), amount);1323		<TotalSupply<T>>::insert((collection.id, token), amount);13241325		if amount > total_pieces {1326			let mint_amount = amount - total_pieces;1327			<PalletEvm<T>>::deposit_log(1328				ERC20Events::Transfer {1329					from: H160::default(),1330					to: *owner.as_eth(),1331					value: mint_amount.into(),1332				}1333				.to_log(T::EvmTokenAddressMapping::token_to_address(1334					collection.id,1335					token,1336				)),1337			);1338			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1339				collection.id,1340				token,1341				owner.clone(),1342				mint_amount,1343			));1344		} else if total_pieces > amount {1345			let burn_amount = total_pieces - amount;1346			<PalletEvm<T>>::deposit_log(1347				ERC20Events::Transfer {1348					from: *owner.as_eth(),1349					to: H160::default(),1350					value: burn_amount.into(),1351				}1352				.to_log(T::EvmTokenAddressMapping::token_to_address(1353					collection.id,1354					token,1355				)),1356			);1357			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1358				collection.id,1359				token,1360				owner.clone(),1361				burn_amount,1362			));1363		}13641365		Ok(())1366	}13671368	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1369		let mut owner = None;1370		let mut count = 0;1371		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1372			count += 1;1373			if count > 1 {1374				return None;1375			}1376			owner = Some(key);1377		}1378		owner1379	}13801381	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1382		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1383	}13841385	pub fn set_collection_properties(1386		collection: &RefungibleHandle<T>,1387		sender: &T::CrossAccountId,1388		properties: Vec<Property>,1389	) -> DispatchResult {1390		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1391	}13921393	pub fn delete_collection_properties(1394		collection: &RefungibleHandle<T>,1395		sender: &T::CrossAccountId,1396		property_keys: Vec<PropertyKey>,1397	) -> DispatchResult {1398		<PalletCommon<T>>::delete_collection_properties(1399			collection,1400			sender,1401			property_keys.into_iter(),1402		)1403	}14041405	pub fn set_token_property_permissions(1406		collection: &RefungibleHandle<T>,1407		sender: &T::CrossAccountId,1408		property_permissions: Vec<PropertyKeyPermission>,1409	) -> DispatchResult {1410		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1411	}14121413	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1414		<PalletCommon<T>>::property_permissions(collection_id)1415	}14161417	pub fn set_scoped_token_property_permissions(1418		collection: &RefungibleHandle<T>,1419		sender: &T::CrossAccountId,1420		scope: PropertyScope,1421		property_permissions: Vec<PropertyKeyPermission>,1422	) -> DispatchResult {1423		<PalletCommon<T>>::set_scoped_token_property_permissions(1424			collection,1425			sender,1426			scope,1427			property_permissions,1428		)1429	}14301431	/// Returns 10 token in no particular order.1432	///1433	/// There is no direct way to get token holders in ascending order,1434	/// since `iter_prefix` returns values in no particular order.1435	/// Therefore, getting the 10 largest holders with a large value of holders1436	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1437	pub fn token_owners(1438		collection_id: CollectionId,1439		token: TokenId,1440	) -> Option<Vec<T::CrossAccountId>> {1441		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1442			.map(|(owner, _amount)| owner)1443			.take(10)1444			.collect();14451446		if res.is_empty() {1447			None1448		} else {1449			Some(res)1450		}1451	}14521453	/// Sets or unsets the approval of a given operator.1454	///1455	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1456	/// - `owner`: Token owner1457	/// - `operator`: Operator1458	/// - `approve`: Should operator status be granted or revoked?1459	pub fn set_allowance_for_all(1460		collection: &RefungibleHandle<T>,1461		owner: &T::CrossAccountId,1462		operator: &T::CrossAccountId,1463		approve: bool,1464	) -> DispatchResult {1465		if collection.permissions.access() == AccessMode::AllowList {1466			collection.check_allowlist(owner)?;1467			collection.check_allowlist(operator)?;1468		}14691470		<PalletCommon<T>>::ensure_correct_receiver(operator)?;14711472		// =========14731474		<CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1475		<PalletEvm<T>>::deposit_log(1476			ERC721Events::ApprovalForAll {1477				owner: *owner.as_eth(),1478				operator: *operator.as_eth(),1479				approved: approve,1480			}1481			.to_log(collection_id_to_address(collection.id)),1482		);1483		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1484			collection.id,1485			owner.clone(),1486			operator.clone(),1487			approve,1488		));1489		Ok(())1490	}14911492	/// Tells whether the given `owner` approves the `operator`.1493	pub fn allowance_for_all(1494		collection: &RefungibleHandle<T>,1495		owner: &T::CrossAccountId,1496		operator: &T::CrossAccountId,1497	) -> bool {1498		<CollectionAllowance<T>>::get((collection.id, owner, operator))1499	}15001501	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1502		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1503			properties.recompute_consumed_space();1504		});15051506		Ok(())1507	}1508}
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -641,6 +641,8 @@
 	TransferEnabled
 }
 
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x5b5e139f
 contract ERC721Metadata is Dummy, ERC165 {
 	// /// @notice A descriptive name for a collection of NFTs in this contract
@@ -783,7 +785,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xabf30dc2
+/// @dev the ERC-165 identifier for this interface is 0xb365c124
 contract ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -985,6 +987,15 @@
 		dummy;
 		return 0x0000000000000000000000000000000000000000;
 	}
+
+	/// @notice Returns collection helper contract address
+	/// @dev EVM selector for this function is: 0x1896cce6,
+	///  or in textual repr: collectionHelperAddress()
+	function collectionHelperAddress() public view returns (address) {
+		require(false, stub_error);
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
 }
 
 /// @dev anonymous struct
@@ -1042,7 +1053,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard
 /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x4016cd87
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
 contract ERC721 is Dummy, ERC165, ERC721Events {
 	/// @notice Count all RFTs assigned to an owner
 	/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -1075,9 +1086,9 @@
 	}
 
 	/// @dev Not implemented
-	/// @dev EVM selector for this function is: 0x60a11672,
-	///  or in textual repr: safeTransferFromWithData(address,address,uint256,bytes)
-	function safeTransferFromWithData(
+	/// @dev EVM selector for this function is: 0xb88d4fde,
+	///  or in textual repr: safeTransferFrom(address,address,uint256,bytes)
+	function safeTransferFrom(
 		address from,
 		address to,
 		uint256 tokenId,
@@ -1172,15 +1183,6 @@
 		operator;
 		dummy;
 		return false;
-	}
-
-	/// @notice Returns collection helper contract address
-	/// @dev EVM selector for this function is: 0x1896cce6,
-	///  or in textual repr: collectionHelperAddress()
-	function collectionHelperAddress() public view returns (address) {
-		require(false, stub_error);
-		dummy;
-		return 0x0000000000000000000000000000000000000000;
 	}
 }
 
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -246,21 +246,21 @@
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_578_000 as u64)
-			// Standard Error: 5_396_287
-			.saturating_add(Weight::from_ref_time(633_314_546 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(25_518_267 as u64)
+			// Standard Error: 20_451
+			.saturating_add(Weight::from_ref_time(5_041_089 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_583_000 as u64)
-			// Standard Error: 5_762_380
-			.saturating_add(Weight::from_ref_time(696_007_076 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(13_715_000 as u64)
+			// Standard Error: 28_323
+			.saturating_add(Weight::from_ref_time(13_113_351 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
@@ -478,21 +478,21 @@
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_578_000 as u64)
-			// Standard Error: 5_396_287
-			.saturating_add(Weight::from_ref_time(633_314_546 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(25_518_267 as u64)
+			// Standard Error: 20_451
+			.saturating_add(Weight::from_ref_time(5_041_089 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible TokenProperties (r:1 w:1)
 	// Storage: Common CollectionPropertyPermissions (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
-		Weight::from_ref_time(4_583_000 as u64)
-			// Standard Error: 5_762_380
-			.saturating_add(Weight::from_ref_time(696_007_076 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(13_715_000 as u64)
+			// Standard Error: 28_323
+			.saturating_add(Weight::from_ref_time(13_113_351 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -33,7 +33,6 @@
 };
 use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
 use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
-use sp_std::vec;
 use up_data_structs::{
 	CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
 	CreateCollectionData,
@@ -316,13 +315,14 @@
 			<PalletCommon<T>>::set_collection_properties(
 				&collection,
 				&caller,
-				vec![up_data_structs::Property {
+				[up_data_structs::Property {
 					key: key::base_uri(),
 					value: base_uri
 						.into_bytes()
 						.try_into()
 						.map_err(|_| "base uri is too large")?,
-				}],
+				}]
+				.into_iter(),
 			)
 			.map_err(dispatch_to_evm::<T>)?;
 		}
modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -139,8 +139,7 @@
 			| BalanceOf { .. }
 			| OwnerOf { .. }
 			| GetApproved { .. }
-			| IsApprovedForAll { .. }
-			| CollectionHelperAddress => None,
+			| IsApprovedForAll { .. } => None,
 
 			// Not sponsored
 			SafeTransferFromWithData { .. }
@@ -230,7 +229,8 @@
 			| CrossOwnerOf { .. }
 			| Properties { .. }
 			| NextTokenId
-			| TokenContractAddress { .. } => None,
+			| TokenContractAddress { .. }
+			| CollectionHelperAddress => None,
 
 			// Not sponsored
 			BurnFrom { .. }
modifiedruntime/common/identity.rsdiffbeforeafterboth
--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -24,6 +24,9 @@
 	transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
 };
 
+#[cfg(feature = "collator-selection")]
+use sp_runtime::transaction_validity::InvalidTransaction;
+
 #[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
 pub struct DisableIdentityCalls;
 
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -451,7 +451,9 @@
                 }
 
                 fn account_code_at(address: H160) -> Vec<u8> {
-                    EVM::account_codes(address)
+                    use pallet_evm::OnMethodCall;
+                    <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)
+                        .unwrap_or_else(|| EVM::account_codes(address))
                 }
 
                 fn author() -> H160 {
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -193,6 +193,7 @@
     'refungible',
     'rmrk',
     'app-promotion',
+    'collator-selection',
     'foreign-assets',
     'pallet-test-utils',
 ]
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -51,6 +51,12 @@
   },
   {
     "anonymous": false,
+    "inputs": [],
+    "name": "MintingFinished",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
     "inputs": [
       {
         "indexed": true,
@@ -417,6 +423,13 @@
     "type": "function"
   },
   {
+    "inputs": [],
+    "name": "finishMinting",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [
       { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
     ],
@@ -504,6 +517,13 @@
   },
   {
     "inputs": [],
+    "name": "mintingFinished",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
     "name": "name",
     "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
     "stateMutability": "view",
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -51,6 +51,12 @@
   },
   {
     "anonymous": false,
+    "inputs": [],
+    "name": "MintingFinished",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
     "inputs": [
       {
         "indexed": true,
@@ -399,6 +405,13 @@
     "type": "function"
   },
   {
+    "inputs": [],
+    "name": "finishMinting",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [
       { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
     ],
@@ -486,6 +499,13 @@
   },
   {
     "inputs": [],
+    "name": "mintingFinished",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
     "name": "name",
     "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
     "stateMutability": "view",
@@ -596,7 +616,7 @@
       { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
       { "internalType": "bytes", "name": "data", "type": "bytes" }
     ],
-    "name": "safeTransferFromWithData",
+    "name": "safeTransferFrom",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -98,6 +98,16 @@
   },
   {
     "inputs": [
+      { "internalType": "address", "name": "from", "type": "address" },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "burnFrom",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
       {
         "components": [
           { "internalType": "address", "name": "eth", "type": "address" },
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -536,7 +536,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e48fdb4
+/// @dev the ERC-165 identifier for this interface is 0x16de3152
 interface ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -661,6 +661,11 @@
 	/// @dev EVM selector for this function is: 0xb904db03,
 	///  or in textual repr: mintCross((address,uint256),(string,bytes)[])
 	function mintCross(CrossAddress memory to, Property[] memory properties) external returns (uint256);
+
+	/// @notice Returns collection helper contract address
+	/// @dev EVM selector for this function is: 0x1896cce6,
+	///  or in textual repr: collectionHelperAddress()
+	function collectionHelperAddress() external view returns (address);
 }
 
 /// @dev anonymous struct
@@ -703,7 +708,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard
 /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x983a942b
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
 interface ERC721 is Dummy, ERC165, ERC721Events {
 	/// @notice Count all NFTs assigned to an owner
 	/// @dev NFTs assigned to the zero address are considered invalid, and this
@@ -786,11 +791,6 @@
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
 	function isApprovedForAll(address owner, address operator) external view returns (bool);
-
-	/// @notice Returns collection helper contract address
-	/// @dev EVM selector for this function is: 0x1896cce6,
-	///  or in textual repr: collectionHelperAddress()
-	function collectionHelperAddress() external view returns (address);
 }
 
 interface UniqueNFT is
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -441,6 +441,8 @@
 	TransferEnabled
 }
 
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x5b5e139f
 interface ERC721Metadata is Dummy, ERC165 {
 	// /// @notice A descriptive name for a collection of NFTs in this contract
@@ -534,7 +536,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xabf30dc2
+/// @dev the ERC-165 identifier for this interface is 0xb365c124
 interface ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -660,6 +662,11 @@
 	/// @dev EVM selector for this function is: 0xab76fac6,
 	///  or in textual repr: tokenContractAddress(uint256)
 	function tokenContractAddress(uint256 token) external view returns (address);
+
+	/// @notice Returns collection helper contract address
+	/// @dev EVM selector for this function is: 0x1896cce6,
+	///  or in textual repr: collectionHelperAddress()
+	function collectionHelperAddress() external view returns (address);
 }
 
 /// @dev anonymous struct
@@ -702,7 +709,7 @@
 
 /// @title ERC-721 Non-Fungible Token Standard
 /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x4016cd87
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
 interface ERC721 is Dummy, ERC165, ERC721Events {
 	/// @notice Count all RFTs assigned to an owner
 	/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -725,9 +732,9 @@
 	function ownerOf(uint256 tokenId) external view returns (address);
 
 	/// @dev Not implemented
-	/// @dev EVM selector for this function is: 0x60a11672,
-	///  or in textual repr: safeTransferFromWithData(address,address,uint256,bytes)
-	function safeTransferFromWithData(
+	/// @dev EVM selector for this function is: 0xb88d4fde,
+	///  or in textual repr: safeTransferFrom(address,address,uint256,bytes)
+	function safeTransferFrom(
 		address from,
 		address to,
 		uint256 tokenId,
@@ -783,11 +790,6 @@
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
 	function isApprovedForAll(address owner, address operator) external view returns (bool);
-
-	/// @notice Returns collection helper contract address
-	/// @dev EVM selector for this function is: 0x1896cce6,
-	///  or in textual repr: collectionHelperAddress()
-	function collectionHelperAddress() external view returns (address);
 }
 
 interface UniqueRefungible is
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -16,14 +16,17 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
+import {UniqueFTCollection, UniqueNFToken, UniqueRFToken} from '../util/playgrounds/unique';
 
 describe('Integration Test: Unnesting', () => {
   let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
 
   before(async () => {
     await usingPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({filename: __filename});
-      [alice] = await helper.arrange.createAccounts([50n], donor);
+      [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 50n, 50n], donor);
     });
   });
 
@@ -63,6 +66,208 @@
     expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
     expect(await targetToken.getChildren()).to.be.length(0);
   });
+
+  itSub.ifWithPallets('ReFungible: allows the owner to successfully unnest a token', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
+
+    const collectionRFT = await helper.rft.mintCollection(alice);
+
+    // Nest and unnest
+    const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
+    await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
+
+    // Nest and burn
+    await token.transfer(alice, targetToken.nestingAccount(), 5n);
+    await expect(token.burnFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+    expect(await targetToken.getChildren()).to.be.length(0);
+  });
+
+  async function checkNestedAmountState({
+    expectedBalance,
+    childrenShouldPresent,
+    nested,
+    targetNft,
+  }: {
+    expectedBalance: bigint,
+    childrenShouldPresent: boolean,
+    nested: UniqueFTCollection | UniqueRFToken,
+    targetNft: UniqueNFToken,
+  }) {
+    const balance = await nested.getBalance(targetNft.nestingAccount());
+    expect(balance).to.be.equal(expectedBalance);
+
+    const children = await targetNft.getChildren();
+
+    if (childrenShouldPresent) {
+      expect(children[0]).to.be.deep.equal({
+        collectionId: nested.collectionId,
+        tokenId: (nested instanceof UniqueFTCollection) ? 0 : nested.tokenId,
+      });
+    } else {
+      expect(children.length).to.be.equal(0);
+    }
+  }
+
+  function ownerOrAdminUnnestCases(modes: ('ft' | 'nft' | 'rft')[]): {
+    mode: 'ft' | 'nft' | 'rft',
+    sender: string,
+    op: 'transfer' | 'burn',
+    requiredPallets: Pallets[],
+  }[] {
+    const senders = ['owner', 'admin'];
+    const ops = ['transfer', 'burn'];
+
+    const cases = [];
+    for (const mode of modes) {
+      const requiredPallets = (mode === 'rft')
+        ? [Pallets.ReFungible]
+        : [];
+
+      for (const sender of senders) {
+        for (const op of ops) {
+          cases.push({
+            mode: mode as 'ft' | 'nft' | 'rft',
+            sender,
+            op: op as 'transfer' | 'burn',
+            requiredPallets,
+          });
+        }
+      }
+    }
+
+    return cases;
+  }
+
+  ownerOrAdminUnnestCases(['ft', 'rft']).map(testCase =>
+    itSub.ifWithPallets(`[${testCase.mode}]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, testCase.requiredPallets, async({helper}) => {
+      const owner = alice;
+      const admin = bob;
+
+      const unnester = (testCase.sender === 'owner')
+        ? owner
+        : admin;
+
+      const collectionNFT = await helper.nft.mintCollection(owner);
+      await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+      const collectionNested = await helper[testCase.mode as 'ft' | 'rft'].mintCollection(owner, {
+        limits: {
+          ownerCanTransfer: true,
+        },
+      });
+      await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+      const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+
+      let nested: UniqueFTCollection | UniqueRFToken;
+      const totalAmount = 5n;
+      const firstUnnestAmount = 2n;
+      const restUnnestAmount = totalAmount - firstUnnestAmount;
+
+      if (collectionNested instanceof UniqueFTCollection) {
+        await collectionNested.mint(owner, totalAmount, {Substrate: charlie.address});
+        nested = collectionNested;
+      } else {
+        nested = await collectionNested.mintToken(owner, totalAmount, {Substrate: charlie.address});
+      }
+
+      // transfer/burn `amount` of nested assets by `unnester`.
+      const doOperationAndCheck = async ({
+        amount,
+        shouldBeNestedAfterOp,
+      }: {
+        amount: bigint,
+        shouldBeNestedAfterOp: boolean,
+      }) => {
+        const nestedBalanceBeforeOp = await nested.getBalance(targetNft.nestingAccount());
+
+        if (testCase.op === 'transfer') {
+          const bobBalanceBeforeOp = await nested.getBalance({Substrate: bob.address});
+
+          await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address}, amount);
+          expect(await nested.getBalance({Substrate: bob.address})).to.be.equal(bobBalanceBeforeOp + amount);
+        } else {
+          if (nested instanceof UniqueFTCollection) {
+            await nested.burnTokensFrom(unnester, targetNft.nestingAccount(), amount);
+          } else {
+            await nested.burnFrom(unnester, targetNft.nestingAccount(), amount);
+          }
+        }
+
+        await checkNestedAmountState({
+          expectedBalance: nestedBalanceBeforeOp - amount,
+          childrenShouldPresent: shouldBeNestedAfterOp,
+          nested,
+          targetNft,
+        });
+      };
+
+      // Initial setup: nest (fungibles/rft parts).
+      // Check NFT's balance of nested assets and NFT's children.
+      await nested.transfer(charlie, targetNft.nestingAccount(), totalAmount);
+      await checkNestedAmountState({
+        expectedBalance: totalAmount,
+        childrenShouldPresent: true,
+        nested,
+        targetNft,
+      });
+
+      // Transfer/burn only a part of nested assets.
+      // Check that NFT's balance of the nested assets correctly decreased and NFT's children are not changed.
+      await doOperationAndCheck({
+        amount: firstUnnestAmount,
+        shouldBeNestedAfterOp: true,
+      });
+
+      // Transfer/burn all remaining nested assets.
+      // Check that NFT's balance of the nested assets is 0 and NFT has no more children.
+      await doOperationAndCheck({
+        amount: restUnnestAmount,
+        shouldBeNestedAfterOp: false,
+      });
+    }));
+
+  ownerOrAdminUnnestCases(['nft']).map(testCase =>
+    itSub(`[nft]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, async ({helper}) => {
+      const owner = alice;
+      const admin = bob;
+
+      const unnester = (testCase.sender === 'owner')
+        ? owner
+        : admin;
+
+      const collectionNFT = await helper.nft.mintCollection(owner);
+      await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+      const collectionNested = await helper.nft.mintCollection(owner, {
+        limits: {
+          ownerCanTransfer: true,
+        },
+      });
+      await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+      const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+      const nested = await collectionNested.mintToken(owner, {Substrate: charlie.address});
+
+      await nested.transfer(charlie, targetNft.nestingAccount());
+      expect(await targetNft.getChildren()).to.be.deep.equal([{
+        collectionId: nested.collectionId,
+        tokenId: nested.tokenId,
+      }]);
+
+      if (testCase.op === 'transfer') {
+        await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address});
+      } else {
+        await nested.burnFrom(unnester, targetNft.nestingAccount());
+      }
+
+      expect((await targetNft.getChildren()).length).to.be.equal(0);
+    }));
 });
 
 describe('Negative Test: Unnesting', () => {
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -76,6 +76,7 @@
           appPromotion,
           testUtils,
           ...rmrkPallets,
+          ...collatorSelection,
         );
       } else if (chain.eq('QUARTZ by UNIQUE') || chain.eq('SAPPHIRE by UNIQUE')) {
         requiredPallets.push(
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -651,6 +651,9 @@
     try {
       result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;
       events = this.eventHelper.extractEvents(result.result.events);
+      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');
+      if (errorEvent)
+        throw Error(errorEvent.method + ': ' + extrinsic);
     }
     catch(e) {
       if(!(e as object).hasOwnProperty('status')) throw e;