difftreelog
fix(xcm) get rid of xcm warns, fix quartz CurrencyIdConvert
in: master
19 files changed
pallets/foreing-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//! # Foreing assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! The foreing 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 transactional, 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, MultiAsset};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 TryAsForeing<T, F> {109 fn try_as_foreing(asset: T) -> Option<F>;110}111112impl TryAsForeing<AssetIds, ForeignAssetId> for AssetIds {113 fn try_as_foreing(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;125mod weights;126127pub use module::*;128pub use weights::WeightInfo;129130/// Type alias for currency balance.131pub type BalanceOf<T> =132 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;133134/// A mapping between ForeignAssetId and AssetMetadata.135pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {136 /// Returns the AssetMetadata associated with a given ForeignAssetId.137 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;138 /// Returns the MultiLocation associated with a given ForeignAssetId.139 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;140 /// Returns the CurrencyId associated with a given MultiLocation.141 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;142}143144pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);145146impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>147 for XcmForeignAssetIdMapping<T>148{149 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {150 log::trace!(target: "fassets::asset_metadatas", "call");151 Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))152 }153154 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {155 log::trace!(target: "fassets::get_multi_location", "call");156 Pallet::<T>::foreign_asset_locations(foreign_asset_id)157 }158159 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {160 log::trace!(target: "fassets::get_currency_id", "call");161 Some(AssetIds::ForeignAssetId(162 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),163 ))164 }165}166167#[frame_support::pallet]168pub mod module {169 use super::*;170171 #[pallet::config]172 pub trait Config:173 frame_system::Config174 + pallet_common::Config175 + pallet_fungible::Config176 + orml_tokens::Config177 + pallet_balances::Config178 {179 /// The overarching event type.180 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;181182 /// Currency type for withdraw and balance storage.183 type Currency: Currency<Self::AccountId>;184185 /// Required origin for registering asset.186 type RegisterOrigin: EnsureOrigin<Self::Origin>;187188 /// Weight information for the extrinsics in this module.189 type WeightInfo: WeightInfo;190 }191192 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]193 pub struct AssetMetadata<Balance> {194 pub name: Vec<u8>,195 pub symbol: Vec<u8>,196 pub decimals: u8,197 pub minimal_balance: Balance,198 }199200 #[pallet::error]201 pub enum Error<T> {202 /// The given location could not be used (e.g. because it cannot be expressed in the203 /// desired version of XCM).204 BadLocation,205 /// MultiLocation existed206 MultiLocationExisted,207 /// AssetId not exists208 AssetIdNotExists,209 /// AssetId exists210 AssetIdExisted,211 }212213 #[pallet::event]214 #[pallet::generate_deposit(fn deposit_event)]215 pub enum Event<T: Config> {216 /// The foreign asset registered.217 ForeignAssetRegistered {218 asset_id: ForeignAssetId,219 asset_address: MultiLocation,220 metadata: AssetMetadata<BalanceOf<T>>,221 },222 /// The foreign asset updated.223 ForeignAssetUpdated {224 asset_id: ForeignAssetId,225 asset_address: MultiLocation,226 metadata: AssetMetadata<BalanceOf<T>>,227 },228 /// The asset registered.229 AssetRegistered {230 asset_id: AssetIds,231 metadata: AssetMetadata<BalanceOf<T>>,232 },233 /// The asset updated.234 AssetUpdated {235 asset_id: AssetIds,236 metadata: AssetMetadata<BalanceOf<T>>,237 },238 }239240 /// Next available Foreign AssetId ID.241 ///242 /// NextForeignAssetId: ForeignAssetId243 #[pallet::storage]244 #[pallet::getter(fn next_foreign_asset_id)]245 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;246 /// The storages for MultiLocations.247 ///248 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>249 #[pallet::storage]250 #[pallet::getter(fn foreign_asset_locations)]251 pub type ForeignAssetLocations<T: Config> =252 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;253254 /// The storages for CurrencyIds.255 ///256 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>257 #[pallet::storage]258 #[pallet::getter(fn location_to_currency_ids)]259 pub type LocationToCurrencyIds<T: Config> =260 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;261262 /// The storages for AssetMetadatas.263 ///264 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>265 #[pallet::storage]266 #[pallet::getter(fn asset_metadatas)]267 pub type AssetMetadatas<T: Config> =268 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;269270 /// The storages for assets to fungible collection binding271 ///272 #[pallet::storage]273 #[pallet::getter(fn asset_binding)]274 pub type AssetBinding<T: Config> =275 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;276277 #[pallet::pallet]278 #[pallet::without_storage_info]279 pub struct Pallet<T>(_);280281 #[pallet::call]282 impl<T: Config> Pallet<T> {283 #[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]284 #[transactional]285 pub fn register_foreign_asset(286 origin: OriginFor<T>,287 owner: T::AccountId,288 location: Box<VersionedMultiLocation>,289 metadata: Box<AssetMetadata<BalanceOf<T>>>,290 ) -> DispatchResult {291 T::RegisterOrigin::ensure_origin(origin.clone())?;292293 let location: MultiLocation = (*location)294 .try_into()295 .map_err(|()| Error::<T>::BadLocation)?;296297 let md = metadata.clone();298 let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();299 let mut description: Vec<u16> = "Foreing assets collection for "300 .encode_utf16()301 .collect::<Vec<u16>>();302 description.append(&mut name.clone());303304 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {305 name: name.try_into().unwrap(),306 description: description.try_into().unwrap(),307 mode: CollectionMode::Fungible(18),308 ..Default::default()309 };310311 let bounded_collection_id = <PalletFungible<T>>::init_foreign_collection(312 CrossAccountId::from_sub(owner),313 data,314 )?;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 #[transactional]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}447448use sp_runtime::SaturatedConversion;449use sp_runtime::traits::Saturating;450pub 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};458459use xcm::latest::{Fungibility::Fungible as XcmFungible};460461pub struct FreeForAll<462 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,463 AssetId: Get<MultiLocation>,464 AccountId,465 Currency: CurrencyT<AccountId>,466 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,467>(468 Weight,469 Currency::Balance,470 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,471);472473impl<474 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,475 AssetId: Get<MultiLocation>,476 AccountId,477 Currency: CurrencyT<AccountId>,478 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,479 > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>480{481 fn new() -> Self {482 Self(0, Zero::zero(), PhantomData)483 }484485 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {486 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);487 Ok(payment)488 }489}490impl<491 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,492 AssetId: Get<MultiLocation>,493 AccountId,494 Currency: CurrencyT<AccountId>,495 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,496 > Drop for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>497{498 fn drop(&mut self) {499 OnUnbalanced::on_unbalanced(Currency::issue(self.1));500 }501}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//! # Foreing assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! The foreing 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 transactional, 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 TryAsForeing<T, F> {109 fn try_as_foreing(asset: T) -> Option<F>;110}111112impl TryAsForeing<AssetIds, ForeignAssetId> for AssetIds {113 fn try_as_foreing(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;125mod weights;126127pub use module::*;128pub use weights::WeightInfo;129130/// Type alias for currency balance.131pub type BalanceOf<T> =132 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;133134/// A mapping between ForeignAssetId and AssetMetadata.135pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {136 /// Returns the AssetMetadata associated with a given ForeignAssetId.137 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;138 /// Returns the MultiLocation associated with a given ForeignAssetId.139 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;140 /// Returns the CurrencyId associated with a given MultiLocation.141 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;142}143144pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);145146impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>147 for XcmForeignAssetIdMapping<T>148{149 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {150 log::trace!(target: "fassets::asset_metadatas", "call");151 Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))152 }153154 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {155 log::trace!(target: "fassets::get_multi_location", "call");156 Pallet::<T>::foreign_asset_locations(foreign_asset_id)157 }158159 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {160 log::trace!(target: "fassets::get_currency_id", "call");161 Some(AssetIds::ForeignAssetId(162 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),163 ))164 }165}166167#[frame_support::pallet]168pub mod module {169 use super::*;170171 #[pallet::config]172 pub trait Config:173 frame_system::Config174 + pallet_common::Config175 + pallet_fungible::Config176 + orml_tokens::Config177 + pallet_balances::Config178 {179 /// The overarching event type.180 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;181182 /// Currency type for withdraw and balance storage.183 type Currency: Currency<Self::AccountId>;184185 /// Required origin for registering asset.186 type RegisterOrigin: EnsureOrigin<Self::Origin>;187188 /// Weight information for the extrinsics in this module.189 type WeightInfo: WeightInfo;190 }191192 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]193 pub struct AssetMetadata<Balance> {194 pub name: Vec<u8>,195 pub symbol: Vec<u8>,196 pub decimals: u8,197 pub minimal_balance: Balance,198 }199200 #[pallet::error]201 pub enum Error<T> {202 /// The given location could not be used (e.g. because it cannot be expressed in the203 /// desired version of XCM).204 BadLocation,205 /// MultiLocation existed206 MultiLocationExisted,207 /// AssetId not exists208 AssetIdNotExists,209 /// AssetId exists210 AssetIdExisted,211 }212213 #[pallet::event]214 #[pallet::generate_deposit(fn deposit_event)]215 pub enum Event<T: Config> {216 /// The foreign asset registered.217 ForeignAssetRegistered {218 asset_id: ForeignAssetId,219 asset_address: MultiLocation,220 metadata: AssetMetadata<BalanceOf<T>>,221 },222 /// The foreign asset updated.223 ForeignAssetUpdated {224 asset_id: ForeignAssetId,225 asset_address: MultiLocation,226 metadata: AssetMetadata<BalanceOf<T>>,227 },228 /// The asset registered.229 AssetRegistered {230 asset_id: AssetIds,231 metadata: AssetMetadata<BalanceOf<T>>,232 },233 /// The asset updated.234 AssetUpdated {235 asset_id: AssetIds,236 metadata: AssetMetadata<BalanceOf<T>>,237 },238 }239240 /// Next available Foreign AssetId ID.241 ///242 /// NextForeignAssetId: ForeignAssetId243 #[pallet::storage]244 #[pallet::getter(fn next_foreign_asset_id)]245 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;246 /// The storages for MultiLocations.247 ///248 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>249 #[pallet::storage]250 #[pallet::getter(fn foreign_asset_locations)]251 pub type ForeignAssetLocations<T: Config> =252 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;253254 /// The storages for CurrencyIds.255 ///256 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>257 #[pallet::storage]258 #[pallet::getter(fn location_to_currency_ids)]259 pub type LocationToCurrencyIds<T: Config> =260 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;261262 /// The storages for AssetMetadatas.263 ///264 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>265 #[pallet::storage]266 #[pallet::getter(fn asset_metadatas)]267 pub type AssetMetadatas<T: Config> =268 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;269270 /// The storages for assets to fungible collection binding271 ///272 #[pallet::storage]273 #[pallet::getter(fn asset_binding)]274 pub type AssetBinding<T: Config> =275 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;276277 #[pallet::pallet]278 #[pallet::without_storage_info]279 pub struct Pallet<T>(_);280281 #[pallet::call]282 impl<T: Config> Pallet<T> {283 #[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]284 #[transactional]285 pub fn register_foreign_asset(286 origin: OriginFor<T>,287 owner: T::AccountId,288 location: Box<VersionedMultiLocation>,289 metadata: Box<AssetMetadata<BalanceOf<T>>>,290 ) -> DispatchResult {291 T::RegisterOrigin::ensure_origin(origin.clone())?;292293 let location: MultiLocation = (*location)294 .try_into()295 .map_err(|()| Error::<T>::BadLocation)?;296297 let md = metadata.clone();298 let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();299 let mut description: Vec<u16> = "Foreing assets collection for "300 .encode_utf16()301 .collect::<Vec<u16>>();302 description.append(&mut name.clone());303304 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {305 name: name.try_into().unwrap(),306 description: description.try_into().unwrap(),307 mode: CollectionMode::Fungible(18),308 ..Default::default()309 };310311 let bounded_collection_id = <PalletFungible<T>>::init_foreign_collection(312 CrossAccountId::from_sub(owner),313 data,314 )?;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 #[transactional]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<487 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,488 AssetId: Get<MultiLocation>,489 AccountId,490 Currency: CurrencyT<AccountId>,491 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,492 > Drop for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>493{494 fn drop(&mut self) {495 OnUnbalanced::on_unbalanced(Currency::issue(self.1));496 }497}runtime/common/config/xcm.rsdiffbeforeafterboth--- a/runtime/common/config/xcm.rs
+++ /dev/null
@@ -1,493 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use frame_support::{
- traits::{
- Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,
- Everything, fungibles,
- },
- weights::{Weight, WeightToFeePolynomial, WeightToFee},
- parameter_types, match_types,
-};
-use frame_system::EnsureRoot;
-use sp_runtime::{
- traits::{Saturating, CheckedConversion, Zero},
- SaturatedConversion,
-};
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain::primitives::Sibling;
-use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
-use xcm::latest::{
- AssetId::{Concrete},
- Fungibility::Fungible as XcmFungible,
- MultiAsset, Error as XcmError, Instruction, Xcm,
-};
-use xcm_builder::{
- AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,
- FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser,
- RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
- SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
- ParentIsPreset, ConvertedConcreteAssetId,
-};
-use xcm_executor::{Config, XcmExecutor, Assets};
-use xcm_executor::traits::{
- Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,
- ShouldExecute,
-};
-use pallet_foreing_assets::{
- AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,
- TryAsForeing, ForeignAssetId,
-};
-use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
-use crate::{
- Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,
- xcm_config::Barrier,
-};
-#[cfg(feature = "foreign-assets")]
-use crate::ForeingAssets;
-
-use up_common::{
- types::{AccountId, Balance},
- constants::*,
-};
-
-parameter_types! {
- pub const RelayLocation: MultiLocation = MultiLocation::parent();
- pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
- pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
- pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
-}
-
-/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
-/// when determining ownership of accounts for asset transacting and when attempting to use XCM
-/// `Transact` in order to determine the dispatch Origin.
-pub type LocationToAccountId = (
- // The parent (Relay-chain) origin converts to the default `AccountId`.
- ParentIsPreset<AccountId>,
- // Sibling parachain origins convert to AccountId via the `ParaId::into`.
- SiblingParachainConvertsVia<Sibling, AccountId>,
- // Straight up local `AccountId32` origins just alias directly to `AccountId`.
- AccountId32Aliases<RelayNetwork, AccountId>,
-);
-
-pub struct OnlySelfCurrency;
-impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
- fn matches_fungible(a: &MultiAsset) -> Option<B> {
- let paraid = Parachain(ParachainInfo::parachain_id().into());
- match (&a.id, &a.fun) {
- (
- Concrete(MultiLocation {
- parents: 1,
- interior: X1(loc),
- }),
- XcmFungible(ref amount),
- ) if paraid == *loc => CheckedConversion::checked_from(*amount),
- (
- Concrete(MultiLocation {
- parents: 0,
- interior: Here,
- }),
- XcmFungible(ref amount),
- ) => CheckedConversion::checked_from(*amount),
- _ => None,
- }
- }
-}
-
-/// Means for transacting assets on this chain.
-pub type LocalAssetTransactor = CurrencyAdapter<
- // Use this currency:
- Balances,
- // Use this currency when it is a fungible asset matching the given location or name:
- OnlySelfCurrency,
- // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // We don't track any teleports.
- (),
->;
-
-/// No local origins on this chain are allowed to dispatch XCM sends/executions.
-pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);
-
-/// The means for routing XCM messages which are not for local execution into the right message
-/// queues.
-pub type XcmRouter = (
- // Two routers - use UMP to communicate with the relay chain:
- cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,
- // ..and XCMP to communicate with the sibling chains.
- XcmpQueue,
-);
-
-/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
-/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
-/// biases the kind of local `Origin` it will become.
-pub type XcmOriginToTransactDispatchOrigin = (
- // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
- // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
- // foreign chains who want to have a local sovereign account on this chain which they control.
- SovereignSignedViaLocation<LocationToAccountId, Origin>,
- // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
- // recognised.
- RelayChainAsNative<RelayOrigin, Origin>,
- // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
- // recognised.
- SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
- // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
- // transaction from the Root origin.
- ParentAsSuperuser<Origin>,
- // Native signed account converter; this just converts an `AccountId32` origin into a normal
- // `Origin::Signed` origin of the same 32-byte value.
- SignedAccountId32AsNative<RelayNetwork, Origin>,
- // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
- XcmPassthrough<Origin>,
-);
-
-parameter_types! {
- // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
- pub UnitWeightCost: Weight = 1_000_000;
- // 1200 UNIQUEs buy 1 second of weight.
- pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);
- pub const MaxInstructions: u32 = 100;
-}
-
-match_types! {
- pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {
- MultiLocation { parents: 1, interior: Here } |
- MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }
- };
-}
-
-pub trait TryPass {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut Xcm<Call>,
- ) -> Result<(), ()>;
-}
-
-#[impl_trait_for_tuples::impl_for_tuples(30)]
-impl TryPass for Tuple {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut Xcm<Call>,
- ) -> Result<(), ()> {
- for_tuples!( #(
- Tuple::try_pass(origin, message)?;
- )* );
-
- Ok(())
- }
-}
-
-pub struct DenyTransact;
-impl TryPass for DenyTransact {
- fn try_pass<Call>(
- _origin: &MultiLocation,
- message: &mut Xcm<Call>,
- ) -> Result<(), ()> {
- let transact_inst = message
- .0
- .iter()
- .find(|inst| matches![inst, Instruction::Transact { .. }]);
-
- match transact_inst {
- Some(_) => {
- log::warn!(
- target: "xcm::barrier",
- "transact XCM rejected"
- );
-
- Err(())
- }
- None => Ok(()),
- }
- }
-}
-
-/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
-/// If it passes the Deny, and matches one of the Allow cases then it is let through.
-pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
-where
- Deny: TryPass,
- Allow: ShouldExecute;
-
-impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
-where
- Deny: TryPass,
- Allow: ShouldExecute,
-{
- fn should_execute<Call>(
- origin: &MultiLocation,
- message: &mut Xcm<Call>,
- max_weight: Weight,
- weight_credit: &mut Weight,
- ) -> Result<(), ()> {
- Deny::try_pass(origin, message)?;
- Allow::should_execute(origin, message, max_weight, weight_credit)
- }
-}
-
-pub struct UsingOnlySelfCurrencyComponents<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
->(
- Weight,
- Currency::Balance,
- PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
-);
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > WeightTrader
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn new() -> Self {
- Self(0, Zero::zero(), PhantomData)
- }
-
- fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
- Ok(payment)
- }
-}
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > Drop
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn drop(&mut self) {
- OnUnbalanced::on_unbalanced(Currency::issue(self.1));
- }
-}
-
-parameter_types! {
- pub CheckingAccount: AccountId = PolkadotXcm::check_account();
-}
-/// Allow checking in assets that have issuance > 0.
-#[cfg(feature = "foreign-assets")]
-pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);
-
-#[cfg(feature = "foreign-assets")]
-impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>
- for NonZeroIssuance<AccountId, ForeingAssets>
-where
- ForeingAssets: fungibles::Inspect<AccountId>,
-{
- fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {
- !ForeingAssets::total_issuance(*id).is_zero()
- }
-}
-
-#[cfg(feature = "foreign-assets")]
-pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-#[cfg(feature = "foreign-assets")]
-impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
- ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
-where
- AssetId: Borrow<AssetId>,
- AssetId: TryAsForeing<AssetId, ForeignAssetId>,
- AssetIds: Borrow<AssetId>,
-{
- fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
- let id = id.borrow();
-
- log::trace!(
- target: "xcm::AsInnerId::Convert",
- "AsInnerId {:?}",
- id
- );
-
- let parent = MultiLocation::parent();
- let here = MultiLocation::here();
- let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-
- if *id == parent {
- return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));
- }
-
- if *id == here || *id == self_location {
- return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
- }
-
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
- Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
- ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
- }
- _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),
- }
- }
-
- fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {
- log::trace!(
- target: "xcm::AsInnerId::Reverse",
- "AsInnerId",
- );
-
- let asset_id = what.borrow();
-
- let parent_id =
- ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();
- let here_id =
- ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();
-
- if asset_id.clone() == parent_id {
- return Ok(MultiLocation::parent());
- }
-
- if asset_id.clone() == here_id {
- return Ok(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- ));
- }
-
- match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {
- Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {
- Some(location) => Ok(location),
- None => Err(()),
- },
- None => Err(()),
- }
- }
-}
-
-/// Means for transacting assets besides the native currency on this chain.
-#[cfg(feature = "foreign-assets")]
-pub type FungiblesTransactor = FungiblesAdapter<
- // Use this fungibles implementation:
- ForeingAssets,
- // Use this currency when it is a fungible asset matching the given location or name:
- ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,
- // Convert an XCM MultiLocation into a local account id:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // We only want to allow teleports of known assets. We use non-zero issuance as an indication
- // that this asset is known.
- NonZeroIssuance<AccountId, ForeingAssets>,
- // The account to use for tracking teleports.
- CheckingAccount,
->;
-
-/// Means for transacting assets on this chain.
-#[cfg(feature = "foreign-assets")]
-pub type AssetTransactors = FungiblesTransactor;
-
-#[cfg(not(feature = "foreign-assets"))]
-pub type AssetTransactors = LocalAssetTransactor;
-
-#[cfg(feature = "foreign-assets")]
-pub struct AllAsset;
-#[cfg(feature = "foreign-assets")]
-impl FilterAssetLocation for AllAsset {
- fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {
- true
- }
-}
-
-#[cfg(feature = "foreign-assets")]
-pub type IsReserve = AllAsset;
-#[cfg(not(feature = "foreign-assets"))]
-pub type IsReserve = NativeAsset;
-
-#[cfg(feature = "foreign-assets")]
-type Trader<T> = FreeForAll<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-#[cfg(not(feature = "foreign-assets"))]
-type Trader<T> = UsingOnlySelfCurrencyComponents<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-
-pub struct XcmConfig<T>(PhantomData<T>);
-impl<T> Config for XcmConfig<T>
-where
- T: pallet_configuration::Config,
-{
- type Call = Call;
- type XcmSender = XcmRouter;
- // How to withdraw and deposit an asset.
- type AssetTransactor = AssetTransactors;
- type OriginConverter = XcmOriginToTransactDispatchOrigin;
- type IsReserve = IsReserve;
- type IsTeleporter = (); // Teleportation is disabled
- type LocationInverter = LocationInverter<Ancestry>;
- type Barrier = Barrier;
- type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
- type Trader = Trader<T>;
- type ResponseHandler = (); // Don't handle responses for now.
- type SubscriptionService = PolkadotXcm;
-
- type AssetTrap = PolkadotXcm;
- type AssetClaims = PolkadotXcm;
-}
-
-impl pallet_xcm::Config for Runtime {
- type Event = Event;
- type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;
- type XcmRouter = XcmRouter;
- type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;
- type XcmExecuteFilter = Everything;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type XcmTeleportFilter = Everything;
- type XcmReserveTransferFilter = Everything;
- type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
- type LocationInverter = LocationInverter<Ancestry>;
- type Origin = Origin;
- type Call = Call;
- const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
- type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
-}
-
-impl cumulus_pallet_xcm::Config for Runtime {
- type Event = Event;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
-}
-
-impl cumulus_pallet_xcmp_queue::Config for Runtime {
- type WeightInfo = ();
- type Event = Event;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type ChannelInfo = ParachainSystem;
- type VersionWrapper = ();
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
- type ControllerOrigin = EnsureRoot<AccountId>;
- type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
-}
-
-impl cumulus_pallet_dmp_queue::Config for Runtime {
- type Event = Event;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
-}
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -0,0 +1,160 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use frame_support::{
+ traits::{Contains, Get, fungibles},
+ parameter_types,
+};
+use sp_runtime::traits::Zero;
+use xcm::v1::{Junction::*, MultiLocation, Junctions::*};
+use xcm::latest::MultiAsset;
+use xcm_builder::{FungiblesAdapter, ConvertedConcreteAssetId};
+use xcm_executor::traits::{Convert as ConvertXcm, JustTry, FilterAssetLocation};
+use pallet_foreing_assets::{
+ AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, NativeCurrency, FreeForAll, TryAsForeing,
+ ForeignAssetId,
+};
+use sp_std::{borrow::Borrow, marker::PhantomData};
+use crate::{Runtime, Balances, ParachainInfo, PolkadotXcm, ForeingAssets};
+
+use super::{LocationToAccountId, RelayLocation};
+
+use up_common::types::{AccountId, Balance};
+
+parameter_types! {
+ pub CheckingAccount: AccountId = PolkadotXcm::check_account();
+}
+
+/// Allow checking in assets that have issuance > 0.
+pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);
+
+impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>
+ for NonZeroIssuance<AccountId, ForeingAssets>
+where
+ ForeingAssets: fungibles::Inspect<AccountId>,
+{
+ fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {
+ !ForeingAssets::total_issuance(*id).is_zero()
+ }
+}
+
+pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
+impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
+ ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
+where
+ AssetId: Borrow<AssetId>,
+ AssetId: TryAsForeing<AssetId, ForeignAssetId>,
+ AssetIds: Borrow<AssetId>,
+{
+ fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
+ let id = id.borrow();
+
+ log::trace!(
+ target: "xcm::AsInnerId::Convert",
+ "AsInnerId {:?}",
+ id
+ );
+
+ let parent = MultiLocation::parent();
+ let here = MultiLocation::here();
+ let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
+
+ if *id == parent {
+ return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));
+ }
+
+ if *id == here || *id == self_location {
+ return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
+ }
+
+ match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
+ Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
+ ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
+ }
+ _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),
+ }
+ }
+
+ fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {
+ log::trace!(
+ target: "xcm::AsInnerId::Reverse",
+ "AsInnerId",
+ );
+
+ let asset_id = what.borrow();
+
+ let parent_id =
+ ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();
+ let here_id =
+ ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();
+
+ if asset_id.clone() == parent_id {
+ return Ok(MultiLocation::parent());
+ }
+
+ if asset_id.clone() == here_id {
+ return Ok(MultiLocation::new(
+ 1,
+ X1(Parachain(ParachainInfo::get().into())),
+ ));
+ }
+
+ match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {
+ Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {
+ Some(location) => Ok(location),
+ None => Err(()),
+ },
+ None => Err(()),
+ }
+ }
+}
+
+/// Means for transacting assets besides the native currency on this chain.
+pub type FungiblesTransactor = FungiblesAdapter<
+ // Use this fungibles implementation:
+ ForeingAssets,
+ // Use this currency when it is a fungible asset matching the given location or name:
+ ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,
+ // Convert an XCM MultiLocation into a local account id:
+ LocationToAccountId,
+ // Our chain's account ID type (we can't get away without mentioning it explicitly):
+ AccountId,
+ // We only want to allow teleports of known assets. We use non-zero issuance as an indication
+ // that this asset is known.
+ NonZeroIssuance<AccountId, ForeingAssets>,
+ // The account to use for tracking teleports.
+ CheckingAccount,
+>;
+
+/// Means for transacting assets on this chain.
+pub type AssetTransactors = FungiblesTransactor;
+
+pub struct AllAsset;
+impl FilterAssetLocation for AllAsset {
+ fn filter_asset_location(_asset: &MultiAsset, _origin: &MultiLocation) -> bool {
+ true
+ }
+}
+
+pub type IsReserve = AllAsset;
+
+pub type Trader<T> = FreeForAll<
+ pallet_configuration::WeightToFee<T, Balance>,
+ RelayLocation,
+ AccountId,
+ Balances,
+ (),
+>;
runtime/common/config/xcm/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/xcm/mod.rs
@@ -0,0 +1,232 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use frame_support::{traits::Everything, weights::Weight, parameter_types};
+use frame_system::EnsureRoot;
+use pallet_xcm::XcmPassthrough;
+use polkadot_parachain::primitives::Sibling;
+use xcm::v1::{Junction::*, MultiLocation, NetworkId};
+use xcm::latest::{Instruction, Xcm};
+use xcm_builder::{
+ AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, LocationInverter, ParentAsSuperuser,
+ RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
+ SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, ParentIsPreset,
+};
+use xcm_executor::{Config, XcmExecutor, traits::ShouldExecute};
+use sp_std::marker::PhantomData;
+use crate::{
+ Runtime, Call, Event, Origin, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,
+ xcm_config::Barrier,
+};
+
+use up_common::types::AccountId;
+
+#[cfg(feature = "foreign-assets")]
+mod foreignassets;
+
+#[cfg(not(feature = "foreign-assets"))]
+mod nativeassets;
+
+#[cfg(feature = "foreign-assets")]
+use foreignassets as xcm_assets;
+
+#[cfg(not(feature = "foreign-assets"))]
+use nativeassets as xcm_assets;
+
+use xcm_assets::{AssetTransactors, IsReserve, Trader};
+
+parameter_types! {
+ pub const RelayLocation: MultiLocation = MultiLocation::parent();
+ pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
+ pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
+ pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
+}
+
+/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
+/// when determining ownership of accounts for asset transacting and when attempting to use XCM
+/// `Transact` in order to determine the dispatch Origin.
+pub type LocationToAccountId = (
+ // The parent (Relay-chain) origin converts to the default `AccountId`.
+ ParentIsPreset<AccountId>,
+ // Sibling parachain origins convert to AccountId via the `ParaId::into`.
+ SiblingParachainConvertsVia<Sibling, AccountId>,
+ // Straight up local `AccountId32` origins just alias directly to `AccountId`.
+ AccountId32Aliases<RelayNetwork, AccountId>,
+);
+
+/// No local origins on this chain are allowed to dispatch XCM sends/executions.
+pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);
+
+/// The means for routing XCM messages which are not for local execution into the right message
+/// queues.
+pub type XcmRouter = (
+ // Two routers - use UMP to communicate with the relay chain:
+ cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,
+ // ..and XCMP to communicate with the sibling chains.
+ XcmpQueue,
+);
+
+/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
+/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
+/// biases the kind of local `Origin` it will become.
+pub type XcmOriginToTransactDispatchOrigin = (
+ // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
+ // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
+ // foreign chains who want to have a local sovereign account on this chain which they control.
+ SovereignSignedViaLocation<LocationToAccountId, Origin>,
+ // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
+ // recognised.
+ RelayChainAsNative<RelayOrigin, Origin>,
+ // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
+ // recognised.
+ SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
+ // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
+ // transaction from the Root origin.
+ ParentAsSuperuser<Origin>,
+ // Native signed account converter; this just converts an `AccountId32` origin into a normal
+ // `Origin::Signed` origin of the same 32-byte value.
+ SignedAccountId32AsNative<RelayNetwork, Origin>,
+ // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
+ XcmPassthrough<Origin>,
+);
+
+parameter_types! {
+ // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
+ pub UnitWeightCost: Weight = 1_000_000;
+ pub const MaxInstructions: u32 = 100;
+}
+
+pub trait TryPass {
+ fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()>;
+}
+
+#[impl_trait_for_tuples::impl_for_tuples(30)]
+impl TryPass for Tuple {
+ fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {
+ for_tuples!( #(
+ Tuple::try_pass(origin, message)?;
+ )* );
+
+ Ok(())
+ }
+}
+
+pub struct DenyTransact;
+impl TryPass for DenyTransact {
+ fn try_pass<Call>(_origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {
+ let transact_inst = message
+ .0
+ .iter()
+ .find(|inst| matches![inst, Instruction::Transact { .. }]);
+
+ match transact_inst {
+ Some(_) => {
+ log::warn!(
+ target: "xcm::barrier",
+ "transact XCM rejected"
+ );
+
+ Err(())
+ }
+ None => Ok(()),
+ }
+ }
+}
+
+/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
+/// If it passes the Deny, and matches one of the Allow cases then it is let through.
+pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
+where
+ Deny: TryPass,
+ Allow: ShouldExecute;
+
+impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
+where
+ Deny: TryPass,
+ Allow: ShouldExecute,
+{
+ fn should_execute<Call>(
+ origin: &MultiLocation,
+ message: &mut Xcm<Call>,
+ max_weight: Weight,
+ weight_credit: &mut Weight,
+ ) -> Result<(), ()> {
+ Deny::try_pass(origin, message)?;
+ Allow::should_execute(origin, message, max_weight, weight_credit)
+ }
+}
+
+pub struct XcmConfig<T>(PhantomData<T>);
+impl<T> Config for XcmConfig<T>
+where
+ T: pallet_configuration::Config,
+{
+ type Call = Call;
+ type XcmSender = XcmRouter;
+ // How to withdraw and deposit an asset.
+ type AssetTransactor = AssetTransactors;
+ type OriginConverter = XcmOriginToTransactDispatchOrigin;
+ type IsReserve = IsReserve;
+ type IsTeleporter = (); // Teleportation is disabled
+ type LocationInverter = LocationInverter<Ancestry>;
+ type Barrier = Barrier;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type Trader = Trader<T>;
+ type ResponseHandler = (); // Don't handle responses for now.
+ type SubscriptionService = PolkadotXcm;
+
+ type AssetTrap = PolkadotXcm;
+ type AssetClaims = PolkadotXcm;
+}
+
+impl pallet_xcm::Config for Runtime {
+ type Event = Event;
+ type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;
+ type XcmRouter = XcmRouter;
+ type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;
+ type XcmExecuteFilter = Everything;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type XcmTeleportFilter = Everything;
+ type XcmReserveTransferFilter = Everything;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type LocationInverter = LocationInverter<Ancestry>;
+ type Origin = Origin;
+ type Call = Call;
+ const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
+ type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
+}
+
+impl cumulus_pallet_xcm::Config for Runtime {
+ type Event = Event;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+}
+
+impl cumulus_pallet_xcmp_queue::Config for Runtime {
+ type WeightInfo = ();
+ type Event = Event;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type ChannelInfo = ParachainSystem;
+ type VersionWrapper = ();
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+ type ControllerOrigin = EnsureRoot<AccountId>;
+ type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
+}
+
+impl cumulus_pallet_dmp_queue::Config for Runtime {
+ type Event = Event;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+}
runtime/common/config/xcm/nativeassets.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/xcm/nativeassets.rs
@@ -0,0 +1,129 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use frame_support::{
+ traits::{tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get},
+ weights::{Weight, WeightToFeePolynomial},
+};
+use sp_runtime::traits::{CheckedConversion, Zero};
+use xcm::v1::{Junction::*, MultiLocation, Junctions::*};
+use xcm::latest::{
+ AssetId::{Concrete},
+ Fungibility::Fungible as XcmFungible,
+ MultiAsset, Error as XcmError,
+};
+use xcm_builder::{CurrencyAdapter, NativeAsset};
+use xcm_executor::{
+ Assets,
+ traits::{MatchesFungible, WeightTrader},
+};
+use sp_std::marker::PhantomData;
+use crate::{Balances, ParachainInfo};
+use super::{LocationToAccountId, RelayLocation};
+
+use up_common::types::{AccountId, Balance};
+
+pub struct OnlySelfCurrency;
+impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
+ fn matches_fungible(a: &MultiAsset) -> Option<B> {
+ let paraid = Parachain(ParachainInfo::parachain_id().into());
+ match (&a.id, &a.fun) {
+ (
+ Concrete(MultiLocation {
+ parents: 1,
+ interior: X1(loc),
+ }),
+ XcmFungible(ref amount),
+ ) if paraid == *loc => CheckedConversion::checked_from(*amount),
+ (
+ Concrete(MultiLocation {
+ parents: 0,
+ interior: Here,
+ }),
+ XcmFungible(ref amount),
+ ) => CheckedConversion::checked_from(*amount),
+ _ => None,
+ }
+ }
+}
+
+/// Means for transacting assets on this chain.
+pub type LocalAssetTransactor = CurrencyAdapter<
+ // Use this currency:
+ Balances,
+ // Use this currency when it is a fungible asset matching the given location or name:
+ OnlySelfCurrency,
+ // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
+ LocationToAccountId,
+ // Our chain's account ID type (we can't get away without mentioning it explicitly):
+ AccountId,
+ // We don't track any teleports.
+ (),
+>;
+
+pub type AssetTransactors = LocalAssetTransactor;
+
+pub type IsReserve = NativeAsset;
+
+pub struct UsingOnlySelfCurrencyComponents<
+ WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+ AssetId: Get<MultiLocation>,
+ AccountId,
+ Currency: CurrencyT<AccountId>,
+ OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+>(
+ Weight,
+ Currency::Balance,
+ PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
+);
+impl<
+ WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+ AssetId: Get<MultiLocation>,
+ AccountId,
+ Currency: CurrencyT<AccountId>,
+ OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+ > WeightTrader
+ for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+{
+ fn new() -> Self {
+ Self(0, Zero::zero(), PhantomData)
+ }
+
+ fn buy_weight(&mut self, _weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+ Ok(payment)
+ }
+}
+impl<
+ WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
+ AssetId: Get<MultiLocation>,
+ AccountId,
+ Currency: CurrencyT<AccountId>,
+ OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
+ > Drop
+ for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+{
+ fn drop(&mut self) {
+ OnUnbalanced::on_unbalanced(Currency::issue(self.1));
+ }
+}
+
+pub type Trader<T> = UsingOnlySelfCurrencyComponents<
+ pallet_configuration::WeightToFee<T, Balance>,
+ RelayLocation,
+ AccountId,
+ Balances,
+ (),
+>;
runtime/common/tests/mod.rsdiffbeforeafterboth--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -29,20 +29,18 @@
}
fn new_test_ext(para_id: u32) -> sp_io::TestExternalities {
- let cfg = GenesisConfig {
- aura: AuraConfig {
- authorities: vec![
- get_from_seed::<AuraId>("Alice"),
- get_from_seed::<AuraId>("Bob"),
- ],
- },
- parachain_info: ParachainInfoConfig {
- parachain_id: para_id.into(),
- },
- ..GenesisConfig::default()
- };
+ let cfg = GenesisConfig {
+ aura: AuraConfig {
+ authorities: vec![
+ get_from_seed::<AuraId>("Alice"),
+ get_from_seed::<AuraId>("Bob"),
+ ],
+ },
+ parachain_info: ParachainInfoConfig {
+ parachain_id: para_id.into(),
+ },
+ ..GenesisConfig::default()
+ };
- cfg.build_storage()
- .unwrap()
- .into()
+ cfg.build_storage().unwrap().into()
}
runtime/common/tests/xcm.rsdiffbeforeafterboth--- a/runtime/common/tests/xcm.rs
+++ b/runtime/common/tests/xcm.rs
@@ -20,154 +20,143 @@
use crate::Call;
use super::new_test_ext;
-fn catch_xcm_barrier_log(
- logger: &mut Logger,
- expected_msg: &str
-) -> Result<(), String> {
- for record in logger {
- if record.target() == "xcm::barrier"
- && record.args() == expected_msg {
- return Ok(());
- }
- }
+fn catch_xcm_barrier_log(logger: &mut Logger, expected_msg: &str) -> Result<(), String> {
+ for record in logger {
+ if record.target() == "xcm::barrier" && record.args() == expected_msg {
+ return Ok(());
+ }
+ }
- Err(format!("the expected XCM barrier log `{}` is not found", expected_msg))
+ Err(format!(
+ "the expected XCM barrier log `{}` is not found",
+ expected_msg
+ ))
}
/// WARNING: Uses log capturing
/// See https://docs.rs/logtest/latest/logtest/index.html#constraints
pub fn barrier_denies_transact<B: ShouldExecute>(logger: &mut Logger) {
- let location = MultiLocation {
- parents: 0,
- interior: Junctions::Here,
- };
+ let location = MultiLocation {
+ parents: 0,
+ interior: Junctions::Here,
+ };
- // We will never decode this "call",
- // so it is irrelevant what we are passing to the `transact` cmd.
- let fake_encoded_call = vec![0u8];
+ // We will never decode this "call",
+ // so it is irrelevant what we are passing to the `transact` cmd.
+ let fake_encoded_call = vec![0u8];
- let transact_inst = Transact {
- origin_type: OriginKind::Superuser,
- require_weight_at_most: 0,
- call: fake_encoded_call.into(),
- };
+ let transact_inst = Transact {
+ origin_type: OriginKind::Superuser,
+ require_weight_at_most: 0,
+ call: fake_encoded_call.into(),
+ };
- let mut xcm_program = Xcm::<Call>(vec![transact_inst]);
+ let mut xcm_program = Xcm::<Call>(vec![transact_inst]);
- let max_weight = 100_000;
- let mut weight_credit = 100_000_000;
+ let max_weight = 100_000;
+ let mut weight_credit = 100_000_000;
- let result = B::should_execute(
- &location,
- &mut xcm_program,
- max_weight,
- &mut weight_credit
- );
+ let result = B::should_execute(&location, &mut xcm_program, max_weight, &mut weight_credit);
- assert!(result.is_err(), "the barrier should disallow the XCM transact cmd");
+ assert!(
+ result.is_err(),
+ "the barrier should disallow the XCM transact cmd"
+ );
- catch_xcm_barrier_log(logger, "transact XCM rejected").unwrap();
+ catch_xcm_barrier_log(logger, "transact XCM rejected").unwrap();
}
fn xcm_execute<B: ShouldExecute>(
- self_para_id: u32,
- location: &MultiLocation,
- xcm: &mut Xcm<Call>
+ self_para_id: u32,
+ location: &MultiLocation,
+ xcm: &mut Xcm<Call>,
) -> Result<(), ()> {
- new_test_ext(self_para_id).execute_with(|| {
- let max_weight = 100_000;
- let mut weight_credit = 100_000_000;
+ new_test_ext(self_para_id).execute_with(|| {
+ let max_weight = 100_000;
+ let mut weight_credit = 100_000_000;
- B::should_execute(
- &location,
- xcm,
- max_weight,
- &mut weight_credit
- )
- })
+ B::should_execute(&location, xcm, max_weight, &mut weight_credit)
+ })
}
fn make_multiassets(location: &MultiLocation) -> MultiAssets {
- let id = AssetId::Concrete(location.clone());
- let fun = Fungibility::Fungible(42);
- let multiasset = MultiAsset {
- id,
- fun,
- };
+ let id = AssetId::Concrete(location.clone());
+ let fun = Fungibility::Fungible(42);
+ let multiasset = MultiAsset { id, fun };
- multiasset.into()
+ multiasset.into()
}
fn make_transfer_reserve_asset(location: &MultiLocation) -> Xcm<Call> {
- let assets = make_multiassets(location);
- let inst = TransferReserveAsset {
- assets,
- dest: location.clone(),
- xcm: Xcm(vec![]),
- };
+ let assets = make_multiassets(location);
+ let inst = TransferReserveAsset {
+ assets,
+ dest: location.clone(),
+ xcm: Xcm(vec![]),
+ };
- Xcm::<Call>(vec![inst])
+ Xcm::<Call>(vec![inst])
}
fn make_deposit_reserve_asset(location: &MultiLocation) -> Xcm<Call> {
- let assets = make_multiassets(location);
- let inst = DepositReserveAsset {
- assets: assets.into(),
- max_assets: 42,
- dest: location.clone(),
- xcm: Xcm(vec![]),
- };
+ let assets = make_multiassets(location);
+ let inst = DepositReserveAsset {
+ assets: assets.into(),
+ max_assets: 42,
+ dest: location.clone(),
+ xcm: Xcm(vec![]),
+ };
- Xcm::<Call>(vec![inst])
+ Xcm::<Call>(vec![inst])
}
fn expect_transfer_location_denied<B: ShouldExecute>(
- logger: &mut Logger,
- self_para_id: u32,
- location: &MultiLocation,
- xcm: &mut Xcm<Call>
+ logger: &mut Logger,
+ self_para_id: u32,
+ location: &MultiLocation,
+ xcm: &mut Xcm<Call>,
) -> Result<(), String> {
- let result = xcm_execute::<B>(self_para_id, location, xcm);
+ let result = xcm_execute::<B>(self_para_id, location, xcm);
- if result.is_ok() {
- return Err("the barrier should deny the unknown location".into());
- }
+ if result.is_ok() {
+ return Err("the barrier should deny the unknown location".into());
+ }
- catch_xcm_barrier_log(logger, "Unexpected deposit or transfer location")
+ catch_xcm_barrier_log(logger, "Unexpected deposit or transfer location")
}
/// WARNING: Uses log capturing
/// See https://docs.rs/logtest/latest/logtest/index.html#constraints
pub fn barrier_denies_transfer_from_unknown_location<B>(
- logger: &mut Logger,
- self_para_id: u32,
+ logger: &mut Logger,
+ self_para_id: u32,
) -> Result<(), String>
where
- B: ShouldExecute
+ B: ShouldExecute,
{
- const UNKNOWN_PARACHAIN_ID: u32 = 4057;
+ const UNKNOWN_PARACHAIN_ID: u32 = 4057;
- let unknown_location = MultiLocation {
- parents: 1,
- interior: X1(Parachain(UNKNOWN_PARACHAIN_ID)),
- };
+ let unknown_location = MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(UNKNOWN_PARACHAIN_ID)),
+ };
- let mut transfer_reserve_asset = make_transfer_reserve_asset(&unknown_location);
- let mut deposit_reserve_asset = make_deposit_reserve_asset(&unknown_location);
+ let mut transfer_reserve_asset = make_transfer_reserve_asset(&unknown_location);
+ let mut deposit_reserve_asset = make_deposit_reserve_asset(&unknown_location);
- expect_transfer_location_denied::<B>(
- logger,
- self_para_id,
- &unknown_location,
- &mut transfer_reserve_asset
- )?;
+ expect_transfer_location_denied::<B>(
+ logger,
+ self_para_id,
+ &unknown_location,
+ &mut transfer_reserve_asset,
+ )?;
- expect_transfer_location_denied::<B>(
- logger,
- self_para_id,
- &unknown_location,
- &mut deposit_reserve_asset
- )?;
+ expect_transfer_location_denied::<B>(
+ logger,
+ self_para_id,
+ &unknown_location,
+ &mut deposit_reserve_asset,
+ )?;
- Ok(())
+ Ok(())
}
runtime/opal/src/tests/logcapture.rsdiffbeforeafterboth--- a/runtime/opal/src/tests/logcapture.rs
+++ b/runtime/opal/src/tests/logcapture.rs
@@ -19,7 +19,7 @@
#[test]
fn opal_log_capture_tests() {
- let mut logger = Logger::start();
-
- opal_xcm_tests(&mut logger);
+ let mut logger = Logger::start();
+
+ opal_xcm_tests(&mut logger);
}
runtime/opal/src/tests/mod.rsdiffbeforeafterboth--- a/runtime/opal/src/tests/mod.rs
+++ b/runtime/opal/src/tests/mod.rs
@@ -14,5 +14,5 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+mod logcapture;
mod xcm;
-mod logcapture;
runtime/opal/src/tests/xcm.rsdiffbeforeafterboth--- a/runtime/opal/src/tests/xcm.rs
+++ b/runtime/opal/src/tests/xcm.rs
@@ -15,18 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use logtest::Logger;
-use crate::{
- runtime_common::tests::xcm::*,
- xcm_config::Barrier,
-};
+use crate::{runtime_common::tests::xcm::*, xcm_config::Barrier};
const OPAL_PARA_ID: u32 = 2095; // Same as Quartz
pub fn opal_xcm_tests(logger: &mut Logger) {
- barrier_denies_transact::<Barrier>(logger);
+ barrier_denies_transact::<Barrier>(logger);
- barrier_denies_transfer_from_unknown_location::<Barrier>(
- logger,
- OPAL_PARA_ID,
- ).expect_err("opal runtime allows any location");
+ barrier_denies_transfer_from_unknown_location::<Barrier>(logger, OPAL_PARA_ID)
+ .expect_err("opal runtime allows any location");
}
runtime/opal/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/opal/src/xcm_config.rs
+++ b/runtime/opal/src/xcm_config.rs
@@ -14,98 +14,41 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use cumulus_pallet_xcm;
use frame_support::{
{match_types, parameter_types, weights::Weight},
pallet_prelude::Get,
- traits::{Contains, Everything, fungibles},
+ traits::{Contains, Everything},
};
-use frame_system::EnsureRoot;
use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain::primitives::Sibling;
-use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};
-use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
+use sp_runtime::traits::{AccountIdConversion, Convert};
+use sp_std::{vec, vec::Vec};
use xcm::{
- latest::{MultiAsset, Xcm},
- prelude::{Concrete, Fungible as XcmFungible},
+ latest::Xcm,
v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
};
use xcm_builder::{
- AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, EnsureXcmOrigin,
- FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset,
- RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
- SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
- ConvertedConcreteAssetId,
-};
-use xcm_executor::{
- {Config, XcmExecutor},
- traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},
+ AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, FixedWeightBounds, LocationInverter,
+ TakeWeightCredit,
};
+use xcm_executor::{XcmExecutor, traits::ShouldExecute};
-use up_common::{
- constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},
- types::{AccountId, Balance},
-};
-
+use up_common::types::{AccountId, Balance};
use crate::{
- Balances, Call, DmpQueue, Event, ForeingAssets, Origin, ParachainInfo, ParachainSystem,
- PolkadotXcm, Runtime, XcmpQueue,
+ Call, Event, ParachainInfo, Runtime,
+ runtime_common::config::{
+ substrate::{TreasuryModuleId, MaxLocks, MaxReserves},
+ pallets::TreasuryAccountId,
+ xcm::*,
+ },
};
-use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};
-use crate::runtime_common::config::pallets::TreasuryAccountId;
-use crate::runtime_common::config::xcm::*;
-use crate::*;
use pallet_foreing_assets::{
- AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,
- TryAsForeing, ForeignAssetId,
+ AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
};
// Signed version of balance
pub type Amount = i128;
-
-parameter_types! {
- pub const RelayLocation: MultiLocation = MultiLocation::parent();
- pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
- pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
- pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
- pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-}
-/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
-/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
-/// biases the kind of local `Origin` it will become.
-pub type XcmOriginToTransactDispatchOrigin = (
- // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
- // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
- // foreign chains who want to have a local sovereign account on this chain which they control.
- SovereignSignedViaLocation<LocationToAccountId, Origin>,
- // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
- // recognised.
- RelayChainAsNative<RelayOrigin, Origin>,
- // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
- // recognised.
- SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
- // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
- // transaction from the Root origin.
- ParentAsSuperuser<Origin>,
- // Native signed account converter; this just converts an `AccountId32` origin into a normal
- // `Origin::Signed` origin of the same 32-byte value.
- SignedAccountId32AsNative<RelayNetwork, Origin>,
- // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
- XcmPassthrough<Origin>,
-);
-
-parameter_types! {
- // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
- pub UnitWeightCost: Weight = 1_000_000;
- // 1200 UNIQUEs buy 1 second of weight.
- pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);
- pub const MaxInstructions: u32 = 100;
- pub const MaxAuthorities: u32 = 100_000;
-}
-
match_types! {
pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
@@ -123,8 +66,8 @@
fn should_execute<Call>(
_origin: &MultiLocation,
_message: &mut Xcm<Call>,
- max_weight: Weight,
- weight_credit: &mut Weight,
+ _max_weight: Weight,
+ _weight_credit: &mut Weight,
) -> Result<(), ()> {
Ok(())
}
@@ -138,31 +81,9 @@
AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,
// ^^^ Parent & its unit plurality gets free execution
AllowAllDebug,
- )
+ ),
>;
-
-pub struct AllAsset;
-impl FilterAssetLocation for AllAsset {
- fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {
- true
- }
-}
-pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
- match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetIds::ForeignAssetId(foreign_asset_id) => {
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
- }
- }
- }
-}
impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(location: MultiLocation) -> Option<CurrencyId> {
if location == MultiLocation::here()
@@ -185,15 +106,39 @@
}
}
-pub fn get_all_module_accounts() -> Vec<AccountId> {
- vec![TreasuryModuleId::get().into_account_truncating()]
+impl orml_tokens::Config for Runtime {
+ type Event = Event;
+ type Balance = Balance;
+ type Amount = Amount;
+ type CurrencyId = CurrencyId;
+ type WeightInfo = ();
+ type ExistentialDeposits = ExistentialDeposits;
+ type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
+ type MaxLocks = MaxLocks;
+ type MaxReserves = MaxReserves;
+ // TODO: Add all module accounts
+ type DustRemovalWhitelist = DustRemovalWhitelist;
+ /// The id type for named reserves.
+ type ReserveIdentifier = ();
+ type OnNewTokenAccount = ();
+ type OnKilledTokenAccount = ();
}
-pub struct DustRemovalWhitelist;
-impl Contains<AccountId> for DustRemovalWhitelist {
- fn contains(a: &AccountId) -> bool {
- get_all_module_accounts().contains(a)
- }
+impl orml_xtokens::Config for Runtime {
+ type Event = Event;
+ type Balance = Balance;
+ type CurrencyId = CurrencyId;
+ type CurrencyIdConvert = CurrencyIdConvert;
+ type AccountIdToMultiLocation = AccountIdToMultiLocation;
+ type SelfLocation = SelfLocation;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type BaseXcmWeight = BaseXcmWeight;
+ type LocationInverter = LocationInverter<Ancestry>;
+ type MaxAssetsForTransfer = MaxAssetsForTransfer;
+ type MinXcmFee = ParachainMinFee;
+ type MultiLocationsFilter = Everything;
+ type ReserveProvider = AbsoluteReserveProvider;
}
parameter_type_with_key! {
@@ -208,27 +153,35 @@
};
}
-impl orml_tokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type Amount = Amount;
- type CurrencyId = CurrencyId;
- type WeightInfo = ();
- type ExistentialDeposits = ExistentialDeposits;
- type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
- type MaxLocks = MaxLocks;
- type MaxReserves = MaxReserves;
- // TODO: Add all module accounts
- type DustRemovalWhitelist = DustRemovalWhitelist;
- /// The id type for named reserves.
- type ReserveIdentifier = ();
- type OnNewTokenAccount = ();
- type OnKilledTokenAccount = ();
+pub struct DustRemovalWhitelist;
+impl Contains<AccountId> for DustRemovalWhitelist {
+ fn contains(a: &AccountId) -> bool {
+ get_all_module_accounts().contains(a)
+ }
+}
+
+pub struct CurrencyIdConvert;
+impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
+ fn convert(id: AssetIds) -> Option<MultiLocation> {
+ match id {
+ AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+ 1,
+ X1(Parachain(ParachainInfo::get().into())),
+ )),
+ AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
+ AssetIds::ForeignAssetId(foreign_asset_id) => {
+ XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
+ }
+ }
+ }
}
parameter_types! {
pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this
pub const MaxAssetsForTransfer: usize = 2;
+
+ pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
+ pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
}
parameter_type_with_key! {
@@ -237,6 +190,9 @@
};
}
+pub fn get_all_module_accounts() -> Vec<AccountId> {
+ vec![TreasuryModuleId::get().into_account_truncating()]
+}
pub struct AccountIdToMultiLocation;
impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {
fn convert(account: AccountId) -> MultiLocation {
@@ -246,21 +202,4 @@
})
.into()
}
-}
-
-impl orml_xtokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type CurrencyId = CurrencyId;
- type CurrencyIdConvert = CurrencyIdConvert;
- type AccountIdToMultiLocation = AccountIdToMultiLocation;
- type SelfLocation = SelfLocation;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
- type BaseXcmWeight = BaseXcmWeight;
- type LocationInverter = LocationInverter<Ancestry>;
- type MaxAssetsForTransfer = MaxAssetsForTransfer;
- type MinXcmFee = ParachainMinFee;
- type MultiLocationsFilter = Everything;
- type ReserveProvider = AbsoluteReserveProvider;
}
runtime/quartz/src/tests/logcapture.rsdiffbeforeafterboth--- a/runtime/quartz/src/tests/logcapture.rs
+++ b/runtime/quartz/src/tests/logcapture.rs
@@ -19,7 +19,7 @@
#[test]
fn quartz_log_capture_tests() {
- let mut logger = Logger::start();
-
- quartz_xcm_tests(&mut logger);
+ let mut logger = Logger::start();
+
+ quartz_xcm_tests(&mut logger);
}
runtime/quartz/src/tests/mod.rsdiffbeforeafterboth--- a/runtime/quartz/src/tests/mod.rs
+++ b/runtime/quartz/src/tests/mod.rs
@@ -14,5 +14,5 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+mod logcapture;
mod xcm;
-mod logcapture;
runtime/quartz/src/tests/xcm.rsdiffbeforeafterboth--- a/runtime/quartz/src/tests/xcm.rs
+++ b/runtime/quartz/src/tests/xcm.rs
@@ -15,18 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use logtest::Logger;
-use crate::{
- runtime_common::tests::xcm::*,
- xcm_config::Barrier,
-};
+use crate::{runtime_common::tests::xcm::*, xcm_config::Barrier};
const QUARTZ_PARA_ID: u32 = 2095;
pub fn quartz_xcm_tests(logger: &mut Logger) {
- barrier_denies_transact::<Barrier>(logger);
+ barrier_denies_transact::<Barrier>(logger);
- barrier_denies_transfer_from_unknown_location::<Barrier>(
- logger,
- QUARTZ_PARA_ID,
- ).expect("quartz runtime denies an unknown location");
+ barrier_denies_transfer_from_unknown_location::<Barrier>(logger, QUARTZ_PARA_ID)
+ .expect("quartz runtime denies an unknown location");
}
runtime/quartz/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/quartz/src/xcm_config.rs
+++ b/runtime/quartz/src/xcm_config.rs
@@ -14,53 +14,31 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use cumulus_pallet_xcm;
use frame_support::{
- {match_types, parameter_types, weights::Weight},
- pallet_prelude::Get,
- traits::{Contains, Everything, fungibles},
+ {match_types, parameter_types, weights::Weight},
+ pallet_prelude::Get,
+ traits::{Contains, Everything},
};
-use frame_system::EnsureRoot;
use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain::primitives::Sibling;
-use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};
-use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
+use sp_runtime::traits::{AccountIdConversion, Convert};
+use sp_std::{vec, vec::Vec};
use xcm::{
- latest::{MultiAsset, Xcm},
- prelude::{Concrete, Fungible as XcmFungible},
- v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
+ latest::Xcm,
+ v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
};
use xcm_builder::{
- AllowKnownQueryResponses, AllowSubscriptionsFrom,
- AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
- EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,
- ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
- SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
- ConvertedConcreteAssetId,
+ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom,
+ AllowUnpaidExecutionFrom, FixedWeightBounds, LocationInverter, TakeWeightCredit,
};
-use xcm_executor::{
- {Config, XcmExecutor},
- traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible},
-};
+use xcm_executor::XcmExecutor;
-use up_common::{
- constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},
- types::{AccountId, Balance},
-};
-use pallet_foreing_assets::{
- AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
- FreeForAll, TryAsForeing, ForeignAssetId,
-};
-use crate::{
- Balances, Call, DmpQueue, Event, Origin, ParachainInfo,
- ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,
-};
+use up_common::types::{AccountId, Balance};
+use pallet_foreing_assets::{AssetIds, CurrencyId, NativeCurrency};
+use crate::{Call, Event, ParachainInfo, PolkadotXcm, Runtime};
use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};
use crate::runtime_common::config::pallets::TreasuryAccountId;
use crate::runtime_common::config::xcm::*;
-use crate::*;
-use xcm::opaque::latest::prelude::{ DepositReserveAsset, DepositAsset, TransferAsset, TransferReserveAsset };
+use xcm::opaque::latest::prelude::{DepositReserveAsset, TransferReserveAsset};
// Signed version of balance
pub type Amount = i128;
@@ -76,103 +54,113 @@
};
}
+pub type Barrier = DenyThenTry<
+ (DenyTransact, DenyExchangeWithUnknownLocation),
+ (
+ TakeWeightCredit,
+ AllowTopLevelPaidExecutionFrom<Everything>,
+ // Parent and its exec plurality get free execution
+ AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
+ // Expected responses are OK.
+ AllowKnownQueryResponses<PolkadotXcm>,
+ // Subscriptions for version tracking are OK.
+ AllowSubscriptionsFrom<ParentOrSiblings>,
+ ),
+>;
+
pub fn get_allowed_locations() -> Vec<MultiLocation> {
- vec![
- // Self location
- MultiLocation { parents: 0, interior: Here },
- // Parent location
- MultiLocation { parents: 1, interior: Here },
- // Karura/Acala location
- MultiLocation { parents: 1, interior: X1(Parachain(2000)) },
- // Moonriver location
- MultiLocation { parents: 1, interior: X1(Parachain(2023)) },
- // Self parachain address
- MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },
- ]
+ vec![
+ // Self location
+ MultiLocation {
+ parents: 0,
+ interior: Here,
+ },
+ // Parent location
+ MultiLocation {
+ parents: 1,
+ interior: Here,
+ },
+ // Karura/Acala location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(2000)),
+ },
+ // Moonriver location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(2023)),
+ },
+ // Self parachain address
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(ParachainInfo::get().into())),
+ },
+ ]
}
// Allow xcm exchange only with locations in list
pub struct DenyExchangeWithUnknownLocation;
impl TryPass for DenyExchangeWithUnknownLocation {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut Xcm<Call>,
- ) -> Result<(), ()> {
+ fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {
+ // Check if deposit or transfer belongs to allowed parachains
+ let mut allowed = get_allowed_locations().contains(origin);
- // Check if deposit or transfer belongs to allowed parachains
- let mut allowed = get_allowed_locations().contains(origin);
+ message.0.iter().for_each(|inst| match inst {
+ DepositReserveAsset { dest: dst, .. } => {
+ allowed |= get_allowed_locations().contains(dst);
+ }
+ TransferReserveAsset { dest: dst, .. } => {
+ allowed |= get_allowed_locations().contains(dst);
+ }
+ _ => {}
+ });
- message.0.iter().for_each(|inst| {
- match inst {
- DepositReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }
- TransferReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }
- _ => {}
- }
- });
+ if allowed {
+ return Ok(());
+ }
- if allowed {
- return Ok(());
- }
-
- log::warn!(
+ log::warn!(
target: "xcm::barrier",
"Unexpected deposit or transfer location"
);
- // Deny
- Err(())
- }
+ // Deny
+ Err(())
+ }
}
-pub type Barrier = DenyThenTry<
- (
- DenyTransact,
- DenyExchangeWithUnknownLocation,
- ),
- (
- TakeWeightCredit,
- AllowTopLevelPaidExecutionFrom<Everything>,
- // Parent and its exec plurality get free execution
- AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
- // Expected responses are OK.
- AllowKnownQueryResponses<PolkadotXcm>,
- // Subscriptions for version tracking are OK.
- AllowSubscriptionsFrom<ParentOrSiblings>,
- ),
->;
-
impl orml_tokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type Amount = Amount;
- type CurrencyId = CurrencyId;
- type WeightInfo = ();
- type ExistentialDeposits = ExistentialDeposits;
- type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
- type MaxLocks = MaxLocks;
- type MaxReserves = MaxReserves;
- // TODO: Add all module accounts
- type DustRemovalWhitelist = DustRemovalWhitelist;
- /// The id type for named reserves.
- type ReserveIdentifier = ();
- type OnNewTokenAccount = ();
- type OnKilledTokenAccount = ();
+ type Event = Event;
+ type Balance = Balance;
+ type Amount = Amount;
+ type CurrencyId = CurrencyId;
+ type WeightInfo = ();
+ type ExistentialDeposits = ExistentialDeposits;
+ type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
+ type MaxLocks = MaxLocks;
+ type MaxReserves = MaxReserves;
+ // TODO: Add all module accounts
+ type DustRemovalWhitelist = DustRemovalWhitelist;
+ /// The id type for named reserves.
+ type ReserveIdentifier = ();
+ type OnNewTokenAccount = ();
+ type OnKilledTokenAccount = ();
}
impl orml_xtokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type CurrencyId = CurrencyId;
- type CurrencyIdConvert = CurrencyIdConvert;
- type AccountIdToMultiLocation = AccountIdToMultiLocation;
- type SelfLocation = SelfLocation;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
- type BaseXcmWeight = BaseXcmWeight;
- type LocationInverter = LocationInverter<Ancestry>;
- type MaxAssetsForTransfer = MaxAssetsForTransfer;
- type MinXcmFee = ParachainMinFee;
- type MultiLocationsFilter = Everything;
- type ReserveProvider = AbsoluteReserveProvider;
+ type Event = Event;
+ type Balance = Balance;
+ type CurrencyId = CurrencyId;
+ type CurrencyIdConvert = CurrencyIdConvert;
+ type AccountIdToMultiLocation = AccountIdToMultiLocation;
+ type SelfLocation = SelfLocation;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type BaseXcmWeight = BaseXcmWeight;
+ type LocationInverter = LocationInverter<Ancestry>;
+ type MaxAssetsForTransfer = MaxAssetsForTransfer;
+ type MinXcmFee = ParachainMinFee;
+ type MultiLocationsFilter = Everything;
+ type ReserveProvider = AbsoluteReserveProvider;
}
parameter_type_with_key! {
@@ -189,34 +177,28 @@
pub struct DustRemovalWhitelist;
impl Contains<AccountId> for DustRemovalWhitelist {
- fn contains(a: &AccountId) -> bool {
- get_all_module_accounts().contains(a)
- }
+ fn contains(a: &AccountId) -> bool {
+ get_all_module_accounts().contains(a)
+ }
}
pub struct CurrencyIdConvert;
impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
- match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetIds::ForeignAssetId(_) => None,
- }
- }
+ fn convert(id: AssetIds) -> Option<MultiLocation> {
+ match id {
+ AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+ 1,
+ X1(Parachain(ParachainInfo::get().into())),
+ )),
+ _ => None,
+ }
+ }
}
parameter_types! {
pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this
pub const MaxAssetsForTransfer: usize = 2;
-}
-parameter_types! {
- pub const RelayLocation: MultiLocation = MultiLocation::parent();
- pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
- pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
}
@@ -228,16 +210,16 @@
}
pub fn get_all_module_accounts() -> Vec<AccountId> {
- vec![TreasuryModuleId::get().into_account_truncating()]
+ vec![TreasuryModuleId::get().into_account_truncating()]
}
pub struct AccountIdToMultiLocation;
impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {
- fn convert(account: AccountId) -> MultiLocation {
- X1(AccountId32 {
- network: NetworkId::Any,
- id: account.into(),
- })
- .into()
- }
+ fn convert(account: AccountId) -> MultiLocation {
+ X1(AccountId32 {
+ network: NetworkId::Any,
+ id: account.into(),
+ })
+ .into()
+ }
}
runtime/unique/src/tests/logcapture.rsdiffbeforeafterboth--- a/runtime/unique/src/tests/logcapture.rs
+++ b/runtime/unique/src/tests/logcapture.rs
@@ -19,7 +19,7 @@
#[test]
fn unique_log_capture_tests() {
- let mut logger = Logger::start();
-
- unique_xcm_tests(&mut logger);
+ let mut logger = Logger::start();
+
+ unique_xcm_tests(&mut logger);
}
runtime/unique/src/tests/mod.rsdiffbeforeafterboth--- a/runtime/unique/src/tests/mod.rs
+++ b/runtime/unique/src/tests/mod.rs
@@ -14,5 +14,5 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+mod logcapture;
mod xcm;
-mod logcapture;
runtime/unique/src/tests/xcm.rsdiffbeforeafterboth--- a/runtime/unique/src/tests/xcm.rs
+++ b/runtime/unique/src/tests/xcm.rs
@@ -15,18 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use logtest::Logger;
-use crate::{
- runtime_common::tests::xcm::*,
- xcm_config::Barrier,
-};
+use crate::{runtime_common::tests::xcm::*, xcm_config::Barrier};
const UNIQUE_PARA_ID: u32 = 2037;
pub fn unique_xcm_tests(logger: &mut Logger) {
- barrier_denies_transact::<Barrier>(logger);
+ barrier_denies_transact::<Barrier>(logger);
- barrier_denies_transfer_from_unknown_location::<Barrier>(
- logger,
- UNIQUE_PARA_ID,
- ).expect("unique runtime denies an unknown location");
+ barrier_denies_transfer_from_unknown_location::<Barrier>(logger, UNIQUE_PARA_ID)
+ .expect("unique runtime denies an unknown location");
}
runtime/unique/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/unique/src/xcm_config.rs
+++ b/runtime/unique/src/xcm_config.rs
@@ -14,143 +14,153 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use cumulus_pallet_xcm;
use frame_support::{
- {match_types, parameter_types, weights::Weight},
- pallet_prelude::Get,
- traits::{Contains, Everything, fungibles},
+ {match_types, parameter_types, weights::Weight},
+ pallet_prelude::Get,
+ traits::{Contains, Everything},
};
-use frame_system::EnsureRoot;
use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain::primitives::Sibling;
-use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};
-use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
+use sp_runtime::traits::{AccountIdConversion, Convert};
+use sp_std::{vec, vec::Vec};
use xcm::{
- latest::{MultiAsset, Xcm},
- prelude::{Concrete, Fungible as XcmFungible},
- v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
+ latest::Xcm,
+ v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
};
use xcm_builder::{
- AllowKnownQueryResponses, AllowSubscriptionsFrom,
- AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
- EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,
- ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
- SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
- ConvertedConcreteAssetId,
+ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom,
+ AllowUnpaidExecutionFrom, FixedWeightBounds, LocationInverter, TakeWeightCredit,
};
-use xcm_executor::{
- {Config, XcmExecutor},
- traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible},
-};
+use xcm_executor::XcmExecutor;
-use up_common::{
- constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},
- types::{AccountId, Balance},
-};
-use pallet_foreing_assets::{
- AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
- FreeForAll, TryAsForeing, ForeignAssetId,
-};
-use crate::{
- Balances, Call, DmpQueue, Event, Origin, ParachainInfo,
- ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,
-};
+use up_common::types::{AccountId, Balance};
+use pallet_foreing_assets::{AssetIds, CurrencyId, NativeCurrency};
+use crate::{Call, Event, ParachainInfo, PolkadotXcm, Runtime};
use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};
use crate::runtime_common::config::pallets::TreasuryAccountId;
use crate::runtime_common::config::xcm::*;
-use crate::*;
-use xcm::opaque::latest::prelude::{ DepositReserveAsset, DepositAsset, TransferAsset, TransferReserveAsset };
+use xcm::opaque::latest::prelude::{DepositReserveAsset, TransferReserveAsset};
// Signed version of balance
pub type Amount = i128;
+match_types! {
+ pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
+ MultiLocation { parents: 1, interior: Here } |
+ MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
+ };
+ pub type ParentOrSiblings: impl Contains<MultiLocation> = {
+ MultiLocation { parents: 1, interior: Here } |
+ MultiLocation { parents: 1, interior: X1(_) }
+ };
+}
pub type Barrier = DenyThenTry<
- (
- DenyTransact,
- DenyExchangeWithUnknownLocation,
- ),
- (
- TakeWeightCredit,
- AllowTopLevelPaidExecutionFrom<Everything>,
- // Parent and its exec plurality get free execution
- AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
- // Expected responses are OK.
- AllowKnownQueryResponses<PolkadotXcm>,
- // Subscriptions for version tracking are OK.
- AllowSubscriptionsFrom<ParentOrSiblings>,
- ),
+ (DenyTransact, DenyExchangeWithUnknownLocation),
+ (
+ TakeWeightCredit,
+ AllowTopLevelPaidExecutionFrom<Everything>,
+ // Parent and its exec plurality get free execution
+ AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
+ // Expected responses are OK.
+ AllowKnownQueryResponses<PolkadotXcm>,
+ // Subscriptions for version tracking are OK.
+ AllowSubscriptionsFrom<ParentOrSiblings>,
+ ),
>;
pub fn get_allowed_locations() -> Vec<MultiLocation> {
- vec![
- // Self location
- MultiLocation { parents: 0, interior: Here },
- // Parent location
- MultiLocation { parents: 1, interior: Here },
- // Karura/Acala location
- MultiLocation { parents: 1, interior: X1(Parachain(2000)) },
- // Moonbeam location
- MultiLocation { parents: 1, interior: X1(Parachain(2004)) },
- // Self parachain address
- MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },
- ]
+ vec![
+ // Self location
+ MultiLocation {
+ parents: 0,
+ interior: Here,
+ },
+ // Parent location
+ MultiLocation {
+ parents: 1,
+ interior: Here,
+ },
+ // Karura/Acala location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(2000)),
+ },
+ // Moonbeam location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(2004)),
+ },
+ // Self parachain address
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(ParachainInfo::get().into())),
+ },
+ ]
}
// Allow xcm exchange only with locations in list
pub struct DenyExchangeWithUnknownLocation;
impl TryPass for DenyExchangeWithUnknownLocation {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut Xcm<Call>,
- ) -> Result<(), ()> {
+ fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {
+ // Check if deposit or transfer belongs to allowed parachains
+ let mut allowed = get_allowed_locations().contains(origin);
- // Check if deposit or transfer belongs to allowed parachains
- let mut allowed = get_allowed_locations().contains(origin);
-
- message.0.iter().for_each(|inst| {
- match inst {
- DepositReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }
- TransferReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }
- _ => {}
- }
- });
+ message.0.iter().for_each(|inst| match inst {
+ DepositReserveAsset { dest: dst, .. } => {
+ allowed |= get_allowed_locations().contains(dst);
+ }
+ TransferReserveAsset { dest: dst, .. } => {
+ allowed |= get_allowed_locations().contains(dst);
+ }
+ _ => {}
+ });
- if allowed {
- return Ok(());
- }
+ if allowed {
+ return Ok(());
+ }
- log::warn!(
+ log::warn!(
target: "xcm::barrier",
"Unexpected deposit or transfer location"
);
- // Deny
- Err(())
- }
-}
-
-
-match_types! {
- pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
- MultiLocation { parents: 1, interior: Here } |
- MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
- };
- pub type ParentOrSiblings: impl Contains<MultiLocation> = {
- MultiLocation { parents: 1, interior: Here } |
- MultiLocation { parents: 1, interior: X1(_) }
- };
+ // Deny
+ Err(())
+ }
}
-pub fn get_all_module_accounts() -> Vec<AccountId> {
- vec![TreasuryModuleId::get().into_account_truncating()]
+impl orml_tokens::Config for Runtime {
+ type Event = Event;
+ type Balance = Balance;
+ type Amount = Amount;
+ type CurrencyId = CurrencyId;
+ type WeightInfo = ();
+ type ExistentialDeposits = ExistentialDeposits;
+ type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
+ type MaxLocks = MaxLocks;
+ type MaxReserves = MaxReserves;
+ // TODO: Add all module accounts
+ type DustRemovalWhitelist = DustRemovalWhitelist;
+ /// The id type for named reserves.
+ type ReserveIdentifier = ();
+ type OnNewTokenAccount = ();
+ type OnKilledTokenAccount = ();
}
-pub struct DustRemovalWhitelist;
-impl Contains<AccountId> for DustRemovalWhitelist {
- fn contains(a: &AccountId) -> bool {
- get_all_module_accounts().contains(a)
- }
+impl orml_xtokens::Config for Runtime {
+ type Event = Event;
+ type Balance = Balance;
+ type CurrencyId = CurrencyId;
+ type CurrencyIdConvert = CurrencyIdConvert;
+ type AccountIdToMultiLocation = AccountIdToMultiLocation;
+ type SelfLocation = SelfLocation;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type BaseXcmWeight = BaseXcmWeight;
+ type LocationInverter = LocationInverter<Ancestry>;
+ type MaxAssetsForTransfer = MaxAssetsForTransfer;
+ type MinXcmFee = ParachainMinFee;
+ type MultiLocationsFilter = Everything;
+ type ReserveProvider = AbsoluteReserveProvider;
}
parameter_type_with_key! {
@@ -165,60 +175,32 @@
};
}
-impl orml_tokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type Amount = Amount;
- type CurrencyId = CurrencyId;
- type WeightInfo = ();
- type ExistentialDeposits = ExistentialDeposits;
- type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
- type MaxLocks = MaxLocks;
- type MaxReserves = MaxReserves;
- // TODO: Add all module accounts
- type DustRemovalWhitelist = DustRemovalWhitelist;
- /// The id type for named reserves.
- type ReserveIdentifier = ();
- type OnNewTokenAccount = ();
- type OnKilledTokenAccount = ();
-}
-
-impl orml_xtokens::Config for Runtime {
- type Event = Event;
- type Balance = Balance;
- type CurrencyId = CurrencyId;
- type CurrencyIdConvert = CurrencyIdConvert;
- type AccountIdToMultiLocation = AccountIdToMultiLocation;
- type SelfLocation = SelfLocation;
- type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
- type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
- type BaseXcmWeight = BaseXcmWeight;
- type LocationInverter = LocationInverter<Ancestry>;
- type MaxAssetsForTransfer = MaxAssetsForTransfer;
- type MinXcmFee = ParachainMinFee;
- type MultiLocationsFilter = Everything;
- type ReserveProvider = AbsoluteReserveProvider;
+pub struct DustRemovalWhitelist;
+impl Contains<AccountId> for DustRemovalWhitelist {
+ fn contains(a: &AccountId) -> bool {
+ get_all_module_accounts().contains(a)
+ }
}
pub struct CurrencyIdConvert;
impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
- match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- _ => None,
- }
- }
+ fn convert(id: AssetIds) -> Option<MultiLocation> {
+ match id {
+ AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+ 1,
+ X1(Parachain(ParachainInfo::get().into())),
+ )),
+ _ => None,
+ }
+ }
}
parameter_types! {
pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this
pub const MaxAssetsForTransfer: usize = 2;
- pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
- pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
+ pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
+ pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
}
parameter_type_with_key! {
@@ -227,14 +209,17 @@
};
}
+pub fn get_all_module_accounts() -> Vec<AccountId> {
+ vec![TreasuryModuleId::get().into_account_truncating()]
+}
pub struct AccountIdToMultiLocation;
impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {
- fn convert(account: AccountId) -> MultiLocation {
- X1(AccountId32 {
- network: NetworkId::Any,
- id: account.into(),
- })
- .into()
- }
+ fn convert(account: AccountId) -> MultiLocation {
+ X1(AccountId32 {
+ network: NetworkId::Any,
+ id: account.into(),
+ })
+ .into()
+ }
}