difftreelog
Set XCM incoming transaction fee amount to 0.
in: master
2 files changed
pallets/foreing-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreing-assets/src/lib.rs
+++ b/pallets/foreing-assets/src/lib.rs
@@ -486,7 +486,7 @@
fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
- let amount = WeightToFee::weight_to_fee(&weight);
+ let amount: Currency::Balance = (0 as u32).into();
let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;
let asset_id = payment
runtime/common/config/xcm.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/>.1617use 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}7071/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used72/// when determining ownership of accounts for asset transacting and when attempting to use XCM73/// `Transact` in order to determine the dispatch Origin.74pub type LocationToAccountId = (75 // The parent (Relay-chain) origin converts to the default `AccountId`.76 ParentIsPreset<AccountId>,77 // Sibling parachain origins convert to AccountId via the `ParaId::into`.78 SiblingParachainConvertsVia<Sibling, AccountId>,79 // Straight up local `AccountId32` origins just alias directly to `AccountId`.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}9293/// Means for transacting assets on this chain.94pub type LocalAssetTransactor = CurrencyAdapter<95 // Use this currency:96 Balances,97 // Use this currency when it is a fungible asset matching the given location or name:98 OnlySelfCurrency,99 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:100 LocationToAccountId,101 // Our chain's account ID type (we can't get away without mentioning it explicitly):102 AccountId,103 // We don't track any teleports.104 (),105>;106107/// No local origins on this chain are allowed to dispatch XCM sends/executions.108pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);109110/// The means for routing XCM messages which are not for local execution into the right message111/// queues.112pub type XcmRouter = (113 // Two routers - use UMP to communicate with the relay chain:114 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,115 // ..and XCMP to communicate with the sibling chains.116 XcmpQueue,117);118119/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,120/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can121/// biases the kind of local `Origin` it will become.122pub type XcmOriginToTransactDispatchOrigin = (123 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location124 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for125 // foreign chains who want to have a local sovereign account on this chain which they control.126 SovereignSignedViaLocation<LocationToAccountId, Origin>,127 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when128 // recognised.129 RelayChainAsNative<RelayOrigin, Origin>,130 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when131 // recognised.132 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,133 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a134 // transaction from the Root origin.135 ParentAsSuperuser<Origin>,136 // Native signed account converter; this just converts an `AccountId32` origin into a normal137 // `Origin::Signed` origin of the same 32-byte value.138 SignedAccountId32AsNative<RelayNetwork, Origin>,139 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.140 XcmPassthrough<Origin>,141);142143parameter_types! {144 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.145 pub UnitWeightCost: Weight = 1_000_000;146 // 1200 UNIQUEs buy 1 second of weight.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}157158/*159pub type Barrier = (160 TakeWeightCredit,161 AllowTopLevelPaidExecutionFrom<Everything>,162 // ^^^ Parent & its unit plurality gets free execution163);164 */165166pub 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 // location to this parachain through relay chain195 let option1: xcm::v1::AssetId = Concrete(MultiLocation {196 parents: 1,197 interior: X1(Parachain(ParachainInfo::parachain_id().into())),198 });199 // direct location200 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}251/// Allow checking in assets that have issuance > 0.252#[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}338339/// Means for transacting assets besides the native currency on this chain.340#[cfg(feature = "foreign-assets")]341pub type FungiblesTransactor = FungiblesAdapter<342 // Use this fungibles implementation:343 ForeingAssets,344 // Use this currency when it is a fungible asset matching the given location or name:345 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,346 // Convert an XCM MultiLocation into a local account id:347 LocationToAccountId,348 // Our chain's account ID type (we can't get away without mentioning it explicitly):349 AccountId,350 // We only want to allow teleports of known assets. We use non-zero issuance as an indication351 // that this asset is known.352 NonZeroIssuance<AccountId, ForeingAssets>,353 // The account to use for tracking teleports.354 CheckingAccount,355>;356357/// Means for transacting assets on this chain.358#[cfg(feature = "foreign-assets")]359pub type AssetTransactors = FungiblesTransactor;360361#[cfg(not(feature = "foreign-assets"))]362pub type AssetTransactors = LocalAssetTransactor;363364#[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;375#[cfg(not(feature = "foreign-assets"))]376pub type IsReserve = NativeAsset;377378#[cfg(feature = "foreign-assets")]379type Trader<T> =380 UsingAnyCurrencyComponents<381 pallet_configuration::WeightToFee<T, Balance>,382 RelayLocation, AccountId, Balances, ()>;383#[cfg(not(feature = "foreign-assets"))]384type Trader<T> = UsingOnlySelfCurrencyComponents<385 pallet_configuration::WeightToFee<T, Balance>,386 RelayLocation,387 AccountId,388 Balances,389 (),390>;391392pub struct XcmConfig<T>(PhantomData<T>);393impl<T> Config for XcmConfig<T>394where395 T: pallet_configuration::Config,396{397 type Call = Call;398 type XcmSender = XcmRouter;399 // How to withdraw and deposit an asset.400 type AssetTransactor = AssetTransactors;401 type OriginConverter = XcmOriginToTransactDispatchOrigin;402 type IsReserve = IsReserve;403 type IsTeleporter = (); // Teleportation is disabled404 type LocationInverter = LocationInverter<Ancestry>;405 type Barrier = Barrier;406 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;407 type Trader = Trader<T>;408 type ResponseHandler = (); // Don't handle responses for now.409 type SubscriptionService = PolkadotXcm;410411 type AssetTrap = PolkadotXcm;412 type AssetClaims = PolkadotXcm;413}414415impl pallet_xcm::Config for Runtime {416 type Event = Event;417 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;418 type XcmRouter = XcmRouter;419 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;420 type XcmExecuteFilter = Everything;421 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;422 type XcmTeleportFilter = Everything;423 type XcmReserveTransferFilter = Everything;424 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;425 type LocationInverter = LocationInverter<Ancestry>;426 type Origin = Origin;427 type Call = Call;428 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;429 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;430}431432impl cumulus_pallet_xcm::Config for Runtime {433 type Event = Event;434 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;435}436437impl cumulus_pallet_xcmp_queue::Config for Runtime {438 type WeightInfo = ();439 type Event = Event;440 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;441 type ChannelInfo = ParachainSystem;442 type VersionWrapper = ();443 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;444 type ControllerOrigin = EnsureRoot<AccountId>;445 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;446}447448impl cumulus_pallet_dmp_queue::Config for Runtime {449 type Event = Event;450 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;451 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;452}4531// 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/>.1617use 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}7071/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used72/// when determining ownership of accounts for asset transacting and when attempting to use XCM73/// `Transact` in order to determine the dispatch Origin.74pub type LocationToAccountId = (75 // The parent (Relay-chain) origin converts to the default `AccountId`.76 ParentIsPreset<AccountId>,77 // Sibling parachain origins convert to AccountId via the `ParaId::into`.78 SiblingParachainConvertsVia<Sibling, AccountId>,79 // Straight up local `AccountId32` origins just alias directly to `AccountId`.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}9293/// Means for transacting assets on this chain.94pub type LocalAssetTransactor = CurrencyAdapter<95 // Use this currency:96 Balances,97 // Use this currency when it is a fungible asset matching the given location or name:98 OnlySelfCurrency,99 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:100 LocationToAccountId,101 // Our chain's account ID type (we can't get away without mentioning it explicitly):102 AccountId,103 // We don't track any teleports.104 (),105>;106107/// No local origins on this chain are allowed to dispatch XCM sends/executions.108pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);109110/// The means for routing XCM messages which are not for local execution into the right message111/// queues.112pub type XcmRouter = (113 // Two routers - use UMP to communicate with the relay chain:114 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,115 // ..and XCMP to communicate with the sibling chains.116 XcmpQueue,117);118119/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,120/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can121/// biases the kind of local `Origin` it will become.122pub type XcmOriginToTransactDispatchOrigin = (123 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location124 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for125 // foreign chains who want to have a local sovereign account on this chain which they control.126 SovereignSignedViaLocation<LocationToAccountId, Origin>,127 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when128 // recognised.129 RelayChainAsNative<RelayOrigin, Origin>,130 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when131 // recognised.132 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,133 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a134 // transaction from the Root origin.135 ParentAsSuperuser<Origin>,136 // Native signed account converter; this just converts an `AccountId32` origin into a normal137 // `Origin::Signed` origin of the same 32-byte value.138 SignedAccountId32AsNative<RelayNetwork, Origin>,139 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.140 XcmPassthrough<Origin>,141);142143parameter_types! {144 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.145 pub UnitWeightCost: Weight = 1_000_000;146 // 1200 UNIQUEs buy 1 second of weight.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}157158/*159pub type Barrier = (160 TakeWeightCredit,161 AllowTopLevelPaidExecutionFrom<Everything>,162 // ^^^ Parent & its unit plurality gets free execution163);164 */165166pub 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 //let amount = WeightToFee::weight_to_fee(&weight);193 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;194195 // location to this parachain through relay chain196 let option1: xcm::v1::AssetId = Concrete(MultiLocation {197 parents: 1,198 interior: X1(Parachain(ParachainInfo::parachain_id().into())),199 });200 // direct location201 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}252/// Allow checking in assets that have issuance > 0.253#[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}339340/// Means for transacting assets besides the native currency on this chain.341#[cfg(feature = "foreign-assets")]342pub type FungiblesTransactor = FungiblesAdapter<343 // Use this fungibles implementation:344 ForeingAssets,345 // Use this currency when it is a fungible asset matching the given location or name:346 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,347 // Convert an XCM MultiLocation into a local account id:348 LocationToAccountId,349 // Our chain's account ID type (we can't get away without mentioning it explicitly):350 AccountId,351 // We only want to allow teleports of known assets. We use non-zero issuance as an indication352 // that this asset is known.353 NonZeroIssuance<AccountId, ForeingAssets>,354 // The account to use for tracking teleports.355 CheckingAccount,356>;357358/// Means for transacting assets on this chain.359#[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 // How to withdraw and deposit an asset.401 type AssetTransactor = AssetTransactors;402 type OriginConverter = XcmOriginToTransactDispatchOrigin;403 type IsReserve = IsReserve;404 type IsTeleporter = (); // Teleportation is disabled405 type LocationInverter = LocationInverter<Ancestry>;406 type Barrier = Barrier;407 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;408 type Trader = Trader<T>;409 type ResponseHandler = (); // Don't handle responses for now.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