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_executor::traits::{Convert as ConvertXcm, MatchesFungible, WeightTrader};39use xcm_builder::{40 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,41 FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,42 SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,43 SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,44};45use xcm_executor::{Config, XcmExecutor, Assets};46use pallet_foreing_assets::{47 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,48 UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,49};50use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};51use crate::{52 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue53};54#[cfg(feature = "foreign-assets")]55use crate::ForeingAssets;5657use up_common::{58 types::{AccountId, Balance},59 constants::*,60};6162parameter_types! {63 pub const RelayLocation: MultiLocation = MultiLocation::parent();64 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;65 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();66 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();67}6869707172pub type LocationToAccountId = (73 74 ParentIsPreset<AccountId>,75 76 SiblingParachainConvertsVia<Sibling, AccountId>,77 78 AccountId32Aliases<RelayNetwork, AccountId>,79);8081pub struct OnlySelfCurrency;82impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {83 fn matches_fungible(a: &MultiAsset) -> Option<B> {84 match (&a.id, &a.fun) {85 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),86 _ => None,87 }88 }89}909192pub type LocalAssetTransactor = CurrencyAdapter<93 94 Balances,95 96 OnlySelfCurrency,97 98 LocationToAccountId,99 100 AccountId,101 102 (),103>;104105106pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);107108109110pub type XcmRouter = (111 112 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,113 114 XcmpQueue,115);116117118119120pub type XcmOriginToTransactDispatchOrigin = (121 122 123 124 SovereignSignedViaLocation<LocationToAccountId, Origin>,125 126 127 RelayChainAsNative<RelayOrigin, Origin>,128 129 130 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,131 132 133 ParentAsSuperuser<Origin>,134 135 136 SignedAccountId32AsNative<RelayNetwork, Origin>,137 138 XcmPassthrough<Origin>,139);140141parameter_types! {142 143 pub UnitWeightCost: Weight = 1_000_000;144 145 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);146 pub const MaxInstructions: u32 = 100;147}148149match_types! {150 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {151 MultiLocation { parents: 1, interior: Here } |152 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }153 };154}155156pub type Barrier = (157 TakeWeightCredit,158 AllowTopLevelPaidExecutionFrom<Everything>,159 160);161162pub struct UsingOnlySelfCurrencyComponents<163 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,164 AssetId: Get<MultiLocation>,165 AccountId,166 Currency: CurrencyT<AccountId>,167 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,168>(169 Weight,170 Currency::Balance,171 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,172);173impl<174 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,175 AssetId: Get<MultiLocation>,176 AccountId,177 Currency: CurrencyT<AccountId>,178 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,179 > WeightTrader180 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>181{182 fn new() -> Self {183 Self(0, Zero::zero(), PhantomData)184 }185186 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {187 let amount = WeightToFee::weight_to_fee(&weight);188 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;189190 191 let option1: xcm::v1::AssetId = Concrete(MultiLocation {192 parents: 1,193 interior: X1(Parachain(ParachainInfo::parachain_id().into())),194 });195 196 let option2: xcm::v1::AssetId = Concrete(MultiLocation {197 parents: 0,198 interior: Here,199 });200201 let required = if payment.fungible.contains_key(&option1) {202 (option1, u128_amount).into()203 } else if payment.fungible.contains_key(&option2) {204 (option2, u128_amount).into()205 } else {206 (Concrete(MultiLocation::default()), u128_amount).into()207 };208209 let unused = payment210 .checked_sub(required)211 .map_err(|_| XcmError::TooExpensive)?;212 self.0 = self.0.saturating_add(weight);213 self.1 = self.1.saturating_add(amount);214 Ok(unused)215 }216217 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {218 let weight = weight.min(self.0);219 let amount = WeightToFee::weight_to_fee(&weight);220 self.0 -= weight;221 self.1 = self.1.saturating_sub(amount);222 let amount: u128 = amount.saturated_into();223 if amount > 0 {224 Some((AssetId::get(), amount).into())225 } else {226 None227 }228 }229}230impl<231 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,232 AssetId: Get<MultiLocation>,233 AccountId,234 Currency: CurrencyT<AccountId>,235 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,236 > Drop237 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>238{239 fn drop(&mut self) {240 OnUnbalanced::on_unbalanced(Currency::issue(self.1));241 }242}243244parameter_types! {245 pub CheckingAccount: AccountId = PolkadotXcm::check_account();246}247248#[cfg(feature = "foreign-assets")]249pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);250251#[cfg(feature = "foreign-assets")]252impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>253for NonZeroIssuance<AccountId, ForeingAssets>254 where255 ForeingAssets: fungibles::Inspect<AccountId>,256{257 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {258 !ForeingAssets::total_issuance(*id).is_zero()259 }260}261262#[cfg(feature = "foreign-assets")]263pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);264#[cfg(feature = "foreign-assets")]265impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>266ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>267 where268 AssetId: Borrow<AssetId>,269 AssetId: TryAsForeing<AssetId, ForeignAssetId>,270 AssetIds: Borrow<AssetId>,271{272 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {273 let id = id.borrow();274275 log::trace!(276 target: "xcm::AsInnerId::Convert",277 "AsInnerId {:?}",278 id279 );280281 let parent = MultiLocation::parent();282 let here = MultiLocation::here();283 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));284285 if *id == parent {286 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));287 }288289 if *id == here || *id == self_location {290 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));291 }292293 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {294 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {295 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))296 }297 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),298 }299 }300301 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {302 log::trace!(303 target: "xcm::AsInnerId::Reverse",304 "AsInnerId",305 );306307 let asset_id = what.borrow();308309 let parent_id =310 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();311 let here_id =312 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();313314 if asset_id.clone() == parent_id {315 return Ok(MultiLocation::parent());316 }317318 if asset_id.clone() == here_id {319 return Ok(MultiLocation::new(320 1,321 X1(Parachain(ParachainInfo::get().into())),322 ));323 }324325 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {326 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {327 Some(location) => Ok(location),328 None => Err(()),329 },330 None => Err(()),331 }332 }333}334335336#[cfg(feature = "foreign-assets")]337pub type FungiblesTransactor = FungiblesAdapter<338 339 ForeingAssets,340 341 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,342 343 LocationToAccountId,344 345 AccountId,346 347 348 NonZeroIssuance<AccountId, ForeingAssets>,349 350 CheckingAccount,351>;352353354#[cfg(feature = "foreign-assets")]355pub type AssetTransactors = FungiblesTransactor;356#[cfg(not(feature = "foreign-assets"))]357pub type AssetTransactors = LocalAssetTransactor;358359pub struct XcmConfig<T>(PhantomData<T>);360impl<T> Config for XcmConfig<T>361where362 T: pallet_configuration::Config,363{364 type Call = Call;365 type XcmSender = XcmRouter;366 367 type AssetTransactor = LocalAssetTransactor;368 type OriginConverter = XcmOriginToTransactDispatchOrigin;369 type IsReserve = NativeAsset;370 type IsTeleporter = (); 371 type LocationInverter = LocationInverter<Ancestry>;372 type Barrier = Barrier;373 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;374 type Trader = UsingOnlySelfCurrencyComponents<375 pallet_configuration::WeightToFee<T, Balance>,376 RelayLocation,377 AccountId,378 Balances,379 (),380 >;381 type ResponseHandler = (); 382 type SubscriptionService = PolkadotXcm;383384 type AssetTrap = PolkadotXcm;385 type AssetClaims = PolkadotXcm;386}387388impl pallet_xcm::Config for Runtime {389 type Event = Event;390 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;391 type XcmRouter = XcmRouter;392 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;393 type XcmExecuteFilter = Everything;394 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;395 type XcmTeleportFilter = Everything;396 type XcmReserveTransferFilter = Everything;397 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;398 type LocationInverter = LocationInverter<Ancestry>;399 type Origin = Origin;400 type Call = Call;401 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;402 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;403}404405impl cumulus_pallet_xcm::Config for Runtime {406 type Event = Event;407 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;408}409410impl cumulus_pallet_xcmp_queue::Config for Runtime {411 type WeightInfo = ();412 type Event = Event;413 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;414 type ChannelInfo = ParachainSystem;415 type VersionWrapper = ();416 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;417 type ControllerOrigin = EnsureRoot<AccountId>;418 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;419}420421impl cumulus_pallet_dmp_queue::Config for Runtime {422 type Event = Event;423 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;424 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;425}426