git.delta.rocks / unique-network / refs/commits / 8065c75e5568

difftreelog

Merge pull request #463 from UniqueNetwork/feature/remove_const_data_rft

Yaroslav Bolyukin2022-08-03parents: #b21ac36 #a7dc6fb.patch.diff
in: master

10 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6311,7 +6311,7 @@
 
 [[package]]
 name = "pallet-refungible"
-version = "0.1.2"
+version = "0.2.0"
 dependencies = [
  "ethereum",
  "evm-coder",
@@ -12732,7 +12732,7 @@
 
 [[package]]
 name = "up-data-structs"
-version = "0.1.2"
+version = "0.2.0"
 dependencies = [
  "derivative",
  "frame-support",
modifiedpallets/refungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,6 +2,11 @@
 
 All notable changes to this project will be documented in this file.
 
+## [v0.2.0] - 2022-08-01
+### Deprecated
+- `ItemData`
+- `TokenData`
+
 ## [v0.1.2] - 2022-07-14
 
 ### Other changes
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "pallet-refungible"
-version = "0.1.2"
+version = "0.2.0"
 license = "GPLv3"
 edition = "2021"
 
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -32,7 +32,7 @@
 
 use crate::{
 	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
-	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TotalSupply,
 };
 
 macro_rules! max_weight_of {
@@ -155,7 +155,6 @@
 ) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {
 	match data {
 		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {
-			const_data: data.const_data,
 			users: {
 				let mut out = BTreeMap::new();
 				out.insert(to.clone(), data.pieces);
@@ -421,7 +420,7 @@
 	}
 
 	fn collection_tokens(&self) -> Vec<TokenId> {
-		<TokenData<T>>::iter_prefix((self.id,))
+		<TotalSupply<T>>::iter_prefix((self.id,))
 			.map(|(id, _)| id)
 			.collect()
 	}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,100};101use pallet_structure::Pallet as PalletStructure;102use scale_info::TypeInfo;103use sp_core::H160;104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,108	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,109	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,110	TrySetProperty,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;121122/// Token data, stored independently from other data used to describe it123/// for the convenience of database access. Notably contains the token metadata.124#[struct_versioning::versioned(version = 2, upper)]125#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]126pub struct ItemData {127	pub const_data: BoundedVec<u8, CustomDataLimit>,128129	#[version(..2)]130	pub variable_data: BoundedVec<u8, CustomDataLimit>,131}132133#[frame_support::pallet]134pub mod pallet {135	use super::*;136	use frame_support::{137		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,138		traits::StorageVersion,139	};140	use frame_system::pallet_prelude::*;141	use up_data_structs::{CollectionId, TokenId};142	use super::weights::WeightInfo;143144	#[pallet::error]145	pub enum Error<T> {146		/// Not Refungible item data used to mint in Refungible collection.147		NotRefungibleDataUsedToMintFungibleCollectionToken,148		/// Maximum refungibility exceeded.149		WrongRefungiblePieces,150		/// Refungible token can't be repartitioned by user who isn't owns all pieces.151		RepartitionWhileNotOwningAllPieces,152		/// Refungible token can't nest other tokens.153		RefungibleDisallowsNesting,154		/// Setting item properties is not allowed.155		SettingPropertiesNotAllowed,156	}157158	#[pallet::config]159	pub trait Config:160		frame_system::Config + pallet_common::Config + pallet_structure::Config161	{162		type WeightInfo: WeightInfo;163	}164165	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);166167	#[pallet::pallet]168	#[pallet::storage_version(STORAGE_VERSION)]169	#[pallet::generate_store(pub(super) trait Store)]170	pub struct Pallet<T>(_);171172	/// Total amount of minted tokens in a collection.173	#[pallet::storage]174	pub type TokensMinted<T: Config> =175		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;176177	/// Amount of tokens burnt in a collection.178	#[pallet::storage]179	pub type TokensBurnt<T: Config> =180		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182	/// Token data, used to partially describe a token.183	#[pallet::storage]184	pub type TokenData<T: Config> = StorageNMap<185		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),186		Value = ItemData,187		QueryKind = ValueQuery,188	>;189190	/// Amount of pieces a refungible token is split into.191	#[pallet::storage]192	#[pallet::getter(fn token_properties)]193	pub type TokenProperties<T: Config> = StorageNMap<194		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195		Value = up_data_structs::Properties,196		QueryKind = ValueQuery,197		OnEmpty = up_data_structs::TokenProperties,198	>;199200	/// Total amount of pieces for token201	#[pallet::storage]202	pub type TotalSupply<T: Config> = StorageNMap<203		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204		Value = u128,205		QueryKind = ValueQuery,206	>;207208	/// Used to enumerate tokens owned by account.209	#[pallet::storage]210	pub type Owned<T: Config> = StorageNMap<211		Key = (212			Key<Twox64Concat, CollectionId>,213			Key<Blake2_128Concat, T::CrossAccountId>,214			Key<Twox64Concat, TokenId>,215		),216		Value = bool,217		QueryKind = ValueQuery,218	>;219220	/// Amount of tokens (not pieces) partially owned by an account within a collection.221	#[pallet::storage]222	pub type AccountBalance<T: Config> = StorageNMap<223		Key = (224			Key<Twox64Concat, CollectionId>,225			// Owner226			Key<Blake2_128Concat, T::CrossAccountId>,227		),228		Value = u32,229		QueryKind = ValueQuery,230	>;231232	/// Amount of token pieces owned by account.233	#[pallet::storage]234	pub type Balance<T: Config> = StorageNMap<235		Key = (236			Key<Twox64Concat, CollectionId>,237			Key<Twox64Concat, TokenId>,238			// Owner239			Key<Blake2_128Concat, T::CrossAccountId>,240		),241		Value = u128,242		QueryKind = ValueQuery,243	>;244245	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.246	#[pallet::storage]247	pub type Allowance<T: Config> = StorageNMap<248		Key = (249			Key<Twox64Concat, CollectionId>,250			Key<Twox64Concat, TokenId>,251			// Owner252			Key<Blake2_128, T::CrossAccountId>,253			// Spender254			Key<Blake2_128Concat, T::CrossAccountId>,255		),256		Value = u128,257		QueryKind = ValueQuery,258	>;259260	#[pallet::hooks]261	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {262		fn on_runtime_upgrade() -> Weight {263			StorageVersion::new(1).put::<Pallet<T>>();264265			0266		}267	}268}269270pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);271impl<T: Config> RefungibleHandle<T> {272	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {273		Self(inner)274	}275	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {276		self.0277	}278	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {279		&mut self.0280	}281}282283impl<T: Config> Deref for RefungibleHandle<T> {284	type Target = pallet_common::CollectionHandle<T>;285286	fn deref(&self) -> &Self::Target {287		&self.0288	}289}290291impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {292	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {293		self.0.recorder()294	}295	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {296		self.0.into_recorder()297	}298}299300impl<T: Config> Pallet<T> {301	/// Get number of RFT tokens in collection302	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {303		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)304	}305306	/// Check that RFT token exists307	///308	/// - `token`: Token ID.309	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {310		<TotalSupply<T>>::contains_key((collection.id, token))311	}312313	pub fn set_scoped_token_property(314		collection_id: CollectionId,315		token_id: TokenId,316		scope: PropertyScope,317		property: Property,318	) -> DispatchResult {319		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {320			properties.try_scoped_set(scope, property.key, property.value)321		})322		.map_err(<CommonError<T>>::from)?;323324		Ok(())325	}326327	pub fn set_scoped_token_properties(328		collection_id: CollectionId,329		token_id: TokenId,330		scope: PropertyScope,331		properties: impl Iterator<Item = Property>,332	) -> DispatchResult {333		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {334			stored_properties.try_scoped_set_from_iter(scope, properties)335		})336		.map_err(<CommonError<T>>::from)?;337338		Ok(())339	}340}341342// unchecked calls skips any permission checks343impl<T: Config> Pallet<T> {344	/// Create RFT collection345	///346	/// `init_collection` will take non-refundable deposit for collection creation.347	///348	/// - `data`: Contains settings for collection limits and permissions.349	pub fn init_collection(350		owner: T::CrossAccountId,351		data: CreateCollectionData<T::AccountId>,352	) -> Result<CollectionId, DispatchError> {353		<PalletCommon<T>>::init_collection(owner, data, false)354	}355356	/// Destroy RFT collection357	///358	/// `destroy_collection` will throw error if collection contains any tokens.359	/// Only owner can destroy collection.360	pub fn destroy_collection(361		collection: RefungibleHandle<T>,362		sender: &T::CrossAccountId,363	) -> DispatchResult {364		let id = collection.id;365366		if Self::collection_has_tokens(id) {367			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());368		}369370		// =========371372		PalletCommon::destroy_collection(collection.0, sender)?;373374		<TokensMinted<T>>::remove(id);375		<TokensBurnt<T>>::remove(id);376		<TokenData<T>>::remove_prefix((id,), None);377		<TotalSupply<T>>::remove_prefix((id,), None);378		<Balance<T>>::remove_prefix((id,), None);379		<Allowance<T>>::remove_prefix((id,), None);380		<Owned<T>>::remove_prefix((id,), None);381		<AccountBalance<T>>::remove_prefix((id,), None);382		Ok(())383	}384385	fn collection_has_tokens(collection_id: CollectionId) -> bool {386		<TokenData<T>>::iter_prefix((collection_id,))387			.next()388			.is_some()389	}390391	pub fn burn_token_unchecked(392		collection: &RefungibleHandle<T>,393		token_id: TokenId,394	) -> DispatchResult {395		let burnt = <TokensBurnt<T>>::get(collection.id)396			.checked_add(1)397			.ok_or(ArithmeticError::Overflow)?;398399		<TokensBurnt<T>>::insert(collection.id, burnt);400		<TokenData<T>>::remove((collection.id, token_id));401		<TokenProperties<T>>::remove((collection.id, token_id));402		<TotalSupply<T>>::remove((collection.id, token_id));403		<Balance<T>>::remove_prefix((collection.id, token_id), None);404		<Allowance<T>>::remove_prefix((collection.id, token_id), None);405		// TODO: ERC721 transfer event406		Ok(())407	}408409	/// Burn RFT token pieces410	///411	/// `burn` will decrease total amount of token pieces and amount owned by sender.412	/// `burn` can be called even if there are multiple owners of the RFT token.413	/// If sender wouldn't have any pieces left after `burn` than she will stop being414	/// one of the owners of the token. If there is no account that owns any pieces of415	/// the token than token will be burned too.416	///417	/// - `amount`: Amount of token pieces to burn.418	/// - `token`: Token who's pieces should be burned419	/// - `collection`: Collection that contains the token420	pub fn burn(421		collection: &RefungibleHandle<T>,422		owner: &T::CrossAccountId,423		token: TokenId,424		amount: u128,425	) -> DispatchResult {426		let total_supply = <TotalSupply<T>>::get((collection.id, token))427			.checked_sub(amount)428			.ok_or(<CommonError<T>>::TokenValueTooLow)?;429430		// This was probally last owner of this token?431		if total_supply == 0 {432			// Ensure user actually owns this amount433			ensure!(434				<Balance<T>>::get((collection.id, token, owner)) == amount,435				<CommonError<T>>::TokenValueTooLow436			);437			let account_balance = <AccountBalance<T>>::get((collection.id, owner))438				.checked_sub(1)439				// Should not occur440				.ok_or(ArithmeticError::Underflow)?;441442			// =========443444			<Owned<T>>::remove((collection.id, owner, token));445			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);446			<AccountBalance<T>>::insert((collection.id, owner), account_balance);447			Self::burn_token_unchecked(collection, token)?;448			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(449				collection.id,450				token,451				owner.clone(),452				amount,453			));454			return Ok(());455		}456457		let balance = <Balance<T>>::get((collection.id, token, owner))458			.checked_sub(amount)459			.ok_or(<CommonError<T>>::TokenValueTooLow)?;460		let account_balance = if balance == 0 {461			<AccountBalance<T>>::get((collection.id, owner))462				.checked_sub(1)463				// Should not occur464				.ok_or(ArithmeticError::Underflow)?465		} else {466			0467		};468469		// =========470471		if balance == 0 {472			<Owned<T>>::remove((collection.id, owner, token));473			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);474			<Balance<T>>::remove((collection.id, token, owner));475			<AccountBalance<T>>::insert((collection.id, owner), account_balance);476		} else {477			<Balance<T>>::insert((collection.id, token, owner), balance);478		}479		<TotalSupply<T>>::insert((collection.id, token), total_supply);480481		<PalletEvm<T>>::deposit_log(482			ERC20Events::Transfer {483				from: *owner.as_eth(),484				to: H160::default(),485				value: amount.into(),486			}487			.to_log(T::EvmTokenAddressMapping::token_to_address(488				collection.id,489				token,490			)),491		);492		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(493			collection.id,494			token,495			owner.clone(),496			amount,497		));498		Ok(())499	}500501	#[transactional]502	fn modify_token_properties(503		collection: &RefungibleHandle<T>,504		sender: &T::CrossAccountId,505		token_id: TokenId,506		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,507		is_token_create: bool,508		nesting_budget: &dyn Budget,509	) -> DispatchResult {510		let is_collection_admin = || collection.is_owner_or_admin(sender);511		let is_token_owner = || -> Result<bool, DispatchError> {512			let balance = collection.balance(sender.clone(), token_id);513			let total_pieces: u128 =514				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);515			if balance != total_pieces {516				return Ok(false);517			}518519			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(520				sender.clone(),521				collection.id,522				token_id,523				None,524				nesting_budget,525			)?;526527			Ok(is_bundle_owner)528		};529530		for (key, value) in properties {531			let permission = <PalletCommon<T>>::property_permissions(collection.id)532				.get(&key)533				.cloned()534				.unwrap_or_else(PropertyPermission::none);535536			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))537				.get(&key)538				.is_some();539540			match permission {541				PropertyPermission { mutable: false, .. } if is_property_exists => {542					return Err(<CommonError<T>>::NoPermission.into());543				}544545				PropertyPermission {546					collection_admin,547					token_owner,548					..549				} => {550					//TODO: investigate threats during public minting.551					let is_token_create =552						is_token_create && (collection_admin || token_owner) && value.is_some();553					if !(is_token_create554						|| (collection_admin && is_collection_admin())555						|| (token_owner && is_token_owner()?))556					{557						fail!(<CommonError<T>>::NoPermission);558					}559				}560			}561562			match value {563				Some(value) => {564					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {565						properties.try_set(key.clone(), value)566					})567					.map_err(<CommonError<T>>::from)?;568569					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(570						collection.id,571						token_id,572						key,573					));574				}575				None => {576					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {577						properties.remove(&key)578					})579					.map_err(<CommonError<T>>::from)?;580581					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(582						collection.id,583						token_id,584						key,585					));586				}587			}588		}589590		Ok(())591	}592593	pub fn set_token_properties(594		collection: &RefungibleHandle<T>,595		sender: &T::CrossAccountId,596		token_id: TokenId,597		properties: impl Iterator<Item = Property>,598		is_token_create: bool,599		nesting_budget: &dyn Budget,600	) -> DispatchResult {601		Self::modify_token_properties(602			collection,603			sender,604			token_id,605			properties.map(|p| (p.key, Some(p.value))),606			is_token_create,607			nesting_budget,608		)609	}610611	pub fn set_token_property(612		collection: &RefungibleHandle<T>,613		sender: &T::CrossAccountId,614		token_id: TokenId,615		property: Property,616		nesting_budget: &dyn Budget,617	) -> DispatchResult {618		let is_token_create = false;619620		Self::set_token_properties(621			collection,622			sender,623			token_id,624			[property].into_iter(),625			is_token_create,626			nesting_budget,627		)628	}629630	pub fn delete_token_properties(631		collection: &RefungibleHandle<T>,632		sender: &T::CrossAccountId,633		token_id: TokenId,634		property_keys: impl Iterator<Item = PropertyKey>,635		nesting_budget: &dyn Budget,636	) -> DispatchResult {637		let is_token_create = false;638639		Self::modify_token_properties(640			collection,641			sender,642			token_id,643			property_keys.into_iter().map(|key| (key, None)),644			is_token_create,645			nesting_budget,646		)647	}648649	pub fn delete_token_property(650		collection: &RefungibleHandle<T>,651		sender: &T::CrossAccountId,652		token_id: TokenId,653		property_key: PropertyKey,654		nesting_budget: &dyn Budget,655	) -> DispatchResult {656		Self::delete_token_properties(657			collection,658			sender,659			token_id,660			[property_key].into_iter(),661			nesting_budget,662		)663	}664665	/// Transfer RFT token pieces from one account to another.666	///667	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.668	///669	/// - `from`: Owner of token pieces to transfer.670	/// - `to`: Recepient of transfered token pieces.671	/// - `amount`: Amount of token pieces to transfer.672	/// - `token`: Token whos pieces should be transfered673	/// - `collection`: Collection that contains the token674	pub fn transfer(675		collection: &RefungibleHandle<T>,676		from: &T::CrossAccountId,677		to: &T::CrossAccountId,678		token: TokenId,679		amount: u128,680		nesting_budget: &dyn Budget,681	) -> DispatchResult {682		ensure!(683			collection.limits.transfers_enabled(),684			<CommonError<T>>::TransferNotAllowed685		);686687		if collection.permissions.access() == AccessMode::AllowList {688			collection.check_allowlist(from)?;689			collection.check_allowlist(to)?;690		}691		<PalletCommon<T>>::ensure_correct_receiver(to)?;692693		let balance_from = <Balance<T>>::get((collection.id, token, from))694			.checked_sub(amount)695			.ok_or(<CommonError<T>>::TokenValueTooLow)?;696		let mut create_target = false;697		let from_to_differ = from != to;698		let balance_to = if from != to {699			let old_balance = <Balance<T>>::get((collection.id, token, to));700			if old_balance == 0 {701				create_target = true;702			}703			Some(704				old_balance705					.checked_add(amount)706					.ok_or(ArithmeticError::Overflow)?,707			)708		} else {709			None710		};711712		let account_balance_from = if balance_from == 0 {713			Some(714				<AccountBalance<T>>::get((collection.id, from))715					.checked_sub(1)716					// Should not occur717					.ok_or(ArithmeticError::Underflow)?,718			)719		} else {720			None721		};722		// Account data is created in token, AccountBalance should be increased723		// But only if from != to as we shouldn't check overflow in this case724		let account_balance_to = if create_target && from_to_differ {725			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))726				.checked_add(1)727				.ok_or(ArithmeticError::Overflow)?;728			ensure!(729				account_balance_to < collection.limits.account_token_ownership_limit(),730				<CommonError<T>>::AccountTokenLimitExceeded,731			);732733			Some(account_balance_to)734		} else {735			None736		};737738		// =========739740		<PalletStructure<T>>::nest_if_sent_to_token(741			from.clone(),742			to,743			collection.id,744			token,745			nesting_budget,746		)?;747748		if let Some(balance_to) = balance_to {749			// from != to750			if balance_from == 0 {751				<Balance<T>>::remove((collection.id, token, from));752				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);753			} else {754				<Balance<T>>::insert((collection.id, token, from), balance_from);755			}756			<Balance<T>>::insert((collection.id, token, to), balance_to);757			if let Some(account_balance_from) = account_balance_from {758				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);759				<Owned<T>>::remove((collection.id, from, token));760			}761			if let Some(account_balance_to) = account_balance_to {762				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);763				<Owned<T>>::insert((collection.id, to, token), true);764			}765		}766767		<PalletEvm<T>>::deposit_log(768			ERC20Events::Transfer {769				from: *from.as_eth(),770				to: *to.as_eth(),771				value: amount.into(),772			}773			.to_log(T::EvmTokenAddressMapping::token_to_address(774				collection.id,775				token,776			)),777		);778		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(779			collection.id,780			token,781			from.clone(),782			to.clone(),783			amount,784		));785		Ok(())786	}787788	/// Batched operation to create multiple RFT tokens.789	///790	/// Same as `create_item` but creates multiple tokens.791	///792	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.793	pub fn create_multiple_items(794		collection: &RefungibleHandle<T>,795		sender: &T::CrossAccountId,796		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,797		nesting_budget: &dyn Budget,798	) -> DispatchResult {799		if !collection.is_owner_or_admin(sender) {800			ensure!(801				collection.permissions.mint_mode(),802				<CommonError<T>>::PublicMintingNotAllowed803			);804			collection.check_allowlist(sender)?;805806			for item in data.iter() {807				for user in item.users.keys() {808					collection.check_allowlist(user)?;809				}810			}811		}812813		for item in data.iter() {814			for (owner, _) in item.users.iter() {815				<PalletCommon<T>>::ensure_correct_receiver(owner)?;816			}817		}818819		// Total pieces per tokens820		let totals = data821			.iter()822			.map(|data| {823				Ok(data824					.users825					.iter()826					.map(|u| u.1)827					.try_fold(0u128, |acc, v| acc.checked_add(*v))828					.ok_or(ArithmeticError::Overflow)?)829			})830			.collect::<Result<Vec<_>, DispatchError>>()?;831		for total in &totals {832			ensure!(833				*total <= MAX_REFUNGIBLE_PIECES,834				<Error<T>>::WrongRefungiblePieces835			);836		}837838		let first_token_id = <TokensMinted<T>>::get(collection.id);839		let tokens_minted = first_token_id840			.checked_add(data.len() as u32)841			.ok_or(ArithmeticError::Overflow)?;842		ensure!(843			tokens_minted < collection.limits.token_limit(),844			<CommonError<T>>::CollectionTokenLimitExceeded845		);846847		let mut balances = BTreeMap::new();848		for data in &data {849			for owner in data.users.keys() {850				let balance = balances851					.entry(owner)852					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));853				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;854855				ensure!(856					*balance <= collection.limits.account_token_ownership_limit(),857					<CommonError<T>>::AccountTokenLimitExceeded,858				);859			}860		}861862		for (i, token) in data.iter().enumerate() {863			let token_id = TokenId(first_token_id + i as u32 + 1);864			for (to, _) in token.users.iter() {865				<PalletStructure<T>>::check_nesting(866					sender.clone(),867					to,868					collection.id,869					token_id,870					nesting_budget,871				)?;872			}873		}874875		// =========876877		with_transaction(|| {878			for (i, data) in data.iter().enumerate() {879				let token_id = first_token_id + i as u32 + 1;880				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);881882				<TokenData<T>>::insert(883					(collection.id, token_id),884					ItemData {885						const_data: data.const_data.clone(),886					},887				);888889				for (user, amount) in data.users.iter() {890					if *amount == 0 {891						continue;892					}893					<Balance<T>>::insert((collection.id, token_id, &user), amount);894					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);895					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(896						user,897						collection.id,898						TokenId(token_id),899					);900				}901902				if let Err(e) = Self::set_token_properties(903					collection,904					sender,905					TokenId(token_id),906					data.properties.clone().into_iter(),907					true,908					nesting_budget,909				) {910					return TransactionOutcome::Rollback(Err(e));911				}912			}913			TransactionOutcome::Commit(Ok(()))914		})?;915916		<TokensMinted<T>>::insert(collection.id, tokens_minted);917918		for (account, balance) in balances {919			<AccountBalance<T>>::insert((collection.id, account), balance);920		}921922		for (i, token) in data.into_iter().enumerate() {923			let token_id = first_token_id + i as u32 + 1;924925			for (user, amount) in token.users.into_iter() {926				if amount == 0 {927					continue;928				}929930				<PalletEvm<T>>::deposit_log(931					ERC20Events::Transfer {932						from: H160::default(),933						to: *user.as_eth(),934						value: amount.into(),935					}936					.to_log(T::EvmTokenAddressMapping::token_to_address(937						collection.id,938						TokenId(token_id),939					)),940				);941				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(942					collection.id,943					TokenId(token_id),944					user,945					amount,946				));947			}948		}949		Ok(())950	}951952	pub fn set_allowance_unchecked(953		collection: &RefungibleHandle<T>,954		sender: &T::CrossAccountId,955		spender: &T::CrossAccountId,956		token: TokenId,957		amount: u128,958	) {959		if amount == 0 {960			<Allowance<T>>::remove((collection.id, token, sender, spender));961		} else {962			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);963		}964965		<PalletEvm<T>>::deposit_log(966			ERC20Events::Approval {967				owner: *sender.as_eth(),968				spender: *spender.as_eth(),969				value: amount.into(),970			}971			.to_log(T::EvmTokenAddressMapping::token_to_address(972				collection.id,973				token,974			)),975		);976		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(977			collection.id,978			token,979			sender.clone(),980			spender.clone(),981			amount,982		))983	}984985	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.986	///987	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.988	pub fn set_allowance(989		collection: &RefungibleHandle<T>,990		sender: &T::CrossAccountId,991		spender: &T::CrossAccountId,992		token: TokenId,993		amount: u128,994	) -> DispatchResult {995		if collection.permissions.access() == AccessMode::AllowList {996			collection.check_allowlist(sender)?;997			collection.check_allowlist(spender)?;998		}9991000		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10011002		if <Balance<T>>::get((collection.id, token, sender)) < amount {1003			ensure!(1004				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1005				<CommonError<T>>::CantApproveMoreThanOwned1006			);1007		}10081009		// =========10101011		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1012		Ok(())1013	}10141015	/// Returns allowance, which should be set after transaction1016	fn check_allowed(1017		collection: &RefungibleHandle<T>,1018		spender: &T::CrossAccountId,1019		from: &T::CrossAccountId,1020		token: TokenId,1021		amount: u128,1022		nesting_budget: &dyn Budget,1023	) -> Result<Option<u128>, DispatchError> {1024		if spender.conv_eq(from) {1025			return Ok(None);1026		}1027		if collection.permissions.access() == AccessMode::AllowList {1028			// `from`, `to` checked in [`transfer`]1029			collection.check_allowlist(spender)?;1030		}1031		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1032			// TODO: should collection owner be allowed to perform this transfer?1033			ensure!(1034				<PalletStructure<T>>::check_indirectly_owned(1035					spender.clone(),1036					source.0,1037					source.1,1038					None,1039					nesting_budget1040				)?,1041				<CommonError<T>>::ApprovedValueTooLow,1042			);1043			return Ok(None);1044		}1045		let allowance =1046			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1047		if allowance.is_none() {1048			ensure!(1049				collection.ignores_allowance(spender),1050				<CommonError<T>>::ApprovedValueTooLow1051			);1052		}1053		Ok(allowance)1054	}10551056	/// Transfer RFT token pieces from one account to another.1057	///1058	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1059	/// The owner should set allowance for the spender to transfer pieces.1060	///1061	/// [`transfer`]: struct.Pallet.html#method.transfer1062	pub fn transfer_from(1063		collection: &RefungibleHandle<T>,1064		spender: &T::CrossAccountId,1065		from: &T::CrossAccountId,1066		to: &T::CrossAccountId,1067		token: TokenId,1068		amount: u128,1069		nesting_budget: &dyn Budget,1070	) -> DispatchResult {1071		let allowance =1072			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10731074		// =========10751076		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1077		if let Some(allowance) = allowance {1078			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1079		}1080		Ok(())1081	}10821083	/// Burn RFT token pieces from the account.1084	///1085	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1086	/// set allowance for the spender to burn pieces1087	///1088	/// [`burn`]: struct.Pallet.html#method.burn1089	pub fn burn_from(1090		collection: &RefungibleHandle<T>,1091		spender: &T::CrossAccountId,1092		from: &T::CrossAccountId,1093		token: TokenId,1094		amount: u128,1095		nesting_budget: &dyn Budget,1096	) -> DispatchResult {1097		let allowance =1098			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10991100		// =========11011102		Self::burn(collection, from, token, amount)?;1103		if let Some(allowance) = allowance {1104			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1105		}1106		Ok(())1107	}11081109	/// Create RFT token.1110	///1111	/// The sender should be the owner/admin of the collection or collection should be configured1112	/// to allow public minting.1113	///1114	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1115	///   of token pieces they will receive.1116	pub fn create_item(1117		collection: &RefungibleHandle<T>,1118		sender: &T::CrossAccountId,1119		data: CreateRefungibleExData<T::CrossAccountId>,1120		nesting_budget: &dyn Budget,1121	) -> DispatchResult {1122		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1123	}11241125	/// Repartition RFT token.1126	///1127	/// `repartition` will set token balance of the sender and total amount of token pieces.1128	/// Sender should own all of the token pieces. `repartition' could be done even if some1129	/// token pieces were burned before.1130	///1131	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1132	pub fn repartition(1133		collection: &RefungibleHandle<T>,1134		owner: &T::CrossAccountId,1135		token: TokenId,1136		amount: u128,1137	) -> DispatchResult {1138		ensure!(1139			amount <= MAX_REFUNGIBLE_PIECES,1140			<Error<T>>::WrongRefungiblePieces1141		);1142		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1143		// Ensure user owns all pieces1144		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1145		let balance = <Balance<T>>::get((collection.id, token, owner));1146		ensure!(1147			total_pieces == balance,1148			<Error<T>>::RepartitionWhileNotOwningAllPieces1149		);11501151		<Balance<T>>::insert((collection.id, token, owner), amount);1152		<TotalSupply<T>>::insert((collection.id, token), amount);11531154		if amount > total_pieces {1155			let mint_amount = amount - total_pieces;1156			<PalletEvm<T>>::deposit_log(1157				ERC20Events::Transfer {1158					from: H160::default(),1159					to: *owner.as_eth(),1160					value: mint_amount.into(),1161				}1162				.to_log(T::EvmTokenAddressMapping::token_to_address(1163					collection.id,1164					token,1165				)),1166			);1167			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1168				collection.id,1169				token,1170				owner.clone(),1171				mint_amount,1172			));1173		} else if total_pieces > amount {1174			let burn_amount = total_pieces - amount;1175			<PalletEvm<T>>::deposit_log(1176				ERC20Events::Transfer {1177					from: *owner.as_eth(),1178					to: H160::default(),1179					value: burn_amount.into(),1180				}1181				.to_log(T::EvmTokenAddressMapping::token_to_address(1182					collection.id,1183					token,1184				)),1185			);1186			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1187				collection.id,1188				token,1189				owner.clone(),1190				burn_amount,1191			));1192		}11931194		Ok(())1195	}11961197	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1198		let mut owner = None;1199		let mut count = 0;1200		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1201			count += 1;1202			if count > 1 {1203				return None;1204			}1205			owner = Some(key);1206		}1207		owner1208	}12091210	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1211		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1212	}12131214	pub fn set_collection_properties(1215		collection: &RefungibleHandle<T>,1216		sender: &T::CrossAccountId,1217		properties: Vec<Property>,1218	) -> DispatchResult {1219		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1220	}12211222	pub fn delete_collection_properties(1223		collection: &RefungibleHandle<T>,1224		sender: &T::CrossAccountId,1225		property_keys: Vec<PropertyKey>,1226	) -> DispatchResult {1227		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1228	}12291230	pub fn set_token_property_permissions(1231		collection: &RefungibleHandle<T>,1232		sender: &T::CrossAccountId,1233		property_permissions: Vec<PropertyKeyPermission>,1234	) -> DispatchResult {1235		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1236	}12371238	/// Returns 10 token in no particular order.1239	///1240	/// There is no direct way to get token holders in ascending order,1241	/// since `iter_prefix` returns values in no particular order.1242	/// Therefore, getting the 10 largest holders with a large value of holders1243	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1244	pub fn token_owners(1245		collection_id: CollectionId,1246		token: TokenId,1247	) -> Option<Vec<T::CrossAccountId>> {1248		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1249			.map(|(owner, _amount)| owner)1250			.take(10)1251			.collect();12521253		if res.is_empty() {1254			None1255		} else {1256			Some(res)1257		}1258	}1259}
after · pallets/refungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,100};101use pallet_structure::Pallet as PalletStructure;102use scale_info::TypeInfo;103use sp_core::H160;104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,108	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,109	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,110	TrySetProperty,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;121122/// Token data, stored independently from other data used to describe it123/// for the convenience of database access. Notably contains the token metadata.124#[struct_versioning::versioned(version = 2, upper)]125#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]126#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]127pub struct ItemData {128	pub const_data: BoundedVec<u8, CustomDataLimit>,129130	#[version(..2)]131	pub variable_data: BoundedVec<u8, CustomDataLimit>,132}133134#[frame_support::pallet]135pub mod pallet {136	use super::*;137	use frame_support::{138		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,139		traits::StorageVersion,140	};141	use frame_system::pallet_prelude::*;142	use up_data_structs::{CollectionId, TokenId};143	use super::weights::WeightInfo;144145	#[pallet::error]146	pub enum Error<T> {147		/// Not Refungible item data used to mint in Refungible collection.148		NotRefungibleDataUsedToMintFungibleCollectionToken,149		/// Maximum refungibility exceeded.150		WrongRefungiblePieces,151		/// Refungible token can't be repartitioned by user who isn't owns all pieces.152		RepartitionWhileNotOwningAllPieces,153		/// Refungible token can't nest other tokens.154		RefungibleDisallowsNesting,155		/// Setting item properties is not allowed.156		SettingPropertiesNotAllowed,157	}158159	#[pallet::config]160	pub trait Config:161		frame_system::Config + pallet_common::Config + pallet_structure::Config162	{163		type WeightInfo: WeightInfo;164	}165166	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);167168	#[pallet::pallet]169	#[pallet::storage_version(STORAGE_VERSION)]170	#[pallet::generate_store(pub(super) trait Store)]171	pub struct Pallet<T>(_);172173	/// Total amount of minted tokens in a collection.174	#[pallet::storage]175	pub type TokensMinted<T: Config> =176		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;177178	/// Amount of tokens burnt in a collection.179	#[pallet::storage]180	pub type TokensBurnt<T: Config> =181		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;182183	/// Token data, used to partially describe a token.184	// TODO: remove185	#[pallet::storage]186	#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]187	pub type TokenData<T: Config> = StorageNMap<188		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),189		Value = ItemData,190		QueryKind = ValueQuery,191	>;192193	/// Amount of pieces a refungible token is split into.194	#[pallet::storage]195	#[pallet::getter(fn token_properties)]196	pub type TokenProperties<T: Config> = StorageNMap<197		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),198		Value = up_data_structs::Properties,199		QueryKind = ValueQuery,200		OnEmpty = up_data_structs::TokenProperties,201	>;202203	/// Total amount of pieces for token204	#[pallet::storage]205	pub type TotalSupply<T: Config> = StorageNMap<206		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),207		Value = u128,208		QueryKind = ValueQuery,209	>;210211	/// Used to enumerate tokens owned by account.212	#[pallet::storage]213	pub type Owned<T: Config> = StorageNMap<214		Key = (215			Key<Twox64Concat, CollectionId>,216			Key<Blake2_128Concat, T::CrossAccountId>,217			Key<Twox64Concat, TokenId>,218		),219		Value = bool,220		QueryKind = ValueQuery,221	>;222223	/// Amount of tokens (not pieces) partially owned by an account within a collection.224	#[pallet::storage]225	pub type AccountBalance<T: Config> = StorageNMap<226		Key = (227			Key<Twox64Concat, CollectionId>,228			// Owner229			Key<Blake2_128Concat, T::CrossAccountId>,230		),231		Value = u32,232		QueryKind = ValueQuery,233	>;234235	/// Amount of token pieces owned by account.236	#[pallet::storage]237	pub type Balance<T: Config> = StorageNMap<238		Key = (239			Key<Twox64Concat, CollectionId>,240			Key<Twox64Concat, TokenId>,241			// Owner242			Key<Blake2_128Concat, T::CrossAccountId>,243		),244		Value = u128,245		QueryKind = ValueQuery,246	>;247248	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.249	#[pallet::storage]250	pub type Allowance<T: Config> = StorageNMap<251		Key = (252			Key<Twox64Concat, CollectionId>,253			Key<Twox64Concat, TokenId>,254			// Owner255			Key<Blake2_128, T::CrossAccountId>,256			// Spender257			Key<Blake2_128Concat, T::CrossAccountId>,258		),259		Value = u128,260		QueryKind = ValueQuery,261	>;262263	#[pallet::hooks]264	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265		fn on_runtime_upgrade() -> Weight {266			let storage_version = StorageVersion::get::<Pallet<T>>();267			if storage_version < StorageVersion::new(2) {268				<TokenData<T>>::remove_all(None);269			}270			StorageVersion::new(2).put::<Pallet<T>>();271272			0273		}274	}275}276277pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);278impl<T: Config> RefungibleHandle<T> {279	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {280		Self(inner)281	}282	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {283		self.0284	}285	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {286		&mut self.0287	}288}289290impl<T: Config> Deref for RefungibleHandle<T> {291	type Target = pallet_common::CollectionHandle<T>;292293	fn deref(&self) -> &Self::Target {294		&self.0295	}296}297298impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {299	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {300		self.0.recorder()301	}302	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {303		self.0.into_recorder()304	}305}306307impl<T: Config> Pallet<T> {308	/// Get number of RFT tokens in collection309	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {310		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)311	}312313	/// Check that RFT token exists314	///315	/// - `token`: Token ID.316	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {317		<TotalSupply<T>>::contains_key((collection.id, token))318	}319320	pub fn set_scoped_token_property(321		collection_id: CollectionId,322		token_id: TokenId,323		scope: PropertyScope,324		property: Property,325	) -> DispatchResult {326		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {327			properties.try_scoped_set(scope, property.key, property.value)328		})329		.map_err(<CommonError<T>>::from)?;330331		Ok(())332	}333334	pub fn set_scoped_token_properties(335		collection_id: CollectionId,336		token_id: TokenId,337		scope: PropertyScope,338		properties: impl Iterator<Item = Property>,339	) -> DispatchResult {340		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {341			stored_properties.try_scoped_set_from_iter(scope, properties)342		})343		.map_err(<CommonError<T>>::from)?;344345		Ok(())346	}347}348349// unchecked calls skips any permission checks350impl<T: Config> Pallet<T> {351	/// Create RFT collection352	///353	/// `init_collection` will take non-refundable deposit for collection creation.354	///355	/// - `data`: Contains settings for collection limits and permissions.356	pub fn init_collection(357		owner: T::CrossAccountId,358		data: CreateCollectionData<T::AccountId>,359	) -> Result<CollectionId, DispatchError> {360		<PalletCommon<T>>::init_collection(owner, data, false)361	}362363	/// Destroy RFT collection364	///365	/// `destroy_collection` will throw error if collection contains any tokens.366	/// Only owner can destroy collection.367	pub fn destroy_collection(368		collection: RefungibleHandle<T>,369		sender: &T::CrossAccountId,370	) -> DispatchResult {371		let id = collection.id;372373		if Self::collection_has_tokens(id) {374			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());375		}376377		// =========378379		PalletCommon::destroy_collection(collection.0, sender)?;380381		<TokensMinted<T>>::remove(id);382		<TokensBurnt<T>>::remove(id);383		<TotalSupply<T>>::remove_prefix((id,), None);384		<Balance<T>>::remove_prefix((id,), None);385		<Allowance<T>>::remove_prefix((id,), None);386		<Owned<T>>::remove_prefix((id,), None);387		<AccountBalance<T>>::remove_prefix((id,), None);388		Ok(())389	}390391	fn collection_has_tokens(collection_id: CollectionId) -> bool {392		<TotalSupply<T>>::iter_prefix((collection_id,))393			.next()394			.is_some()395	}396397	pub fn burn_token_unchecked(398		collection: &RefungibleHandle<T>,399		token_id: TokenId,400	) -> DispatchResult {401		let burnt = <TokensBurnt<T>>::get(collection.id)402			.checked_add(1)403			.ok_or(ArithmeticError::Overflow)?;404405		<TokensBurnt<T>>::insert(collection.id, burnt);406		<TokenProperties<T>>::remove((collection.id, token_id));407		<TotalSupply<T>>::remove((collection.id, token_id));408		<Balance<T>>::remove_prefix((collection.id, token_id), None);409		<Allowance<T>>::remove_prefix((collection.id, token_id), None);410		// TODO: ERC721 transfer event411		Ok(())412	}413414	/// Burn RFT token pieces415	///416	/// `burn` will decrease total amount of token pieces and amount owned by sender.417	/// `burn` can be called even if there are multiple owners of the RFT token.418	/// If sender wouldn't have any pieces left after `burn` than she will stop being419	/// one of the owners of the token. If there is no account that owns any pieces of420	/// the token than token will be burned too.421	///422	/// - `amount`: Amount of token pieces to burn.423	/// - `token`: Token who's pieces should be burned424	/// - `collection`: Collection that contains the token425	pub fn burn(426		collection: &RefungibleHandle<T>,427		owner: &T::CrossAccountId,428		token: TokenId,429		amount: u128,430	) -> DispatchResult {431		let total_supply = <TotalSupply<T>>::get((collection.id, token))432			.checked_sub(amount)433			.ok_or(<CommonError<T>>::TokenValueTooLow)?;434435		// This was probally last owner of this token?436		if total_supply == 0 {437			// Ensure user actually owns this amount438			ensure!(439				<Balance<T>>::get((collection.id, token, owner)) == amount,440				<CommonError<T>>::TokenValueTooLow441			);442			let account_balance = <AccountBalance<T>>::get((collection.id, owner))443				.checked_sub(1)444				// Should not occur445				.ok_or(ArithmeticError::Underflow)?;446447			// =========448449			<Owned<T>>::remove((collection.id, owner, token));450			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);451			<AccountBalance<T>>::insert((collection.id, owner), account_balance);452			Self::burn_token_unchecked(collection, token)?;453			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(454				collection.id,455				token,456				owner.clone(),457				amount,458			));459			return Ok(());460		}461462		let balance = <Balance<T>>::get((collection.id, token, owner))463			.checked_sub(amount)464			.ok_or(<CommonError<T>>::TokenValueTooLow)?;465		let account_balance = if balance == 0 {466			<AccountBalance<T>>::get((collection.id, owner))467				.checked_sub(1)468				// Should not occur469				.ok_or(ArithmeticError::Underflow)?470		} else {471			0472		};473474		// =========475476		if balance == 0 {477			<Owned<T>>::remove((collection.id, owner, token));478			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);479			<Balance<T>>::remove((collection.id, token, owner));480			<AccountBalance<T>>::insert((collection.id, owner), account_balance);481		} else {482			<Balance<T>>::insert((collection.id, token, owner), balance);483		}484		<TotalSupply<T>>::insert((collection.id, token), total_supply);485486		<PalletEvm<T>>::deposit_log(487			ERC20Events::Transfer {488				from: *owner.as_eth(),489				to: H160::default(),490				value: amount.into(),491			}492			.to_log(T::EvmTokenAddressMapping::token_to_address(493				collection.id,494				token,495			)),496		);497		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(498			collection.id,499			token,500			owner.clone(),501			amount,502		));503		Ok(())504	}505506	#[transactional]507	fn modify_token_properties(508		collection: &RefungibleHandle<T>,509		sender: &T::CrossAccountId,510		token_id: TokenId,511		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,512		is_token_create: bool,513		nesting_budget: &dyn Budget,514	) -> DispatchResult {515		let is_collection_admin = || collection.is_owner_or_admin(sender);516		let is_token_owner = || -> Result<bool, DispatchError> {517			let balance = collection.balance(sender.clone(), token_id);518			let total_pieces: u128 =519				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);520			if balance != total_pieces {521				return Ok(false);522			}523524			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(525				sender.clone(),526				collection.id,527				token_id,528				None,529				nesting_budget,530			)?;531532			Ok(is_bundle_owner)533		};534535		for (key, value) in properties {536			let permission = <PalletCommon<T>>::property_permissions(collection.id)537				.get(&key)538				.cloned()539				.unwrap_or_else(PropertyPermission::none);540541			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))542				.get(&key)543				.is_some();544545			match permission {546				PropertyPermission { mutable: false, .. } if is_property_exists => {547					return Err(<CommonError<T>>::NoPermission.into());548				}549550				PropertyPermission {551					collection_admin,552					token_owner,553					..554				} => {555					//TODO: investigate threats during public minting.556					let is_token_create =557						is_token_create && (collection_admin || token_owner) && value.is_some();558					if !(is_token_create559						|| (collection_admin && is_collection_admin())560						|| (token_owner && is_token_owner()?))561					{562						fail!(<CommonError<T>>::NoPermission);563					}564				}565			}566567			match value {568				Some(value) => {569					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {570						properties.try_set(key.clone(), value)571					})572					.map_err(<CommonError<T>>::from)?;573574					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(575						collection.id,576						token_id,577						key,578					));579				}580				None => {581					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582						properties.remove(&key)583					})584					.map_err(<CommonError<T>>::from)?;585586					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(587						collection.id,588						token_id,589						key,590					));591				}592			}593		}594595		Ok(())596	}597598	pub fn set_token_properties(599		collection: &RefungibleHandle<T>,600		sender: &T::CrossAccountId,601		token_id: TokenId,602		properties: impl Iterator<Item = Property>,603		is_token_create: bool,604		nesting_budget: &dyn Budget,605	) -> DispatchResult {606		Self::modify_token_properties(607			collection,608			sender,609			token_id,610			properties.map(|p| (p.key, Some(p.value))),611			is_token_create,612			nesting_budget,613		)614	}615616	pub fn set_token_property(617		collection: &RefungibleHandle<T>,618		sender: &T::CrossAccountId,619		token_id: TokenId,620		property: Property,621		nesting_budget: &dyn Budget,622	) -> DispatchResult {623		let is_token_create = false;624625		Self::set_token_properties(626			collection,627			sender,628			token_id,629			[property].into_iter(),630			is_token_create,631			nesting_budget,632		)633	}634635	pub fn delete_token_properties(636		collection: &RefungibleHandle<T>,637		sender: &T::CrossAccountId,638		token_id: TokenId,639		property_keys: impl Iterator<Item = PropertyKey>,640		nesting_budget: &dyn Budget,641	) -> DispatchResult {642		let is_token_create = false;643644		Self::modify_token_properties(645			collection,646			sender,647			token_id,648			property_keys.into_iter().map(|key| (key, None)),649			is_token_create,650			nesting_budget,651		)652	}653654	pub fn delete_token_property(655		collection: &RefungibleHandle<T>,656		sender: &T::CrossAccountId,657		token_id: TokenId,658		property_key: PropertyKey,659		nesting_budget: &dyn Budget,660	) -> DispatchResult {661		Self::delete_token_properties(662			collection,663			sender,664			token_id,665			[property_key].into_iter(),666			nesting_budget,667		)668	}669670	/// Transfer RFT token pieces from one account to another.671	///672	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.673	///674	/// - `from`: Owner of token pieces to transfer.675	/// - `to`: Recepient of transfered token pieces.676	/// - `amount`: Amount of token pieces to transfer.677	/// - `token`: Token whos pieces should be transfered678	/// - `collection`: Collection that contains the token679	pub fn transfer(680		collection: &RefungibleHandle<T>,681		from: &T::CrossAccountId,682		to: &T::CrossAccountId,683		token: TokenId,684		amount: u128,685		nesting_budget: &dyn Budget,686	) -> DispatchResult {687		ensure!(688			collection.limits.transfers_enabled(),689			<CommonError<T>>::TransferNotAllowed690		);691692		if collection.permissions.access() == AccessMode::AllowList {693			collection.check_allowlist(from)?;694			collection.check_allowlist(to)?;695		}696		<PalletCommon<T>>::ensure_correct_receiver(to)?;697698		let balance_from = <Balance<T>>::get((collection.id, token, from))699			.checked_sub(amount)700			.ok_or(<CommonError<T>>::TokenValueTooLow)?;701		let mut create_target = false;702		let from_to_differ = from != to;703		let balance_to = if from != to {704			let old_balance = <Balance<T>>::get((collection.id, token, to));705			if old_balance == 0 {706				create_target = true;707			}708			Some(709				old_balance710					.checked_add(amount)711					.ok_or(ArithmeticError::Overflow)?,712			)713		} else {714			None715		};716717		let account_balance_from = if balance_from == 0 {718			Some(719				<AccountBalance<T>>::get((collection.id, from))720					.checked_sub(1)721					// Should not occur722					.ok_or(ArithmeticError::Underflow)?,723			)724		} else {725			None726		};727		// Account data is created in token, AccountBalance should be increased728		// But only if from != to as we shouldn't check overflow in this case729		let account_balance_to = if create_target && from_to_differ {730			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))731				.checked_add(1)732				.ok_or(ArithmeticError::Overflow)?;733			ensure!(734				account_balance_to < collection.limits.account_token_ownership_limit(),735				<CommonError<T>>::AccountTokenLimitExceeded,736			);737738			Some(account_balance_to)739		} else {740			None741		};742743		// =========744745		<PalletStructure<T>>::nest_if_sent_to_token(746			from.clone(),747			to,748			collection.id,749			token,750			nesting_budget,751		)?;752753		if let Some(balance_to) = balance_to {754			// from != to755			if balance_from == 0 {756				<Balance<T>>::remove((collection.id, token, from));757				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);758			} else {759				<Balance<T>>::insert((collection.id, token, from), balance_from);760			}761			<Balance<T>>::insert((collection.id, token, to), balance_to);762			if let Some(account_balance_from) = account_balance_from {763				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);764				<Owned<T>>::remove((collection.id, from, token));765			}766			if let Some(account_balance_to) = account_balance_to {767				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);768				<Owned<T>>::insert((collection.id, to, token), true);769			}770		}771772		<PalletEvm<T>>::deposit_log(773			ERC20Events::Transfer {774				from: *from.as_eth(),775				to: *to.as_eth(),776				value: amount.into(),777			}778			.to_log(T::EvmTokenAddressMapping::token_to_address(779				collection.id,780				token,781			)),782		);783		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(784			collection.id,785			token,786			from.clone(),787			to.clone(),788			amount,789		));790		Ok(())791	}792793	/// Batched operation to create multiple RFT tokens.794	///795	/// Same as `create_item` but creates multiple tokens.796	///797	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.798	pub fn create_multiple_items(799		collection: &RefungibleHandle<T>,800		sender: &T::CrossAccountId,801		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,802		nesting_budget: &dyn Budget,803	) -> DispatchResult {804		if !collection.is_owner_or_admin(sender) {805			ensure!(806				collection.permissions.mint_mode(),807				<CommonError<T>>::PublicMintingNotAllowed808			);809			collection.check_allowlist(sender)?;810811			for item in data.iter() {812				for user in item.users.keys() {813					collection.check_allowlist(user)?;814				}815			}816		}817818		for item in data.iter() {819			for (owner, _) in item.users.iter() {820				<PalletCommon<T>>::ensure_correct_receiver(owner)?;821			}822		}823824		// Total pieces per tokens825		let totals = data826			.iter()827			.map(|data| {828				Ok(data829					.users830					.iter()831					.map(|u| u.1)832					.try_fold(0u128, |acc, v| acc.checked_add(*v))833					.ok_or(ArithmeticError::Overflow)?)834			})835			.collect::<Result<Vec<_>, DispatchError>>()?;836		for total in &totals {837			ensure!(838				*total <= MAX_REFUNGIBLE_PIECES,839				<Error<T>>::WrongRefungiblePieces840			);841		}842843		let first_token_id = <TokensMinted<T>>::get(collection.id);844		let tokens_minted = first_token_id845			.checked_add(data.len() as u32)846			.ok_or(ArithmeticError::Overflow)?;847		ensure!(848			tokens_minted < collection.limits.token_limit(),849			<CommonError<T>>::CollectionTokenLimitExceeded850		);851852		let mut balances = BTreeMap::new();853		for data in &data {854			for owner in data.users.keys() {855				let balance = balances856					.entry(owner)857					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));858				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;859860				ensure!(861					*balance <= collection.limits.account_token_ownership_limit(),862					<CommonError<T>>::AccountTokenLimitExceeded,863				);864			}865		}866867		for (i, token) in data.iter().enumerate() {868			let token_id = TokenId(first_token_id + i as u32 + 1);869			for (to, _) in token.users.iter() {870				<PalletStructure<T>>::check_nesting(871					sender.clone(),872					to,873					collection.id,874					token_id,875					nesting_budget,876				)?;877			}878		}879880		// =========881882		with_transaction(|| {883			for (i, data) in data.iter().enumerate() {884				let token_id = first_token_id + i as u32 + 1;885				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);886887				for (user, amount) in data.users.iter() {888					if *amount == 0 {889						continue;890					}891					<Balance<T>>::insert((collection.id, token_id, &user), amount);892					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);893					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(894						user,895						collection.id,896						TokenId(token_id),897					);898				}899900				if let Err(e) = Self::set_token_properties(901					collection,902					sender,903					TokenId(token_id),904					data.properties.clone().into_iter(),905					true,906					nesting_budget,907				) {908					return TransactionOutcome::Rollback(Err(e));909				}910			}911			TransactionOutcome::Commit(Ok(()))912		})?;913914		<TokensMinted<T>>::insert(collection.id, tokens_minted);915916		for (account, balance) in balances {917			<AccountBalance<T>>::insert((collection.id, account), balance);918		}919920		for (i, token) in data.into_iter().enumerate() {921			let token_id = first_token_id + i as u32 + 1;922923			for (user, amount) in token.users.into_iter() {924				if amount == 0 {925					continue;926				}927928				<PalletEvm<T>>::deposit_log(929					ERC20Events::Transfer {930						from: H160::default(),931						to: *user.as_eth(),932						value: amount.into(),933					}934					.to_log(T::EvmTokenAddressMapping::token_to_address(935						collection.id,936						TokenId(token_id),937					)),938				);939				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(940					collection.id,941					TokenId(token_id),942					user,943					amount,944				));945			}946		}947		Ok(())948	}949950	pub fn set_allowance_unchecked(951		collection: &RefungibleHandle<T>,952		sender: &T::CrossAccountId,953		spender: &T::CrossAccountId,954		token: TokenId,955		amount: u128,956	) {957		if amount == 0 {958			<Allowance<T>>::remove((collection.id, token, sender, spender));959		} else {960			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);961		}962963		<PalletEvm<T>>::deposit_log(964			ERC20Events::Approval {965				owner: *sender.as_eth(),966				spender: *spender.as_eth(),967				value: amount.into(),968			}969			.to_log(T::EvmTokenAddressMapping::token_to_address(970				collection.id,971				token,972			)),973		);974		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(975			collection.id,976			token,977			sender.clone(),978			spender.clone(),979			amount,980		))981	}982983	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.984	///985	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.986	pub fn set_allowance(987		collection: &RefungibleHandle<T>,988		sender: &T::CrossAccountId,989		spender: &T::CrossAccountId,990		token: TokenId,991		amount: u128,992	) -> DispatchResult {993		if collection.permissions.access() == AccessMode::AllowList {994			collection.check_allowlist(sender)?;995			collection.check_allowlist(spender)?;996		}997998		<PalletCommon<T>>::ensure_correct_receiver(spender)?;9991000		if <Balance<T>>::get((collection.id, token, sender)) < amount {1001			ensure!(1002				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1003				<CommonError<T>>::CantApproveMoreThanOwned1004			);1005		}10061007		// =========10081009		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1010		Ok(())1011	}10121013	/// Returns allowance, which should be set after transaction1014	fn check_allowed(1015		collection: &RefungibleHandle<T>,1016		spender: &T::CrossAccountId,1017		from: &T::CrossAccountId,1018		token: TokenId,1019		amount: u128,1020		nesting_budget: &dyn Budget,1021	) -> Result<Option<u128>, DispatchError> {1022		if spender.conv_eq(from) {1023			return Ok(None);1024		}1025		if collection.permissions.access() == AccessMode::AllowList {1026			// `from`, `to` checked in [`transfer`]1027			collection.check_allowlist(spender)?;1028		}1029		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1030			// TODO: should collection owner be allowed to perform this transfer?1031			ensure!(1032				<PalletStructure<T>>::check_indirectly_owned(1033					spender.clone(),1034					source.0,1035					source.1,1036					None,1037					nesting_budget1038				)?,1039				<CommonError<T>>::ApprovedValueTooLow,1040			);1041			return Ok(None);1042		}1043		let allowance =1044			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1045		if allowance.is_none() {1046			ensure!(1047				collection.ignores_allowance(spender),1048				<CommonError<T>>::ApprovedValueTooLow1049			);1050		}1051		Ok(allowance)1052	}10531054	/// Transfer RFT token pieces from one account to another.1055	///1056	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1057	/// The owner should set allowance for the spender to transfer pieces.1058	///1059	/// [`transfer`]: struct.Pallet.html#method.transfer1060	pub fn transfer_from(1061		collection: &RefungibleHandle<T>,1062		spender: &T::CrossAccountId,1063		from: &T::CrossAccountId,1064		to: &T::CrossAccountId,1065		token: TokenId,1066		amount: u128,1067		nesting_budget: &dyn Budget,1068	) -> DispatchResult {1069		let allowance =1070			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10711072		// =========10731074		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1075		if let Some(allowance) = allowance {1076			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1077		}1078		Ok(())1079	}10801081	/// Burn RFT token pieces from the account.1082	///1083	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1084	/// set allowance for the spender to burn pieces1085	///1086	/// [`burn`]: struct.Pallet.html#method.burn1087	pub fn burn_from(1088		collection: &RefungibleHandle<T>,1089		spender: &T::CrossAccountId,1090		from: &T::CrossAccountId,1091		token: TokenId,1092		amount: u128,1093		nesting_budget: &dyn Budget,1094	) -> DispatchResult {1095		let allowance =1096			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10971098		// =========10991100		Self::burn(collection, from, token, amount)?;1101		if let Some(allowance) = allowance {1102			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1103		}1104		Ok(())1105	}11061107	/// Create RFT token.1108	///1109	/// The sender should be the owner/admin of the collection or collection should be configured1110	/// to allow public minting.1111	///1112	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1113	///   of token pieces they will receive.1114	pub fn create_item(1115		collection: &RefungibleHandle<T>,1116		sender: &T::CrossAccountId,1117		data: CreateRefungibleExData<T::CrossAccountId>,1118		nesting_budget: &dyn Budget,1119	) -> DispatchResult {1120		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1121	}11221123	/// Repartition RFT token.1124	///1125	/// `repartition` will set token balance of the sender and total amount of token pieces.1126	/// Sender should own all of the token pieces. `repartition' could be done even if some1127	/// token pieces were burned before.1128	///1129	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1130	pub fn repartition(1131		collection: &RefungibleHandle<T>,1132		owner: &T::CrossAccountId,1133		token: TokenId,1134		amount: u128,1135	) -> DispatchResult {1136		ensure!(1137			amount <= MAX_REFUNGIBLE_PIECES,1138			<Error<T>>::WrongRefungiblePieces1139		);1140		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1141		// Ensure user owns all pieces1142		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1143		let balance = <Balance<T>>::get((collection.id, token, owner));1144		ensure!(1145			total_pieces == balance,1146			<Error<T>>::RepartitionWhileNotOwningAllPieces1147		);11481149		<Balance<T>>::insert((collection.id, token, owner), amount);1150		<TotalSupply<T>>::insert((collection.id, token), amount);11511152		if amount > total_pieces {1153			let mint_amount = amount - total_pieces;1154			<PalletEvm<T>>::deposit_log(1155				ERC20Events::Transfer {1156					from: H160::default(),1157					to: *owner.as_eth(),1158					value: mint_amount.into(),1159				}1160				.to_log(T::EvmTokenAddressMapping::token_to_address(1161					collection.id,1162					token,1163				)),1164			);1165			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1166				collection.id,1167				token,1168				owner.clone(),1169				mint_amount,1170			));1171		} else if total_pieces > amount {1172			let burn_amount = total_pieces - amount;1173			<PalletEvm<T>>::deposit_log(1174				ERC20Events::Transfer {1175					from: *owner.as_eth(),1176					to: H160::default(),1177					value: burn_amount.into(),1178				}1179				.to_log(T::EvmTokenAddressMapping::token_to_address(1180					collection.id,1181					token,1182				)),1183			);1184			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1185				collection.id,1186				token,1187				owner.clone(),1188				burn_amount,1189			));1190		}11911192		Ok(())1193	}11941195	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1196		let mut owner = None;1197		let mut count = 0;1198		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1199			count += 1;1200			if count > 1 {1201				return None;1202			}1203			owner = Some(key);1204		}1205		owner1206	}12071208	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1209		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1210	}12111212	pub fn set_collection_properties(1213		collection: &RefungibleHandle<T>,1214		sender: &T::CrossAccountId,1215		properties: Vec<Property>,1216	) -> DispatchResult {1217		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1218	}12191220	pub fn delete_collection_properties(1221		collection: &RefungibleHandle<T>,1222		sender: &T::CrossAccountId,1223		property_keys: Vec<PropertyKey>,1224	) -> DispatchResult {1225		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1226	}12271228	pub fn set_token_property_permissions(1229		collection: &RefungibleHandle<T>,1230		sender: &T::CrossAccountId,1231		property_permissions: Vec<PropertyKeyPermission>,1232	) -> DispatchResult {1233		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1234	}12351236	/// Returns 10 token in no particular order.1237	///1238	/// There is no direct way to get token holders in ascending order,1239	/// since `iter_prefix` returns values in no particular order.1240	/// Therefore, getting the 10 largest holders with a large value of holders1241	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1242	pub fn token_owners(1243		collection_id: CollectionId,1244		token: TokenId,1245	) -> Option<Vec<T::CrossAccountId>> {1246		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1247			.map(|(owner, _amount)| owner)1248			.take(10)1249			.collect();12501251		if res.is_empty() {1252			None1253		} else {1254			Some(res)1255		}1256	}1257}
modifiedprimitives/data-structs/CHANGELOG.mddiffbeforeafterboth
--- a/primitives/data-structs/CHANGELOG.md
+++ b/primitives/data-structs/CHANGELOG.md
@@ -2,6 +2,9 @@
 
 All notable changes to this project will be documented in this file.
 
+## [v0.2.0] - 2022-08-01
+### Deprecated
+- `CreateReFungibleData::const_data`
 
 ## [v0.1.2] - 2022-07-25
 ### Added
modifiedprimitives/data-structs/Cargo.tomldiffbeforeafterboth
--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -6,7 +6,7 @@
 license = 'GPLv3'
 homepage = "https://unique.network"
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.2'
+version = '0.2.0'
 
 [dependencies]
 scale-info = { version = "2.0.1", default-features = false, features = [
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -780,12 +780,7 @@
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 #[derivative(Debug)]
 pub struct CreateReFungibleData {
-	/// Immutable metadata of the token
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
-	#[derivative(Debug(format_with = "bounded::vec_debug"))]
-	pub const_data: BoundedVec<u8, CustomDataLimit>,
-
-	/// Pieces of created token.
+	/// Number of pieces the RFT is split into
 	pub pieces: u128,
 
 	/// Key-value pairs used to describe the token as metadata
@@ -832,11 +827,6 @@
 #[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
 #[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
 pub struct CreateRefungibleExData<CrossAccountId> {
-	/// Custom data stored in token.
-	#[derivative(Debug(format_with = "bounded::vec_debug"))]
-	pub const_data: BoundedVec<u8, CustomDataLimit>,
-
-	/// Users who will be assigned the specified number of token parts.
 	#[derivative(Debug(format_with = "bounded::map_debug"))]
 	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
@@ -869,16 +859,6 @@
 	/// Extended data for create ReFungible item in case of
 	/// single token, which may have many owners
 	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
-}
-
-impl CreateItemData {
-	/// Get size of custom data.
-	pub fn data_size(&self) -> usize {
-		match self {
-			CreateItemData::ReFungible(data) => data.const_data.len(),
-			_ => 0,
-		}
-	}
 }
 
 impl From<CreateNftData> for CreateItemData {
modifiedruntime/common/src/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/src/sponsoring.rs
+++ b/runtime/common/src/sponsoring.rs
@@ -156,17 +156,13 @@
 pub fn withdraw_create_item<T: Config>(
 	collection: &CollectionHandle<T>,
 	who: &T::CrossAccountId,
-	_properties: &CreateItemData,
+	properties: &CreateItemData,
 ) -> Option<()> {
-	if _properties.data_size() as u32 > collection.limits.sponsored_data_size() {
-		return None;
-	}
-
 	// sponsor timeout
 	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
 	let limit = collection
 		.limits
-		.sponsor_transfer_timeout(match _properties {
+		.sponsor_transfer_timeout(match properties {
 			CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,
 			CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
 			CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -62,7 +62,6 @@
 
 fn default_re_fungible_data() -> CreateReFungibleData {
 	CreateReFungibleData {
-		const_data: vec![1, 2, 3].try_into().unwrap(),
 		pieces: 1023,
 		properties: vec![Property {
 			key: b"test-prop".to_vec().try_into().unwrap(),
@@ -298,7 +297,6 @@
 		let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
 		let balance =
 			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
-		assert_eq!(item.const_data, data.const_data.into_inner());
 		assert_eq!(balance, 1023);
 	});
 }
@@ -333,7 +331,6 @@
 			));
 			let balance =
 				<pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
-			assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
 			assert_eq!(balance, 1023);
 		}
 	});
@@ -446,7 +443,6 @@
 		let data = default_re_fungible_data();
 		create_test_item(collection_id, &data.clone().into());
 		let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
-		assert_eq!(item.const_data, data.const_data.into_inner());
 		assert_eq!(
 			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
 			1