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 = WeightToFee::weight_to_fee(&weight);192 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;193194 195 let option1: xcm::v1::AssetId = Concrete(MultiLocation {196 parents: 1,197 interior: X1(Parachain(ParachainInfo::parachain_id().into())),198 });199 200 let option2: xcm::v1::AssetId = Concrete(MultiLocation {201 parents: 0,202 interior: Here,203 });204205 let required = if payment.fungible.contains_key(&option1) {206 (option1, u128_amount).into()207 } else if payment.fungible.contains_key(&option2) {208 (option2, u128_amount).into()209 } else {210 (Concrete(MultiLocation::default()), u128_amount).into()211 };212213 let unused = payment214 .checked_sub(required)215 .map_err(|_| XcmError::TooExpensive)?;216 self.0 = self.0.saturating_add(weight);217 self.1 = self.1.saturating_add(amount);218 Ok(unused)219 }220221 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {222 let weight = weight.min(self.0);223 let amount = WeightToFee::weight_to_fee(&weight);224 self.0 -= weight;225 self.1 = self.1.saturating_sub(amount);226 let amount: u128 = amount.saturated_into();227 if amount > 0 {228 Some((AssetId::get(), amount).into())229 } else {230 None231 }232 }233}234impl<235 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,236 AssetId: Get<MultiLocation>,237 AccountId,238 Currency: CurrencyT<AccountId>,239 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,240 > Drop241 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>242{243 fn drop(&mut self) {244 OnUnbalanced::on_unbalanced(Currency::issue(self.1));245 }246}247248parameter_types! {249 pub CheckingAccount: AccountId = PolkadotXcm::check_account();250}251252#[cfg(feature = "foreign-assets")]253pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);254255#[cfg(feature = "foreign-assets")]256impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>257for NonZeroIssuance<AccountId, ForeingAssets>258 where259 ForeingAssets: fungibles::Inspect<AccountId>,260{261 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {262 !ForeingAssets::total_issuance(*id).is_zero()263 }264}265266#[cfg(feature = "foreign-assets")]267pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);268#[cfg(feature = "foreign-assets")]269impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>270ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>271 where272 AssetId: Borrow<AssetId>,273 AssetId: TryAsForeing<AssetId, ForeignAssetId>,274 AssetIds: Borrow<AssetId>,275{276 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {277 let id = id.borrow();278279 log::trace!(280 target: "xcm::AsInnerId::Convert",281 "AsInnerId {:?}",282 id283 );284285 let parent = MultiLocation::parent();286 let here = MultiLocation::here();287 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));288289 if *id == parent {290 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));291 }292293 if *id == here || *id == self_location {294 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));295 }296297 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {298 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {299 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))300 }301 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),302 }303 }304305 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {306 log::trace!(307 target: "xcm::AsInnerId::Reverse",308 "AsInnerId",309 );310311 let asset_id = what.borrow();312313 let parent_id =314 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();315 let here_id =316 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();317318 if asset_id.clone() == parent_id {319 return Ok(MultiLocation::parent());320 }321322 if asset_id.clone() == here_id {323 return Ok(MultiLocation::new(324 1,325 X1(Parachain(ParachainInfo::get().into())),326 ));327 }328329 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {330 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {331 Some(location) => Ok(location),332 None => Err(()),333 },334 None => Err(()),335 }336 }337}338339340#[cfg(feature = "foreign-assets")]341pub type FungiblesTransactor = FungiblesAdapter<342 343 ForeingAssets,344 345 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,346 347 LocationToAccountId,348 349 AccountId,350 351 352 NonZeroIssuance<AccountId, ForeingAssets>,353 354 CheckingAccount,355>;356357358#[cfg(feature = "foreign-assets")]359pub type AssetTransactors = FungiblesTransactor;360361362363364#[cfg(feature = "foreign-assets")]365pub struct AllAsset;366#[cfg(feature = "foreign-assets")]367impl FilterAssetLocation for AllAsset {368 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {369 true370 }371}372373#[cfg(feature = "foreign-assets")]374pub type IsReserve = AllAsset;375376377378#[cfg(feature = "foreign-assets")]379type Trader<T> =380 UsingAnyCurrencyComponents<381 pallet_configuration::WeightToFee<T, Balance>,382 RelayLocation, AccountId, Balances, ()>;383384385386387388389390391392393394pub struct XcmConfig<T>(PhantomData<T>);395impl<T> Config for XcmConfig<T>396where397 T: pallet_configuration::Config,398{399 type Call = Call;400 type XcmSender = XcmRouter;401 402 type AssetTransactor = LocalAssetTransactor;403 type OriginConverter = XcmOriginToTransactDispatchOrigin;404 type IsReserve = IsReserve;405 type IsTeleporter = (); 406 type LocationInverter = LocationInverter<Ancestry>;407 type Barrier = Barrier;408 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;409 type Trader = Trader<T>;410 type ResponseHandler = (); 411 type SubscriptionService = PolkadotXcm;412413 type AssetTrap = PolkadotXcm;414 type AssetClaims = PolkadotXcm;415}416417impl pallet_xcm::Config for Runtime {418 type Event = Event;419 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;420 type XcmRouter = XcmRouter;421 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;422 type XcmExecuteFilter = Everything;423 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;424 type XcmTeleportFilter = Everything;425 type XcmReserveTransferFilter = Everything;426 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;427 type LocationInverter = LocationInverter<Ancestry>;428 type Origin = Origin;429 type Call = Call;430 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;431 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;432}433434impl cumulus_pallet_xcm::Config for Runtime {435 type Event = Event;436 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;437}438439impl cumulus_pallet_xcmp_queue::Config for Runtime {440 type WeightInfo = ();441 type Event = Event;442 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;443 type ChannelInfo = ParachainSystem;444 type VersionWrapper = ();445 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;446 type ControllerOrigin = EnsureRoot<AccountId>;447 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;448}449450impl cumulus_pallet_dmp_queue::Config for Runtime {451 type Event = Event;452 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;453 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;454}455