git.delta.rocks / unique-network / refs/commits / 866ddf622d14

difftreelog

source

pallets/foreign-assets/src/lib.rs14.3 KiBsourcehistory
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//! The foreign assests pallet provides functions for:26//!27//! - Local and foreign assets management. The foreign assets can be updated without runtime upgrade.28//! - Bounds between asset and target collection for cross chain transfer and inner transfers.29//!30//! ## Overview31//!32//! Under construction3334#![cfg_attr(not(feature = "std"), no_std)]35#![allow(clippy::unused_unit)]3637use frame_support::{38	dispatch::DispatchResult,39	ensure,40	pallet_prelude::*,41	traits::{fungible, fungibles, Currency, EnsureOrigin},42	RuntimeDebug,43};44use frame_system::pallet_prelude::*;45use up_data_structs::{CollectionMode};46use pallet_fungible::{Pallet as PalletFungible};47use scale_info::{TypeInfo};48use sp_runtime::{49	traits::{One, Zero},50	ArithmeticError,51};52use sp_std::{boxed::Box, vec::Vec};53use up_data_structs::{CollectionId, TokenId, CreateCollectionData};5455// NOTE:v1::MultiLocation is used in storages, we would need to do migration if upgrade the56// MultiLocation in the future.57use xcm::opaque::latest::{prelude::XcmError, Weight};58use xcm::{v1::MultiLocation, VersionedMultiLocation};59use xcm_executor::{traits::WeightTrader, Assets};6061use pallet_common::erc::CrossAccountId;6263#[cfg(feature = "std")]64use serde::{Deserialize, Serialize};6566// TODO: Move to primitives67// Id of native currency.68// 0 - QTZ\UNQ69// 1 - KSM\DOT70#[derive(71	Clone,72	Copy,73	Eq,74	PartialEq,75	PartialOrd,76	Ord,77	MaxEncodedLen,78	RuntimeDebug,79	Encode,80	Decode,81	TypeInfo,82)]83#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]84pub enum NativeCurrency {85	Here = 0,86	Parent = 1,87}8889#[derive(90	Clone,91	Copy,92	Eq,93	PartialEq,94	PartialOrd,95	Ord,96	MaxEncodedLen,97	RuntimeDebug,98	Encode,99	Decode,100	TypeInfo,101)]102#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]103pub enum AssetIds {104	ForeignAssetId(ForeignAssetId),105	NativeAssetId(NativeCurrency),106}107108pub trait TryAsForeign<T, F> {109	fn try_as_foreign(asset: T) -> Option<F>;110}111112impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {113	fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {114		match asset {115			AssetIds::ForeignAssetId(id) => Some(id),116			_ => None,117		}118	}119}120121pub type ForeignAssetId = u32;122pub type CurrencyId = AssetIds;123124mod impl_fungibles;125pub mod weights;126127#[cfg(feature = "runtime-benchmarks")]128mod benchmarking;129130pub use module::*;131pub use weights::WeightInfo;132133/// Type alias for currency balance.134pub type BalanceOf<T> =135	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;136137/// A mapping between ForeignAssetId and AssetMetadata.138pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {139	/// Returns the AssetMetadata associated with a given ForeignAssetId.140	fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;141	/// Returns the MultiLocation associated with a given ForeignAssetId.142	fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;143	/// Returns the CurrencyId associated with a given MultiLocation.144	fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;145}146147pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);148149impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>150	for XcmForeignAssetIdMapping<T>151{152	fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {153		log::trace!(target: "fassets::asset_metadatas", "call");154		Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))155	}156157	fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {158		log::trace!(target: "fassets::get_multi_location", "call");159		Pallet::<T>::foreign_asset_locations(foreign_asset_id)160	}161162	fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {163		log::trace!(target: "fassets::get_currency_id", "call");164		Pallet::<T>::location_to_currency_ids(multi_location)165			.map(|id| AssetIds::ForeignAssetId(id))166	}167}168169#[frame_support::pallet]170pub mod module {171	use super::*;172173	#[pallet::config]174	pub trait Config:175		frame_system::Config176		+ pallet_common::Config177		+ pallet_fungible::Config178		+ orml_tokens::Config179		+ pallet_balances::Config180	{181		/// The overarching event type.182		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;183184		/// Currency type for withdraw and balance storage.185		type Currency: Currency<Self::AccountId>;186187		/// Required origin for registering asset.188		type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;189190		/// Weight information for the extrinsics in this module.191		type WeightInfo: WeightInfo;192	}193194	#[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]195	pub struct AssetMetadata<Balance> {196		pub name: Vec<u8>,197		pub symbol: Vec<u8>,198		pub decimals: u8,199		pub minimal_balance: Balance,200	}201202	#[pallet::error]203	pub enum Error<T> {204		/// The given location could not be used (e.g. because it cannot be expressed in the205		/// desired version of XCM).206		BadLocation,207		/// MultiLocation existed208		MultiLocationExisted,209		/// AssetId not exists210		AssetIdNotExists,211		/// AssetId exists212		AssetIdExisted,213	}214215	#[pallet::event]216	#[pallet::generate_deposit(fn deposit_event)]217	pub enum Event<T: Config> {218		/// The foreign asset registered.219		ForeignAssetRegistered {220			asset_id: ForeignAssetId,221			asset_address: MultiLocation,222			metadata: AssetMetadata<BalanceOf<T>>,223		},224		/// The foreign asset updated.225		ForeignAssetUpdated {226			asset_id: ForeignAssetId,227			asset_address: MultiLocation,228			metadata: AssetMetadata<BalanceOf<T>>,229		},230		/// The asset registered.231		AssetRegistered {232			asset_id: AssetIds,233			metadata: AssetMetadata<BalanceOf<T>>,234		},235		/// The asset updated.236		AssetUpdated {237			asset_id: AssetIds,238			metadata: AssetMetadata<BalanceOf<T>>,239		},240	}241242	/// Next available Foreign AssetId ID.243	///244	/// NextForeignAssetId: ForeignAssetId245	#[pallet::storage]246	#[pallet::getter(fn next_foreign_asset_id)]247	pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;248	/// The storages for MultiLocations.249	///250	/// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>251	#[pallet::storage]252	#[pallet::getter(fn foreign_asset_locations)]253	pub type ForeignAssetLocations<T: Config> =254		StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;255256	/// The storages for CurrencyIds.257	///258	/// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>259	#[pallet::storage]260	#[pallet::getter(fn location_to_currency_ids)]261	pub type LocationToCurrencyIds<T: Config> =262		StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;263264	/// The storages for AssetMetadatas.265	///266	/// AssetMetadatas: map AssetIds => Option<AssetMetadata>267	#[pallet::storage]268	#[pallet::getter(fn asset_metadatas)]269	pub type AssetMetadatas<T: Config> =270		StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;271272	/// The storages for assets to fungible collection binding273	///274	#[pallet::storage]275	#[pallet::getter(fn asset_binding)]276	pub type AssetBinding<T: Config> =277		StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;278279	#[pallet::pallet]280	#[pallet::without_storage_info]281	pub struct Pallet<T>(_);282283	#[pallet::call]284	impl<T: Config> Pallet<T> {285		#[pallet::call_index(0)]286		#[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]287		pub fn register_foreign_asset(288			origin: OriginFor<T>,289			owner: T::AccountId,290			location: Box<VersionedMultiLocation>,291			metadata: Box<AssetMetadata<BalanceOf<T>>>,292		) -> DispatchResult {293			T::RegisterOrigin::ensure_origin(origin.clone())?;294295			let location: MultiLocation = (*location)296				.try_into()297				.map_err(|()| Error::<T>::BadLocation)?;298299			let md = metadata.clone();300			let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();301			let mut description: Vec<u16> = "Foreign assets collection for "302				.encode_utf16()303				.collect::<Vec<u16>>();304			description.append(&mut name.clone());305306			let data: CreateCollectionData<T::AccountId> = CreateCollectionData {307				name: name.try_into().unwrap(),308				description: description.try_into().unwrap(),309				mode: CollectionMode::Fungible(md.decimals),310				..Default::default()311			};312			let owner = T::CrossAccountId::from_sub(owner);313			let bounded_collection_id =314				<PalletFungible<T>>::init_foreign_collection(owner.clone(), owner, data)?;315			let foreign_asset_id =316				Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;317318			Self::deposit_event(Event::<T>::ForeignAssetRegistered {319				asset_id: foreign_asset_id,320				asset_address: location,321				metadata: *metadata,322			});323			Ok(())324		}325326		#[pallet::call_index(1)]327		#[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]328		pub fn update_foreign_asset(329			origin: OriginFor<T>,330			foreign_asset_id: ForeignAssetId,331			location: Box<VersionedMultiLocation>,332			metadata: Box<AssetMetadata<BalanceOf<T>>>,333		) -> DispatchResult {334			T::RegisterOrigin::ensure_origin(origin)?;335336			let location: MultiLocation = (*location)337				.try_into()338				.map_err(|()| Error::<T>::BadLocation)?;339			Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;340341			Self::deposit_event(Event::<T>::ForeignAssetUpdated {342				asset_id: foreign_asset_id,343				asset_address: location,344				metadata: *metadata,345			});346			Ok(())347		}348	}349}350351impl<T: Config> Pallet<T> {352	fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {353		NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {354			let id = *current;355			*current = current356				.checked_add(One::one())357				.ok_or(ArithmeticError::Overflow)?;358			Ok(id)359		})360	}361362	fn do_register_foreign_asset(363		location: &MultiLocation,364		metadata: &AssetMetadata<BalanceOf<T>>,365		bounded_collection_id: CollectionId,366	) -> Result<ForeignAssetId, DispatchError> {367		let foreign_asset_id = Self::get_next_foreign_asset_id()?;368		LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {369			ensure!(370				maybe_currency_ids.is_none(),371				Error::<T>::MultiLocationExisted372			);373			*maybe_currency_ids = Some(foreign_asset_id);374			// *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));375376			ForeignAssetLocations::<T>::try_mutate(377				foreign_asset_id,378				|maybe_location| -> DispatchResult {379					ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);380					*maybe_location = Some(location.clone());381382					AssetMetadatas::<T>::try_mutate(383						AssetIds::ForeignAssetId(foreign_asset_id),384						|maybe_asset_metadatas| -> DispatchResult {385							ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);386							*maybe_asset_metadatas = Some(metadata.clone());387							Ok(())388						},389					)390				},391			)?;392393			AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {394				*collection_id = Some(bounded_collection_id);395				Ok(())396			})397		})?;398399		Ok(foreign_asset_id)400	}401402	fn do_update_foreign_asset(403		foreign_asset_id: ForeignAssetId,404		location: &MultiLocation,405		metadata: &AssetMetadata<BalanceOf<T>>,406	) -> DispatchResult {407		ForeignAssetLocations::<T>::try_mutate(408			foreign_asset_id,409			|maybe_multi_locations| -> DispatchResult {410				let old_multi_locations = maybe_multi_locations411					.as_mut()412					.ok_or(Error::<T>::AssetIdNotExists)?;413414				AssetMetadatas::<T>::try_mutate(415					AssetIds::ForeignAssetId(foreign_asset_id),416					|maybe_asset_metadatas| -> DispatchResult {417						ensure!(418							maybe_asset_metadatas.is_some(),419							Error::<T>::AssetIdNotExists420						);421422						// modify location423						if location != old_multi_locations {424							LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());425							LocationToCurrencyIds::<T>::try_mutate(426								location,427								|maybe_currency_ids| -> DispatchResult {428									ensure!(429										maybe_currency_ids.is_none(),430										Error::<T>::MultiLocationExisted431									);432									// *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));433									*maybe_currency_ids = Some(foreign_asset_id);434									Ok(())435								},436							)?;437						}438						*maybe_asset_metadatas = Some(metadata.clone());439						*old_multi_locations = location.clone();440						Ok(())441					},442				)443			},444		)445	}446}447448pub use frame_support::{449	traits::{450		fungibles::{Balanced, CreditOf},451		tokens::currency::Currency as CurrencyT,452		OnUnbalanced as OnUnbalancedT,453	},454	weights::{WeightToFeePolynomial, WeightToFee},455};456457pub struct FreeForAll<458	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,459	AssetId: Get<MultiLocation>,460	AccountId,461	Currency: CurrencyT<AccountId>,462	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,463>(464	Weight,465	Currency::Balance,466	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,467);468469impl<470		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,471		AssetId: Get<MultiLocation>,472		AccountId,473		Currency: CurrencyT<AccountId>,474		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,475	> WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>476{477	fn new() -> Self {478		Self(0, Zero::zero(), PhantomData)479	}480481	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {482		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);483		Ok(payment)484	}485}486impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop487	for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>488where489	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,490	AssetId: Get<MultiLocation>,491	Currency: CurrencyT<AccountId>,492	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,493{494	fn drop(&mut self) {495		OnUnbalanced::on_unbalanced(Currency::issue(self.1));496	}497}