1234567891011121314151617use frame_support::{18 traits::{19 Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,20 Everything, 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,41 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,42 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,43 ParentIsPreset, ConvertedConcreteAssetId,44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{47 Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,48};49use pallet_foreing_assets::{50 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,51 TryAsForeing, ForeignAssetId,52};53use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};54use crate::{55 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,56 xcm_config::Barrier,57};58#[cfg(feature = "foreign-assets")]59use crate::ForeingAssets;6061use up_common::{62 types::{AccountId, Balance},63 constants::*,64};6566parameter_types! {67 pub const RelayLocation: MultiLocation = MultiLocation::parent();68 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;69 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();70 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();71}7273747576pub type LocationToAccountId = (77 78 ParentIsPreset<AccountId>,79 80 SiblingParachainConvertsVia<Sibling, AccountId>,81 82 AccountId32Aliases<RelayNetwork, AccountId>,83);8485pub struct OnlySelfCurrency;86impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {87 fn matches_fungible(a: &MultiAsset) -> Option<B> {88 let paraid = Parachain(ParachainInfo::parachain_id().into());89 match (&a.id, &a.fun) {90 (91 Concrete(MultiLocation {92 parents: 1,93 interior: X1(loc),94 }),95 XcmFungible(ref amount),96 ) if paraid == *loc => CheckedConversion::checked_from(*amount),97 (98 Concrete(MultiLocation {99 parents: 0,100 interior: Here,101 }),102 XcmFungible(ref amount),103 ) => CheckedConversion::checked_from(*amount),104 _ => None,105 }106 }107}108109110pub type LocalAssetTransactor = CurrencyAdapter<111 112 Balances,113 114 OnlySelfCurrency,115 116 LocationToAccountId,117 118 AccountId,119 120 (),121>;122123124pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);125126127128pub type XcmRouter = (129 130 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,131 132 XcmpQueue,133);134135136137138pub type XcmOriginToTransactDispatchOrigin = (139 140 141 142 SovereignSignedViaLocation<LocationToAccountId, Origin>,143 144 145 RelayChainAsNative<RelayOrigin, Origin>,146 147 148 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,149 150 151 ParentAsSuperuser<Origin>,152 153 154 SignedAccountId32AsNative<RelayNetwork, Origin>,155 156 XcmPassthrough<Origin>,157);158159parameter_types! {160 161 pub UnitWeightCost: Weight = 1_000_000;162 163 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);164 pub const MaxInstructions: u32 = 100;165}166167match_types! {168 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {169 MultiLocation { parents: 1, interior: Here } |170 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }171 };172}173174175176177178179180181182pub struct UsingOnlySelfCurrencyComponents<183 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,184 AssetId: Get<MultiLocation>,185 AccountId,186 Currency: CurrencyT<AccountId>,187 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,188>(189 Weight,190 Currency::Balance,191 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,192);193impl<194 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,195 AssetId: Get<MultiLocation>,196 AccountId,197 Currency: CurrencyT<AccountId>,198 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,199 > WeightTrader200 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>201{202 fn new() -> Self {203 Self(0, Zero::zero(), PhantomData)204 }205206 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {207 Ok(payment)208 }209}210impl<211 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,212 AssetId: Get<MultiLocation>,213 AccountId,214 Currency: CurrencyT<AccountId>,215 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,216 > Drop217 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>218{219 fn drop(&mut self) {220 OnUnbalanced::on_unbalanced(Currency::issue(self.1));221 }222}223224parameter_types! {225 pub CheckingAccount: AccountId = PolkadotXcm::check_account();226}227228#[cfg(feature = "foreign-assets")]229pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);230231#[cfg(feature = "foreign-assets")]232impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>233 for NonZeroIssuance<AccountId, ForeingAssets>234where235 ForeingAssets: fungibles::Inspect<AccountId>,236{237 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {238 !ForeingAssets::total_issuance(*id).is_zero()239 }240}241242#[cfg(feature = "foreign-assets")]243pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);244#[cfg(feature = "foreign-assets")]245impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>246 ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>247where248 AssetId: Borrow<AssetId>,249 AssetId: TryAsForeing<AssetId, ForeignAssetId>,250 AssetIds: Borrow<AssetId>,251{252 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {253 let id = id.borrow();254255 log::trace!(256 target: "xcm::AsInnerId::Convert",257 "AsInnerId {:?}",258 id259 );260261 let parent = MultiLocation::parent();262 let here = MultiLocation::here();263 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));264265 if *id == parent {266 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));267 }268269 if *id == here || *id == self_location {270 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));271 }272273 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {274 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {275 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))276 }277 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),278 }279 }280281 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {282 log::trace!(283 target: "xcm::AsInnerId::Reverse",284 "AsInnerId",285 );286287 let asset_id = what.borrow();288289 let parent_id =290 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();291 let here_id =292 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();293294 if asset_id.clone() == parent_id {295 return Ok(MultiLocation::parent());296 }297298 if asset_id.clone() == here_id {299 return Ok(MultiLocation::new(300 1,301 X1(Parachain(ParachainInfo::get().into())),302 ));303 }304305 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {306 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {307 Some(location) => Ok(location),308 None => Err(()),309 },310 None => Err(()),311 }312 }313}314315316#[cfg(feature = "foreign-assets")]317pub type FungiblesTransactor = FungiblesAdapter<318 319 ForeingAssets,320 321 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,322 323 LocationToAccountId,324 325 AccountId,326 327 328 NonZeroIssuance<AccountId, ForeingAssets>,329 330 CheckingAccount,331>;332333334#[cfg(feature = "foreign-assets")]335pub type AssetTransactors = FungiblesTransactor;336337#[cfg(not(feature = "foreign-assets"))]338pub type AssetTransactors = LocalAssetTransactor;339340#[cfg(feature = "foreign-assets")]341pub struct AllAsset;342#[cfg(feature = "foreign-assets")]343impl FilterAssetLocation for AllAsset {344 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {345 true346 }347}348349#[cfg(feature = "foreign-assets")]350pub type IsReserve = AllAsset;351#[cfg(not(feature = "foreign-assets"))]352pub type IsReserve = NativeAsset;353354#[cfg(feature = "foreign-assets")]355type Trader<T> = FreeForAll<356 pallet_configuration::WeightToFee<T, Balance>,357 RelayLocation,358 AccountId,359 Balances,360 (),361>;362#[cfg(not(feature = "foreign-assets"))]363type Trader<T> = UsingOnlySelfCurrencyComponents<364 pallet_configuration::WeightToFee<T, Balance>,365 RelayLocation,366 AccountId,367 Balances,368 (),369>;370371pub struct XcmConfig<T>(PhantomData<T>);372impl<T> Config for XcmConfig<T>373where374 T: pallet_configuration::Config,375{376 type Call = Call;377 type XcmSender = XcmRouter;378 379 type AssetTransactor = AssetTransactors;380 type OriginConverter = XcmOriginToTransactDispatchOrigin;381 type IsReserve = IsReserve;382 type IsTeleporter = (); 383 type LocationInverter = LocationInverter<Ancestry>;384 type Barrier = Barrier;385 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;386 type Trader = Trader<T>;387 type ResponseHandler = (); 388 type SubscriptionService = PolkadotXcm;389390 type AssetTrap = PolkadotXcm;391 type AssetClaims = PolkadotXcm;392}393394impl pallet_xcm::Config for Runtime {395 type Event = Event;396 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;397 type XcmRouter = XcmRouter;398 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;399 type XcmExecuteFilter = Everything;400 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;401 type XcmTeleportFilter = Everything;402 type XcmReserveTransferFilter = Everything;403 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;404 type LocationInverter = LocationInverter<Ancestry>;405 type Origin = Origin;406 type Call = Call;407 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;408 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;409}410411impl cumulus_pallet_xcm::Config for Runtime {412 type Event = Event;413 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;414}415416impl cumulus_pallet_xcmp_queue::Config for Runtime {417 type WeightInfo = ();418 type Event = Event;419 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;420 type ChannelInfo = ParachainSystem;421 type VersionWrapper = ();422 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;423 type ControllerOrigin = EnsureRoot<AccountId>;424 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;425}426427impl cumulus_pallet_dmp_queue::Config for Runtime {428 type Event = Event;429 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;430 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;431}