1234567891011121314151617use frame_support::{18 traits::{19 Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,20 fungibles,21 },22 weights::{Weight, WeightToFeePolynomial, WeightToFee},23 parameter_types, match_types,24};25use frame_system::EnsureRoot;26use sp_runtime::{27 traits::{Saturating, CheckedConversion, Zero},28 SaturatedConversion,29};30use pallet_xcm::XcmPassthrough;31use polkadot_parachain::primitives::Sibling;32use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};33use xcm::latest::{34 AssetId::{Concrete},35 Fungibility::Fungible as XcmFungible,36 MultiAsset, Error as XcmError,37};38use xcm_builder::{39 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40 FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,41 SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,42 SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,43 ConvertedConcreteAssetId44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation};47use pallet_foreing_assets::{48 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,49 UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,50};51use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};52use crate::{53 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,54 xcm_config::Barrier55};56#[cfg(feature = "foreign-assets")]57use crate::ForeingAssets;5859use up_common::{60 types::{AccountId, Balance},61 constants::*,62};6364parameter_types! {65 pub const RelayLocation: MultiLocation = MultiLocation::parent();66 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;67 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();68 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();69}7071727374pub type LocationToAccountId = (75 76 ParentIsPreset<AccountId>,77 78 SiblingParachainConvertsVia<Sibling, AccountId>,79 80 AccountId32Aliases<RelayNetwork, AccountId>,81);8283pub struct OnlySelfCurrency;84impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {85 fn matches_fungible(a: &MultiAsset) -> Option<B> {86 match (&a.id, &a.fun) {87 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),88 _ => None,89 }90 }91}929394pub type LocalAssetTransactor = CurrencyAdapter<95 96 Balances,97 98 OnlySelfCurrency,99 100 LocationToAccountId,101 102 AccountId,103 104 (),105>;106107108pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);109110111112pub type XcmRouter = (113 114 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,115 116 XcmpQueue,117);118119120121122pub type XcmOriginToTransactDispatchOrigin = (123 124 125 126 SovereignSignedViaLocation<LocationToAccountId, Origin>,127 128 129 RelayChainAsNative<RelayOrigin, Origin>,130 131 132 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,133 134 135 ParentAsSuperuser<Origin>,136 137 138 SignedAccountId32AsNative<RelayNetwork, Origin>,139 140 XcmPassthrough<Origin>,141);142143parameter_types! {144 145 pub UnitWeightCost: Weight = 1_000_000;146 147 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);148 pub const MaxInstructions: u32 = 100;149}150151match_types! {152 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {153 MultiLocation { parents: 1, interior: Here } |154 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }155 };156}157158159160161162163164165166pub struct UsingOnlySelfCurrencyComponents<167 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,168 AssetId: Get<MultiLocation>,169 AccountId,170 Currency: CurrencyT<AccountId>,171 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,172>(173 Weight,174 Currency::Balance,175 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,176);177impl<178 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,179 AssetId: Get<MultiLocation>,180 AccountId,181 Currency: CurrencyT<AccountId>,182 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,183 > WeightTrader184 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>185{186 fn new() -> Self {187 Self(0, Zero::zero(), PhantomData)188 }189190 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {191 let amount: Currency::Balance = (0 as u32).into();192 193 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;194195 196 let option1: xcm::v1::AssetId = Concrete(MultiLocation {197 parents: 1,198 interior: X1(Parachain(ParachainInfo::parachain_id().into())),199 });200 201 let option2: xcm::v1::AssetId = Concrete(MultiLocation {202 parents: 0,203 interior: Here,204 });205206 let required = if payment.fungible.contains_key(&option1) {207 (option1, u128_amount).into()208 } else if payment.fungible.contains_key(&option2) {209 (option2, u128_amount).into()210 } else {211 (Concrete(MultiLocation::default()), u128_amount).into()212 };213214 let unused = payment215 .checked_sub(required)216 .map_err(|_| XcmError::TooExpensive)?;217 self.0 = self.0.saturating_add(weight);218 self.1 = self.1.saturating_add(amount);219 Ok(unused)220 }221222 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {223 let weight = weight.min(self.0);224 let amount = WeightToFee::weight_to_fee(&weight);225 self.0 -= weight;226 self.1 = self.1.saturating_sub(amount);227 let amount: u128 = amount.saturated_into();228 if amount > 0 {229 Some((AssetId::get(), amount).into())230 } else {231 None232 }233 }234}235impl<236 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,237 AssetId: Get<MultiLocation>,238 AccountId,239 Currency: CurrencyT<AccountId>,240 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,241 > Drop242 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>243{244 fn drop(&mut self) {245 OnUnbalanced::on_unbalanced(Currency::issue(self.1));246 }247}248249parameter_types! {250 pub CheckingAccount: AccountId = PolkadotXcm::check_account();251}252253#[cfg(feature = "foreign-assets")]254pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);255256#[cfg(feature = "foreign-assets")]257impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>258for NonZeroIssuance<AccountId, ForeingAssets>259 where260 ForeingAssets: fungibles::Inspect<AccountId>,261{262 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {263 !ForeingAssets::total_issuance(*id).is_zero()264 }265}266267#[cfg(feature = "foreign-assets")]268pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);269#[cfg(feature = "foreign-assets")]270impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>271ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>272 where273 AssetId: Borrow<AssetId>,274 AssetId: TryAsForeing<AssetId, ForeignAssetId>,275 AssetIds: Borrow<AssetId>,276{277 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {278 let id = id.borrow();279280 log::trace!(281 target: "xcm::AsInnerId::Convert",282 "AsInnerId {:?}",283 id284 );285286 let parent = MultiLocation::parent();287 let here = MultiLocation::here();288 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));289290 if *id == parent {291 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));292 }293294 if *id == here || *id == self_location {295 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));296 }297298 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {299 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {300 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))301 }302 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),303 }304 }305306 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {307 log::trace!(308 target: "xcm::AsInnerId::Reverse",309 "AsInnerId",310 );311312 let asset_id = what.borrow();313314 let parent_id =315 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();316 let here_id =317 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();318319 if asset_id.clone() == parent_id {320 return Ok(MultiLocation::parent());321 }322323 if asset_id.clone() == here_id {324 return Ok(MultiLocation::new(325 1,326 X1(Parachain(ParachainInfo::get().into())),327 ));328 }329330 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {331 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {332 Some(location) => Ok(location),333 None => Err(()),334 },335 None => Err(()),336 }337 }338}339340341#[cfg(feature = "foreign-assets")]342pub type FungiblesTransactor = FungiblesAdapter<343 344 ForeingAssets,345 346 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,347 348 LocationToAccountId,349 350 AccountId,351 352 353 NonZeroIssuance<AccountId, ForeingAssets>,354 355 CheckingAccount,356>;357358359#[cfg(feature = "foreign-assets")]360pub type AssetTransactors = FungiblesTransactor;361362#[cfg(not(feature = "foreign-assets"))]363pub type AssetTransactors = LocalAssetTransactor;364365#[cfg(feature = "foreign-assets")]366pub struct AllAsset;367#[cfg(feature = "foreign-assets")]368impl FilterAssetLocation for AllAsset {369 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {370 true371 }372}373374#[cfg(feature = "foreign-assets")]375pub type IsReserve = AllAsset;376#[cfg(not(feature = "foreign-assets"))]377pub type IsReserve = NativeAsset;378379#[cfg(feature = "foreign-assets")]380type Trader<T> =381 UsingAnyCurrencyComponents<382 pallet_configuration::WeightToFee<T, Balance>,383 RelayLocation, AccountId, Balances, ()>;384#[cfg(not(feature = "foreign-assets"))]385type Trader<T> = UsingOnlySelfCurrencyComponents<386 pallet_configuration::WeightToFee<T, Balance>,387 RelayLocation,388 AccountId,389 Balances,390 (),391>;392393pub struct XcmConfig<T>(PhantomData<T>);394impl<T> Config for XcmConfig<T>395where396 T: pallet_configuration::Config,397{398 type Call = Call;399 type XcmSender = XcmRouter;400 401 type AssetTransactor = AssetTransactors;402 type OriginConverter = XcmOriginToTransactDispatchOrigin;403 type IsReserve = IsReserve;404 type IsTeleporter = (); 405 type LocationInverter = LocationInverter<Ancestry>;406 type Barrier = Barrier;407 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;408 type Trader = Trader<T>;409 type ResponseHandler = (); 410 type SubscriptionService = PolkadotXcm;411412 type AssetTrap = PolkadotXcm;413 type AssetClaims = PolkadotXcm;414}415416impl pallet_xcm::Config for Runtime {417 type Event = Event;418 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;419 type XcmRouter = XcmRouter;420 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;421 type XcmExecuteFilter = Everything;422 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;423 type XcmTeleportFilter = Everything;424 type XcmReserveTransferFilter = Everything;425 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;426 type LocationInverter = LocationInverter<Ancestry>;427 type Origin = Origin;428 type Call = Call;429 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;430 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;431}432433impl cumulus_pallet_xcm::Config for Runtime {434 type Event = Event;435 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;436}437438impl cumulus_pallet_xcmp_queue::Config for Runtime {439 type WeightInfo = ();440 type Event = Event;441 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;442 type ChannelInfo = ParachainSystem;443 type VersionWrapper = ();444 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;445 type ControllerOrigin = EnsureRoot<AccountId>;446 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;447}448449impl cumulus_pallet_dmp_queue::Config for Runtime {450 type Event = Event;451 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;452 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;453}454