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

difftreelog

feat xcm nft support

Daniel Shiposha2023-10-18parent: #5bde44b.patch.diff
in: master

5 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2351,6 +2351,11 @@
 	/// Is the collection a foreign one?
 	fn is_foreign(&self) -> bool;
 
+	/// Does the token have children?
+	fn token_has_children(&self, _token: TokenId) -> bool {
+		false
+	}
+
 	/// Create a collection's item using a transaction.
 	///
 	/// This function performs additional XCM-related checks before the actual creation.
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
before · pallets/foreign-assets/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//! # Foreign assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! Under construction2627#![cfg_attr(not(feature = "std"), no_std)]28#![allow(clippy::unused_unit)]2930use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::EnsureOrigin, PalletId};31use frame_system::pallet_prelude::*;32use pallet_common::{33	dispatch::CollectionDispatch, erc::CrossAccountId, XcmExtensions, NATIVE_FUNGIBLE_COLLECTION_ID,34};35use sp_runtime::traits::AccountIdConversion;36use sp_std::{vec, vec::Vec};37use staging_xcm::{38	opaque::latest::{prelude::XcmError, Weight},39	v3::{prelude::*, MultiAsset, XcmContext},40};41use staging_xcm_executor::{42	traits::{ConvertLocation, Error as XcmExecutorError, TransactAsset, WeightTrader},43	Assets,44};45use up_data_structs::{46	budget::ZeroBudget, CollectionId, CollectionMode, CollectionName, CreateCollectionData,47	CreateFungibleData, CreateItemData, CreateNftData, Property, PropertyKey, TokenId,48};4950pub mod weights;5152#[cfg(feature = "runtime-benchmarks")]53mod benchmarking;5455pub use module::*;56pub use weights::WeightInfo;5758#[frame_support::pallet]59pub mod module {60	use up_data_structs::{61		CollectionDescription, Property, PropertyKeyPermission, PropertyPermission,62	};6364	use super::*;6566	#[pallet::config]67	pub trait Config:68		frame_system::Config69		+ pallet_common::Config70		+ pallet_fungible::Config71		+ pallet_balances::Config72	{73		/// The overarching event type.74		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;7576		/// Origin for force registering of a foreign asset.77		type ForceRegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;7879		/// The ID of the foreign assets pallet.80		type PalletId: Get<PalletId>;8182		/// Self-location of this parachain.83		type SelfLocation: Get<MultiLocation>;8485		/// The converter from a MultiLocation to a CrossAccountId.86		type LocationToAccountId: ConvertLocation<Self::CrossAccountId>;8788		/// Weight information for the extrinsics in this module.89		type WeightInfo: WeightInfo;90	}9192	#[pallet::error]93	pub enum Error<T> {94		/// The foreign asset is already registered95		ForeignAssetAlreadyRegistered,96	}9798	#[pallet::event]99	#[pallet::generate_deposit(fn deposit_event)]100	pub enum Event<T: Config> {101		/// The foreign asset registered.102		ForeignAssetRegistered {103			asset_id: CollectionId,104			reserve_location: MultiLocation,105		},106	}107108	/// The corresponding collections of reserve locations.109	#[pallet::storage]110	#[pallet::getter(fn foreign_reserve_location_to_collection)]111	pub type ForeignReserveLocationToCollection<T: Config> =112		StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, CollectionId, OptionQuery>;113114	/// The corresponding reserve location of collections.115	#[pallet::storage]116	#[pallet::getter(fn collection_to_foreign_reserve_location)]117	pub type CollectionToForeignReserveLocation<T: Config> =118		StorageMap<_, Twox64Concat, CollectionId, staging_xcm::v3::MultiLocation, OptionQuery>;119120	/// The correponding NFT token id of reserve NFTs121	#[pallet::storage]122	#[pallet::getter(fn foreign_reserve_asset_instance_to_token_id)]123	pub type ForeignReserveAssetInstanceToTokenId<T: Config> = StorageDoubleMap<124		Hasher1 = Twox64Concat,125		Key1 = CollectionId,126		Hasher2 = Twox64Concat,127		Key2 = staging_xcm::v3::AssetInstance,128		Value = TokenId,129		QueryKind = OptionQuery,130	>;131132	#[pallet::pallet]133	pub struct Pallet<T>(_);134135	#[pallet::call]136	impl<T: Config> Pallet<T> {137		#[pallet::call_index(0)]138		#[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]139		pub fn force_register_foreign_asset(140			origin: OriginFor<T>,141			reserve_location: MultiLocation,142			name: CollectionName,143			mode: CollectionMode,144		) -> DispatchResult {145			T::ForceRegisterOrigin::ensure_origin(origin.clone())?;146147			let foreign_collection_owner = Self::pallet_account();148149			let description: CollectionDescription = "Foreign Assets Collection"150				.encode_utf16()151				.collect::<Vec<_>>()152				.try_into()153				.expect("description length < max description length; qed");154155			let collection_id = T::CollectionDispatch::create_foreign(156				foreign_collection_owner,157				CreateCollectionData {158					name,159					description,160					mode,161162					properties: vec![Property {163						key: Self::reserve_location_property_key(),164						value: reserve_location165							.encode()166							.try_into()167							.expect("multilocation is less than 32k; qed"),168					}]169					.try_into()170					.expect("just one property can always be stored; qed"),171172					token_property_permissions: vec![PropertyKeyPermission {173						key: Self::reserve_asset_instance_property_key(),174						permission: PropertyPermission {175							mutable: false,176							collection_admin: true,177							token_owner: false,178						},179					}]180					.try_into()181					.expect("just one property permission can always be stored; qed"),182					..Default::default()183				},184			)?;185186			<ForeignReserveLocationToCollection<T>>::insert(reserve_location, collection_id);187			<CollectionToForeignReserveLocation<T>>::insert(collection_id, reserve_location);188189			Self::deposit_event(Event::<T>::ForeignAssetRegistered {190				asset_id: collection_id,191				reserve_location,192			});193194			Ok(())195		}196	}197}198199impl<T: Config> Pallet<T> {200	fn pallet_account() -> T::CrossAccountId {201		let owner: T::AccountId = T::PalletId::get().into_account_truncating();202		T::CrossAccountId::from_sub(owner)203	}204205	fn reserve_location_property_key() -> PropertyKey {206		b"reserve-location"207			.to_vec()208			.try_into()209			.expect("key length < max property key length; qed")210	}211212	fn reserve_asset_instance_property_key() -> PropertyKey {213		b"reserve-asset-instance"214			.to_vec()215			.try_into()216			.expect("key length < max property key length; qed")217	}218219	fn native_asset_location_to_collection(220		asset_location: &MultiLocation,221	) -> Result<Option<CollectionId>, XcmError> {222		let self_location = T::SelfLocation::get();223224		if *asset_location == Here.into() {225			Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))226		} else if *asset_location == self_location {227			Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))228		} else if asset_location.parents == self_location.parents {229			match asset_location230				.interior231				.match_and_split(&self_location.interior)232			{233				Some(GeneralIndex(collection_id)) => Ok(Some(CollectionId(234					(*collection_id)235						.try_into()236						.map_err(|_| XcmExecutorError::AssetIdConversionFailed)?,237				))),238				_ => Ok(None),239			}240		} else {241			Ok(None)242		}243	}244245	fn multiasset_to_collection(asset: &MultiAsset) -> Result<CollectionId, XcmError> {246		let AssetId::Concrete(asset_reserve_location) = asset.id else {247			return Err(XcmExecutorError::AssetNotHandled.into());248		};249250		Self::native_asset_location_to_collection(&asset_reserve_location)?251			.or_else(|| Self::foreign_reserve_location_to_collection(asset_reserve_location))252			.ok_or_else(|| XcmExecutorError::AssetIdConversionFailed.into())253	}254255	fn native_asset_instance_to_token_id(256		asset_instance: &AssetInstance,257	) -> Result<TokenId, XcmError> {258		match asset_instance {259			AssetInstance::Index(token_id) => Ok(TokenId(260				(*token_id)261					.try_into()262					.map_err(|_| XcmError::AssetNotFound)?,263			)),264			_ => Err(XcmError::AssetNotFound),265		}266	}267268	/// Obtains the token id of the `asset_instance` in the collection.269	///270	/// Returns `Ok(None)` only if the `asset_instance` points to a foreign item271	/// and it haven't been created on this blockchain yet.272	///273	/// If the `asset_instance` points to a native item, it cannot return `Ok(None)`.274	fn asset_instance_to_token_id(275		xcm_ext: &dyn XcmExtensions<T>,276		collection_id: CollectionId,277		asset_instance: &AssetInstance,278	) -> Result<Option<TokenId>, XcmError> {279		if xcm_ext.is_foreign() {280			Ok(Self::foreign_reserve_asset_instance_to_token_id(281				collection_id,282				asset_instance,283			))284		} else {285			Self::native_asset_instance_to_token_id(asset_instance).map(Some)286		}287	}288289	fn create_foreign_asset_instance(290		xcm_ext: &dyn XcmExtensions<T>,291		collection_id: CollectionId,292		asset_instance: &AssetInstance,293		to: T::CrossAccountId,294	) -> XcmResult {295		let asset_instance_encoded = asset_instance.encode();296297		let derivative_token_id = xcm_ext298			.create_item(299				&Self::pallet_account(),300				to,301				CreateItemData::NFT(CreateNftData {302					properties: vec![Property {303					key: Self::reserve_asset_instance_property_key(),304					value: asset_instance_encoded305						.try_into()306						.expect("asset instance length <= 32 bytes which is less than value length limit; qed"),307				}]308					.try_into()309					.expect("just one property can always be stored; qed"),310				}),311				&ZeroBudget,312			)313			.map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))?;314315		<ForeignReserveAssetInstanceToTokenId<T>>::insert(316			collection_id,317			asset_instance,318			derivative_token_id,319		);320321		Ok(())322	}323324	fn deposit_asset_instance(325		xcm_ext: &dyn XcmExtensions<T>,326		collection_id: CollectionId,327		to: T::CrossAccountId,328		asset_instance: &AssetInstance,329	) -> XcmResult {330		if let Some(token_id) =331			Self::asset_instance_to_token_id(xcm_ext, collection_id, asset_instance)?332		{333			let depositor = &Self::pallet_account();334			let from = depositor;335			let amount = 1;336337			xcm_ext338				.transfer_item(depositor, from, &to, token_id, amount, &ZeroBudget)339				.map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))340		} else {341			Self::create_foreign_asset_instance(xcm_ext, collection_id, asset_instance, to)342		}343	}344}345346impl<T: Config> TransactAsset for Pallet<T> {347	fn can_check_in(348		_origin: &MultiLocation,349		_what: &MultiAsset,350		_context: &XcmContext,351	) -> XcmResult {352		Err(XcmError::Unimplemented)353	}354355	fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}356357	fn can_check_out(358		_dest: &MultiLocation,359		_what: &MultiAsset,360		_context: &XcmContext,361	) -> XcmResult {362		Err(XcmError::Unimplemented)363	}364365	fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}366367	fn deposit_asset(what: &MultiAsset, to: &MultiLocation, context: &XcmContext) -> XcmResult {368		let collection_id = Self::multiasset_to_collection(what)?;369		let dispatch =370			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;371372		let collection = dispatch.as_dyn();373		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::Unimplemented)?;374375		let to = T::LocationToAccountId::convert_location(to)376			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;377378		match what.fun {379			Fungibility::Fungible(amount) => xcm_ext380				.create_item(381					&Self::pallet_account(),382					to,383					CreateItemData::Fungible(CreateFungibleData { value: amount }),384					&ZeroBudget,385				)386				.map(|_| ())387				.map_err(|_| XcmError::FailedToTransactAsset("fungible item deposit failed")),388389			Fungibility::NonFungible(asset_instance) => {390				Self::deposit_asset_instance(xcm_ext, collection_id, to, &asset_instance)391			}392		}393	}394395	fn withdraw_asset(396		what: &MultiAsset,397		from: &MultiLocation,398		_maybe_context: Option<&XcmContext>,399	) -> Result<staging_xcm_executor::Assets, XcmError> {400		Err(XcmError::Unimplemented)401	}402403	fn internal_transfer_asset(404		what: &MultiAsset,405		from: &MultiLocation,406		to: &MultiLocation,407		_context: &XcmContext,408	) -> Result<staging_xcm_executor::Assets, XcmError> {409		Err(XcmError::Unimplemented)410	}411}412413pub struct CurrencyIdConvert<T: Config>(PhantomData<T>);414impl<T: Config> sp_runtime::traits::Convert<CollectionId, Option<MultiLocation>>415	for CurrencyIdConvert<T>416{417	fn convert(collection_id: CollectionId) -> Option<MultiLocation> {418		if collection_id == NATIVE_FUNGIBLE_COLLECTION_ID {419			Some(Here.into())420		} else {421			let dispatch = T::CollectionDispatch::dispatch(collection_id).ok()?;422			let collection = dispatch.as_dyn();423			let xcm_ext = collection.xcm_extensions()?;424425			if xcm_ext.is_foreign() {426				<Pallet<T>>::collection_to_foreign_reserve_location(collection_id)427			} else {428				T::SelfLocation::get()429					.pushed_with_interior(GeneralIndex(collection_id.0.into()))430					.ok()431			}432		}433	}434}435436pub use frame_support::{437	traits::{438		fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,439	},440	weights::{WeightToFee, WeightToFeePolynomial},441};442443pub struct FreeForAll;444445impl WeightTrader for FreeForAll {446	fn new() -> Self {447		Self448	}449450	fn buy_weight(451		&mut self,452		weight: Weight,453		payment: Assets,454		_xcm: &XcmContext,455	) -> Result<Assets, XcmError> {456		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);457		Ok(payment)458	}459}
after · pallets/foreign-assets/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//! # Foreign assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! Under construction2627#![cfg_attr(not(feature = "std"), no_std)]28#![allow(clippy::unused_unit)]2930use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::EnsureOrigin, PalletId};31use frame_system::pallet_prelude::*;32use pallet_common::{33	dispatch::CollectionDispatch, erc::CrossAccountId, XcmExtensions, NATIVE_FUNGIBLE_COLLECTION_ID,34};35use sp_runtime::traits::AccountIdConversion;36use sp_std::{vec, vec::Vec};37use staging_xcm::{38	opaque::latest::{prelude::XcmError, Weight},39	v3::{prelude::*, MultiAsset, XcmContext},40};41use staging_xcm_executor::{42	traits::{ConvertLocation, Error as XcmExecutorError, TransactAsset, WeightTrader},43	Assets,44};45use up_data_structs::{46	budget::ZeroBudget, CollectionId, CollectionMode, CollectionName, CreateCollectionData,47	CreateFungibleData, CreateItemData, CreateNftData, Property, PropertyKey, TokenId,48};4950pub mod weights;5152#[cfg(feature = "runtime-benchmarks")]53mod benchmarking;5455pub use module::*;56pub use weights::WeightInfo;5758#[frame_support::pallet]59pub mod module {60	use up_data_structs::{61		CollectionDescription, Property, PropertyKeyPermission, PropertyPermission,62	};6364	use super::*;6566	#[pallet::config]67	pub trait Config:68		frame_system::Config69		+ pallet_common::Config70		+ pallet_fungible::Config71		+ pallet_balances::Config72	{73		/// The overarching event type.74		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;7576		/// Origin for force registering of a foreign asset.77		type ForceRegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;7879		/// The ID of the foreign assets pallet.80		type PalletId: Get<PalletId>;8182		/// Self-location of this parachain.83		type SelfLocation: Get<MultiLocation>;8485		/// The converter from a MultiLocation to a CrossAccountId.86		type LocationToAccountId: ConvertLocation<Self::CrossAccountId>;8788		/// Weight information for the extrinsics in this module.89		type WeightInfo: WeightInfo;90	}9192	#[pallet::error]93	pub enum Error<T> {94		/// The foreign asset is already registered95		ForeignAssetAlreadyRegistered,96	}9798	#[pallet::event]99	#[pallet::generate_deposit(fn deposit_event)]100	pub enum Event<T: Config> {101		/// The foreign asset registered.102		ForeignAssetRegistered {103			asset_id: CollectionId,104			reserve_location: MultiLocation,105		},106	}107108	/// The corresponding collections of reserve locations.109	#[pallet::storage]110	#[pallet::getter(fn foreign_reserve_location_to_collection)]111	pub type ForeignReserveLocationToCollection<T: Config> =112		StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, CollectionId, OptionQuery>;113114	/// The corresponding reserve location of collections.115	#[pallet::storage]116	#[pallet::getter(fn collection_to_foreign_reserve_location)]117	pub type CollectionToForeignReserveLocation<T: Config> =118		StorageMap<_, Twox64Concat, CollectionId, staging_xcm::v3::MultiLocation, OptionQuery>;119120	/// The correponding NFT token id of reserve NFTs121	#[pallet::storage]122	#[pallet::getter(fn foreign_reserve_asset_instance_to_token_id)]123	pub type ForeignReserveAssetInstanceToTokenId<T: Config> = StorageDoubleMap<124		Hasher1 = Twox64Concat,125		Key1 = CollectionId,126		Hasher2 = Twox64Concat,127		Key2 = staging_xcm::v3::AssetInstance,128		Value = TokenId,129		QueryKind = OptionQuery,130	>;131132	#[pallet::pallet]133	pub struct Pallet<T>(_);134135	#[pallet::call]136	impl<T: Config> Pallet<T> {137		#[pallet::call_index(0)]138		#[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]139		pub fn force_register_foreign_asset(140			origin: OriginFor<T>,141			reserve_location: MultiLocation,142			name: CollectionName,143			mode: CollectionMode,144		) -> DispatchResult {145			T::ForceRegisterOrigin::ensure_origin(origin.clone())?;146147			let foreign_collection_owner = Self::pallet_account();148149			let description: CollectionDescription = "Foreign Assets Collection"150				.encode_utf16()151				.collect::<Vec<_>>()152				.try_into()153				.expect("description length < max description length; qed");154155			let collection_id = T::CollectionDispatch::create_foreign(156				foreign_collection_owner,157				CreateCollectionData {158					name,159					description,160					mode,161162					properties: vec![Property {163						key: Self::reserve_location_property_key(),164						value: reserve_location165							.encode()166							.try_into()167							.expect("multilocation is less than 32k; qed"),168					}]169					.try_into()170					.expect("just one property can always be stored; qed"),171172					token_property_permissions: vec![PropertyKeyPermission {173						key: Self::reserve_asset_instance_property_key(),174						permission: PropertyPermission {175							mutable: false,176							collection_admin: true,177							token_owner: false,178						},179					}]180					.try_into()181					.expect("just one property permission can always be stored; qed"),182					..Default::default()183				},184			)?;185186			<ForeignReserveLocationToCollection<T>>::insert(reserve_location, collection_id);187			<CollectionToForeignReserveLocation<T>>::insert(collection_id, reserve_location);188189			Self::deposit_event(Event::<T>::ForeignAssetRegistered {190				asset_id: collection_id,191				reserve_location,192			});193194			Ok(())195		}196	}197}198199impl<T: Config> Pallet<T> {200	fn pallet_account() -> T::CrossAccountId {201		let owner: T::AccountId = T::PalletId::get().into_account_truncating();202		T::CrossAccountId::from_sub(owner)203	}204205	fn reserve_location_property_key() -> PropertyKey {206		b"reserve-location"207			.to_vec()208			.try_into()209			.expect("key length < max property key length; qed")210	}211212	fn reserve_asset_instance_property_key() -> PropertyKey {213		b"reserve-asset-instance"214			.to_vec()215			.try_into()216			.expect("key length < max property key length; qed")217	}218219	fn native_asset_location_to_collection(220		asset_location: &MultiLocation,221	) -> Result<Option<CollectionId>, XcmError> {222		let self_location = T::SelfLocation::get();223224		if *asset_location == Here.into() {225			Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))226		} else if *asset_location == self_location {227			Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))228		} else if asset_location.parents == self_location.parents {229			match asset_location230				.interior231				.match_and_split(&self_location.interior)232			{233				Some(GeneralIndex(collection_id)) => Ok(Some(CollectionId(234					(*collection_id)235						.try_into()236						.map_err(|_| XcmExecutorError::AssetIdConversionFailed)?,237				))),238				_ => Ok(None),239			}240		} else {241			Ok(None)242		}243	}244245	fn multiasset_to_collection(asset: &MultiAsset) -> Result<CollectionId, XcmError> {246		let AssetId::Concrete(asset_reserve_location) = asset.id else {247			return Err(XcmExecutorError::AssetNotHandled.into());248		};249250		Self::native_asset_location_to_collection(&asset_reserve_location)?251			.or_else(|| Self::foreign_reserve_location_to_collection(asset_reserve_location))252			.ok_or_else(|| XcmExecutorError::AssetIdConversionFailed.into())253	}254255	fn native_asset_instance_to_token_id(256		asset_instance: &AssetInstance,257	) -> Result<TokenId, XcmError> {258		match asset_instance {259			AssetInstance::Index(token_id) => Ok(TokenId(260				(*token_id)261					.try_into()262					.map_err(|_| XcmError::AssetNotFound)?,263			)),264			_ => Err(XcmError::AssetNotFound),265		}266	}267268	/// Obtains the token id of the `asset_instance` in the collection.269	///270	/// Returns `Ok(None)` only if the `asset_instance` points to a foreign item271	/// and it haven't been created on this blockchain yet.272	///273	/// If the `asset_instance` points to a native item, it cannot return `Ok(None)`.274	fn asset_instance_to_token_id(275		xcm_ext: &dyn XcmExtensions<T>,276		collection_id: CollectionId,277		asset_instance: &AssetInstance,278	) -> Result<Option<TokenId>, XcmError> {279		if xcm_ext.is_foreign() {280			Ok(Self::foreign_reserve_asset_instance_to_token_id(281				collection_id,282				asset_instance,283			))284		} else {285			Self::native_asset_instance_to_token_id(asset_instance).map(Some)286		}287	}288289	fn create_foreign_asset_instance(290		xcm_ext: &dyn XcmExtensions<T>,291		collection_id: CollectionId,292		asset_instance: &AssetInstance,293		to: T::CrossAccountId,294	) -> XcmResult {295		let asset_instance_encoded = asset_instance.encode();296297		let derivative_token_id = xcm_ext298			.create_item(299				&Self::pallet_account(),300				to,301				CreateItemData::NFT(CreateNftData {302					properties: vec![Property {303					key: Self::reserve_asset_instance_property_key(),304					value: asset_instance_encoded305						.try_into()306						.expect("asset instance length <= 32 bytes which is less than value length limit; qed"),307				}]308					.try_into()309					.expect("just one property can always be stored; qed"),310				}),311				&ZeroBudget,312			)313			.map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))?;314315		<ForeignReserveAssetInstanceToTokenId<T>>::insert(316			collection_id,317			asset_instance,318			derivative_token_id,319		);320321		Ok(())322	}323324	fn deposit_asset_instance(325		xcm_ext: &dyn XcmExtensions<T>,326		collection_id: CollectionId,327		to: T::CrossAccountId,328		asset_instance: &AssetInstance,329	) -> XcmResult {330		if let Some(token_id) =331			Self::asset_instance_to_token_id(xcm_ext, collection_id, asset_instance)?332		{333			let depositor = &Self::pallet_account();334			let from = depositor;335			let amount = 1;336337			xcm_ext338				.transfer_item(depositor, from, &to, token_id, amount, &ZeroBudget)339				.map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))340		} else {341			Self::create_foreign_asset_instance(xcm_ext, collection_id, asset_instance, to)342		}343	}344}345346impl<T: Config> TransactAsset for Pallet<T> {347	fn can_check_in(348		_origin: &MultiLocation,349		_what: &MultiAsset,350		_context: &XcmContext,351	) -> XcmResult {352		Err(XcmError::Unimplemented)353	}354355	fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}356357	fn can_check_out(358		_dest: &MultiLocation,359		_what: &MultiAsset,360		_context: &XcmContext,361	) -> XcmResult {362		Err(XcmError::Unimplemented)363	}364365	fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}366367	fn deposit_asset(what: &MultiAsset, to: &MultiLocation, _context: &XcmContext) -> XcmResult {368		let collection_id = Self::multiasset_to_collection(what)?;369		let dispatch =370			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;371372		let collection = dispatch.as_dyn();373		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::Unimplemented)?;374375		let to = T::LocationToAccountId::convert_location(to)376			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;377378		match what.fun {379			Fungibility::Fungible(amount) => xcm_ext380				.create_item(381					&Self::pallet_account(),382					to,383					CreateItemData::Fungible(CreateFungibleData { value: amount }),384					&ZeroBudget,385				)386				.map(|_| ())387				.map_err(|_| XcmError::FailedToTransactAsset("fungible item deposit failed")),388389			Fungibility::NonFungible(asset_instance) => {390				Self::deposit_asset_instance(xcm_ext, collection_id, to, &asset_instance)391			}392		}393	}394395	fn withdraw_asset(396		what: &MultiAsset,397		from: &MultiLocation,398		_maybe_context: Option<&XcmContext>,399	) -> Result<staging_xcm_executor::Assets, XcmError> {400		let from = T::LocationToAccountId::convert_location(from)401			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;402403		let collection_id = Self::multiasset_to_collection(what)?;404		let dispatch =405			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;406407		let collection = dispatch.as_dyn();408		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;409410		match what.fun {411			Fungibility::Fungible(amount) => xcm_ext412				.burn_item(from, TokenId::default(), amount)413				.map_err(|_| XcmError::FailedToTransactAsset("fungible item withdraw failed"))?,414415			Fungibility::NonFungible(asset_instance) => {416				let token_id =417					Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?418						.ok_or(XcmError::AssetNotFound)?;419420				if xcm_ext.token_has_children(token_id) {421					return Err(XcmError::Unimplemented);422				}423424				let depositor = &from;425				let to = Self::pallet_account();426				let amount = 1;427				xcm_ext428					.transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)429					.map_err(|_| {430						XcmError::FailedToTransactAsset("nonfungible item withdraw failed")431					})?;432			}433		}434435		Ok(what.clone().into())436	}437438	fn internal_transfer_asset(439		what: &MultiAsset,440		from: &MultiLocation,441		to: &MultiLocation,442		_context: &XcmContext,443	) -> Result<staging_xcm_executor::Assets, XcmError> {444		let collection_id = Self::multiasset_to_collection(what)?;445446		let dispatch =447			T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;448		let collection = dispatch.as_dyn();449		let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;450451		let from = T::LocationToAccountId::convert_location(from)452			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;453454		let to = T::LocationToAccountId::convert_location(to)455			.ok_or(XcmExecutorError::AccountIdConversionFailed)?;456457		let depositor = &from;458459		match what.fun {460			Fungibility::Fungible(amount) => xcm_ext461				.transfer_item(462					depositor,463					&from,464					&to,465					TokenId::default(),466					amount,467					&ZeroBudget,468				)469				.map_err(|_| XcmError::FailedToTransactAsset("fungible item transfer failed"))?,470471			Fungibility::NonFungible(asset_instance) => {472				let token_id =473					Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?474						.ok_or(XcmError::AssetNotFound)?;475476				let amount = 1;477478				xcm_ext479					.transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)480					.map_err(|_| {481						XcmError::FailedToTransactAsset("nonfungible item transfer failed")482					})?;483			}484		}485486		Ok(what.clone().into())487	}488}489490pub struct CurrencyIdConvert<T: Config>(PhantomData<T>);491impl<T: Config> sp_runtime::traits::Convert<CollectionId, Option<MultiLocation>>492	for CurrencyIdConvert<T>493{494	fn convert(collection_id: CollectionId) -> Option<MultiLocation> {495		if collection_id == NATIVE_FUNGIBLE_COLLECTION_ID {496			Some(Here.into())497		} else {498			let dispatch = T::CollectionDispatch::dispatch(collection_id).ok()?;499			let collection = dispatch.as_dyn();500			let xcm_ext = collection.xcm_extensions()?;501502			if xcm_ext.is_foreign() {503				<Pallet<T>>::collection_to_foreign_reserve_location(collection_id)504			} else {505				T::SelfLocation::get()506					.pushed_with_interior(GeneralIndex(collection_id.0.into()))507					.ok()508			}509		}510	}511}512513pub use frame_support::{514	traits::{515		fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,516	},517	weights::{WeightToFee, WeightToFeePolynomial},518};519520pub struct FreeForAll;521522impl WeightTrader for FreeForAll {523	fn new() -> Self {524		Self525	}526527	fn buy_weight(528		&mut self,529		weight: Weight,530		payment: Assets,531		_xcm: &XcmContext,532	) -> Result<Assets, XcmError> {533		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);534		Ok(payment)535	}536}
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -95,9 +95,8 @@
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
 use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
 use up_data_structs::{
-	budget::{Budget, ZeroBudget},
-	mapping::TokenAddressMapping,
-	AccessMode, CollectionId, CreateCollectionData, Property, PropertyKey, TokenId,
+	budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, Property, PropertyKey,
+	TokenId,
 };
 use weights::WeightInfo;
 
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -576,6 +576,10 @@
 		self.flags.foreign
 	}
 
+	fn token_has_children(&self, token: TokenId) -> bool {
+		<Pallet<T>>::token_has_children(self.id, token)
+	}
+
 	fn create_item_internal(
 		&self,
 		depositor: &<T>::CrossAccountId,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -117,8 +117,8 @@
 use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
 use up_data_structs::{
 	budget::Budget, mapping::TokenAddressMapping, AccessMode, AuxPropertyValue, CollectionId,
-	CreateCollectionData, CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property,
-	PropertyKey, PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
+	CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property, PropertyKey,
+	PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
 	TokenProperties as TokenPropertiesT,
 };
 use weights::WeightInfo;