git.delta.rocks / unique-network / refs/commits / 5db875a32d8f

difftreelog

refactor split refungible into its own pallet

Yaroslav Bolyukin2021-10-12parent: #6d7ceb4.patch.diff
in: master

8 files changed

addedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/Cargo.toml
@@ -0,0 +1,31 @@
+[package]
+name = "pallet-refungible"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies]
+frame-support = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+frame-system = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-runtime = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-std = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-core = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+pallet-common = { default-features = false, path = '../common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+
+[features]
+default = ["std"]
+std = [
+    "frame-support/std",
+    "frame-system/std",
+    "sp-runtime/std",
+    "sp-std/std",
+    "nft-data-structs/std",
+    "pallet-common/std",
+]
+runtime-benchmarks = []
addedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/benchmarking.rs
@@ -0,0 +1 @@
+#![cfg(feature = "runtime-benchmarking")]
addedpallets/refungible/src/common.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/common.rs
@@ -0,0 +1,201 @@
+use core::marker::PhantomData;
+
+use sp_std::collections::btree_map::BTreeMap;
+use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
+use nft_data_structs::TokenId;
+use pallet_common::{
+	CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
+};
+use sp_runtime::DispatchError;
+use sp_std::vec::Vec;
+
+use crate::{
+	AccountBalance, Allowance, Balance, Config, CreateItemData, DataKind, Error, Owned, Pallet,
+	RefungibleHandle, SelfWeightOf, TokenData, weights::WeightInfo,
+};
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+	fn create_item() -> Weight {
+		<SelfWeightOf<T>>::create_item()
+	}
+
+	fn create_multiple_items(amount: u32) -> Weight {
+		<SelfWeightOf<T>>::create_multiple_items(amount)
+	}
+
+	fn burn_item() -> Weight {
+		<SelfWeightOf<T>>::burn_item()
+	}
+
+	fn transfer() -> Weight {
+		<SelfWeightOf<T>>::transfer()
+	}
+
+	fn approve() -> Weight {
+		<SelfWeightOf<T>>::approve()
+	}
+
+	fn transfer_from() -> Weight {
+		<SelfWeightOf<T>>::transfer_from()
+	}
+
+	fn set_variable_metadata(_bytes: u32) -> Weight {
+		<SelfWeightOf<T>>::set_variable_metadata()
+	}
+}
+
+fn map_create_data<T: Config>(
+	data: nft_data_structs::CreateItemData,
+	to: &T::CrossAccountId,
+) -> Result<CreateItemData<T>, DispatchError> {
+	match data {
+		nft_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData {
+			const_data: data.const_data,
+			variable_data: data.variable_data,
+			users: {
+				let mut out = BTreeMap::new();
+				out.insert(to.clone(), data.pieces);
+				out
+			},
+		}),
+		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),
+	}
+}
+
+impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {
+	fn create_item(
+		&self,
+		sender: T::CrossAccountId,
+		to: T::CrossAccountId,
+		data: nft_data_structs::CreateItemData,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
+			<SelfWeightOf<T>>::create_item(),
+		)
+	}
+
+	fn create_multiple_items(
+		&self,
+		sender: T::CrossAccountId,
+		to: T::CrossAccountId,
+		data: Vec<nft_data_structs::CreateItemData>,
+	) -> DispatchResultWithPostInfo {
+		let data = data
+			.into_iter()
+			.map(|d| map_create_data::<T>(d, &to))
+			.collect::<Result<Vec<_>, DispatchError>>()?;
+
+		let amount = data.len();
+		with_weight(
+			<Pallet<T>>::create_multiple_items(self, &sender, data),
+			<SelfWeightOf<T>>::create_multiple_items(amount as u32),
+		)
+	}
+
+	fn burn_item(
+		&self,
+		sender: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::burn(self, &sender, token, amount),
+			<SelfWeightOf<T>>::burn_item(),
+		)
+	}
+
+	fn transfer(
+		&self,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::transfer(&self, &from, &to, token, amount),
+			<SelfWeightOf<T>>::transfer(),
+		)
+	}
+
+	fn approve(
+		&self,
+		sender: T::CrossAccountId,
+		spender: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_allowance(&self, &sender, &spender, token, amount),
+			<SelfWeightOf<T>>::approve(),
+		)
+	}
+
+	fn transfer_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::transfer_from(&self, &sender, &from, &to, token, amount),
+			<SelfWeightOf<T>>::approve(),
+		)
+	}
+
+	fn set_variable_metadata(
+		&self,
+		sender: T::CrossAccountId,
+		token: TokenId,
+		data: Vec<u8>,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
+			<SelfWeightOf<T>>::set_variable_metadata(),
+		)
+	}
+
+	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
+		<Owned<T>>::iter_prefix((self.id, account.as_sub()))
+			.map(|(id, _)| id)
+			.collect()
+	}
+
+	fn token_exists(&self, token: TokenId) -> bool {
+		<Pallet<T>>::token_exists(self, token)
+	}
+
+	fn token_owner(&self, _token: TokenId) -> T::CrossAccountId {
+		T::CrossAccountId::default()
+	}
+	fn const_metadata(&self, token: TokenId) -> Vec<u8> {
+		<TokenData<T>>::get((self.id, token, DataKind::Constant))
+	}
+	fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
+		<TokenData<T>>::get((self.id, token, DataKind::Variable))
+	}
+
+	fn collection_tokens(&self) -> u32 {
+		<Pallet<T>>::total_supply(self)
+	}
+
+	fn account_balance(&self, account: T::CrossAccountId) -> u32 {
+		<AccountBalance<T>>::get((self.id, account.as_sub()))
+	}
+
+	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
+		<Balance<T>>::get((self.id, token, account.as_sub()))
+	}
+
+	fn allowance(
+		&self,
+		sender: T::CrossAccountId,
+		spender: T::CrossAccountId,
+		token: TokenId,
+	) -> u128 {
+		<Allowance<T>>::get((self.id, token, sender.as_sub(), spender))
+	}
+}
addedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/erc.rs
@@ -0,0 +1,34 @@
+use nft_data_structs::TokenId;
+use pallet_common::erc::CommonEvmHandler;
+
+use crate::{Config, RefungibleHandle};
+
+impl<T: Config> CommonEvmHandler for RefungibleHandle<T> {
+	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
+
+	fn call(
+		self,
+		_source: &sp_core::H160,
+		_input: &[u8],
+		_value: sp_core::U256,
+	) -> Option<pallet_common::erc::PrecompileOutput> {
+		// TODO: Implement RFT variant of ERC721
+		None
+	}
+}
+
+pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
+
+impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T> {
+	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");
+
+	fn call(
+		self,
+		_source: &sp_core::H160,
+		_input: &[u8],
+		_value: sp_core::U256,
+	) -> Option<pallet_common::erc::PrecompileOutput> {
+		// TODO: Implement RFT variant of ERC20
+		None
+	}
+}
addedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/lib.rs
@@ -0,0 +1,572 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use frame_support::{ensure, BoundedVec};
+use nft_data_structs::{
+	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,
+	MAX_REFUNGIBLE_PIECES, TokenId,
+};
+use pallet_common::{
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
+};
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
+use core::ops::Deref;
+
+pub use pallet::*;
+pub mod benchmarking;
+pub mod common;
+pub mod erc;
+pub mod weights;
+pub struct CreateItemData<T: Config> {
+	pub const_data: BoundedVec<u8, CustomDataLimit>,
+	pub variable_data: BoundedVec<u8, CustomDataLimit>,
+	pub users: BTreeMap<T::CrossAccountId, u128>,
+}
+pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+
+#[frame_support::pallet]
+pub mod pallet {
+	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+	use sp_std::vec::Vec;
+	use nft_data_structs::{CollectionId, TokenId};
+	use super::weights::WeightInfo;
+
+	#[pallet::error]
+	pub enum Error<T> {
+		/// Not Refungible item data used to mint in Refungible collection.
+		NotRefungibleDataUsedToMintFungibleCollectionToken,
+		/// Maximum refungibility exceeded
+		WrongRefungiblePieces,
+	}
+
+	#[pallet::config]
+	pub trait Config: frame_system::Config + pallet_common::Config {
+		type WeightInfo: WeightInfo;
+	}
+
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	pub struct Pallet<T>(_);
+
+	#[pallet::storage]
+	pub(super) type TokensMinted<T: Config> =
+		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+	#[pallet::storage]
+	pub(super) type TokensBurnt<T: Config> =
+		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+
+	#[derive(Encode, Decode)]
+	pub enum DataKind {
+		Constant,
+		Variable,
+	}
+
+	#[pallet::storage]
+	pub(super) type TokenData<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, TokenId>,
+			Key<Identity, DataKind>,
+		),
+		Value = Vec<u8>,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type TotalSupply<T: Config> = StorageNMap<
+		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+		Value = u128,
+		QueryKind = ValueQuery,
+	>;
+
+	/// Used to enumerate tokens owned by account
+	#[pallet::storage]
+	pub(super) type Owned<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Blake2_128Concat, T::AccountId>,
+			Key<Twox64Concat, TokenId>,
+		),
+		Value = bool,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type AccountBalance<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			// Owner
+			Key<Blake2_128Concat, T::AccountId>,
+		),
+		Value = u32,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type Balance<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, TokenId>,
+			// Owner
+			Key<Blake2_128Concat, T::AccountId>,
+		),
+		Value = u128,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type Allowance<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, TokenId>,
+			// Owner
+			Key<Blake2_128, T::AccountId>,
+			// Spender
+			Key<Blake2_128Concat, T::CrossAccountId>,
+		),
+		Value = u128,
+		QueryKind = ValueQuery,
+	>;
+}
+
+pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
+impl<T: Config> RefungibleHandle<T> {
+	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {
+		Self(inner)
+	}
+	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
+		self.0
+	}
+}
+impl<T: Config> Deref for RefungibleHandle<T> {
+	type Target = pallet_common::CollectionHandle<T>;
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+
+impl<T: Config> Pallet<T> {
+	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {
+		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)
+	}
+	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {
+		<TotalSupply<T>>::contains_key((collection.id, token))
+	}
+}
+
+// unchecked calls skips any permission checks
+impl<T: Config> Pallet<T> {
+	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+		PalletCommon::init_collection(data)
+	}
+	pub fn destroy_collection(
+		collection: RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+	) -> DispatchResult {
+		let id = collection.id;
+
+		// =========
+
+		PalletCommon::destroy_collection(collection.0, sender)?;
+
+		<TokensMinted<T>>::remove(id);
+		<TokensBurnt<T>>::remove(id);
+		<TokenData<T>>::remove_prefix((id,), None);
+		<TotalSupply<T>>::remove_prefix((id,), None);
+		<Balance<T>>::remove_prefix((id,), None);
+		<Allowance<T>>::remove_prefix((id,), None);
+		Ok(())
+	}
+
+	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
+		let burnt = <TokensBurnt<T>>::get(collection.id)
+			.checked_add(1)
+			.ok_or(ArithmeticError::Overflow)?;
+
+		<TokensBurnt<T>>::insert(collection.id, burnt);
+		<TokenData<T>>::remove_prefix((collection.id, token_id), None);
+		<TotalSupply<T>>::remove((collection.id, token_id));
+		<Balance<T>>::remove_prefix((collection.id, token_id), None);
+		<Allowance<T>>::remove_prefix((collection.id, token_id), None);
+		// TODO: ERC721 transfer event
+		return Ok(());
+	}
+
+	pub fn burn(
+		collection: &RefungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		let total_supply = <TotalSupply<T>>::get((collection.id, token))
+			.checked_sub(amount)
+			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
+
+		// This was probally last owner of this token?
+		if total_supply == 0 {
+			// Ensure user actually owns this amount
+			ensure!(
+				<Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,
+				<CommonError<T>>::TokenValueTooLow
+			);
+
+			// =========
+
+			<Owned<T>>::remove((collection.id, owner.as_sub(), token));
+			Self::burn_token(collection, token)?;
+			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+				collection.id,
+				token,
+				owner.clone(),
+				amount,
+			));
+			return Ok(());
+		}
+
+		let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))
+			.checked_sub(amount)
+			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
+		let account_balance = if balance == 0 {
+			<AccountBalance<T>>::get((collection.id, owner.as_sub()))
+				.checked_sub(1)
+				// Should not occur
+				.ok_or(ArithmeticError::Underflow)?
+		} else {
+			0
+		};
+
+		// =========
+
+		if balance == 0 {
+			<Balance<T>>::remove((collection.id, token, owner.as_sub()));
+			<AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+		} else {
+			<Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);
+		}
+		<TotalSupply<T>>::insert((collection.id, token), total_supply);
+		// TODO: ERC20 transfer event
+		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+			collection.id,
+			token,
+			owner.clone(),
+			amount,
+		));
+		Ok(())
+	}
+
+	pub fn transfer(
+		collection: &RefungibleHandle<T>,
+		from: &T::CrossAccountId,
+		to: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		ensure!(
+			collection.transfers_enabled,
+			<CommonError<T>>::TransferNotAllowed
+		);
+
+		if collection.access == AccessMode::WhiteList {
+			collection.check_whitelist(from)?;
+			collection.check_whitelist(to)?;
+		}
+		<PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+		let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))
+			.checked_sub(amount)
+			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
+		let mut create_target = false;
+		let from_to_differ = from != to;
+		let balance_to = if from != to {
+			let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));
+			if old_balance == 0 {
+				create_target = true;
+			}
+			Some(
+				old_balance
+					.checked_add(amount)
+					.ok_or(ArithmeticError::Overflow)?,
+			)
+		} else {
+			None
+		};
+
+		let account_balance_from = if balance_from == 0 {
+			Some(
+				<AccountBalance<T>>::get((collection.id, from.as_sub()))
+					.checked_sub(1)
+					// Should not occur
+					.ok_or(ArithmeticError::Underflow)?,
+			)
+		} else {
+			None
+		};
+		// Account data is created in token, AccountBalance should be increased
+		// But only if from != to as we shouldn't check overflow in this case
+		let account_balance_to = if create_target && from_to_differ {
+			let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+				.checked_add(1)
+				.ok_or(ArithmeticError::Overflow)?;
+			ensure!(
+				account_balance_to < collection.limits.account_token_ownership_limit(),
+				<CommonError<T>>::AccountTokenLimitExceeded,
+			);
+
+			Some(account_balance_to)
+		} else {
+			None
+		};
+
+		// =========
+
+		if let Some(balance_to) = balance_to {
+			// from != to
+			if balance_from == 0 {
+				<Balance<T>>::remove((collection.id, token, from.as_sub()));
+			} else {
+				<Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);
+			}
+			<Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);
+			if let Some(account_balance_from) = account_balance_from {
+				<AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);
+			}
+			if let Some(account_balance_to) = account_balance_to {
+				<AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);
+			}
+
+			<Owned<T>>::remove((collection.id, from.as_sub(), token));
+			<Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+		}
+
+		// TODO: ERC20 transfer event
+		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(
+			collection.id,
+			token,
+			from.clone(),
+			to.clone(),
+			amount,
+		));
+		Ok(())
+	}
+
+	pub fn create_multiple_items(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		data: Vec<CreateItemData<T>>,
+	) -> DispatchResult {
+		let unrestricted_minting = collection.is_owner_or_admin(sender)?;
+		if !unrestricted_minting {
+			ensure!(
+				collection.mint_mode,
+				<CommonError<T>>::PublicMintingNotAllowed
+			);
+			collection.check_whitelist(sender)?;
+
+			for item in data.iter() {
+				for (user, _) in &item.users {
+					collection.check_whitelist(&user)?;
+				}
+			}
+		}
+
+		for item in data.iter() {
+			for (owner, _) in item.users.iter() {
+				<PalletCommon<T>>::ensure_correct_receiver(owner)?;
+			}
+		}
+
+		// Total pieces per tokens
+		let totals = data
+			.iter()
+			.map(|data| {
+				Ok(data
+					.users
+					.iter()
+					.map(|u| u.1)
+					.try_fold(0u128, |acc, v| acc.checked_add(*v))
+					.ok_or(ArithmeticError::Overflow)?)
+			})
+			.collect::<Result<Vec<_>, DispatchError>>()?;
+		for total in &totals {
+			ensure!(
+				*total <= MAX_REFUNGIBLE_PIECES,
+				<Error<T>>::WrongRefungiblePieces
+			);
+		}
+
+		let first_token_id = <TokensMinted<T>>::get(collection.id);
+		let tokens_minted = first_token_id
+			.checked_add(data.len() as u32)
+			.ok_or(ArithmeticError::Overflow)?;
+		ensure!(
+			tokens_minted < collection.limits.token_limit,
+			<CommonError<T>>::CollectionTokenLimitExceeded
+		);
+
+		let mut balances = BTreeMap::new();
+		for data in &data {
+			for (owner, _) in &data.users {
+				let balance = balances
+					.entry(owner.as_sub())
+					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));
+				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
+
+				ensure!(
+					*balance <= collection.limits.account_token_ownership_limit(),
+					<CommonError<T>>::AccountTokenLimitExceeded,
+				);
+			}
+		}
+
+		// =========
+
+		<TokensMinted<T>>::insert(collection.id, tokens_minted);
+		for (account, balance) in balances {
+			<AccountBalance<T>>::insert((collection.id, account), balance);
+		}
+		for (i, token) in data.into_iter().enumerate() {
+			let token_id = first_token_id + i as u32;
+			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
+
+			if !token.const_data.is_empty() {
+				<TokenData<T>>::insert(
+					(collection.id, token_id, DataKind::Constant),
+					token.const_data,
+				);
+			}
+			if !token.variable_data.is_empty() {
+				<TokenData<T>>::insert(
+					(collection.id, token_id, DataKind::Variable),
+					token.variable_data,
+				);
+			}
+			for (user, amount) in token.users.into_iter() {
+				if amount == 0 {
+					continue;
+				}
+				<Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);
+				<Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);
+				// TODO: ERC20 transfer event
+				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
+					collection.id,
+					TokenId(token_id),
+					user,
+					amount,
+				));
+			}
+		}
+		Ok(())
+	}
+
+	pub fn set_allowance_unchecked(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		spender: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) {
+		<Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);
+		// TODO: ERC20 approval event
+		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+			collection.id,
+			token,
+			sender.clone(),
+			spender.clone(),
+			amount,
+		))
+	}
+
+	pub fn set_allowance(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		spender: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		if collection.access == AccessMode::WhiteList {
+			collection.check_whitelist(&sender)?;
+			collection.check_whitelist(&spender)?;
+		}
+
+		<PalletCommon<T>>::ensure_correct_receiver(spender)?;
+
+		if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {
+			ensure!(
+				collection.ignores_owned_amount(sender)?,
+				<CommonError<T>>::CantApproveMoreThanOwned
+			);
+		}
+
+		// =========
+
+		Self::set_allowance_unchecked(collection, sender, spender, token, amount);
+		Ok(())
+	}
+
+	pub fn transfer_from(
+		collection: &RefungibleHandle<T>,
+		spender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		to: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		if spender == from {
+			return Self::transfer(collection, from, to, token, amount);
+		}
+		if collection.access == AccessMode::WhiteList {
+			// `from`, `to` checked in [`transfer`]
+			collection.check_whitelist(spender)?;
+		}
+
+		let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
+			.checked_sub(amount);
+		if allowance.is_none() {
+			ensure!(
+				collection.ignores_allowance(spender)?,
+				<CommonError<T>>::TokenValueNotEnough
+			);
+		}
+
+		// =========
+
+		Self::transfer(collection, from, to, token, amount)?;
+		if let Some(allowance) = allowance {
+			Self::set_allowance_unchecked(collection, from, spender, token, allowance);
+		}
+		Ok(())
+	}
+
+	pub fn set_variable_metadata(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		token: TokenId,
+		data: Vec<u8>,
+	) -> DispatchResult {
+		ensure!(
+			data.len() as u32 <= CUSTOM_DATA_LIMIT,
+			<CommonError<T>>::TokenVariableDataLimitExceeded
+		);
+		collection.check_can_update_meta(
+			sender,
+			&T::CrossAccountId::from_sub(collection.owner.clone()),
+		)?;
+
+		collection.consume_sstore()?;
+
+		// =========
+
+		<TokenData<T>>::insert((collection.id, token, DataKind::Variable), data);
+		Ok(())
+	}
+
+	/// Delegated to `create_multiple_items`
+	pub fn create_item(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		data: CreateItemData<T>,
+	) -> DispatchResult {
+		Self::create_multiple_items(collection, sender, vec![data])
+	}
+}
addedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/stubs/UniqueRefungible.raw
@@ -0,0 +1 @@
+TODO
addedpallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth

no changes

addedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/weights.rs
@@ -0,0 +1,37 @@
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+pub trait WeightInfo {
+	fn create_item() -> Weight;
+	fn create_multiple_items(b: u32) -> Weight;
+	fn burn_item() -> Weight;
+	fn transfer() -> Weight;
+	fn approve() -> Weight;
+	fn transfer_from() -> Weight;
+	fn set_variable_metadata() -> Weight;
+}
+
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+    fn create_item() -> Weight {0}
+	fn create_multiple_items(_b: u32) -> Weight {0}
+	fn burn_item() -> Weight {0}
+	fn transfer() -> Weight {0}
+	fn approve() -> Weight {0}
+	fn transfer_from() -> Weight {0}
+	fn set_variable_metadata() -> Weight {0}
+}
+
+impl WeightInfo for () {
+    fn create_item() -> Weight {0}
+	fn create_multiple_items(_b: u32) -> Weight {0}
+	fn burn_item() -> Weight {0}
+	fn transfer() -> Weight {0}
+	fn approve() -> Weight {0}
+	fn transfer_from() -> Weight {0}
+	fn set_variable_metadata() -> Weight {0}
+}