difftreelog
chore cargo fmt
in: master
4 files changed
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth1// 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;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 Some(AssetIds::ForeignAssetId(165 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),166 ))167 }168}169170#[frame_support::pallet]171pub mod module {172 use super::*;173174 #[pallet::config]175 pub trait Config:176 frame_system::Config177 + pallet_common::Config178 + pallet_fungible::Config179 + orml_tokens::Config180 + pallet_balances::Config181 {182 /// The overarching event type.183 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;184185 /// Currency type for withdraw and balance storage.186 type Currency: Currency<Self::AccountId>;187188 /// Required origin for registering asset.189 type RegisterOrigin: EnsureOrigin<Self::Origin>;190191 /// Weight information for the extrinsics in this module.192 type WeightInfo: WeightInfo;193 }194195 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]196 pub struct AssetMetadata<Balance> {197 pub name: Vec<u8>,198 pub symbol: Vec<u8>,199 pub decimals: u8,200 pub minimal_balance: Balance,201 }202203 #[pallet::error]204 pub enum Error<T> {205 /// The given location could not be used (e.g. because it cannot be expressed in the206 /// desired version of XCM).207 BadLocation,208 /// MultiLocation existed209 MultiLocationExisted,210 /// AssetId not exists211 AssetIdNotExists,212 /// AssetId exists213 AssetIdExisted,214 }215216 #[pallet::event]217 #[pallet::generate_deposit(fn deposit_event)]218 pub enum Event<T: Config> {219 /// The foreign asset registered.220 ForeignAssetRegistered {221 asset_id: ForeignAssetId,222 asset_address: MultiLocation,223 metadata: AssetMetadata<BalanceOf<T>>,224 },225 /// The foreign asset updated.226 ForeignAssetUpdated {227 asset_id: ForeignAssetId,228 asset_address: MultiLocation,229 metadata: AssetMetadata<BalanceOf<T>>,230 },231 /// The asset registered.232 AssetRegistered {233 asset_id: AssetIds,234 metadata: AssetMetadata<BalanceOf<T>>,235 },236 /// The asset updated.237 AssetUpdated {238 asset_id: AssetIds,239 metadata: AssetMetadata<BalanceOf<T>>,240 },241 }242243 /// Next available Foreign AssetId ID.244 ///245 /// NextForeignAssetId: ForeignAssetId246 #[pallet::storage]247 #[pallet::getter(fn next_foreign_asset_id)]248 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;249 /// The storages for MultiLocations.250 ///251 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>252 #[pallet::storage]253 #[pallet::getter(fn foreign_asset_locations)]254 pub type ForeignAssetLocations<T: Config> =255 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;256257 /// The storages for CurrencyIds.258 ///259 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>260 #[pallet::storage]261 #[pallet::getter(fn location_to_currency_ids)]262 pub type LocationToCurrencyIds<T: Config> =263 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;264265 /// The storages for AssetMetadatas.266 ///267 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>268 #[pallet::storage]269 #[pallet::getter(fn asset_metadatas)]270 pub type AssetMetadatas<T: Config> =271 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;272273 /// The storages for assets to fungible collection binding274 ///275 #[pallet::storage]276 #[pallet::getter(fn asset_binding)]277 pub type AssetBinding<T: Config> =278 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;279280 #[pallet::pallet]281 #[pallet::without_storage_info]282 pub struct Pallet<T>(_);283284 #[pallet::call]285 impl<T: Config> Pallet<T> {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 = <PalletFungible<T>>::init_foreign_collection(314 owner.clone(),315 owner,316 data,317 )?;318 let foreign_asset_id =319 Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;320321 Self::deposit_event(Event::<T>::ForeignAssetRegistered {322 asset_id: foreign_asset_id,323 asset_address: location,324 metadata: *metadata,325 });326 Ok(())327 }328329 #[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]330 pub fn update_foreign_asset(331 origin: OriginFor<T>,332 foreign_asset_id: ForeignAssetId,333 location: Box<VersionedMultiLocation>,334 metadata: Box<AssetMetadata<BalanceOf<T>>>,335 ) -> DispatchResult {336 T::RegisterOrigin::ensure_origin(origin)?;337338 let location: MultiLocation = (*location)339 .try_into()340 .map_err(|()| Error::<T>::BadLocation)?;341 Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;342343 Self::deposit_event(Event::<T>::ForeignAssetUpdated {344 asset_id: foreign_asset_id,345 asset_address: location,346 metadata: *metadata,347 });348 Ok(())349 }350 }351}352353impl<T: Config> Pallet<T> {354 fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {355 NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {356 let id = *current;357 *current = current358 .checked_add(One::one())359 .ok_or(ArithmeticError::Overflow)?;360 Ok(id)361 })362 }363364 fn do_register_foreign_asset(365 location: &MultiLocation,366 metadata: &AssetMetadata<BalanceOf<T>>,367 bounded_collection_id: CollectionId,368 ) -> Result<ForeignAssetId, DispatchError> {369 let foreign_asset_id = Self::get_next_foreign_asset_id()?;370 LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {371 ensure!(372 maybe_currency_ids.is_none(),373 Error::<T>::MultiLocationExisted374 );375 *maybe_currency_ids = Some(foreign_asset_id);376 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));377378 ForeignAssetLocations::<T>::try_mutate(379 foreign_asset_id,380 |maybe_location| -> DispatchResult {381 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);382 *maybe_location = Some(location.clone());383384 AssetMetadatas::<T>::try_mutate(385 AssetIds::ForeignAssetId(foreign_asset_id),386 |maybe_asset_metadatas| -> DispatchResult {387 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);388 *maybe_asset_metadatas = Some(metadata.clone());389 Ok(())390 },391 )392 },393 )?;394395 AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {396 *collection_id = Some(bounded_collection_id);397 Ok(())398 })399 })?;400401 Ok(foreign_asset_id)402 }403404 fn do_update_foreign_asset(405 foreign_asset_id: ForeignAssetId,406 location: &MultiLocation,407 metadata: &AssetMetadata<BalanceOf<T>>,408 ) -> DispatchResult {409 ForeignAssetLocations::<T>::try_mutate(410 foreign_asset_id,411 |maybe_multi_locations| -> DispatchResult {412 let old_multi_locations = maybe_multi_locations413 .as_mut()414 .ok_or(Error::<T>::AssetIdNotExists)?;415416 AssetMetadatas::<T>::try_mutate(417 AssetIds::ForeignAssetId(foreign_asset_id),418 |maybe_asset_metadatas| -> DispatchResult {419 ensure!(420 maybe_asset_metadatas.is_some(),421 Error::<T>::AssetIdNotExists422 );423424 // modify location425 if location != old_multi_locations {426 LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());427 LocationToCurrencyIds::<T>::try_mutate(428 location,429 |maybe_currency_ids| -> DispatchResult {430 ensure!(431 maybe_currency_ids.is_none(),432 Error::<T>::MultiLocationExisted433 );434 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));435 *maybe_currency_ids = Some(foreign_asset_id);436 Ok(())437 },438 )?;439 }440 *maybe_asset_metadatas = Some(metadata.clone());441 *old_multi_locations = location.clone();442 Ok(())443 },444 )445 },446 )447 }448}449450pub use frame_support::{451 traits::{452 fungibles::{Balanced, CreditOf},453 tokens::currency::Currency as CurrencyT,454 OnUnbalanced as OnUnbalancedT,455 },456 weights::{WeightToFeePolynomial, WeightToFee},457};458459pub struct FreeForAll<460 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,461 AssetId: Get<MultiLocation>,462 AccountId,463 Currency: CurrencyT<AccountId>,464 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,465>(466 Weight,467 Currency::Balance,468 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,469);470471impl<472 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,473 AssetId: Get<MultiLocation>,474 AccountId,475 Currency: CurrencyT<AccountId>,476 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,477 > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>478{479 fn new() -> Self {480 Self(0, Zero::zero(), PhantomData)481 }482483 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {484 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);485 Ok(payment)486 }487}488impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop489 for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>490where491 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,492 AssetId: Get<MultiLocation>,493 Currency: CurrencyT<AccountId>,494 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,495{496 fn drop(&mut self) {497 OnUnbalanced::on_unbalanced(Currency::issue(self.1));498 }499}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;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 Some(AssetIds::ForeignAssetId(165 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),166 ))167 }168}169170#[frame_support::pallet]171pub mod module {172 use super::*;173174 #[pallet::config]175 pub trait Config:176 frame_system::Config177 + pallet_common::Config178 + pallet_fungible::Config179 + orml_tokens::Config180 + pallet_balances::Config181 {182 /// The overarching event type.183 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;184185 /// Currency type for withdraw and balance storage.186 type Currency: Currency<Self::AccountId>;187188 /// Required origin for registering asset.189 type RegisterOrigin: EnsureOrigin<Self::Origin>;190191 /// Weight information for the extrinsics in this module.192 type WeightInfo: WeightInfo;193 }194195 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]196 pub struct AssetMetadata<Balance> {197 pub name: Vec<u8>,198 pub symbol: Vec<u8>,199 pub decimals: u8,200 pub minimal_balance: Balance,201 }202203 #[pallet::error]204 pub enum Error<T> {205 /// The given location could not be used (e.g. because it cannot be expressed in the206 /// desired version of XCM).207 BadLocation,208 /// MultiLocation existed209 MultiLocationExisted,210 /// AssetId not exists211 AssetIdNotExists,212 /// AssetId exists213 AssetIdExisted,214 }215216 #[pallet::event]217 #[pallet::generate_deposit(fn deposit_event)]218 pub enum Event<T: Config> {219 /// The foreign asset registered.220 ForeignAssetRegistered {221 asset_id: ForeignAssetId,222 asset_address: MultiLocation,223 metadata: AssetMetadata<BalanceOf<T>>,224 },225 /// The foreign asset updated.226 ForeignAssetUpdated {227 asset_id: ForeignAssetId,228 asset_address: MultiLocation,229 metadata: AssetMetadata<BalanceOf<T>>,230 },231 /// The asset registered.232 AssetRegistered {233 asset_id: AssetIds,234 metadata: AssetMetadata<BalanceOf<T>>,235 },236 /// The asset updated.237 AssetUpdated {238 asset_id: AssetIds,239 metadata: AssetMetadata<BalanceOf<T>>,240 },241 }242243 /// Next available Foreign AssetId ID.244 ///245 /// NextForeignAssetId: ForeignAssetId246 #[pallet::storage]247 #[pallet::getter(fn next_foreign_asset_id)]248 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;249 /// The storages for MultiLocations.250 ///251 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>252 #[pallet::storage]253 #[pallet::getter(fn foreign_asset_locations)]254 pub type ForeignAssetLocations<T: Config> =255 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;256257 /// The storages for CurrencyIds.258 ///259 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>260 #[pallet::storage]261 #[pallet::getter(fn location_to_currency_ids)]262 pub type LocationToCurrencyIds<T: Config> =263 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;264265 /// The storages for AssetMetadatas.266 ///267 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>268 #[pallet::storage]269 #[pallet::getter(fn asset_metadatas)]270 pub type AssetMetadatas<T: Config> =271 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;272273 /// The storages for assets to fungible collection binding274 ///275 #[pallet::storage]276 #[pallet::getter(fn asset_binding)]277 pub type AssetBinding<T: Config> =278 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;279280 #[pallet::pallet]281 #[pallet::without_storage_info]282 pub struct Pallet<T>(_);283284 #[pallet::call]285 impl<T: Config> Pallet<T> {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::weight(<T as Config>::WeightInfo::update_foreign_asset())]327 pub fn update_foreign_asset(328 origin: OriginFor<T>,329 foreign_asset_id: ForeignAssetId,330 location: Box<VersionedMultiLocation>,331 metadata: Box<AssetMetadata<BalanceOf<T>>>,332 ) -> DispatchResult {333 T::RegisterOrigin::ensure_origin(origin)?;334335 let location: MultiLocation = (*location)336 .try_into()337 .map_err(|()| Error::<T>::BadLocation)?;338 Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;339340 Self::deposit_event(Event::<T>::ForeignAssetUpdated {341 asset_id: foreign_asset_id,342 asset_address: location,343 metadata: *metadata,344 });345 Ok(())346 }347 }348}349350impl<T: Config> Pallet<T> {351 fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {352 NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {353 let id = *current;354 *current = current355 .checked_add(One::one())356 .ok_or(ArithmeticError::Overflow)?;357 Ok(id)358 })359 }360361 fn do_register_foreign_asset(362 location: &MultiLocation,363 metadata: &AssetMetadata<BalanceOf<T>>,364 bounded_collection_id: CollectionId,365 ) -> Result<ForeignAssetId, DispatchError> {366 let foreign_asset_id = Self::get_next_foreign_asset_id()?;367 LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {368 ensure!(369 maybe_currency_ids.is_none(),370 Error::<T>::MultiLocationExisted371 );372 *maybe_currency_ids = Some(foreign_asset_id);373 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));374375 ForeignAssetLocations::<T>::try_mutate(376 foreign_asset_id,377 |maybe_location| -> DispatchResult {378 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);379 *maybe_location = Some(location.clone());380381 AssetMetadatas::<T>::try_mutate(382 AssetIds::ForeignAssetId(foreign_asset_id),383 |maybe_asset_metadatas| -> DispatchResult {384 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);385 *maybe_asset_metadatas = Some(metadata.clone());386 Ok(())387 },388 )389 },390 )?;391392 AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {393 *collection_id = Some(bounded_collection_id);394 Ok(())395 })396 })?;397398 Ok(foreign_asset_id)399 }400401 fn do_update_foreign_asset(402 foreign_asset_id: ForeignAssetId,403 location: &MultiLocation,404 metadata: &AssetMetadata<BalanceOf<T>>,405 ) -> DispatchResult {406 ForeignAssetLocations::<T>::try_mutate(407 foreign_asset_id,408 |maybe_multi_locations| -> DispatchResult {409 let old_multi_locations = maybe_multi_locations410 .as_mut()411 .ok_or(Error::<T>::AssetIdNotExists)?;412413 AssetMetadatas::<T>::try_mutate(414 AssetIds::ForeignAssetId(foreign_asset_id),415 |maybe_asset_metadatas| -> DispatchResult {416 ensure!(417 maybe_asset_metadatas.is_some(),418 Error::<T>::AssetIdNotExists419 );420421 // modify location422 if location != old_multi_locations {423 LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());424 LocationToCurrencyIds::<T>::try_mutate(425 location,426 |maybe_currency_ids| -> DispatchResult {427 ensure!(428 maybe_currency_ids.is_none(),429 Error::<T>::MultiLocationExisted430 );431 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));432 *maybe_currency_ids = Some(foreign_asset_id);433 Ok(())434 },435 )?;436 }437 *maybe_asset_metadatas = Some(metadata.clone());438 *old_multi_locations = location.clone();439 Ok(())440 },441 )442 },443 )444 }445}446447pub use frame_support::{448 traits::{449 fungibles::{Balanced, CreditOf},450 tokens::currency::Currency as CurrencyT,451 OnUnbalanced as OnUnbalancedT,452 },453 weights::{WeightToFeePolynomial, WeightToFee},454};455456pub struct FreeForAll<457 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,458 AssetId: Get<MultiLocation>,459 AccountId,460 Currency: CurrencyT<AccountId>,461 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,462>(463 Weight,464 Currency::Balance,465 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,466);467468impl<469 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,470 AssetId: Get<MultiLocation>,471 AccountId,472 Currency: CurrencyT<AccountId>,473 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,474 > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>475{476 fn new() -> Self {477 Self(0, Zero::zero(), PhantomData)478 }479480 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {481 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);482 Ok(payment)483 }484}485impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop486 for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>487where488 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,489 AssetId: Get<MultiLocation>,490 Currency: CurrencyT<AccountId>,491 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,492{493 fn drop(&mut self) {494 OnUnbalanced::on_unbalanced(Currency::issue(self.1));495 }496}pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -250,8 +250,12 @@
..Default::default()
};
- let collection_id_res =
- <PalletNft<T>>::init_collection(cross_sender.clone(), cross_sender.clone(), data, true);
+ let collection_id_res = <PalletNft<T>>::init_collection(
+ cross_sender.clone(),
+ cross_sender.clone(),
+ data,
+ true,
+ );
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
return Err(<Error<T>>::NoAvailableBaseId.into());
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -174,10 +174,12 @@
add_properties,
)?;
check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+ let collection_helpers_address =
+ T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id =
+ T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -189,7 +191,11 @@
.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait
.expect("Collection creation price should be convertible to u128");
if value != creation_price {
- return Err(format!("Sent amount not equals to collection creation price ({0})", creation_price).into());
+ return Err(format!(
+ "Sent amount not equals to collection creation price ({0})",
+ creation_price
+ )
+ .into());
}
Ok(())
}
@@ -225,9 +231,10 @@
false,
)?;
check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id =
- T::CollectionDispatch::create(caller, collection_helpers_address, data).map_err(dispatch_to_evm::<T>)?;
+ let collection_helpers_address =
+ T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+ let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
@@ -255,7 +262,8 @@
true,
)?;
check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+ let collection_helpers_address =
+ T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
@@ -317,6 +325,14 @@
Ok(false)
}
+
+ fn collection_creation_fee(&self) -> Result<value> {
+ let price: u128 = T::CollectionCreationPrice::get()
+ .try_into()
+ .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait
+ .expect("Collection creation price should be convertible to u128");
+ Ok(price.into())
+ }
}
/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -59,7 +59,9 @@
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
let id = match data.mode {
- CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data, false)?,
+ CollectionMode::NFT => {
+ <PalletNonfungible<T>>::init_collection(sender, payer, data, false)?
+ }
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(