git.delta.rocks / unique-network / refs/commits / 97d7053c9b0e

difftreelog

Merge branch 'develop' into feature/contract-sponsoring-modes

Igor Kozyrev2022-02-17parents: #e7ebf1d #71137c9.patch.diff
in: master

34 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -382,9 +382,9 @@
 
 [[package]]
 name = "autocfg"
-version = "1.0.1"
+version = "1.1.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
 
 [[package]]
 name = "backtrace"
@@ -634,9 +634,9 @@
 
 [[package]]
 name = "block-buffer"
-version = "0.10.1"
+version = "0.10.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03588e54c62ae6d763e2a80090d50353b785795361b4ff5b3bf0a5097fc31c0b"
+checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
 dependencies = [
  "generic-array 0.14.5",
 ]
@@ -1097,9 +1097,9 @@
 
 [[package]]
 name = "core-foundation"
-version = "0.9.2"
+version = "0.9.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6888e10551bb93e424d8df1d07f1a8b4fceb0001a3a4b048bfc47554946f47b3"
+checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"
 dependencies = [
  "core-foundation-sys",
  "libc",
@@ -1229,9 +1229,9 @@
 
 [[package]]
 name = "crc32fast"
-version = "1.3.1"
+version = "1.3.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2209c310e29876f7f0b2721e7e26b84aff178aa3da5d091f9bfbf47669e60e3"
+checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
 dependencies = [
  "cfg-if 1.0.0",
 ]
@@ -1288,9 +1288,9 @@
 
 [[package]]
 name = "crypto-common"
-version = "0.1.1"
+version = "0.1.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0"
+checksum = "a4600d695eb3f6ce1cd44e6e291adceb2cc3ab12f20a33777ecd0bf6eba34e06"
 dependencies = [
  "generic-array 0.14.5",
 ]
@@ -1898,13 +1898,12 @@
 
 [[package]]
 name = "digest"
-version = "0.10.1"
+version = "0.10.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b"
+checksum = "8cb780dce4f9a8f5c087362b3a4595936b2019e7c8b30f2c3e9a7e94e6ae9837"
 dependencies = [
- "block-buffer 0.10.1",
+ "block-buffer 0.10.2",
  "crypto-common",
- "generic-array 0.14.5",
 ]
 
 [[package]]
@@ -3241,9 +3240,9 @@
 
 [[package]]
 name = "httparse"
-version = "1.5.1"
+version = "1.6.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "acd94fdbe1d4ff688b67b04eee2e17bd50995534a61539e45adfefb45e5e5503"
+checksum = "9100414882e15fb7feccb4897e5f0ff0ff1ca7d1a86a23208ada4d7a18e6c6c4"
 
 [[package]]
 name = "httpdate"
@@ -4664,9 +4663,9 @@
 
 [[package]]
 name = "memmap2"
-version = "0.5.2"
+version = "0.5.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe3179b85e1fd8b14447cbebadb75e45a1002f541b925f0bfec366d56a81c56d"
+checksum = "057a3db23999c867821a7a59feb06a578fcb03685e983dff90daf9e7d24ac08f"
 dependencies = [
  "libc",
 ]
@@ -8805,7 +8804,7 @@
 source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.16#4aeb95f7f38fcd519e2628f32f79044a8fef99d5"
 dependencies = [
  "impl-trait-for-tuples",
- "memmap2 0.5.2",
+ "memmap2 0.5.3",
  "parity-scale-codec",
  "sc-chain-spec-derive",
  "sc-network",
@@ -9912,7 +9911,7 @@
 dependencies = [
  "cfg-if 1.0.0",
  "cpufeatures 0.2.1",
- "digest 0.10.1",
+ "digest 0.10.2",
 ]
 
 [[package]]
@@ -11644,7 +11643,7 @@
 
 [[package]]
 name = "unique-node"
-version = "0.9.14"
+version = "0.9.16"
 dependencies = [
  "cumulus-client-cli",
  "cumulus-client-collator",
modifiedDockerfile-parachaindiffbeforeafterboth
--- a/Dockerfile-parachain
+++ b/Dockerfile-parachain
@@ -90,7 +90,7 @@
       nvm install v15.5.0 && \
       nvm use v15.5.0
 
-RUN git clone https://github.com/PureStake/polkadot-launch -b jlm-use-para-id-in-specs
+RUN git clone https://github.com/paritytech/polkadot-launch
 
 RUN export NVM_DIR="$HOME/.nvm" && \
     [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
modifiedREADME.mddiffbeforeafterboth
--- a/README.md
+++ b/README.md
@@ -29,26 +29,11 @@
 
 Please see our [walk-thorugh instructions](doc/hackusama_walk_through.md) to try everything out!
 
-## Hackusama Update
-
-During the Kusama Hackaphon the following changes were made:
-
--   Enabled Smart Contracts Pallet
--   Enabled integration between Smart Contracts and Unique Pallet (required special edition of RC4 Substrate version)
--   Fixed misc. bugs in Unique Pallet
--   Deployed Unique TestNet. Public node available at wss://unique.usetech.com, custom UI types - see below in this README.
--   New Features:
-    -   Re-Fungible Token Mode
-    -   Off-Chain Schema to store token image URLs
-    -   Alternative economic model
-    -   Allow Lists and Public Mint Permission
--   Use example: [SubstraPunks Game](https://github.com/usetech-llc/substrapunks), fully hosted on IPFS and Unique Testnet
-    Blockchain.
-
 ## Application Development
 
 If you are building an application that operates NFT tokens, use [this document](doc/application_development.md).
 
+
 ## Building
 
 Building Unique chain requires special versions of Rust and toolchain. We don't use the most recent versions of everything
@@ -57,8 +42,8 @@
 1. Install Rust:
 
 ```bash
+sudo apt-get install git curl libssl-dev llvm pkg-config libclang-dev clang
 curl https://sh.rustup.rs -sSf | sh
-sudo apt-get install libssl-dev pkg-config libclang-dev clang
 ```
 
 2. Remove all installed toolchains with `rustup toolchain list` and `rustup toolchain uninstall <toolchain>`.
@@ -86,111 +71,52 @@
 cargo build --release
 ```
 
-## Run
-
-You can start a development chain with:
-
-```bash
-cargo run -- --dev
-```
-
-Detailed logs may be shown by running the node with the following environment variables set:
-`RUST_LOG=debug RUST_BACKTRACE=1 cargo run -- --dev`.
+## Building as Parachain locally
 
-If you want to see the multi-node consensus algorithm in action locally, then you can create a local testnet with two
-validator nodes for Alice and Bob, who are the initial authorities of the genesis chain that have been endowed with
-testnet units. Give each node a name and expose them so they are listed on the Polkadot
-[telemetry site](https://telemetry.polkadot.io/#/Local%20Testnet). You'll need two terminal windows open.
+Note: checkout this project and all related projects (see below) in the sibling folders (both under the same folder)
 
-We'll start Alice's substrate node first on default TCP port 30333 with her chain database stored locally at
-`/tmp/alice`. The bootnode ID of her node is `QmQZ8TjTqeDj3ciwr93EJ95hxfDsb9pEYDizUAbWpigtQN`, which is generated from
-the `--node-key` value that we specify below:
+### Polkadot launch utility
 
-```bash
-cargo run -- \
-  --base-path /tmp/alice \
-  --chain=local \
-  --alice \
-  --node-key 0000000000000000000000000000000000000000000000000000000000000001 \
-  --telemetry-url ws://telemetry.polkadot.io:1024 \
-  --validator
 ```
-
-In the second terminal, we'll start Bob's substrate node on a different TCP port of 30334, and with his chain database
-stored locally at `/tmp/bob`. We'll specify a value for the `--bootnodes` option that will connect his node to Alice's
-bootnode ID on TCP port 30333:
-
-```bash
-cargo run -- \
-  --base-path /tmp/bob \
-  --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/QmQZ8TjTqeDj3ciwr93EJ95hxfDsb9pEYDizUAbWpigtQN \
-  --chain=local \
-  --bob \
-  --port 30334 \
-  --telemetry-url ws://telemetry.polkadot.io:1024 \
-  --validator
+git clone https://github.com/paritytech/polkadot-launch
 ```
-
-Additional CLI usage options are available and may be shown by running `cargo run -- --help`.
-
-## Building and Running as Parachain locally
-
-Rust toolchain: nightly-2021-11-11
-Note: checkout this project and polkadot project (see below) in the sibling folders (both under the same folder)
 
 ### Build relay
 
 ```
 git clone https://github.com/paritytech/polkadot.git
 cd polkadot
-git checkout release-v0.9.9
+git checkout release-v0.9.16
 cargo build --release
 ```
 
-### Build parachain
+### Build Unique parachain
 
 Run in the root of this project:
 ```
-cargo --build
+cargo build --release
 ```
 
-### Run 4-node Relay
-
-1. Download `rococo-custom-4.json` chain spec here: https://substrate.dev/cumulus-workshop/shared/chainspecs/rococo-custom-4.json
-2. Use these instructions to launch 4 nodes: https://substrate.dev/cumulus-workshop/#/en/2-relay-chain/1-launch
+### Build Acala parachain (optional, full config only)
 
-Example (Run in polkadot folder. Replace `12D3KooWNLAmKcyee3oqSgTMthaQVXaAcXeo8RrGCzMfMVA3B5on` with output from Alice node):
 ```
-./target/release/polkadot --alice --validator --base-path ./cumulus_relay0 --chain rococo-custom-4.json --port 50555 --ws-port 9944
-./target/release/polkadot --bob --validator --base-path ./cumulus_relay1 --chain rococo-custom-4.json --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWNLAmKcyee3oqSgTMthaQVXaAcXeo8RrGCzMfMVA3B5on --port 50556 --ws-port 9945
-./target/release/polkadot --charlie --validator --base-path ./cumulus_relay1 --chain rococo-custom-4.json --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWNLAmKcyee3oqSgTMthaQVXaAcXeo8RrGCzMfMVA3B5on --port 50557 --ws-port 9946
-./target/release/polkadot --dave --validator --base-path ./cumulus_relay1 --chain rococo-custom-4.json --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWNLAmKcyee3oqSgTMthaQVXaAcXeo8RrGCzMfMVA3B5on --port 50558 --ws-port 9947
-
+git clone https://github.com/AcalaNetwork/Acala
+cd Acala
+git checkout 54db3acd409a0b787f116f20e163a3b24101ce38
+make build-release
 ```
 
-3. Export genesis state and runtime wasm from Unique parachain:
+## Running as Parachain locally
 
-Run from this project root:
 ```
-./target/release/unique-collator export-genesis-state --parachain-id 2000 > ./resources/para-2000-genesis
-./target/release/unique-collator export-genesis-wasm > ./resources/para-2000-wasm
+./launch-testnet.sh
 ```
 
-4. Run two parachain nodes:
-
-Replace `12D3KooWN1ah2bFQSysEFnwZqcmcVpDDR8UedXyo6xfzV1zDNMNg` with Alice or Bob relay ID
-
-Run from this project root:
+Optional, full setup with Acala and Statemint
 ```
-./target/release/unique-collator --alice --collator --force-authoring --base-path ./tmp/parachain-alice --parachain-id 2000 --port 40333 --ws-port 9844  -- --execution wasm --chain ../polkadot/rococo-custom-4.json --port 30343 --ws-port 9977
-./target/release/unique-collator --bob --collator --force-authoring --parachain-id 2000 --base-path ./tmp/parachain/bob --port 40334 --ws-port 9845 -- --execution wasm --chain ../polkadot/rococo-custom-4.json --port 30344 --ws-port 9978 --bootnodes /ip4/127.0.0.1/tcp/50556/p2p/12D3KooWN1ah2bFQSysEFnwZqcmcVpDDR8UedXyo6xfzV1zDNMNg
+./launch-testnet-full.sh
 ```
-
-4. Reserve parachain ID as described here: https://substrate.dev/cumulus-workshop/#/en/2-relay-chain/2-reserve
 
-5. Register parachain in relay as described here: https://substrate.dev/cumulus-workshop/#/en/3-parachains/2-register
-
-
 ## Run Integration Tests
 
 1. Install all needed dependecies
@@ -202,40 +128,11 @@
 2. Run tests
 ```
 yarn test
-```
-
-## Benchmarks
-
-First of all, add rust toolchain and make it default.
-```bash
-rustup target add wasm32-unknown-unknown --toolchain nightly-2021-11-11
-```
-
-Then in "/node/src" run build command below
-```bash
-cargo +nightly-2021-11-11 build --release --features runtime-benchmarks
-```
-
-Run benchmark
-```bash
-target/release/unique-collator benchmark --chain dev --pallet "pallet_unique" --extrinsic "*" --repeat 1
 ```
-
-## UI custom types
-
-Moved to [runtime_types.json](./runtime_types.json).
-
-## Running Integration Tests
 
-See [tests/README.md](./tests/README.md).
 
 ## Code Formatting
 
-### Get formatter and linter settings into your branch (if you forked before they were introduced)
-```bash
-git cherry-pick -n 8ff77c21b0d30b2a4648fa35dbf61dfa9d3948a7
-```
-
 ### Apply formatting and clippy fixes
 ```bash
 cargo clippy
@@ -252,84 +149,57 @@
 cd tests && yarn eslint --ext .ts,.js src/
 ```
 
-## Re-Enabling Ink! Contracts
 
-Uncomment following lies:
-1. In node/rpc/Cargo.toml
-```
-# pallet-contracts-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.9' }
-```
+## Karura token transfer
 
-2. In node/rpc/src/lib.rs
-```
-// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
-...
-// use pallet_contracts_rpc::{Contracts, ContractsApi};
-...
-// io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));
+To get started, you need to open inbound and outbound hrmp channels.
 
+### Next, we need to register our asset at Karura.
 ```
+assetRegistry -> registerForeignAsset(location, metadata)
+location:
+	V0(X2(Parent, Parachain(PARA_ID))) 
+metadata:
+	name         OPL
+	symbol       OPL
+	decimals     18
+minimalBalance	 1
+```
 
-3. In runtime/Cargo.toml
+### Next, we can send tokens from Opal to Karura:
 ```
-    # 'pallet-contracts/std',
-    # 'pallet-contracts-primitives/std',
-    # 'pallet-contracts-rpc-runtime-api/std',
-    # 'pallet-contract-helpers/std',
-...
-    # [dependencies.pallet-contracts]
-    # git = 'https://github.com/paritytech/substrate.git'
-    # default-features = false
-    # branch = 'polkadot-v0.9.9'
-    # version = '3.0.0'
+polkadotXcm -> reserveTransferAssets
+dest:
+	V0(X2(Parent, Parachain(<KARURA_PARA_ID>))) 
+beneficiary:
+	X1(AccountId(Any, <ACCOUNT>))
+assets:
+	V1(Concrete(0,Here), Fungible(<AMOUNT>))
+feeAssetItem: 
+	0	
+weightLimit:
+	<LIMIT>
+```	
 
-    # [dependencies.pallet-contracts-primitives]
-    # git = 'https://github.com/paritytech/substrate.git'
-    # default-features = false
-    # branch = 'polkadot-v0.9.9'
-    # version = '3.0.0'
+The result will be displayed in ChainState   
+tokens -> accounts	
 
-    # [dependencies.pallet-contracts-rpc-runtime-api]
-    # git = 'https://github.com/paritytech/substrate.git'
-    # default-features = false
-    # branch = 'polkadot-v0.9.9'
-    # version = '3.0.0'
-...
-    # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
+### To send tokens from Karura to Opal:
 ```
+xtokens -> transfer
 
-4. runtime/src/lib.rs
-```
-// use pallet_contracts::weights::WeightInfo;
-...
-// pub use pallet_timestamp::Call as TimestampCall;
-...
-// mod chain_extension;
-// use crate::chain_extension::{NFTExtension, Imbalance};
-...
-/*
-parameter_types! {
-	pub TombstoneDeposit: Balance = deposit(
-  ...
-}
-*/
-...
-//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
-...
-// impl pallet_contract_helpers::Config for Runtime {}
-...
-// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},
-...
-// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage},
-...
-//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
-...
-/*
-	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>
-		for Runtime
-	{
-    ...
-	}
-*/
+currencyId:
+	ForeingAsset
+		<TOKEN_ID>
 
-```
+amount:
+		<AMOUNT>
+dest:
+	V1
+	(
+		Parents:1, 
+		X2(Parachain(<KARURA_PARA_ID>), AccountId(Any, <ACCOUNT>)
+	)
+destWeight:
+	<WEIGHT>
+```
\ No newline at end of file
modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -4,7 +4,7 @@
 use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
 use jsonrpc_derive::rpc;
 use up_data_structs::{Collection, CollectionId, CollectionStats, TokenId};
-use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
+use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
 use sp_blockchain::HeaderBackend;
 use up_rpc::UniqueApi as UniqueRuntimeApi;
 
@@ -132,7 +132,10 @@
 }
 
 macro_rules! pass_method {
-	($method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty $(=> $mapper:expr)?) => {
+	(
+		$method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty $(=> $mapper:expr)?
+		$(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*
+	) => {
 		fn $method_name(
 			&self,
 			$(
@@ -142,8 +145,25 @@
 		) -> Result<$result> {
 			let api = self.client.runtime_api();
 			let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));
+			let _api_version = if let Ok(Some(api_version)) =
+				api.api_version::<dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>>(&at)
+			{
+				api_version
+			} else {
+				// unreachable for our runtime
+				return Err(RpcError {
+					code: ErrorCode::InvalidParams,
+					message: "Api is not available".into(),
+					data: None,
+				})
+			};
 
-			let result = api.$method_name(&at, $($name),*).map_err(|e| RpcError {
+			let result = $(if _api_version < $ver {
+				api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))
+			} else)*
+			{ api.$method_name(&at, $($name),*) };
+
+			let result = result.map_err(|e| RpcError {
 				code: ErrorCode::ServerError(Error::RuntimeError.into()),
 				message: "Unable to query".into(),
 				data: Some(format!("{:?}", e).into()),
@@ -168,7 +188,10 @@
 {
 	pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);
 	pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);
-	pass_method!(token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);
+	pass_method!(
+		token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>;
+		changed_in 2, token_owner_before_version_2(collection, token) => |u| Some(u)
+	);
 	pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
 	pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
 	pass_method!(collection_tokens(collection: CollectionId) -> u32);
addeddoc/hackusama_update.mddiffbeforeafterboth
--- /dev/null
+++ b/doc/hackusama_update.md
@@ -0,0 +1,15 @@
+## Hackusama Update
+
+During the Kusama Hackaphon the following changes were made:
+
+-   Enabled Smart Contracts Pallet
+-   Enabled integration between Smart Contracts and Unique Pallet (required special edition of RC4 Substrate version)
+-   Fixed misc. bugs in Unique Pallet
+-   Deployed Unique TestNet. Public node available at wss://unique.usetech.com, custom UI types - see below in this README.
+-   New Features:
+    -   Re-Fungible Token Mode
+    -   Off-Chain Schema to store token image URLs
+    -   Alternative economic model
+    -   Allow Lists and Public Mint Permission
+-   Use example: [SubstraPunks Game](https://github.com/usetech-llc/substrapunks), fully hosted on IPFS and Unique Testnet
+    Blockchain.
\ No newline at end of file
addeddoc/re-enable_ink_contracts.mddiffbeforeafterboth
--- /dev/null
+++ b/doc/re-enable_ink_contracts.md
@@ -0,0 +1,81 @@
+## Re-Enabling Ink! Contracts
+
+Uncomment following lies:
+1. In node/rpc/Cargo.toml
+```
+# pallet-contracts-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.9' }
+```
+
+2. In node/rpc/src/lib.rs
+```
+// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
+...
+// use pallet_contracts_rpc::{Contracts, ContractsApi};
+...
+// io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));
+
+```
+
+3. In runtime/Cargo.toml
+```
+    # 'pallet-contracts/std',
+    # 'pallet-contracts-primitives/std',
+    # 'pallet-contracts-rpc-runtime-api/std',
+    # 'pallet-contract-helpers/std',
+...
+    # [dependencies.pallet-contracts]
+    # git = 'https://github.com/paritytech/substrate.git'
+    # default-features = false
+    # branch = 'polkadot-v0.9.9'
+    # version = '3.0.0'
+
+    # [dependencies.pallet-contracts-primitives]
+    # git = 'https://github.com/paritytech/substrate.git'
+    # default-features = false
+    # branch = 'polkadot-v0.9.9'
+    # version = '3.0.0'
+
+    # [dependencies.pallet-contracts-rpc-runtime-api]
+    # git = 'https://github.com/paritytech/substrate.git'
+    # default-features = false
+    # branch = 'polkadot-v0.9.9'
+    # version = '3.0.0'
+...
+    # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
+```
+
+4. runtime/src/lib.rs
+```
+// use pallet_contracts::weights::WeightInfo;
+...
+// pub use pallet_timestamp::Call as TimestampCall;
+...
+// mod chain_extension;
+// use crate::chain_extension::{NFTExtension, Imbalance};
+...
+/*
+parameter_types! {
+	pub TombstoneDeposit: Balance = deposit(
+  ...
+}
+*/
+...
+//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
+...
+// impl pallet_contract_helpers::Config for Runtime {}
+...
+// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},
+...
+// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage},
+...
+//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
+...
+/*
+	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>
+		for Runtime
+	{
+    ...
+	}
+*/
+
+```
\ No newline at end of file
addedlaunch-config-full.jsondiffbeforeafterboth
--- /dev/null
+++ b/launch-config-full.json
@@ -0,0 +1,135 @@
+{
+    "relaychain": {
+        "bin": "../polkadot/target/release/polkadot",
+        "chain": "rococo-local",
+        "nodes": [
+            {
+                "name": "alice",
+                "wsPort": 9844,
+                "rpcPort": 9843,
+                "port": 30444,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace"
+                ]
+            },
+            {
+                "name": "bob",
+                "wsPort": 9855,
+                "rpcPort": 9854,
+                "port": 30555,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace"
+                ]
+            },
+            {
+                "name": "charlie",
+                "wsPort": 9866,
+                "rpcPort": 9865,
+                "port": 30666,
+                "flags": [
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "dave",
+                "wsPort": 9877,
+                "rpcPort": 9876,
+                "port": 30777,
+                "flags": [
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "eve",
+                "wsPort": 9888,
+                "rpcPort": 9887,
+                "port": 30888,
+                "flags": [
+                    "-lparachain::candidate_validation=debug"
+                ]
+            }
+        ],
+        "genesis": {
+            "runtime": {
+                "runtime_genesis_config": {
+                    "parachainsConfiguration": {
+                        "config": {
+                            "validation_upgrade_frequency": 1,
+                            "validation_upgrade_delay": 1
+                        }
+                    }
+                }
+            }
+        }
+    },
+    "parachains": [
+        {
+            "bin": "../unique-chain/target/release/unique-collator",
+            "id": "1000",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "port": 31200,
+                    "wsPort": 9944,
+                    "rpcPort": 9933,
+                    "name": "alice",
+                    "flags": [
+                        "--rpc-cors=all",
+                        "--unsafe-rpc-external",
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
+                    ]
+                },
+                {
+                    "port": 31201,
+                    "wsPort": 9945,
+                    "rpcPort": 9934,
+                    "name": "bob",
+                    "flags": [
+                        "--rpc-cors=all",
+                        "--unsafe-rpc-external",
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
+                    ]
+                }
+            ]
+        },
+        {
+            "bin": "../Acala/target/release/acala",
+            "id": "2000",
+            "chain":  "karura-dev",
+			"balance": "1000000000000000000000",
+			"nodes": [
+				{
+					"wsPort": 9946,
+					"port": 31202,
+					"name": "alice",
+                    "flags": [
+                        "--rpc-cors=all",
+                        "--unsafe-rpc-external",
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
+                    ]
+				}
+			]
+		}
+    ],
+    "simpleParachains": [],
+    "hrmpChannels": [
+        {
+            "sender": 2000,
+            "recipient": 1000,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 1000,
+            "recipient": 2000,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        }
+    ],
+    "finalization": false
+}
deletedlaunch-config-westend.jsondiffbeforeafterboth
--- a/launch-config-westend.json
+++ /dev/null
@@ -1,141 +0,0 @@
-{
-    "relaychain": {
-        "bin": "../polkadot/target/release/polkadot",
-        "chain": "westend-local",
-        "nodes": [
-            {
-                "name": "alice",
-                "wsPort": 9844,
-                "rpcPort": 9843,
-                "port": 30444,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            },
-            {
-                "name": "bob",
-                "wsPort": 9855,
-                "rpcPort": 9854,
-                "port": 30555,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            },
-            {
-                "name": "charlie",
-                "wsPort": 9866,
-                "rpcPort": 9865,
-                "port": 30666,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            },
-            {
-                "name": "dave",
-                "wsPort": 9877,
-                "rpcPort": 9876,
-                "port": 30777,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            },
-            {
-                "name": "eve",
-                "wsPort": 9888,
-                "rpcPort": 9886,
-                "port": 30888,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            },
-            {
-                "name": "ferdie",
-                "wsPort": 9897,
-                "rpcPort": 9896,
-                "port": 30999,
-                "flags": [
-                    "-lparachain::candidate_validation=debug"
-                ]
-            }
-        ],
-        "genesis": {
-            "runtime": {
-                "runtime_genesis_config": {
-                    "parachainsConfiguration": {
-                        "config": {
-                            "validation_upgrade_frequency": 1,
-                            "validation_upgrade_delay": 1
-                        }
-                    }
-                }
-            }
-        }
-    },
-    "parachains": [
-        {
-            "bin": "../unique-chain/target/release/unique-collator",
-            "chain": "westend-local",
-            "balance": "1000000000000000000000000",
-            "nodes": [
-                {
-                    "port": 31200,
-                    "wsPort": 9944,
-                    "rpcPort": 9933,
-                    "name": "alice",
-                    "flags": [
-                        "--rpc-cors=all",
-                        "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
-                    ]
-                },
-                {
-                    "port": 31201,
-                    "wsPort": 9945,
-                    "rpcPort": 9934,
-                    "name": "bob",
-                    "flags": [
-                        "--rpc-cors=all",
-                        "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
-                    ]
-                },
-                {
-                    "port": 31202,
-                    "wsPort": 9946,
-                    "rpcPort": 9935,
-                    "name": "charlie",
-                    "flags": [
-                        "--rpc-cors=all",
-                        "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
-                    ]
-                },
-                {
-                    "port": 31203,
-                    "wsPort": 9947,
-                    "rpcPort": 9936,
-                    "name": "dave",
-                    "flags": [
-                        "--rpc-cors=all",
-                        "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
-                    ]
-                },
-                {
-                    "port": 31204,
-                    "wsPort": 9948,
-                    "rpcPort": 9937,
-                    "name": "eve",
-                    "flags": [
-                        "--rpc-cors=all",
-                        "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
-                    ]
-                }
-            ]
-        }
-    ],
-    "simpleParachains": [],
-    "hrmpChannels": [],
-    "finalization": false
-}
modifiedlaunch-config.jsondiffbeforeafterboth
--- a/launch-config.json
+++ b/launch-config.json
@@ -9,7 +9,8 @@
                 "rpcPort": 9843,
                 "port": 30444,
                 "flags": [
-                    "-lparachain::candidate_validation=debug"
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace"
                 ]
             },
             {
@@ -18,7 +19,8 @@
                 "rpcPort": 9854,
                 "port": 30555,
                 "flags": [
-                    "-lparachain::candidate_validation=debug"
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace"
                 ]
             },
             {
@@ -38,6 +40,15 @@
                 "flags": [
                     "-lparachain::candidate_validation=debug"
                 ]
+            },
+            {
+                "name": "eve",
+                "wsPort": 9888,
+                "rpcPort": 9887,
+                "port": 30888,
+                "flags": [
+                    "-lparachain::candidate_validation=debug"
+                ]
             }
         ],
         "genesis": {
@@ -67,7 +78,8 @@
                     "flags": [
                         "--rpc-cors=all",
                         "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
                     ]
                 },
                 {
@@ -78,7 +90,8 @@
                     "flags": [
                         "--rpc-cors=all",
                         "--unsafe-rpc-external",
-                        "--unsafe-ws-external"
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
                     ]
                 }
             ]
deletedlaunch-test-env.shdiffbeforeafterboth
--- a/launch-test-env.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-cp launch-config.json ../polkadot-launch/launch-config.json
-
-cd ../polkadot-launch
-yarn install
-yarn build
-yarn start launch-config.json
addedlaunch-testnet-full.shdiffbeforeafterboth
--- /dev/null
+++ b/launch-testnet-full.sh
@@ -0,0 +1,6 @@
+cp launch-config-full.json ../polkadot-launch/launch-config-full.json
+
+cd ../polkadot-launch
+yarn install
+yarn build
+yarn start launch-config-full.json
addedlaunch-testnet.shdiffbeforeafterboth
--- /dev/null
+++ b/launch-testnet.sh
@@ -0,0 +1,6 @@
+cp launch-config.json ../polkadot-launch/launch-config.json
+
+cd ../polkadot-launch
+yarn install
+yarn build
+yarn start launch-config.json
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -257,7 +257,7 @@
 license = 'All Rights Reserved'
 name = 'unique-node'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.9.14'
+version = '0.9.16'
 
 [[bin]]
 name = 'unique-collator'
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
 	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
-	TokenId, Weight, WithdrawReasons, CollectionStats, CustomDataLimit,
+	TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+	NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
+	CustomDataLimit, CreateCollectionData, SponsorshipState,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -285,6 +288,10 @@
 		TokenVariableDataLimitExceeded,
 		/// Exceeded max admin count
 		CollectionAdminCountExceeded,
+		/// Collection limit bounds per collection exceeded
+		CollectionLimitBoundsExceeded,
+		/// Tried to enable permissions which are only permitted to be disabled
+		OwnerPermissionsCantBeReverted,
 
 		/// Collection settings not allowing items transferring
 		TransferNotAllowed,
@@ -300,7 +307,7 @@
 		/// Item balance not enough.
 		TokenValueTooLow,
 		/// Requested value more than approved.
-		TokenValueNotEnough,
+		ApprovedValueTooLow,
 		/// Tried to approve more than owned
 		CantApproveMoreThanOwned,
 
@@ -395,7 +402,10 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
 		{
 			ensure!(
 				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,
@@ -418,6 +428,29 @@
 
 		// =========
 
+		let collection = Collection {
+			owner: owner.clone(),
+			name: data.name,
+			mode: data.mode.clone(),
+			mint_mode: false,
+			access: data.access.unwrap_or_default(),
+			description: data.description,
+			token_prefix: data.token_prefix,
+			offchain_schema: data.offchain_schema,
+			schema_version: data.schema_version.unwrap_or_default(),
+			sponsorship: data
+				.pending_sponsor
+				.map(SponsorshipState::Unconfirmed)
+				.unwrap_or_default(),
+			variable_on_chain_schema: data.variable_on_chain_schema,
+			const_on_chain_schema: data.const_on_chain_schema,
+			limits: data
+				.limits
+				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
+				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+		};
+
 		// Take a (non-refundable) deposit of collection creation
 		{
 			let mut imbalance =
@@ -429,7 +462,7 @@
 				),
 			);
 			<T as Config>::Currency::settle(
-				&data.owner,
+				&owner,
 				imbalance,
 				WithdrawReasons::TRANSFER,
 				ExistenceRequirement::KeepAlive,
@@ -438,12 +471,8 @@
 		}
 
 		<CreatedCollectionCount<T>>::put(created_count);
-		<Pallet<T>>::deposit_event(Event::CollectionCreated(
-			id,
-			data.mode.id(),
-			data.owner.clone(),
-		));
-		<CollectionById<T>>::insert(id, data);
+		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
+		<CollectionById<T>>::insert(id, collection);
 		Ok(id)
 	}
 
@@ -527,6 +556,61 @@
 
 		Ok(())
 	}
+
+	pub fn clamp_limits(
+		mode: CollectionMode,
+		old_limit: &CollectionLimits,
+		mut new_limit: CollectionLimits,
+	) -> Result<CollectionLimits, DispatchError> {
+		macro_rules! limit_default {
+				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+					$(
+						if let Some($new) = $new.$field {
+							let $old = $old.$field($($arg)?);
+							let _ = $new;
+							let _ = $old;
+							$check
+						} else {
+							$new.$field = $old.$field
+						}
+					)*
+				}};
+			}
+
+		limit_default!(old_limit, new_limit,
+			account_token_ownership_limit => ensure!(
+				new_limit <= MAX_TOKEN_OWNERSHIP,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsor_transfer_timeout(match mode {
+				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+			}) => ensure!(
+				new_limit <= MAX_SPONSOR_TIMEOUT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsored_data_size => ensure!(
+				new_limit <= CUSTOM_DATA_LIMIT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			token_limit => ensure!(
+				old_limit >= new_limit && new_limit > 0,
+				<Error<T>>::CollectionTokenLimitExceeded
+			),
+			owner_can_transfer => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			owner_can_destroy => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			sponsored_data_rate_limit => {},
+			transfers_enabled => {},
+		);
+		Ok(new_limit)
+	}
 }
 
 #[macro_export]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
 
 use core::ops::Deref;
 use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use up_data_structs::{AccessMode, CollectionId, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
 };
@@ -100,8 +100,11 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: FungibleHandle<T>,
@@ -343,7 +346,7 @@
 		if allowance.is_none() {
 			ensure!(
 				collection.ignores_allowance(spender),
-				<CommonError<T>>::TokenValueNotEnough
+				<CommonError<T>>::ApprovedValueTooLow
 			);
 		}
 
@@ -374,7 +377,7 @@
 		if allowance.is_none() {
 			ensure!(
 				collection.ignores_allowance(spender),
-				<CommonError<T>>::TokenValueNotEnough
+				<CommonError<T>>::ApprovedValueTooLow
 			);
 		}
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -2,7 +2,7 @@
 
 use erc::ERC721Events;
 use frame_support::{BoundedVec, ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, CustomDataLimit, TokenId};
+use up_data_structs::{AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
 };
@@ -140,8 +140,11 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: NonfungibleHandle<T>,
@@ -492,7 +495,7 @@
 		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
 			ensure!(
 				collection.ignores_allowance(spender),
-				<CommonError<T>>::TokenValueNotEnough
+				<CommonError<T>>::ApprovedValueTooLow
 			);
 		}
 
@@ -520,7 +523,7 @@
 		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
 			ensure!(
 				collection.ignores_allowance(spender),
-				<CommonError<T>>::TokenValueNotEnough
+				<CommonError<T>>::ApprovedValueTooLow
 			);
 		}
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5	AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6};7use pallet_common::{8	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,9};10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};12use core::ops::Deref;13use codec::{Encode, Decode, MaxEncodedLen};14use scale_info::TypeInfo;1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23	pub const_data: BoundedVec<u8, CustomDataLimit>,24	pub variable_data: BoundedVec<u8, CustomDataLimit>,25	pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]30pub struct ItemData {31	pub const_data: BoundedVec<u8, CustomDataLimit>,32	pub variable_data: BoundedVec<u8, CustomDataLimit>,33}3435#[frame_support::pallet]36pub mod pallet {37	use super::*;38	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39	use up_data_structs::{CollectionId, TokenId};40	use super::weights::WeightInfo;4142	#[pallet::error]43	pub enum Error<T> {44		/// Not Refungible item data used to mint in Refungible collection.45		NotRefungibleDataUsedToMintFungibleCollectionToken,46		/// Maximum refungibility exceeded47		WrongRefungiblePieces,48	}4950	#[pallet::config]51	pub trait Config: frame_system::Config + pallet_common::Config {52		type WeightInfo: WeightInfo;53	}5455	#[pallet::pallet]56	#[pallet::generate_store(pub(super) trait Store)]57	pub struct Pallet<T>(_);5859	#[pallet::storage]60	pub type TokensMinted<T: Config> =61		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62	#[pallet::storage]63	pub type TokensBurnt<T: Config> =64		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566	#[pallet::storage]67	pub type TokenData<T: Config> = StorageNMap<68		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69		Value = ItemData,70		QueryKind = ValueQuery,71	>;7273	#[pallet::storage]74	pub type TotalSupply<T: Config> = StorageNMap<75		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76		Value = u128,77		QueryKind = ValueQuery,78	>;7980	/// Used to enumerate tokens owned by account81	#[pallet::storage]82	pub type Owned<T: Config> = StorageNMap<83		Key = (84			Key<Twox64Concat, CollectionId>,85			Key<Blake2_128Concat, T::CrossAccountId>,86			Key<Twox64Concat, TokenId>,87		),88		Value = bool,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub type AccountBalance<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			// Owner97			Key<Blake2_128Concat, T::CrossAccountId>,98		),99		Value = u32,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub type Balance<T: Config> = StorageNMap<105		Key = (106			Key<Twox64Concat, CollectionId>,107			Key<Twox64Concat, TokenId>,108			// Owner109			Key<Blake2_128Concat, T::CrossAccountId>,110		),111		Value = u128,112		QueryKind = ValueQuery,113	>;114115	#[pallet::storage]116	pub type Allowance<T: Config> = StorageNMap<117		Key = (118			Key<Twox64Concat, CollectionId>,119			Key<Twox64Concat, TokenId>,120			// Owner121			Key<Blake2_128, T::CrossAccountId>,122			// Spender123			Key<Blake2_128Concat, T::CrossAccountId>,124		),125		Value = u128,126		QueryKind = ValueQuery,127	>;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133		Self(inner)134	}135	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136		self.0137	}138}139impl<T: Config> Deref for RefungibleHandle<T> {140	type Target = pallet_common::CollectionHandle<T>;141142	fn deref(&self) -> &Self::Target {143		&self.0144	}145}146147impl<T: Config> Pallet<T> {148	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150	}151	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152		<TotalSupply<T>>::contains_key((collection.id, token))153	}154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {159		<PalletCommon<T>>::init_collection(data)160	}161	pub fn destroy_collection(162		collection: RefungibleHandle<T>,163		sender: &T::CrossAccountId,164	) -> DispatchResult {165		let id = collection.id;166167		// =========168169		PalletCommon::destroy_collection(collection.0, sender)?;170171		<TokensMinted<T>>::remove(id);172		<TokensBurnt<T>>::remove(id);173		<TokenData<T>>::remove_prefix((id,), None);174		<TotalSupply<T>>::remove_prefix((id,), None);175		<Balance<T>>::remove_prefix((id,), None);176		<Allowance<T>>::remove_prefix((id,), None);177		<Owned<T>>::remove_prefix((id,), None);178		<AccountBalance<T>>::remove_prefix((id,), None);179		Ok(())180	}181182	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {183		let burnt = <TokensBurnt<T>>::get(collection.id)184			.checked_add(1)185			.ok_or(ArithmeticError::Overflow)?;186187		<TokensBurnt<T>>::insert(collection.id, burnt);188		<TokenData<T>>::remove((collection.id, token_id));189		<TotalSupply<T>>::remove((collection.id, token_id));190		<Balance<T>>::remove_prefix((collection.id, token_id), None);191		<Allowance<T>>::remove_prefix((collection.id, token_id), None);192		// TODO: ERC721 transfer event193		Ok(())194	}195196	pub fn burn(197		collection: &RefungibleHandle<T>,198		owner: &T::CrossAccountId,199		token: TokenId,200		amount: u128,201	) -> DispatchResult {202		let total_supply = <TotalSupply<T>>::get((collection.id, token))203			.checked_sub(amount)204			.ok_or(<CommonError<T>>::TokenValueTooLow)?;205206		// This was probally last owner of this token?207		if total_supply == 0 {208			// Ensure user actually owns this amount209			ensure!(210				<Balance<T>>::get((collection.id, token, owner)) == amount,211				<CommonError<T>>::TokenValueTooLow212			);213			let account_balance = <AccountBalance<T>>::get((collection.id, owner))214				.checked_sub(1)215				// Should not occur216				.ok_or(ArithmeticError::Underflow)?;217218			// =========219220			<Owned<T>>::remove((collection.id, owner, token));221			<AccountBalance<T>>::insert((collection.id, owner), account_balance);222			Self::burn_token(collection, token)?;223			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(224				collection.id,225				token,226				owner.clone(),227				amount,228			));229			return Ok(());230		}231232		let balance = <Balance<T>>::get((collection.id, token, owner))233			.checked_sub(amount)234			.ok_or(<CommonError<T>>::TokenValueTooLow)?;235		let account_balance = if balance == 0 {236			<AccountBalance<T>>::get((collection.id, owner))237				.checked_sub(1)238				// Should not occur239				.ok_or(ArithmeticError::Underflow)?240		} else {241			0242		};243244		// =========245246		if balance == 0 {247			<Owned<T>>::remove((collection.id, owner, token));248			<Balance<T>>::remove((collection.id, token, owner));249			<AccountBalance<T>>::insert((collection.id, owner), account_balance);250		} else {251			<Balance<T>>::insert((collection.id, token, owner), balance);252		}253		<TotalSupply<T>>::insert((collection.id, token), total_supply);254		// TODO: ERC20 transfer event255		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(256			collection.id,257			token,258			owner.clone(),259			amount,260		));261		Ok(())262	}263264	pub fn transfer(265		collection: &RefungibleHandle<T>,266		from: &T::CrossAccountId,267		to: &T::CrossAccountId,268		token: TokenId,269		amount: u128,270	) -> DispatchResult {271		ensure!(272			collection.limits.transfers_enabled(),273			<CommonError<T>>::TransferNotAllowed274		);275276		if collection.access == AccessMode::AllowList {277			collection.check_allowlist(from)?;278			collection.check_allowlist(to)?;279		}280		<PalletCommon<T>>::ensure_correct_receiver(to)?;281282		let balance_from = <Balance<T>>::get((collection.id, token, from))283			.checked_sub(amount)284			.ok_or(<CommonError<T>>::TokenValueTooLow)?;285		let mut create_target = false;286		let from_to_differ = from != to;287		let balance_to = if from != to {288			let old_balance = <Balance<T>>::get((collection.id, token, to));289			if old_balance == 0 {290				create_target = true;291			}292			Some(293				old_balance294					.checked_add(amount)295					.ok_or(ArithmeticError::Overflow)?,296			)297		} else {298			None299		};300301		let account_balance_from = if balance_from == 0 {302			Some(303				<AccountBalance<T>>::get((collection.id, from))304					.checked_sub(1)305					// Should not occur306					.ok_or(ArithmeticError::Underflow)?,307			)308		} else {309			None310		};311		// Account data is created in token, AccountBalance should be increased312		// But only if from != to as we shouldn't check overflow in this case313		let account_balance_to = if create_target && from_to_differ {314			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))315				.checked_add(1)316				.ok_or(ArithmeticError::Overflow)?;317			ensure!(318				account_balance_to < collection.limits.account_token_ownership_limit(),319				<CommonError<T>>::AccountTokenLimitExceeded,320			);321322			Some(account_balance_to)323		} else {324			None325		};326327		// =========328329		if let Some(balance_to) = balance_to {330			// from != to331			if balance_from == 0 {332				<Balance<T>>::remove((collection.id, token, from));333			} else {334				<Balance<T>>::insert((collection.id, token, from), balance_from);335			}336			<Balance<T>>::insert((collection.id, token, to), balance_to);337			if let Some(account_balance_from) = account_balance_from {338				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);339				<Owned<T>>::remove((collection.id, from, token));340			}341			if let Some(account_balance_to) = account_balance_to {342				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);343				<Owned<T>>::insert((collection.id, to, token), true);344			}345		}346347		// TODO: ERC20 transfer event348		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(349			collection.id,350			token,351			from.clone(),352			to.clone(),353			amount,354		));355		Ok(())356	}357358	pub fn create_multiple_items(359		collection: &RefungibleHandle<T>,360		sender: &T::CrossAccountId,361		data: Vec<CreateItemData<T>>,362	) -> DispatchResult {363		if !collection.is_owner_or_admin(sender) {364			ensure!(365				collection.mint_mode,366				<CommonError<T>>::PublicMintingNotAllowed367			);368			collection.check_allowlist(sender)?;369370			for item in data.iter() {371				for user in item.users.keys() {372					collection.check_allowlist(user)?;373				}374			}375		}376377		for item in data.iter() {378			for (owner, _) in item.users.iter() {379				<PalletCommon<T>>::ensure_correct_receiver(owner)?;380			}381		}382383		// Total pieces per tokens384		let totals = data385			.iter()386			.map(|data| {387				Ok(data388					.users389					.iter()390					.map(|u| u.1)391					.try_fold(0u128, |acc, v| acc.checked_add(*v))392					.ok_or(ArithmeticError::Overflow)?)393			})394			.collect::<Result<Vec<_>, DispatchError>>()?;395		for total in &totals {396			ensure!(397				*total <= MAX_REFUNGIBLE_PIECES,398				<Error<T>>::WrongRefungiblePieces399			);400		}401402		let first_token_id = <TokensMinted<T>>::get(collection.id);403		let tokens_minted = first_token_id404			.checked_add(data.len() as u32)405			.ok_or(ArithmeticError::Overflow)?;406		ensure!(407			tokens_minted < collection.limits.token_limit(),408			<CommonError<T>>::CollectionTokenLimitExceeded409		);410411		let mut balances = BTreeMap::new();412		for data in &data {413			for owner in data.users.keys() {414				let balance = balances415					.entry(owner)416					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));417				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;418419				ensure!(420					*balance <= collection.limits.account_token_ownership_limit(),421					<CommonError<T>>::AccountTokenLimitExceeded,422				);423			}424		}425426		// =========427428		<TokensMinted<T>>::insert(collection.id, tokens_minted);429		for (account, balance) in balances {430			<AccountBalance<T>>::insert((collection.id, account), balance);431		}432		for (i, token) in data.into_iter().enumerate() {433			let token_id = first_token_id + i as u32 + 1;434			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);435436			<TokenData<T>>::insert(437				(collection.id, token_id),438				ItemData {439					const_data: token.const_data,440					variable_data: token.variable_data,441				},442			);443			for (user, amount) in token.users.into_iter() {444				if amount == 0 {445					continue;446				}447				<Balance<T>>::insert((collection.id, token_id, &user), amount);448				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);449				// TODO: ERC20 transfer event450				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(451					collection.id,452					TokenId(token_id),453					user,454					amount,455				));456			}457		}458		Ok(())459	}460461	pub fn set_allowance_unchecked(462		collection: &RefungibleHandle<T>,463		sender: &T::CrossAccountId,464		spender: &T::CrossAccountId,465		token: TokenId,466		amount: u128,467	) {468		if amount == 0 {469			<Allowance<T>>::remove((collection.id, token, sender, spender));470		} else {471			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);472		}473		// TODO: ERC20 approval event474		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(475			collection.id,476			token,477			sender.clone(),478			spender.clone(),479			amount,480		))481	}482483	pub fn set_allowance(484		collection: &RefungibleHandle<T>,485		sender: &T::CrossAccountId,486		spender: &T::CrossAccountId,487		token: TokenId,488		amount: u128,489	) -> DispatchResult {490		if collection.access == AccessMode::AllowList {491			collection.check_allowlist(sender)?;492			collection.check_allowlist(spender)?;493		}494495		<PalletCommon<T>>::ensure_correct_receiver(spender)?;496497		if <Balance<T>>::get((collection.id, token, sender)) < amount {498			ensure!(499				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),500				<CommonError<T>>::CantApproveMoreThanOwned501			);502		}503504		// =========505506		Self::set_allowance_unchecked(collection, sender, spender, token, amount);507		Ok(())508	}509510	pub fn transfer_from(511		collection: &RefungibleHandle<T>,512		spender: &T::CrossAccountId,513		from: &T::CrossAccountId,514		to: &T::CrossAccountId,515		token: TokenId,516		amount: u128,517	) -> DispatchResult {518		if spender.conv_eq(from) {519			return Self::transfer(collection, from, to, token, amount);520		}521		if collection.access == AccessMode::AllowList {522			// `from`, `to` checked in [`transfer`]523			collection.check_allowlist(spender)?;524		}525526		let allowance =527			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);528		if allowance.is_none() {529			ensure!(530				collection.ignores_allowance(spender),531				<CommonError<T>>::TokenValueNotEnough532			);533		}534535		// =========536537		Self::transfer(collection, from, to, token, amount)?;538		if let Some(allowance) = allowance {539			Self::set_allowance_unchecked(collection, from, spender, token, allowance);540		}541		Ok(())542	}543544	pub fn burn_from(545		collection: &RefungibleHandle<T>,546		spender: &T::CrossAccountId,547		from: &T::CrossAccountId,548		token: TokenId,549		amount: u128,550	) -> DispatchResult {551		if spender.conv_eq(from) {552			return Self::burn(collection, from, token, amount);553		}554		if collection.access == AccessMode::AllowList {555			// `from` checked in [`burn`]556			collection.check_allowlist(spender)?;557		}558559		let allowance =560			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);561		if allowance.is_none() {562			ensure!(563				collection.ignores_allowance(spender),564				<CommonError<T>>::TokenValueNotEnough565			);566		}567568		// =========569570		Self::burn(collection, from, token, amount)?;571		if let Some(allowance) = allowance {572			Self::set_allowance_unchecked(collection, from, spender, token, allowance);573		}574		Ok(())575	}576577	pub fn set_variable_metadata(578		collection: &RefungibleHandle<T>,579		sender: &T::CrossAccountId,580		token: TokenId,581		data: BoundedVec<u8, CustomDataLimit>,582	) -> DispatchResult {583		collection.check_can_update_meta(584			sender,585			&T::CrossAccountId::from_sub(collection.owner.clone()),586		)?;587588		let token_data = <TokenData<T>>::get((collection.id, token));589590		// =========591592		<TokenData<T>>::insert(593			(collection.id, token),594			ItemData {595				variable_data: data,596				..token_data597			},598		);599		Ok(())600	}601602	/// Delegated to `create_multiple_items`603	pub fn create_item(604		collection: &RefungibleHandle<T>,605		sender: &T::CrossAccountId,606		data: CreateItemData<T>,607	) -> DispatchResult {608		Self::create_multiple_items(collection, sender, vec![data])609	}610}
after · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,6};7use pallet_common::{8	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,9};10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};12use core::ops::Deref;13use codec::{Encode, Decode, MaxEncodedLen};14use scale_info::TypeInfo;1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23	pub const_data: BoundedVec<u8, CustomDataLimit>,24	pub variable_data: BoundedVec<u8, CustomDataLimit>,25	pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]30pub struct ItemData {31	pub const_data: BoundedVec<u8, CustomDataLimit>,32	pub variable_data: BoundedVec<u8, CustomDataLimit>,33}3435#[frame_support::pallet]36pub mod pallet {37	use super::*;38	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39	use up_data_structs::{CollectionId, TokenId};40	use super::weights::WeightInfo;4142	#[pallet::error]43	pub enum Error<T> {44		/// Not Refungible item data used to mint in Refungible collection.45		NotRefungibleDataUsedToMintFungibleCollectionToken,46		/// Maximum refungibility exceeded47		WrongRefungiblePieces,48	}4950	#[pallet::config]51	pub trait Config: frame_system::Config + pallet_common::Config {52		type WeightInfo: WeightInfo;53	}5455	#[pallet::pallet]56	#[pallet::generate_store(pub(super) trait Store)]57	pub struct Pallet<T>(_);5859	#[pallet::storage]60	pub type TokensMinted<T: Config> =61		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62	#[pallet::storage]63	pub type TokensBurnt<T: Config> =64		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566	#[pallet::storage]67	pub type TokenData<T: Config> = StorageNMap<68		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69		Value = ItemData,70		QueryKind = ValueQuery,71	>;7273	#[pallet::storage]74	pub type TotalSupply<T: Config> = StorageNMap<75		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76		Value = u128,77		QueryKind = ValueQuery,78	>;7980	/// Used to enumerate tokens owned by account81	#[pallet::storage]82	pub type Owned<T: Config> = StorageNMap<83		Key = (84			Key<Twox64Concat, CollectionId>,85			Key<Blake2_128Concat, T::CrossAccountId>,86			Key<Twox64Concat, TokenId>,87		),88		Value = bool,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub type AccountBalance<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			// Owner97			Key<Blake2_128Concat, T::CrossAccountId>,98		),99		Value = u32,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub type Balance<T: Config> = StorageNMap<105		Key = (106			Key<Twox64Concat, CollectionId>,107			Key<Twox64Concat, TokenId>,108			// Owner109			Key<Blake2_128Concat, T::CrossAccountId>,110		),111		Value = u128,112		QueryKind = ValueQuery,113	>;114115	#[pallet::storage]116	pub type Allowance<T: Config> = StorageNMap<117		Key = (118			Key<Twox64Concat, CollectionId>,119			Key<Twox64Concat, TokenId>,120			// Owner121			Key<Blake2_128, T::CrossAccountId>,122			// Spender123			Key<Blake2_128Concat, T::CrossAccountId>,124		),125		Value = u128,126		QueryKind = ValueQuery,127	>;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133		Self(inner)134	}135	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136		self.0137	}138}139impl<T: Config> Deref for RefungibleHandle<T> {140	type Target = pallet_common::CollectionHandle<T>;141142	fn deref(&self) -> &Self::Target {143		&self.0144	}145}146147impl<T: Config> Pallet<T> {148	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150	}151	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152		<TotalSupply<T>>::contains_key((collection.id, token))153	}154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158	pub fn init_collection(159		owner: T::AccountId,160		data: CreateCollectionData<T::AccountId>,161	) -> Result<CollectionId, DispatchError> {162		<PalletCommon<T>>::init_collection(owner, data)163	}164	pub fn destroy_collection(165		collection: RefungibleHandle<T>,166		sender: &T::CrossAccountId,167	) -> DispatchResult {168		let id = collection.id;169170		// =========171172		PalletCommon::destroy_collection(collection.0, sender)?;173174		<TokensMinted<T>>::remove(id);175		<TokensBurnt<T>>::remove(id);176		<TokenData<T>>::remove_prefix((id,), None);177		<TotalSupply<T>>::remove_prefix((id,), None);178		<Balance<T>>::remove_prefix((id,), None);179		<Allowance<T>>::remove_prefix((id,), None);180		<Owned<T>>::remove_prefix((id,), None);181		<AccountBalance<T>>::remove_prefix((id,), None);182		Ok(())183	}184185	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {186		let burnt = <TokensBurnt<T>>::get(collection.id)187			.checked_add(1)188			.ok_or(ArithmeticError::Overflow)?;189190		<TokensBurnt<T>>::insert(collection.id, burnt);191		<TokenData<T>>::remove((collection.id, token_id));192		<TotalSupply<T>>::remove((collection.id, token_id));193		<Balance<T>>::remove_prefix((collection.id, token_id), None);194		<Allowance<T>>::remove_prefix((collection.id, token_id), None);195		// TODO: ERC721 transfer event196		Ok(())197	}198199	pub fn burn(200		collection: &RefungibleHandle<T>,201		owner: &T::CrossAccountId,202		token: TokenId,203		amount: u128,204	) -> DispatchResult {205		let total_supply = <TotalSupply<T>>::get((collection.id, token))206			.checked_sub(amount)207			.ok_or(<CommonError<T>>::TokenValueTooLow)?;208209		// This was probally last owner of this token?210		if total_supply == 0 {211			// Ensure user actually owns this amount212			ensure!(213				<Balance<T>>::get((collection.id, token, owner)) == amount,214				<CommonError<T>>::TokenValueTooLow215			);216			let account_balance = <AccountBalance<T>>::get((collection.id, owner))217				.checked_sub(1)218				// Should not occur219				.ok_or(ArithmeticError::Underflow)?;220221			// =========222223			<Owned<T>>::remove((collection.id, owner, token));224			<AccountBalance<T>>::insert((collection.id, owner), account_balance);225			Self::burn_token(collection, token)?;226			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(227				collection.id,228				token,229				owner.clone(),230				amount,231			));232			return Ok(());233		}234235		let balance = <Balance<T>>::get((collection.id, token, owner))236			.checked_sub(amount)237			.ok_or(<CommonError<T>>::TokenValueTooLow)?;238		let account_balance = if balance == 0 {239			<AccountBalance<T>>::get((collection.id, owner))240				.checked_sub(1)241				// Should not occur242				.ok_or(ArithmeticError::Underflow)?243		} else {244			0245		};246247		// =========248249		if balance == 0 {250			<Owned<T>>::remove((collection.id, owner, token));251			<Balance<T>>::remove((collection.id, token, owner));252			<AccountBalance<T>>::insert((collection.id, owner), account_balance);253		} else {254			<Balance<T>>::insert((collection.id, token, owner), balance);255		}256		<TotalSupply<T>>::insert((collection.id, token), total_supply);257		// TODO: ERC20 transfer event258		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(259			collection.id,260			token,261			owner.clone(),262			amount,263		));264		Ok(())265	}266267	pub fn transfer(268		collection: &RefungibleHandle<T>,269		from: &T::CrossAccountId,270		to: &T::CrossAccountId,271		token: TokenId,272		amount: u128,273	) -> DispatchResult {274		ensure!(275			collection.limits.transfers_enabled(),276			<CommonError<T>>::TransferNotAllowed277		);278279		if collection.access == AccessMode::AllowList {280			collection.check_allowlist(from)?;281			collection.check_allowlist(to)?;282		}283		<PalletCommon<T>>::ensure_correct_receiver(to)?;284285		let balance_from = <Balance<T>>::get((collection.id, token, from))286			.checked_sub(amount)287			.ok_or(<CommonError<T>>::TokenValueTooLow)?;288		let mut create_target = false;289		let from_to_differ = from != to;290		let balance_to = if from != to {291			let old_balance = <Balance<T>>::get((collection.id, token, to));292			if old_balance == 0 {293				create_target = true;294			}295			Some(296				old_balance297					.checked_add(amount)298					.ok_or(ArithmeticError::Overflow)?,299			)300		} else {301			None302		};303304		let account_balance_from = if balance_from == 0 {305			Some(306				<AccountBalance<T>>::get((collection.id, from))307					.checked_sub(1)308					// Should not occur309					.ok_or(ArithmeticError::Underflow)?,310			)311		} else {312			None313		};314		// Account data is created in token, AccountBalance should be increased315		// But only if from != to as we shouldn't check overflow in this case316		let account_balance_to = if create_target && from_to_differ {317			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))318				.checked_add(1)319				.ok_or(ArithmeticError::Overflow)?;320			ensure!(321				account_balance_to < collection.limits.account_token_ownership_limit(),322				<CommonError<T>>::AccountTokenLimitExceeded,323			);324325			Some(account_balance_to)326		} else {327			None328		};329330		// =========331332		if let Some(balance_to) = balance_to {333			// from != to334			if balance_from == 0 {335				<Balance<T>>::remove((collection.id, token, from));336			} else {337				<Balance<T>>::insert((collection.id, token, from), balance_from);338			}339			<Balance<T>>::insert((collection.id, token, to), balance_to);340			if let Some(account_balance_from) = account_balance_from {341				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);342				<Owned<T>>::remove((collection.id, from, token));343			}344			if let Some(account_balance_to) = account_balance_to {345				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);346				<Owned<T>>::insert((collection.id, to, token), true);347			}348		}349350		// TODO: ERC20 transfer event351		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(352			collection.id,353			token,354			from.clone(),355			to.clone(),356			amount,357		));358		Ok(())359	}360361	pub fn create_multiple_items(362		collection: &RefungibleHandle<T>,363		sender: &T::CrossAccountId,364		data: Vec<CreateItemData<T>>,365	) -> DispatchResult {366		if !collection.is_owner_or_admin(sender) {367			ensure!(368				collection.mint_mode,369				<CommonError<T>>::PublicMintingNotAllowed370			);371			collection.check_allowlist(sender)?;372373			for item in data.iter() {374				for user in item.users.keys() {375					collection.check_allowlist(user)?;376				}377			}378		}379380		for item in data.iter() {381			for (owner, _) in item.users.iter() {382				<PalletCommon<T>>::ensure_correct_receiver(owner)?;383			}384		}385386		// Total pieces per tokens387		let totals = data388			.iter()389			.map(|data| {390				Ok(data391					.users392					.iter()393					.map(|u| u.1)394					.try_fold(0u128, |acc, v| acc.checked_add(*v))395					.ok_or(ArithmeticError::Overflow)?)396			})397			.collect::<Result<Vec<_>, DispatchError>>()?;398		for total in &totals {399			ensure!(400				*total <= MAX_REFUNGIBLE_PIECES,401				<Error<T>>::WrongRefungiblePieces402			);403		}404405		let first_token_id = <TokensMinted<T>>::get(collection.id);406		let tokens_minted = first_token_id407			.checked_add(data.len() as u32)408			.ok_or(ArithmeticError::Overflow)?;409		ensure!(410			tokens_minted < collection.limits.token_limit(),411			<CommonError<T>>::CollectionTokenLimitExceeded412		);413414		let mut balances = BTreeMap::new();415		for data in &data {416			for owner in data.users.keys() {417				let balance = balances418					.entry(owner)419					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));420				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;421422				ensure!(423					*balance <= collection.limits.account_token_ownership_limit(),424					<CommonError<T>>::AccountTokenLimitExceeded,425				);426			}427		}428429		// =========430431		<TokensMinted<T>>::insert(collection.id, tokens_minted);432		for (account, balance) in balances {433			<AccountBalance<T>>::insert((collection.id, account), balance);434		}435		for (i, token) in data.into_iter().enumerate() {436			let token_id = first_token_id + i as u32 + 1;437			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);438439			<TokenData<T>>::insert(440				(collection.id, token_id),441				ItemData {442					const_data: token.const_data,443					variable_data: token.variable_data,444				},445			);446			for (user, amount) in token.users.into_iter() {447				if amount == 0 {448					continue;449				}450				<Balance<T>>::insert((collection.id, token_id, &user), amount);451				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);452				// TODO: ERC20 transfer event453				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(454					collection.id,455					TokenId(token_id),456					user,457					amount,458				));459			}460		}461		Ok(())462	}463464	pub fn set_allowance_unchecked(465		collection: &RefungibleHandle<T>,466		sender: &T::CrossAccountId,467		spender: &T::CrossAccountId,468		token: TokenId,469		amount: u128,470	) {471		if amount == 0 {472			<Allowance<T>>::remove((collection.id, token, sender, spender));473		} else {474			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);475		}476		// TODO: ERC20 approval event477		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(478			collection.id,479			token,480			sender.clone(),481			spender.clone(),482			amount,483		))484	}485486	pub fn set_allowance(487		collection: &RefungibleHandle<T>,488		sender: &T::CrossAccountId,489		spender: &T::CrossAccountId,490		token: TokenId,491		amount: u128,492	) -> DispatchResult {493		if collection.access == AccessMode::AllowList {494			collection.check_allowlist(sender)?;495			collection.check_allowlist(spender)?;496		}497498		<PalletCommon<T>>::ensure_correct_receiver(spender)?;499500		if <Balance<T>>::get((collection.id, token, sender)) < amount {501			ensure!(502				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),503				<CommonError<T>>::CantApproveMoreThanOwned504			);505		}506507		// =========508509		Self::set_allowance_unchecked(collection, sender, spender, token, amount);510		Ok(())511	}512513	pub fn transfer_from(514		collection: &RefungibleHandle<T>,515		spender: &T::CrossAccountId,516		from: &T::CrossAccountId,517		to: &T::CrossAccountId,518		token: TokenId,519		amount: u128,520	) -> DispatchResult {521		if spender.conv_eq(from) {522			return Self::transfer(collection, from, to, token, amount);523		}524		if collection.access == AccessMode::AllowList {525			// `from`, `to` checked in [`transfer`]526			collection.check_allowlist(spender)?;527		}528529		let allowance =530			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);531		if allowance.is_none() {532			ensure!(533				collection.ignores_allowance(spender),534				<CommonError<T>>::ApprovedValueTooLow535			);536		}537538		// =========539540		Self::transfer(collection, from, to, token, amount)?;541		if let Some(allowance) = allowance {542			Self::set_allowance_unchecked(collection, from, spender, token, allowance);543		}544		Ok(())545	}546547	pub fn burn_from(548		collection: &RefungibleHandle<T>,549		spender: &T::CrossAccountId,550		from: &T::CrossAccountId,551		token: TokenId,552		amount: u128,553	) -> DispatchResult {554		if spender.conv_eq(from) {555			return Self::burn(collection, from, token, amount);556		}557		if collection.access == AccessMode::AllowList {558			// `from` checked in [`burn`]559			collection.check_allowlist(spender)?;560		}561562		let allowance =563			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);564		if allowance.is_none() {565			ensure!(566				collection.ignores_allowance(spender),567				<CommonError<T>>::ApprovedValueTooLow568			);569		}570571		// =========572573		Self::burn(collection, from, token, amount)?;574		if let Some(allowance) = allowance {575			Self::set_allowance_unchecked(collection, from, spender, token, allowance);576		}577		Ok(())578	}579580	pub fn set_variable_metadata(581		collection: &RefungibleHandle<T>,582		sender: &T::CrossAccountId,583		token: TokenId,584		data: BoundedVec<u8, CustomDataLimit>,585	) -> DispatchResult {586		collection.check_can_update_meta(587			sender,588			&T::CrossAccountId::from_sub(collection.owner.clone()),589		)?;590591		let token_data = <TokenData<T>>::get((collection.id, token));592593		// =========594595		<TokenData<T>>::insert(596			(collection.id, token),597			ItemData {598				variable_data: data,599				..token_data600			},601		);602		Ok(())603	}604605	/// Delegated to `create_multiple_items`606	pub fn create_item(607		collection: &RefungibleHandle<T>,608		sender: &T::CrossAccountId,609		data: CreateItemData<T>,610	) -> DispatchResult {611		Self::create_multiple_items(collection, sender, vec![data])612	}613}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -36,13 +36,11 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
-	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-	NFT_SPONSOR_TRANSFER_TIMEOUT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
-	MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
-	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
-	CustomDataLimit,
+	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+	OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
+	MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData, CollectionLimits, CollectionId,
+	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	CreateCollectionData, CustomDataLimit,
 };
 use pallet_common::{
 	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -84,10 +82,6 @@
 		ConfirmUnsetSponsorFail,
 		/// Length of items properties must be greater than 0.
 		EmptyArgument,
-		/// Collection limit bounds per collection exceeded
-		CollectionLimitBoundsExceeded,
-		/// Tried to enable permissions which are only permitted to be disabled
-		OwnerPermissionsCantBeReverted,
 	}
 }
 
@@ -321,42 +315,39 @@
 		// returns collection ID
 		#[weight = <SelfWeightOf<T>>::create_collection()]
 		#[transactional]
+		#[deprecated]
 		pub fn create_collection(origin,
 								 collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
 								 collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
 								 token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
-								 mode: CollectionMode) -> DispatchResult {
-
-			// Anyone can create a collection
-			let who = ensure_signed(origin)?;
-
-			// Create new collection
-			let new_collection = Collection {
-				owner: who,
+								 mode: CollectionMode) -> DispatchResult  {
+			let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
 				name: collection_name,
-				mode: mode.clone(),
-				mint_mode: false,
-				access: AccessMode::Normal,
 				description: collection_description,
 				token_prefix,
-				offchain_schema: BoundedVec::default(),
-				schema_version: SchemaVersion::ImageURL,
-				sponsorship: SponsorshipState::Disabled,
-				variable_on_chain_schema: BoundedVec::default(),
-				const_on_chain_schema: BoundedVec::default(),
-				limits: Default::default(),
-				meta_update_permission: Default::default(),
+				mode,
+				..Default::default()
 			};
+			Self::create_collection_ex(origin, data)
+		}
 
-			let _id = match mode {
-				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
+		/// This method creates a collection
+		///
+		/// Prefer it to deprecated [`created_collection`] method
+		#[weight = <SelfWeightOf<T>>::create_collection()]
+		#[transactional]
+		pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+			let owner = ensure_signed(origin)?;
+
+			let _id = match data.mode {
+				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
 				CollectionMode::Fungible(decimal_points) => {
 					// check params
 					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					<PalletFungible<T>>::init_collection(new_collection)?
+					<PalletFungible<T>>::init_collection(owner, data)?
 				}
 				CollectionMode::ReFungible => {
-					<PalletRefungible<T>>::init_collection(new_collection)?
+					<PalletRefungible<T>>::init_collection(owner, data)?
 				}
 			};
 
@@ -1093,61 +1084,12 @@
 			collection_id: CollectionId,
 			new_limit: CollectionLimits,
 		) -> DispatchResult {
-			let mut new_limit = new_limit;
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
 			let old_limit = &target_collection.limits;
 
-			macro_rules! limit_default {
-				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
-					$(
-						if let Some($new) = $new.$field {
-							let $old = $old.$field($($arg)?);
-							let _ = $new;
-							let _ = $old;
-							$check
-						} else {
-							$new.$field = $old.$field
-						}
-					)*
-				}};
-			}
-
-			limit_default!(old_limit, new_limit,
-				account_token_ownership_limit => ensure!(
-					new_limit <= MAX_TOKEN_OWNERSHIP,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsor_transfer_timeout(match target_collection.mode {
-					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-				}) => ensure!(
-					new_limit <= MAX_SPONSOR_TIMEOUT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsored_data_size => ensure!(
-					new_limit <= CUSTOM_DATA_LIMIT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				token_limit => ensure!(
-					old_limit >= new_limit && new_limit > 0,
-					<CommonError<T>>::CollectionTokenLimitExceeded
-				),
-				owner_can_transfer => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				owner_can_destroy => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				sponsored_data_rate_limit => {},
-				transfers_enabled => {},
-			);
-
-			target_collection.limits = new_limit;
+			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
 				collection_id
modifiedpallets/unique/src/tests.rsdiffbeforeafterboth
--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -5,7 +5,7 @@
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
 	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
-	TokenId,
+	TokenId, MAX_TOKEN_OWNERSHIP,
 };
 use frame_support::{assert_noop, assert_ok};
 use sp_std::convert::TryInto;
@@ -601,7 +601,7 @@
 				1
 			)
 			.map_err(|e| e.error),
-			CommonError::<Test>::TokenValueNotEnough
+			CommonError::<Test>::ApprovedValueTooLow
 		);
 
 		// do approve
@@ -916,7 +916,7 @@
 				4
 			)
 			.map_err(|e| e.error),
-			CommonError::<Test>::TokenValueNotEnough
+			CommonError::<Test>::ApprovedValueTooLow
 		);
 	});
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -263,6 +263,31 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derivative(Default(bound = ""))]
+pub struct CreateCollectionData<AccountId> {
+	#[derivative(Default(value = "CollectionMode::NFT"))]
+	pub mode: CollectionMode,
+	pub access: Option<AccessMode>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
+	pub schema_version: Option<SchemaVersion>,
+	pub pending_sponsor: Option<AccountId>,
+	pub limits: Option<CollectionLimits>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
+	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
+	pub meta_update_permission: Option<MetaUpdatePermission>,
+}
+
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct NftItemType<AccountId> {
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -9,10 +9,14 @@
 type Result<T> = core::result::Result<T, DispatchError>;
 
 sp_api::decl_runtime_apis! {
+	#[api_version(2)]
 	pub trait UniqueApi<CrossAccountId, AccountId> where
 		AccountId: Decode,
 		CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
 	{
+		#[changed_in(2)]
+		fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;
+
 		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;
 		fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;
 
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -23,7 +23,8 @@
 use sp_runtime::{
 	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
 	traits::{
-		AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,
+		AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,
+		AccountIdConversion, Zero,
 	},
 	transaction_validity::{TransactionSource, TransactionValidity},
 	ApplyExtrinsicResult, MultiSignature, RuntimeAppPublic,
@@ -45,8 +46,9 @@
 	dispatch::DispatchResult,
 	PalletId, parameter_types, StorageValue, ConsensusEngineId,
 	traits::{
-		Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,
-		LockIdentifier, OnUnbalanced, Randomness, FindAuthor,
+		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
+		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
+		OnUnbalanced, Randomness, FindAuthor,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -69,8 +71,9 @@
 use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
 use fp_rpc::TransactionStatus;
 use sp_runtime::{
-	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
+	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
 	transaction_validity::TransactionValidityError,
+	SaturatedConversion,
 };
 
 // pub use pallet_timestamp::Call as TimestampCall;
@@ -82,13 +85,24 @@
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
-	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,
-	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,
-	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
-	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
+	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,
+	ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
+	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
 };
-use xcm_executor::{Config, XcmExecutor};
+use xcm_executor::{Config, XcmExecutor, Assets};
+use sp_std::{marker::PhantomData};
 
+use xcm::latest::{
+	//	Xcm,
+	AssetId::{Concrete},
+	Fungibility::Fungible as XcmFungible,
+	MultiAsset,
+	Error as XcmError,
+};
+use xcm_executor::traits::{MatchesFungible, WeightTrader};
+//use xcm_executor::traits::MatchesFungible;
+use sp_runtime::traits::CheckedConversion;
+
 // mod chain_extension;
 // use crate::chain_extension::{NFTExtension, Imbalance};
 
@@ -146,10 +160,10 @@
 	spec_name: create_runtime_str!("opal"),
 	impl_name: create_runtime_str!("opal"),
 	authoring_version: 1,
-	spec_version: 914000,
-	impl_version: 1,
+	spec_version: 916001,
+	impl_version: 0,
 	apis: RUNTIME_API_VERSIONS,
-	transaction_version: 0,
+	transaction_version: 1,
 	state_version: 0,
 };
 
@@ -616,12 +630,22 @@
 	AccountId32Aliases<RelayNetwork, AccountId>,
 );
 
+pub struct OnlySelfCurrency;
+impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
+	fn matches_fungible(a: &MultiAsset) -> Option<B> {
+		match (&a.id, &a.fun) {
+			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),
+			_ => None,
+		}
+	}
+}
+
 /// Means for transacting assets on this chain.
 pub type LocalAssetTransactor = CurrencyAdapter<
 	// Use this currency:
 	Balances,
 	// Use this currency when it is a fungible asset matching the given location or name:
-	IsConcrete<RelayLocation>,
+	OnlySelfCurrency,
 	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
 	LocationToAccountId,
 	// Our chain's account ID type (we can't get away without mentioning it explicitly):
@@ -677,6 +701,88 @@
 	// ^^^ Parent & its unit plurality gets free execution
 );
 
+pub struct UsingOnlySelfCurrencyComponents<
+	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+	AssetId: Get<MultiLocation>,
+	AccountId,
+	Currency: CurrencyT<AccountId>,
+	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+>(
+	Weight,
+	Currency::Balance,
+	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
+);
+impl<
+		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+		AssetId: Get<MultiLocation>,
+		AccountId,
+		Currency: CurrencyT<AccountId>,
+		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+	> WeightTrader
+	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+{
+	fn new() -> Self {
+		Self(0, Zero::zero(), PhantomData)
+	}
+
+	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+		let amount = WeightToFee::calc(&weight);
+		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;
+
+		// location to this parachain through relay chain
+		let option1: xcm::v1::AssetId = Concrete(MultiLocation {
+			parents: 1,
+			interior: X1(Parachain(ParachainInfo::parachain_id().into())),
+		});
+		// direct location
+		let option2: xcm::v1::AssetId = Concrete(MultiLocation {
+			parents: 0,
+			interior: Here,
+		});
+
+		let required = if payment.fungible.contains_key(&option1) {
+			(option1, u128_amount).into()
+		} else if payment.fungible.contains_key(&option2) {
+			(option2, u128_amount).into()
+		} else {
+			(Concrete(MultiLocation::default()), u128_amount).into()
+		};
+
+		let unused = payment
+			.checked_sub(required)
+			.map_err(|_| XcmError::TooExpensive)?;
+		self.0 = self.0.saturating_add(weight);
+		self.1 = self.1.saturating_add(amount);
+		Ok(unused)
+	}
+
+	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {
+		let weight = weight.min(self.0);
+		let amount = WeightToFee::calc(&weight);
+		self.0 -= weight;
+		self.1 = self.1.saturating_sub(amount);
+		let amount: u128 = amount.saturated_into();
+		if amount > 0 {
+			Some((AssetId::get(), amount).into())
+		} else {
+			None
+		}
+	}
+}
+impl<
+		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+		AssetId: Get<MultiLocation>,
+		AccountId,
+		Currency: CurrencyT<AccountId>,
+		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+	> Drop
+	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+{
+	fn drop(&mut self) {
+		OnUnbalanced::on_unbalanced(Currency::issue(self.1));
+	}
+}
+
 pub struct XcmConfig;
 impl Config for XcmConfig {
 	type Call = Call;
@@ -689,7 +795,13 @@
 	type LocationInverter = LocationInverter<Ancestry>;
 	type Barrier = Barrier;
 	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
-	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;
+	type Trader = UsingOnlySelfCurrencyComponents<
+		IdentityFee<Balance>,
+		RelayLocation,
+		AccountId,
+		Balances,
+		(),
+	>;
 	type ResponseHandler = (); // Don't handle responses for now.
 	type SubscriptionService = PolkadotXcm;
 
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -64,12 +64,14 @@
     "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
     "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
     "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
+    "testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
     "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
     "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
     "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
+    "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
     "polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --input src/interfaces/ --package .",
-    "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint ws://localhost:9944 --output src/interfaces/ --package .",
-    "polkadot-types": "yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
+    "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
+    "polkadot-types": "yarn polkadot-types-fetch-metadata && yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
   },
   "author": "",
   "license": "SEE LICENSE IN ../LICENSE",
modifiedtests/src/check-event/createCollectionEvent.test.tsdiffbeforeafterboth
--- a/tests/src/check-event/createCollectionEvent.test.ts
+++ b/tests/src/check-event/createCollectionEvent.test.ts
@@ -27,7 +27,7 @@
   });
   it('Check event from createCollection(): ', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const tx = api.tx.unique.createCollection([0x31], [0x32], '0x33', 'NFT');
+      const tx = api.tx.unique.createCollectionEx({name: [0x31], description: [0x32], tokenPrefix: '0x33', mode: 'NFT'});
       const events = await submitTransactionAsync(alice, tx);
       const msg = JSON.stringify(uniqueEventMessage(events));
       expect(msg).to.be.contain(checkSection);
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -3,12 +3,11 @@
 // file 'LICENSE', which is part of this source code package.
 //
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {createCollectionExpectFailure, createCollectionExpectSuccess} from './util/helpers';
+import {expect} from 'chai';
+import privateKey from './substrate/privateKey';
+import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
+import {createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo} from './util/helpers';
 
-chai.use(chaiAsPromised);
-
 describe('integration test: ext. createCollection():', () => {
   it('Create new NFT collection', async () => {
     await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
@@ -28,6 +27,45 @@
   it('Create new ReFungible collection', async () => {
     await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
   });
+  it('Create new collection with extra fields', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+      const tx = api.tx.unique.createCollectionEx({
+        mode: {Fungible: 8},
+        access: 'AllowList',
+        name: [1],
+        description: [2],
+        tokenPrefix: '0x000000',
+        offchainSchema: '0x111111',
+        schemaVersion: 'Unique',
+        pendingSponsor: bob.address,
+        limits: {
+          accountTokenOwnershipLimit: 3,
+        },
+        variableOnChainSchema: '0x222222',
+        constOnChainSchema: '0x333333',
+        metaUpdatePermission: 'Admin',
+      });
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateCollectionResult(events);
+
+      const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+      expect(collection.owner.toString()).to.equal(alice.address);
+      expect(collection.mode.asFungible.toNumber()).to.equal(8);
+      expect(collection.access.isAllowList).to.be.true;
+      expect(collection.name.map(v => v.toNumber())).to.deep.equal([1]);
+      expect(collection.description.map(v => v.toNumber())).to.deep.equal([2]);
+      expect(collection.tokenPrefix.toString()).to.equal('0x000000');
+      expect(collection.offchainSchema.toString()).to.equal('0x111111');
+      expect(collection.schemaVersion.isUnique).to.be.true;
+      expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
+      expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
+      expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
+      expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
+      expect(collection.metaUpdatePermission.isAdmin).to.be.true;
+    });
+  });
 });
 
 describe('(!negative test!) integration test: ext. createCollection():', () => {
@@ -40,4 +78,11 @@
   it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
     await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
   });
+  it('fails when bad limits are set', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const tx = api.tx.unique.createCollectionEx({mode: 'NFT', limits: {tokenLimit: 0}});
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/^common.CollectionTokenLimitExceeded$/);
+    });
+  });
 });
addedtests/src/interfaces/.gitignorediffbeforeafterboth
--- /dev/null
+++ b/tests/src/interfaces/.gitignore
@@ -0,0 +1 @@
+metadata.json
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -69,6 +69,10 @@
        **/
       CollectionDescriptionLimitExceeded: AugmentedError<ApiType>;
       /**
+       * Collection limit bounds per collection exceeded
+       **/
+      CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
+      /**
        * Collection name can not be longer than 63 char.
        **/
       CollectionNameLimitExceeded: AugmentedError<ApiType>;
@@ -97,6 +101,10 @@
        **/
       NoPermission: AugmentedError<ApiType>;
       /**
+       * Tried to enable permissions which are only permitted to be disabled
+       **/
+      OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
+      /**
        * Collection is not in mint mode.
        **/
       PublicMintingNotAllowed: AugmentedError<ApiType>;
@@ -107,7 +115,7 @@
       /**
        * Requested value more than approved.
        **/
-      TokenValueNotEnough: AugmentedError<ApiType>;
+      ApprovedValueTooLow: AugmentedError<ApiType>;
       /**
        * Item balance not enough.
        **/
@@ -436,10 +444,6 @@
        * Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.
        **/
       CollectionDecimalPointLimitExceeded: AugmentedError<ApiType>;
-      /**
-       * Collection limit bounds per collection exceeded
-       **/
-      CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
       /**
        * This address is not set as sponsor, use setCollectionSponsor first.
        **/
@@ -448,10 +452,6 @@
        * Length of items properties must be greater than 0.
        **/
       EmptyArgument: AugmentedError<ApiType>;
-      /**
-       * Tried to enable permissions which are only permitted to be disabled
-       **/
-      OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
       /**
        * Generic error
        **/
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -2,7 +2,7 @@
 /* eslint-disable */
 
 import type { CumulusPrimitivesParachainInherentParachainInherentData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
 import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
 import type { Bytes, Compact, Option, U256, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
 import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
@@ -671,6 +671,12 @@
        **/
       createCollection: AugmentedSubmittable<(collectionName: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], collectionDescription: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], tokenPrefix: Bytes | string | Uint8Array, mode: UpDataStructsCollectionMode | { NFT: any } | { Fungible: any } | { ReFungible: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Vec<u16>, Vec<u16>, Bytes, UpDataStructsCollectionMode]>;
       /**
+       * This method creates a collection
+       * 
+       * Prefer it to deprecated [`created_collection`] method
+       **/
+      createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; offchainSchema?: any; schemaVersion?: any; pendingSponsor?: any; limits?: any; variableOnChainSchema?: any; constOnChainSchema?: any; metaUpdatePermission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+      /**
        * This method creates a concrete instance of NFT Collection created with CreateCollection method.
        * 
        * # Permissions
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -3,7 +3,7 @@
 
 import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
 import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
 import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';
 import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
 import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations';
@@ -1021,6 +1021,7 @@
     UpDataStructsCollectionLimits: UpDataStructsCollectionLimits;
     UpDataStructsCollectionMode: UpDataStructsCollectionMode;
     UpDataStructsCollectionStats: UpDataStructsCollectionStats;
+    UpDataStructsCreateCollectionData: UpDataStructsCreateCollectionData;
     UpDataStructsCreateItemData: UpDataStructsCreateItemData;
     UpDataStructsMetaUpdatePermission: UpDataStructsMetaUpdatePermission;
     UpDataStructsSchemaVersion: UpDataStructsSchemaVersion;
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -67,6 +67,20 @@
       constOnChainSchema: 'Vec<u8>',
       metaUpdatePermission: 'UpDataStructsMetaUpdatePermission',
     },
+    UpDataStructsCreateCollectionData: {
+      mode: 'UpDataStructsCollectionMode',
+      access: 'Option<UpDataStructsAccessMode>',
+      name: 'Vec<u16>',
+      description: 'Vec<u16>',
+      tokenPrefix: 'Vec<u8>',
+      offchainSchema: 'Vec<u8>',
+      schemaVersion: 'Option<UpDataStructsSchemaVersion>',
+      pendingSponsor: 'Option<AccountId>',
+      limits: 'Option<UpDataStructsCollectionLimits>',
+      variableOnChainSchema: 'Vec<u8>',
+      constOnChainSchema: 'Vec<u8>',
+      metaUpdatePermission: 'Option<UpDataStructsMetaUpdatePermission>',
+    },
     UpDataStructsCollectionStats: {
       created: 'u32',
       destroyed: 'u32',
@@ -76,7 +90,13 @@
     UpDataStructsTokenId: 'u32',
     PalletNonfungibleItemData: mkDummy('NftItemData'),
     PalletRefungibleItemData: mkDummy('RftItemData'),
-    UpDataStructsCollectionMode: mkDummy('CollectionMode'),
+    UpDataStructsCollectionMode: {
+      _enum: {
+        NFT: null,
+        Fungible: 'u32',
+        ReFungible: null,
+      },
+    },
     UpDataStructsCreateItemData: mkDummy('CreateItemData'),
     UpDataStructsCollectionLimits: {
       accountTokenOwnershipLimit: 'Option<u32>',
@@ -101,7 +121,9 @@
     UpDataStructsAccessMode: {
       _enum: ['Normal', 'AllowList'],
     },
-    UpDataStructsSchemaVersion: mkDummy('SchemaVersion'),
+    UpDataStructsSchemaVersion: {
+      _enum: ['ImageURL', 'Unique'],
+    },
 
     PalletUnqSchedulerScheduledV2: mkDummy('ScheduledV2'),
     PalletUnqSchedulerCallSpec: mkDummy('CallSpec'),
modifiedtests/src/interfaces/unique/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -77,8 +77,11 @@
 }
 
 /** @name UpDataStructsCollectionMode */
-export interface UpDataStructsCollectionMode extends Struct {
-  readonly dummyCollectionMode: u32;
+export interface UpDataStructsCollectionMode extends Enum {
+  readonly isNft: boolean;
+  readonly isFungible: boolean;
+  readonly asFungible: u32;
+  readonly isReFungible: boolean;
 }
 
 /** @name UpDataStructsCollectionStats */
@@ -88,6 +91,22 @@
   readonly alive: u32;
 }
 
+/** @name UpDataStructsCreateCollectionData */
+export interface UpDataStructsCreateCollectionData extends Struct {
+  readonly mode: UpDataStructsCollectionMode;
+  readonly access: Option<UpDataStructsAccessMode>;
+  readonly name: Vec<u16>;
+  readonly description: Vec<u16>;
+  readonly tokenPrefix: Bytes;
+  readonly offchainSchema: Bytes;
+  readonly schemaVersion: Option<UpDataStructsSchemaVersion>;
+  readonly pendingSponsor: Option<AccountId>;
+  readonly limits: Option<UpDataStructsCollectionLimits>;
+  readonly variableOnChainSchema: Bytes;
+  readonly constOnChainSchema: Bytes;
+  readonly metaUpdatePermission: Option<UpDataStructsMetaUpdatePermission>;
+}
+
 /** @name UpDataStructsCreateItemData */
 export interface UpDataStructsCreateItemData extends Struct {
   readonly dummyCreateItemData: u32;
@@ -101,8 +120,9 @@
 }
 
 /** @name UpDataStructsSchemaVersion */
-export interface UpDataStructsSchemaVersion extends Struct {
-  readonly dummySchemaVersion: u32;
+export interface UpDataStructsSchemaVersion extends Enum {
+  readonly isImageUrl: boolean;
+  readonly isUnique: boolean;
 }
 
 /** @name UpDataStructsSponsorshipState */
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -95,6 +95,32 @@
   return TransactionStatus.Fail;
 }
 
+export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {
+  return new Promise(async (res, rej) => {
+    try {
+      await transaction.signAndSend(sender, ({events, status}) => {
+        if (!status.isInBlock && !status.isFinalized) return;
+        for (const {event} of events) {
+          if (api.events.system.ExtrinsicSuccess.is(event)) {
+            res(events);
+          } else if (api.events.system.ExtrinsicFailed.is(event)) {
+            const {data: [error]} = event;
+            if (error.isModule) {
+              const decoded = api.registry.findMetaError(error.asModule);
+              const {method, section} = decoded;
+              rej(new Error(`${section}.${method}`));
+            } else {
+              rej(new Error(error.toString()));
+            }
+          }
+        }
+      });
+    } catch (e) {
+      rej(e);
+    }
+  });
+}
+
 export function
 submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
   /* eslint no-async-promise-executor: "off" */
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -49,7 +49,7 @@
     };
   } else if ('Substrate' in input) {
     return input;
-  }else if ('substrate' in input) {
+  } else if ('substrate' in input) {
     return {
       Substrate: (input as any).substrate,
     };
@@ -116,15 +116,15 @@
 
 export interface IChainLimits {
   collectionNumbersLimit: number;
-	accountTokenOwnershipLimit: number;
-	collectionsAdminsLimit: number;
-	customDataLimit: number;
-	nftSponsorTransferTimeout: number;
-	fungibleSponsorTransferTimeout: number;
-	refungibleSponsorTransferTimeout: number;
-	offchainSchemaLimit: number;
-	variableOnChainSchemaLimit: number;
-	constOnChainSchemaLimit: number;
+  accountTokenOwnershipLimit: number;
+  collectionsAdminsLimit: number;
+  customDataLimit: number;
+  nftSponsorTransferTimeout: number;
+  fungibleSponsorTransferTimeout: number;
+  refungibleSponsorTransferTimeout: number;
+  offchainSchemaLimit: number;
+  variableOnChainSchemaLimit: number;
+  constOnChainSchemaLimit: number;
 }
 
 export interface IReFungibleTokenDataType {
@@ -283,7 +283,7 @@
       modeprm = {refungible: null};
     }
 
-    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
     const events = await submitTransactionAsync(alicePrivateKey, tx);
     const result = getCreateCollectionResult(events);
 
@@ -329,7 +329,7 @@
 
     // Run the CreateCollection transaction
     const alicePrivateKey = privateKey('//Alice');
-    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
     const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
     const result = getCreateCollectionResult(events);
 
@@ -557,7 +557,7 @@
 
   await usingApi(async (api) => {
 
-    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
     const events = await submitTransactionAsync(sender, tx);
     const result = getGenericResult(events);
 
@@ -569,7 +569,7 @@
 
   await usingApi(async (api) => {
 
-    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
     const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
     const result = getGenericResult(events);
 
@@ -811,8 +811,7 @@
 }
 
 export async function
-getFreeBalance(account: IKeyringPair) : Promise<bigint>
-{
+getFreeBalance(account: IKeyringPair): Promise<bigint> {
   let balance = 0n;
   await usingApi(async (api) => {
     balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
addedtests/src/xcmTransfer.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/xcmTransfer.test.ts
@@ -0,0 +1,178 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+
+import {WsProvider} from '@polkadot/api';
+import {ApiOptions} from '@polkadot/api/types';
+import {IKeyringPair} from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
+import {getGenericResult} from './util/helpers';
+import waitNewBlocks from './substrate/wait-new-blocks';
+import getBalance from './substrate/get-balance';
+import {alicesPublicKey} from './accounts';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const UNIQUE_CHAIN = 1000;
+const KARURA_CHAIN = 2000;
+const KARURA_PORT = '9946';
+
+describe('Integration test: Exchanging OPL with Karura', () => {
+  let alice: IKeyringPair;
+  
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+    });
+
+    const karuraApiOptions: ApiOptions = {
+      provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT),
+    };
+
+    await usingApi(async (api) => {
+      const destination = {
+        V0: {
+          X2: [
+            'Parent',
+            {
+              Parachain: UNIQUE_CHAIN,
+            },
+          ],
+        },
+      };
+
+      const metadata =
+      {
+        name: 'OPL',
+        symbol: 'OPL',
+        decimals: 18,
+        minimalBalance: 1,
+      };
+
+      const tx = api.tx.assetRegistry.registerForeignAsset(destination, metadata);
+      const sudoTx = api.tx.sudo.sudo(tx as any);
+      const events = await submitTransactionAsync(alice, sudoTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+    }, karuraApiOptions);
+  });
+
+  it('Should connect and send OPL to Karura', async () => {
+    let balanceOnKaruraBefore: bigint;
+    
+    await usingApi(async (api) => {
+      const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAsset: 0})).toJSON() as any;
+      balanceOnKaruraBefore = free;
+    }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+
+    await usingApi(async (api) => {
+      const destination = {
+        V0: {
+          X2: [
+            'Parent',
+            {
+              Parachain: KARURA_CHAIN,
+            },
+          ],
+        },
+      };
+
+      const beneficiary = {
+        V0: {
+          X1: {
+            AccountId32: {
+              network: 'Any',
+              id: alice.addressRaw,
+            },
+          },
+        },
+      };
+
+      const assets = {
+        V1: [
+          {
+            id: {
+              Concrete: {
+                parents: 0,
+                interior: 'Here',
+              },
+            },
+            fun: {
+              Fungible: 5000000000,
+            },
+          },
+        ],
+      };
+
+      const feeAssetItem = 0;
+
+      const weightLimit = {
+        Limited: 5000000000,
+      };
+
+      const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+    });
+
+    await usingApi(async (api) => {
+      // todo do something about instant sealing, where there might not be any new blocks
+      await waitNewBlocks(api, 3);
+      const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAsset: 0})).toJSON() as any;
+      expect(free > balanceOnKaruraBefore).to.be.true;
+    }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+  });
+
+  it('Should connect to Karura and send OPL back', async () => {
+    let balanceBefore: bigint;
+    
+    await usingApi(async (api) => {
+      [balanceBefore] = await getBalance(api, [alicesPublicKey]);
+    });
+
+    await usingApi(async (api) => {
+      const destination = {
+        V0: {
+          X3: [
+            'Parent',
+            {
+              Parachain: UNIQUE_CHAIN,
+            },
+            {
+              AccountId32: {
+                network: 'Any',
+                id: alice.addressRaw,
+              },
+            },
+          ],
+        },
+      };
+
+      const id = {
+        ForeignAsset: 0,
+      };
+
+      const amount = 5000000000;
+      const destWeight = 50000000;
+
+      const tx = api.tx.xTokens.transfer(id, amount, destination, destWeight);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+    }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+
+    await usingApi(async (api) => {
+      // todo do something about instant sealing, where there might not be any new blocks
+      await waitNewBlocks(api, 3);
+      const [balanceAfter] = await getBalance(api, [alicesPublicKey]);
+      expect(balanceAfter > balanceBefore).to.be.true;
+    });
+  });
+});
\ No newline at end of file