# Note for reviewer

Most changes are just syntax changes necessary for the new version.
Most important files should be the ones under the `xcm` folder.

# Description 

Added XCMv4.

## Removed `Multi` prefix
The following types have been renamed:
- MultiLocation -> Location
- MultiAsset -> Asset
- MultiAssets -> Assets
- InteriorMultiLocation -> InteriorLocation
- MultiAssetFilter -> AssetFilter
- VersionedMultiAsset -> VersionedAsset
- WildMultiAsset -> WildAsset
- VersionedMultiLocation -> VersionedLocation

In order to fix a name conflict, the `Assets` in `xcm-executor` were
renamed to `HoldingAssets`, as they represent assets in holding.

## Removed `Abstract` asset id

It was not being used anywhere and this simplifies the code.

Now assets are just constructed as follows:

```rust
let asset: Asset = (AssetId(Location::new(1, Here)), 100u128).into();
```

No need for specifying `Concrete` anymore.

## Outcome is now a named fields struct

Instead of

```rust
pub enum Outcome {
  Complete(Weight),
  Incomplete(Weight, Error),
  Error(Error),
}
```

we now have

```rust
pub enum Outcome {
  Complete { used: Weight },
  Incomplete { used: Weight, error: Error },
  Error { error: Error },
}
```

## Added Reanchorable trait

Now both locations and assets implement this trait, making it easier to
reanchor both.

## New syntax for building locations and junctions

Now junctions are built using the following methods:

```rust
let location = Location {
    parents: 1,
    interior: [Parachain(1000), PalletInstance(50), GeneralIndex(1984)].into()
};
```

or

```rust
let location = Location::new(1, [Parachain(1000), PalletInstance(50), GeneralIndex(1984)]);
```

And they are matched like so:

```rust
match location.unpack() {
  (1, [Parachain(id)]) => ...
  (0, Here) => ...,
  (1, [_]) => ...,
}
```

This syntax is mandatory in v4, and has been also implemented for v2 and
v3 for easier migration.

This was needed to make all sizes smaller.

# TODO
- [x] Scaffold v4
- [x] Port github.com/paritytech/polkadot/pull/7236
- [x] Remove `Multi` prefix
- [x] Remove `Abstract` asset id

---------

Co-authored-by: command-bot <>
Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
This commit is contained in:
Francisco Aguirre
2024-01-16 19:18:04 +01:00
committed by GitHub
parent ec7bfae00a
commit 8428f678fe
255 changed files with 12425 additions and 6726 deletions
@@ -31,7 +31,7 @@ use assets_common::{
foreign_creators::ForeignCreators,
local_and_foreign_assets::{LocalFromLeft, TargetFromLeft},
matching::{FromNetwork, FromSiblingParachain},
AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId,
AssetIdForTrustBackedAssetsConvert,
};
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use cumulus_primitives_core::AggregateMessageOrigin;
@@ -80,13 +80,11 @@ use parachains_common::{
Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT,
NORMAL_DISPATCH_RATIO, SLOT_DURATION,
};
use sp_runtime::{Perbill, RuntimeDebug};
use xcm::opaque::v3::MultiLocation;
use xcm_config::{
ForeignAssetsConvertedConcreteId, ForeignCreatorsSovereignAccountOf, GovernanceLocation,
PoolAssetsConvertedConcreteId, TokenLocation, TrustBackedAssetsConvertedConcreteId,
TrustBackedAssetsPalletLocation,
PoolAssetsConvertedConcreteId, TokenLocation, TokenLocationV3,
TrustBackedAssetsConvertedConcreteId, TrustBackedAssetsPalletLocationV3,
};
#[cfg(any(feature = "std", test))]
@@ -95,7 +93,13 @@ pub use sp_runtime::BuildStorage;
// Polkadot imports
use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use xcm::latest::prelude::*;
// We exclude `Assets` since it's the name of a pallet
#[cfg(feature = "runtime-benchmarks")]
use xcm::latest::prelude::{
Asset, Fungible, Here, InteriorLocation, Junction, Junction::*, Location, NetworkId,
NonFungible, Parent, ParentThen, Response, XCM_VERSION,
};
use xcm::latest::prelude::{AssetId, BodyId};
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
@@ -317,10 +321,11 @@ pub type LocalAndForeignAssets = fungibles::UnionOf<
Assets,
ForeignAssets,
LocalFromLeft<
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocationV3>,
AssetIdForTrustBackedAssets,
xcm::v3::Location,
>,
MultiLocation,
xcm::v3::Location,
AccountId,
>;
@@ -328,8 +333,8 @@ pub type LocalAndForeignAssets = fungibles::UnionOf<
pub type NativeAndAssets = fungible::UnionOf<
Balances,
LocalAndForeignAssets,
TargetFromLeft<TokenLocation>,
MultiLocation,
TargetFromLeft<TokenLocationV3, xcm::v3::Location>,
xcm::v3::Location,
AccountId,
>;
@@ -337,15 +342,15 @@ impl pallet_asset_conversion::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type HigherPrecisionBalance = sp_core::U256;
type AssetKind = MultiLocation;
type AssetKind = xcm::v3::Location;
type Assets = NativeAndAssets;
type PoolId = (Self::AssetKind, Self::AssetKind);
type PoolLocator =
pallet_asset_conversion::WithFirstAsset<TokenLocation, AccountId, Self::AssetKind>;
pallet_asset_conversion::WithFirstAsset<TokenLocationV3, AccountId, Self::AssetKind>;
type PoolAssetId = u32;
type PoolAssets = PoolAssets;
type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
type PoolSetupFeeAsset = TokenLocation;
type PoolSetupFeeAsset = TokenLocationV3;
type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
type LPFee = ConstU32<3>;
@@ -355,9 +360,10 @@ impl pallet_asset_conversion::Config for Runtime {
type WeightInfo = weights::pallet_asset_conversion::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
TokenLocation,
TokenLocationV3,
parachain_info::Pallet<Runtime>,
xcm_config::AssetsPalletIndex,
xcm_config::TrustBackedAssetsPalletIndex,
xcm::v3::Location,
>;
}
@@ -379,16 +385,17 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2;
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type AssetId = MultiLocationForAssetId;
type AssetIdParameter = MultiLocationForAssetId;
type AssetId = xcm::v3::MultiLocation;
type AssetIdParameter = xcm::v3::MultiLocation;
type Currency = Balances;
type CreateOrigin = ForeignCreators<
(
FromSiblingParachain<parachain_info::Pallet<Runtime>>,
FromNetwork<xcm_config::UniversalLocation, EthereumNetwork>,
FromSiblingParachain<parachain_info::Pallet<Runtime>, xcm::v3::Location>,
FromNetwork<xcm_config::UniversalLocation, EthereumNetwork, xcm::v3::Location>,
),
ForeignCreatorsSovereignAccountOf,
AccountId,
xcm::v3::Location,
>;
type ForceOrigin = AssetsForceOrigin;
type AssetDeposit = ForeignAssetsAssetDeposit;
@@ -664,7 +671,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(xcm_config::TokenLocation::get());
pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -753,7 +760,7 @@ impl pallet_asset_conversion_tx_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Fungibles = LocalAndForeignAssets;
type OnChargeAssetTransaction =
AssetConversionAdapter<Balances, AssetConversion, TokenLocation>;
AssetConversionAdapter<Balances, AssetConversion, TokenLocationV3>;
}
parameter_types! {
@@ -1157,18 +1164,16 @@ impl_runtime_apis! {
impl pallet_asset_conversion::AssetConversionApi<
Block,
Balance,
MultiLocation,
xcm::v3::Location,
> for Runtime
{
fn quote_price_exact_tokens_for_tokens(asset1: MultiLocation, asset2: MultiLocation, amount: Balance, include_fee: bool) -> Option<Balance> {
fn quote_price_exact_tokens_for_tokens(asset1: xcm::v3::Location, asset2: xcm::v3::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
}
fn quote_price_tokens_for_exact_tokens(asset1: MultiLocation, asset2: MultiLocation, amount: Balance, include_fee: bool) -> Option<Balance> {
fn quote_price_tokens_for_exact_tokens(asset1: xcm::v3::Location, asset2: xcm::v3::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
}
fn get_reserves(asset1: MultiLocation, asset2: MultiLocation) -> Option<(Balance, Balance)> {
fn get_reserves(asset1: xcm::v3::Location, asset2: xcm::v3::Location) -> Option<(Balance, Balance)> {
AssetConversion::get_reserves(asset1, asset2).ok()
}
}
@@ -1222,7 +1227,7 @@ impl_runtime_apis! {
AccountId,
> for Runtime
{
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedMultiAssets, assets_common::runtime_api::FungiblesAccessError> {
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedAssets, assets_common::runtime_api::FungiblesAccessError> {
use assets_common::fungible_conversion::{convert, convert_balance};
Ok([
// collect pallet_balance
@@ -1346,45 +1351,45 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between AH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// AH can reserve transfer native token to some random parachain.
let random_para_id = 43211234;
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
random_para_id.into()
);
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
ParentThen(Parachain(random_para_id).into()).into(),
))
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(xcm::v4::Assets, u32, Location, Box<dyn FnOnce()>)> {
// Transfer to Relay some local AH asset (local-reserve-transfer) while paying
// fees using teleported native token.
// (We don't care that Relay doesn't accept incoming unknown AH local asset)
let dest = Parent.into();
let fee_amount = EXISTENTIAL_DEPOSIT;
let fee_asset: MultiAsset = (MultiLocation::parent(), fee_amount).into();
let fee_asset: Asset = (Location::parent(), fee_amount).into();
let who = frame_benchmarking::whitelisted_caller();
// Give some multiple of the existential deposit
@@ -1402,13 +1407,13 @@ impl_runtime_apis! {
Runtime,
pallet_assets::Instance1
>(true, initial_asset_amount);
let asset_location = MultiLocation::new(
let asset_location = Location::new(
0,
X2(PalletInstance(50), GeneralIndex(u32::from(asset_id).into()))
[PalletInstance(50), GeneralIndex(u32::from(asset_id).into())]
);
let transfer_asset: MultiAsset = (asset_location, asset_amount).into();
let transfer_asset: Asset = (asset_location, asset_amount).into();
let assets: MultiAssets = vec![fee_asset.clone(), transfer_asset].into();
let assets: xcm::v4::Assets = vec![fee_asset.clone(), transfer_asset].into();
let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
// verify transferred successfully
@@ -1432,14 +1437,14 @@ impl_runtime_apis! {
xcm_config::bridging::SiblingBridgeHubParaId::get().into()
);
}
fn ensure_bridged_target_destination() -> Result<MultiLocation, BenchmarkError> {
fn ensure_bridged_target_destination() -> Result<Location, BenchmarkError> {
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
xcm_config::bridging::SiblingBridgeHubParaId::get().into()
);
let bridged_asset_hub = xcm_config::bridging::to_westend::AssetHubWestend::get();
let _ = PolkadotXcm::force_xcm_version(
RuntimeOrigin::root(),
Box::new(bridged_asset_hub),
Box::new(bridged_asset_hub.clone()),
XCM_VERSION,
).map_err(|e| {
log::error!(
@@ -1455,12 +1460,11 @@ impl_runtime_apis! {
}
}
use xcm::latest::prelude::*;
use xcm_config::{TokenLocation, MaxAssetsIntoHolding};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
TokenLocation::get(),
ExistentialDeposit::get()
).into());
@@ -1471,33 +1475,33 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(TokenLocation::get())
}
fn worst_case_holding(depositable_count: u32) -> MultiAssets {
fn worst_case_holding(depositable_count: u32) -> xcm::v4::Assets {
// A mix of fungible, non-fungible, and concrete assets.
let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count;
let holding_fungibles = holding_non_fungibles.saturating_sub(1);
let fungibles_amount: u128 = 100;
let mut assets = (0..holding_fungibles)
.map(|i| {
MultiAsset {
id: Concrete(GeneralIndex(i as u128).into()),
Asset {
id: GeneralIndex(i as u128).into(),
fun: Fungible(fungibles_amount * i as u128),
}
})
.chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) }))
.chain((0..holding_non_fungibles).map(|i| MultiAsset {
id: Concrete(GeneralIndex(i as u128).into()),
.chain(core::iter::once(Asset { id: Here.into(), fun: Fungible(u128::MAX) }))
.chain((0..holding_non_fungibles).map(|i| Asset {
id: GeneralIndex(i as u128).into(),
fun: NonFungible(asset_instance_from(i)),
}))
.collect::<Vec<_>>();
assets.push(MultiAsset {
id: Concrete(TokenLocation::get()),
assets.push(Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(1_000_000 * UNITS),
});
assets.into()
@@ -1505,16 +1509,16 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
TokenLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(TokenLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
// AssetHubRococo trusts AssetHubWestend as reserve for WNDs
pub TrustedReserve: Option<(MultiLocation, MultiAsset)> = Some(
pub TrustedReserve: Option<(Location, Asset)> = Some(
(
xcm_config::bridging::to_westend::AssetHubWestend::get(),
MultiAsset::from((xcm_config::bridging::to_westend::WndLocation::get(), 1000000000000 as u128))
Asset::from((xcm_config::bridging::to_westend::WndLocation::get(), 1000000000000 as u128))
)
);
}
@@ -1526,9 +1530,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(TokenLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -1542,42 +1546,42 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(xcm::v4::Assets, xcm::v4::Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
match xcm_config::bridging::BridgingBenchmarksHelper::prepare_universal_alias() {
Some(alias) => Ok(alias),
None => Err(BenchmarkError::Skip)
}
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(TokenLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, xcm::v4::Assets), BenchmarkError> {
let origin = TokenLocation::get();
let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: xcm::v4::Assets = (TokenLocation::get(), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -24,14 +24,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -50,40 +50,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct AssetHubRococoXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -111,43 +107,35 @@ impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -162,7 +150,7 @@ impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -174,13 +162,13 @@ impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -213,16 +201,16 @@ impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -234,11 +222,11 @@ impl<Call> XcmWeightInfo<Call> for AssetHubRococoXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -20,12 +20,12 @@ use super::{
ToWestendXcmRouter, TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue,
};
use assets_common::{
local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation,
local_and_foreign_assets::MatchesLocalAndForeignAssetsLocation,
matching::{FromNetwork, FromSiblingParachain, IsForeignConcreteAsset},
TrustBackedAssetsAsMultiLocation,
TrustBackedAssetsAsLocation,
};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{
tokens::imbalance::ResolveAssetTo, ConstU32, Contains, Equals, Everything, Nothing,
PalletInfoAccess,
@@ -64,26 +64,32 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const TokenLocation: MultiLocation = MultiLocation::parent();
pub const TokenLocation: Location = Location::parent();
pub const TokenLocationV3: xcm::v3::Location = xcm::v3::Location::parent();
pub const RelayNetwork: NetworkId = NetworkId::Rococo;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap();
pub AssetsPalletIndex: u32 = <Assets as PalletInfoAccess>::index() as u32;
pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(AssetsPalletIndex::get() as u8).into();
pub ForeignAssetsPalletLocation: MultiLocation =
pub TrustBackedAssetsPalletLocation: Location =
PalletInstance(TrustBackedAssetsPalletIndex::get()).into();
pub TrustBackedAssetsPalletIndex: u8 = <Assets as PalletInfoAccess>::index() as u8;
pub TrustBackedAssetsPalletLocationV3: xcm::v3::Location =
xcm::v3::Junction::PalletInstance(<Assets as PalletInfoAccess>::index() as u8).into();
pub ForeignAssetsPalletLocation: Location =
PalletInstance(<ForeignAssets as PalletInfoAccess>::index() as u8).into();
pub PoolAssetsPalletLocation: MultiLocation =
pub PoolAssetsPalletLocation: Location =
PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub PoolAssetsPalletLocationV3: xcm::v3::Location =
xcm::v3::Junction::PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub const GovernanceLocation: Location = Location::parent();
pub StakingPot: AccountId = CollatorSelection::account_id();
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -110,7 +116,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<TokenLocation>,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -128,7 +134,7 @@ pub type FungiblesTransactor = FungiblesAdapter<
Assets,
// Use this currency when it is a fungible asset matching the given location or name:
TrustBackedAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -145,8 +151,8 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte
// Ignore `TrustBackedAssets` explicitly
StartsWith<TrustBackedAssetsPalletLocation>,
// Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means:
// - foreign assets from our consensus should be: `MultiLocation {parents: 1,
// X*(Parachain(xyz), ..)}`
// - foreign assets from our consensus should be: `Location {parents: 1, X*(Parachain(xyz),
// ..)}`
// - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't
// be accepted here
StartsWithExplicitGlobalConsensus<UniversalLocationNetworkId>,
@@ -160,7 +166,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter<
ForeignAssets,
// Use this currency when it is a fungible asset matching the given location or name:
ForeignAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -180,7 +186,7 @@ pub type PoolFungiblesTransactor = FungiblesAdapter<
PoolAssets,
// Use this currency when it is a fungible asset matching the given location or name:
PoolAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -195,20 +201,32 @@ pub type PoolFungiblesTransactor = FungiblesAdapter<
pub type AssetTransactors =
(CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor);
/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`.
pub struct LocalAndForeignAssetsMultiLocationMatcher;
impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher {
fn is_local(location: &MultiLocation) -> bool {
use assets_common::fungible_conversion::MatchesMultiLocation;
TrustBackedAssetsConvertedConcreteId::contains(location)
/// Simple `Location` matcher for Local and Foreign asset `Location`.
pub struct LocalAndForeignAssetsLocationMatcher;
impl MatchesLocalAndForeignAssetsLocation<xcm::v3::Location>
for LocalAndForeignAssetsLocationMatcher
{
fn is_local(location: &xcm::v3::Location) -> bool {
use assets_common::fungible_conversion::MatchesLocation;
let latest_location: Location = if let Ok(location) = (*location).try_into() {
location
} else {
return false;
};
TrustBackedAssetsConvertedConcreteId::contains(&latest_location)
}
fn is_foreign(location: &MultiLocation) -> bool {
use assets_common::fungible_conversion::MatchesMultiLocation;
ForeignAssetsConvertedConcreteId::contains(location)
fn is_foreign(location: &xcm::v3::Location) -> bool {
use assets_common::fungible_conversion::MatchesLocation;
let latest_location: Location = if let Ok(location) = (*location).try_into() {
location
} else {
return false;
};
ForeignAssetsConvertedConcreteId::contains(&latest_location)
}
}
impl Contains<MultiLocation> for LocalAndForeignAssetsMultiLocationMatcher {
fn contains(location: &MultiLocation) -> bool {
impl Contains<xcm::v3::Location> for LocalAndForeignAssetsLocationMatcher {
fn contains(location: &xcm::v3::Location) -> bool {
Self::is_local(location) || Self::is_foreign(location)
}
}
@@ -243,11 +261,11 @@ parameter_types! {
pub XcmAssetFeesReceiver: Option<AccountId> = Authorship::author();
}
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -556,12 +574,12 @@ impl xcm_executor::Config for XcmConfig {
type Trader = (
UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToStakingPot<Runtime>>,
cumulus_primitives_utility::SwapFirstAssetTrader<
TokenLocation,
TokenLocationV3,
crate::AssetConversion,
WeightToFee,
crate::NativeAndAssets,
(
TrustBackedAssetsAsMultiLocation<TrustBackedAssetsPalletLocation, Balance>,
TrustBackedAssetsAsLocation<TrustBackedAssetsPalletLocation, Balance>,
ForeignAssetsConvertedConcreteId,
),
ResolveAssetTo<StakingPot, crate::NativeAndAssets>,
@@ -588,7 +606,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation.
/// Converts a local signed origin into an XCM location.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -664,9 +682,9 @@ pub type ForeignCreatorsSovereignAccountOf = (
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
pub struct XcmBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_assets::BenchmarkHelper<MultiLocation> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> MultiLocation {
MultiLocation { parents: 1, interior: X1(Parachain(id)) }
impl pallet_assets::BenchmarkHelper<xcm::v3::Location> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> xcm::v3::Location {
xcm::v3::Location::new(1, [xcm::v3::Junction::Parachain(id)])
}
}
@@ -698,7 +716,7 @@ pub mod bridging {
pub storage XcmBridgeHubRouterByteFee: Balance = TransactionByteFee::get();
pub SiblingBridgeHubParaId: u32 = bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID;
pub SiblingBridgeHub: MultiLocation = MultiLocation::new(1, X1(Parachain(SiblingBridgeHubParaId::get())));
pub SiblingBridgeHub: Location = Location::new(1, [Parachain(SiblingBridgeHubParaId::get())]);
/// Router expects payment with this `AssetId`.
/// (`AssetId` has to be aligned with `BridgeTable`)
pub XcmBridgeHubRouterFeeAssetId: AssetId = TokenLocation::get().into();
@@ -722,25 +740,25 @@ pub mod bridging {
use super::*;
parameter_types! {
pub SiblingBridgeHubWithBridgeHubWestendInstance: MultiLocation = MultiLocation::new(
pub SiblingBridgeHubWithBridgeHubWestendInstance: Location = Location::new(
1,
X2(
[
Parachain(SiblingBridgeHubParaId::get()),
PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)
)
]
);
pub const WestendNetwork: NetworkId = NetworkId::Westend;
pub AssetHubWestend: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(WestendNetwork::get()), Parachain(bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID)));
pub WndLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(WestendNetwork::get())));
pub AssetHubWestend: Location = Location::new(2, [GlobalConsensus(WestendNetwork::get()), Parachain(bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID)]);
pub WndLocation: Location = Location::new(2, [GlobalConsensus(WestendNetwork::get())]);
pub WndFromAssetHubWestend: (MultiAssetFilter, MultiLocation) = (
Wild(AllOf { fun: WildFungible, id: Concrete(WndLocation::get()) }),
pub WndFromAssetHubWestend: (AssetFilter, Location) = (
Wild(AllOf { fun: WildFungible, id: AssetId(WndLocation::get()) }),
AssetHubWestend::get()
);
/// Set up exporters configuration.
/// `Option<MultiAsset>` represents static "base fee" which is used for total delivery fee calculation.
/// `Option<Asset>` represents static "base fee" which is used for total delivery fee calculation.
pub BridgeTable: sp_std::vec::Vec<NetworkExportTableItem> = sp_std::vec![
NetworkExportTableItem::new(
WestendNetwork::get(),
@@ -757,15 +775,15 @@ pub mod bridging {
];
/// Universal aliases
pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter(
pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter(
sp_std::vec![
(SiblingBridgeHubWithBridgeHubWestendInstance::get(), GlobalConsensus(WestendNetwork::get()))
]
);
}
impl Contains<(MultiLocation, Junction)> for UniversalAliases {
fn contains(alias: &(MultiLocation, Junction)) -> bool {
impl Contains<(Location, Junction)> for UniversalAliases {
fn contains(alias: &(Location, Junction)) -> bool {
UniversalAliases::get().contains(alias)
}
}
@@ -804,16 +822,16 @@ pub mod bridging {
/// Polkadot uses 10 decimals, Kusama and Rococo 12 decimals.
pub const DefaultBridgeHubEthereumBaseFee: Balance = 2_750_872_500_000;
pub storage BridgeHubEthereumBaseFee: Balance = DefaultBridgeHubEthereumBaseFee::get();
pub SiblingBridgeHubWithEthereumInboundQueueInstance: MultiLocation = MultiLocation::new(
pub SiblingBridgeHubWithEthereumInboundQueueInstance: Location = Location::new(
1,
X2(
[
Parachain(SiblingBridgeHubParaId::get()),
PalletInstance(parachains_common::rococo::snowbridge::INBOUND_QUEUE_PALLET_INDEX)
)
]
);
/// Set up exporters configuration.
/// `Option<MultiAsset>` represents static "base fee" which is used for total delivery fee calculation.
/// `Option<Asset>` represents static "base fee" which is used for total delivery fee calculation.
pub BridgeTable: sp_std::vec::Vec<NetworkExportTableItem> = sp_std::vec![
NetworkExportTableItem::new(
EthereumNetwork::get(),
@@ -827,7 +845,7 @@ pub mod bridging {
];
/// Universal aliases
pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter(
pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter(
sp_std::vec![
(SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get())),
]
@@ -837,8 +855,8 @@ pub mod bridging {
pub type IsTrustedBridgedReserveLocationForForeignAsset =
matching::IsForeignConcreteAsset<FromNetwork<UniversalLocation, EthereumNetwork>>;
impl Contains<(MultiLocation, Junction)> for UniversalAliases {
fn contains(alias: &(MultiLocation, Junction)) -> bool {
impl Contains<(Location, Junction)> for UniversalAliases {
fn contains(alias: &(Location, Junction)) -> bool {
UniversalAliases::get().contains(alias)
}
}
@@ -850,7 +868,7 @@ pub mod bridging {
#[cfg(feature = "runtime-benchmarks")]
impl BridgingBenchmarksHelper {
pub fn prepare_universal_alias() -> Option<(MultiLocation, Junction)> {
pub fn prepare_universal_alias() -> Option<(Location, Junction)> {
let alias =
to_westend::UniversalAliases::get()
.into_iter()
@@ -19,12 +19,18 @@
use asset_hub_rococo_runtime::{
xcm_config,
xcm_config::{bridging, ForeignCreatorsSovereignAccountOf, LocationToAccountId, TokenLocation},
xcm_config::{
bridging, ForeignCreatorsSovereignAccountOf, LocationToAccountId, TokenLocation,
TokenLocationV3,
},
AllPalletsWithoutSystem, MetadataDepositBase, MetadataDepositPerByte, RuntimeCall,
RuntimeEvent, ToWestendXcmRouterInstance, XcmpQueue,
};
pub use asset_hub_rococo_runtime::{
xcm_config::{CheckingAccount, TrustBackedAssetsPalletLocation, XcmConfig},
xcm_config::{
CheckingAccount, TrustBackedAssetsPalletLocation, TrustBackedAssetsPalletLocationV3,
XcmConfig,
},
AssetConversion, AssetDeposit, Assets, Balances, CollatorSelection, ExistentialDeposit,
ForeignAssets, ForeignAssetsInstance, ParachainSystem, Runtime, SessionKeys, System,
TrustBackedAssetsInstance,
@@ -49,14 +55,18 @@ use parachains_common::{
};
use sp_runtime::traits::MaybeEquivalence;
use std::convert::Into;
use xcm::latest::prelude::*;
use xcm_executor::traits::{Identity, JustTry, WeightTrader};
use xcm::latest::prelude::{Assets as XcmAssets, *};
use xcm_builder::V4V3LocationConverter;
use xcm_executor::traits::{JustTry, WeightTrader};
const ALICE: [u8; 32] = [1u8; 32];
const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32];
type AssetIdForTrustBackedAssetsConvert =
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>;
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocationV3>;
type AssetIdForTrustBackedAssetsConvertLatest =
assets_common::AssetIdForTrustBackedAssetsConvertLatest<TrustBackedAssetsPalletLocation>;
type RuntimeHelper = asset_test_utils::RuntimeHelper<Runtime, AllPalletsWithoutSystem>;
@@ -99,7 +109,7 @@ fn test_buy_and_refund_weight_in_native() {
let fee = WeightToFee::weight_to_fee(&weight);
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (native_location, fee + extra_amount).into();
let payment: Asset = (native_location.clone(), fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -108,7 +118,7 @@ fn test_buy_and_refund_weight_in_native() {
// assert.
let unused_amount =
unused_asset.fungible.get(&native_location.into()).map_or(0, |a| *a);
unused_asset.fungible.get(&native_location.clone().into()).map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Balances::total_issuance(), total_issuance);
@@ -144,7 +154,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let asset_1: u32 = 1;
let native_location = TokenLocation::get();
let native_location = TokenLocationV3::get();
let asset_1_location =
AssetIdForTrustBackedAssetsConvert::convert_back(&asset_1).unwrap();
// bob's initial balance for native and `asset1` assets.
@@ -180,6 +190,8 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
let asset_total_issuance = Assets::total_issuance(asset_1);
let native_total_issuance = Balances::total_issuance();
let asset_1_location_latest: Location = asset_1_location.try_into().unwrap();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
@@ -187,7 +199,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (asset_1_location, asset_fee + extra_amount).into();
let payment: Asset = (asset_1_location_latest.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -195,8 +207,10 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&asset_1_location.into()).map_or(0, |a| *a);
let unused_amount = unused_asset
.fungible
.get(&asset_1_location_latest.clone().into())
.map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Assets::total_issuance(asset_1), asset_total_issuance + asset_fee);
@@ -210,7 +224,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (asset_1_location, asset_refund).into());
assert_eq!(actual_refund, (asset_1_location_latest, asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
@@ -239,9 +253,15 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
.execute_with(|| {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let native_location = TokenLocation::get();
let foreign_location =
MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) };
let native_location = TokenLocationV3::get();
let foreign_location = xcm::v3::Location {
parents: 1,
interior: (
xcm::v3::Junction::Parachain(1234),
xcm::v3::Junction::GeneralIndex(12345),
)
.into(),
};
// bob's initial balance for native and `asset1` assets.
let initial_balance = 200 * UNITS;
// liquidity for both arms of (native, asset1) pool.
@@ -280,6 +300,8 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
let asset_total_issuance = ForeignAssets::total_issuance(foreign_location);
let native_total_issuance = Balances::total_issuance();
let foreign_location_latest: Location = foreign_location.try_into().unwrap();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
@@ -287,7 +309,7 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (foreign_location, asset_fee + extra_amount).into();
let payment: Asset = (foreign_location_latest.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -295,8 +317,10 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&foreign_location.into()).map_or(0, |a| *a);
let unused_amount = unused_asset
.fungible
.get(&foreign_location_latest.clone().into())
.map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(
ForeignAssets::total_issuance(foreign_location),
@@ -313,7 +337,7 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (foreign_location, asset_refund).into());
assert_eq!(actual_refund, (foreign_location_latest, asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
@@ -343,19 +367,21 @@ fn test_assets_balances_api_works() {
.build()
.execute_with(|| {
let local_asset_id = 1;
let foreign_asset_id_multilocation =
MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) };
let foreign_asset_id_location = xcm::v3::Location::new(
1,
[xcm::v3::Junction::Parachain(1234), xcm::v3::Junction::GeneralIndex(12345)],
);
// check before
assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)),
ForeignAssets::balance(foreign_asset_id_location, AccountId::from(ALICE)),
0
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0);
assert!(Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_as::<MultiAssets>()
.try_as::<XcmAssets>()
.unwrap()
.is_none());
@@ -386,7 +412,7 @@ fn test_assets_balances_api_works() {
let foreign_asset_minimum_asset_balance = 3333333_u128;
assert_ok!(ForeignAssets::force_create(
RuntimeHelper::root_origin(),
foreign_asset_id_multilocation,
foreign_asset_id_location,
AccountId::from(SOME_ASSET_ADMIN).into(),
false,
foreign_asset_minimum_asset_balance
@@ -395,7 +421,7 @@ fn test_assets_balances_api_works() {
// We first mint enough asset for the account to exist for assets
assert_ok!(ForeignAssets::mint(
RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)),
foreign_asset_id_multilocation,
foreign_asset_id_location,
AccountId::from(ALICE).into(),
6 * foreign_asset_minimum_asset_balance
));
@@ -406,12 +432,12 @@ fn test_assets_balances_api_works() {
minimum_asset_balance
);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)),
ForeignAssets::balance(foreign_asset_id_location, AccountId::from(ALICE)),
6 * minimum_asset_balance
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency);
let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE))
let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_into()
.unwrap();
@@ -426,13 +452,13 @@ fn test_assets_balances_api_works() {
)));
// check trusted asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(),
AssetIdForTrustBackedAssetsConvertLatest::convert_back(&local_asset_id).unwrap(),
minimum_asset_balance
)
.into())));
// check foreign asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
Identity::convert_back(&foreign_asset_id_multilocation).unwrap(),
V4V3LocationConverter::convert_back(&foreign_asset_id_location).unwrap(),
6 * foreign_asset_minimum_asset_balance
)
.into())));
@@ -503,7 +529,7 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_
XcmConfig,
TrustBackedAssetsInstance,
AssetIdForTrustBackedAssets,
AssetIdForTrustBackedAssetsConvert,
AssetIdForTrustBackedAssetsConvertLatest,
collator_session_keys(),
ExistentialDeposit::get(),
12345,
@@ -520,11 +546,14 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_
Runtime,
XcmConfig,
ForeignAssetsInstance,
MultiLocation,
xcm::v3::Location,
JustTry,
collator_session_keys(),
ExistentialDeposit::get(),
MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) },
xcm::v3::Location::new(
1,
[xcm::v3::Junction::Parachain(1313), xcm::v3::Junction::GeneralIndex(12345)]
),
Box::new(|| {
assert!(Assets::asset_ids().collect::<Vec<_>>().is_empty());
}),
@@ -539,8 +568,8 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p
WeightToFee,
ForeignCreatorsSovereignAccountOf,
ForeignAssetsInstance,
MultiLocation,
JustTry,
xcm::v3::Location,
V4V3LocationConverter,
collator_session_keys(),
ExistentialDeposit::get(),
AssetDeposit::get(),
@@ -637,12 +666,12 @@ mod asset_hub_rococo_tests {
AccountId::from([73; 32]),
AccountId::from(BLOCK_AUTHOR_ACCOUNT),
// receiving WNDs
(MultiLocation { parents: 2, interior: X1(GlobalConsensus(Westend)) }, 1000000000000, 1_000_000_000),
(xcm::v3::Location::new(2, [xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::Westend)]), 1000000000000, 1_000_000_000),
bridging_to_asset_hub_westend,
(
X1(PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)),
[PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)].into(),
GlobalConsensus(Westend),
X1(Parachain(1000))
[Parachain(1000)].into()
)
)
}
@@ -76,21 +76,25 @@ use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
use xcm::opaque::v3::MultiLocation;
use xcm_config::{
ForeignAssetsConvertedConcreteId, PoolAssetsConvertedConcreteId,
TrustBackedAssetsConvertedConcreteId, TrustBackedAssetsPalletLocation, WestendLocation,
XcmOriginToTransactDispatchOrigin,
TrustBackedAssetsConvertedConcreteId, TrustBackedAssetsPalletLocationV3, WestendLocation,
WestendLocationV3, XcmOriginToTransactDispatchOrigin,
};
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
use assets_common::{
foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId,
};
use assets_common::{foreign_creators::ForeignCreators, matching::FromSiblingParachain};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use xcm::latest::prelude::*;
// We exclude `Assets` since it's the name of a pallet
use xcm::latest::prelude::AssetId;
#[cfg(feature = "runtime-benchmarks")]
use xcm::latest::prelude::{
Asset, Fungible, Here, InteriorLocation, Junction, Junction::*, Location, NetworkId,
NonFungible, Parent, ParentThen, Response, XCM_VERSION,
};
use crate::xcm_config::ForeignCreatorsSovereignAccountOf;
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
@@ -300,10 +304,11 @@ pub type LocalAndForeignAssets = fungibles::UnionOf<
Assets,
ForeignAssets,
LocalFromLeft<
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocationV3>,
AssetIdForTrustBackedAssets,
xcm::v3::Location,
>,
MultiLocation,
xcm::v3::Location,
AccountId,
>;
@@ -311,8 +316,8 @@ pub type LocalAndForeignAssets = fungibles::UnionOf<
pub type NativeAndAssets = fungible::UnionOf<
Balances,
LocalAndForeignAssets,
TargetFromLeft<WestendLocation>,
MultiLocation,
TargetFromLeft<WestendLocationV3, xcm::v3::Location>,
xcm::v3::Location,
AccountId,
>;
@@ -320,15 +325,15 @@ impl pallet_asset_conversion::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type HigherPrecisionBalance = sp_core::U256;
type AssetKind = MultiLocation;
type AssetKind = xcm::v3::Location;
type Assets = NativeAndAssets;
type PoolId = (Self::AssetKind, Self::AssetKind);
type PoolLocator =
pallet_asset_conversion::WithFirstAsset<WestendLocation, AccountId, Self::AssetKind>;
pallet_asset_conversion::WithFirstAsset<WestendLocationV3, AccountId, Self::AssetKind>;
type PoolAssetId = u32;
type PoolAssets = PoolAssets;
type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
type PoolSetupFeeAsset = WestendLocation;
type PoolSetupFeeAsset = WestendLocationV3;
type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
type LPFee = ConstU32<3>;
@@ -338,9 +343,10 @@ impl pallet_asset_conversion::Config for Runtime {
type WeightInfo = weights::pallet_asset_conversion::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
WestendLocation,
WestendLocationV3,
parachain_info::Pallet<Runtime>,
xcm_config::AssetsPalletIndex,
xcm_config::TrustBackedAssetsPalletIndex,
xcm::v3::Location,
>;
}
@@ -362,13 +368,14 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2;
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type AssetId = MultiLocationForAssetId;
type AssetIdParameter = MultiLocationForAssetId;
type AssetId = xcm::v3::Location;
type AssetIdParameter = xcm::v3::Location;
type Currency = Balances;
type CreateOrigin = ForeignCreators<
(FromSiblingParachain<parachain_info::Pallet<Runtime>>,),
FromSiblingParachain<parachain_info::Pallet<Runtime>, xcm::v3::Location>,
ForeignCreatorsSovereignAccountOf,
AccountId,
xcm::v3::Location,
>;
type ForceOrigin = AssetsForceOrigin;
type AssetDeposit = ForeignAssetsAssetDeposit;
@@ -644,7 +651,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(xcm_config::WestendLocation::get());
pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -728,7 +735,7 @@ impl pallet_asset_conversion_tx_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Fungibles = LocalAndForeignAssets;
type OnChargeAssetTransaction =
AssetConversionAdapter<Balances, AssetConversion, WestendLocation>;
AssetConversionAdapter<Balances, AssetConversion, WestendLocationV3>;
}
parameter_types! {
@@ -1229,18 +1236,18 @@ impl_runtime_apis! {
impl pallet_asset_conversion::AssetConversionApi<
Block,
Balance,
MultiLocation,
xcm::v3::Location,
> for Runtime
{
fn quote_price_exact_tokens_for_tokens(asset1: MultiLocation, asset2: MultiLocation, amount: Balance, include_fee: bool) -> Option<Balance> {
fn quote_price_exact_tokens_for_tokens(asset1: xcm::v3::Location, asset2: xcm::v3::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
}
fn quote_price_tokens_for_exact_tokens(asset1: MultiLocation, asset2: MultiLocation, amount: Balance, include_fee: bool) -> Option<Balance> {
fn quote_price_tokens_for_exact_tokens(asset1: xcm::v3::Location, asset2: xcm::v3::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
}
fn get_reserves(asset1: MultiLocation, asset2: MultiLocation) -> Option<(Balance, Balance)> {
fn get_reserves(asset1: xcm::v3::Location, asset2: xcm::v3::Location) -> Option<(Balance, Balance)> {
AssetConversion::get_reserves(asset1, asset2).ok()
}
}
@@ -1294,7 +1301,7 @@ impl_runtime_apis! {
AccountId,
> for Runtime
{
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedMultiAssets, assets_common::runtime_api::FungiblesAccessError> {
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedAssets, assets_common::runtime_api::FungiblesAccessError> {
use assets_common::fungible_conversion::{convert, convert_balance};
Ok([
// collect pallet_balance
@@ -1413,45 +1420,45 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between AH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// AH can reserve transfer native token to some random parachain.
let random_para_id = 43211234;
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
random_para_id.into()
);
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
ParentThen(Parachain(random_para_id).into()).into(),
))
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(xcm::v4::Assets, u32, Location, Box<dyn FnOnce()>)> {
// Transfer to Relay some local AH asset (local-reserve-transfer) while paying
// fees using teleported native token.
// (We don't care that Relay doesn't accept incoming unknown AH local asset)
let dest = Parent.into();
let fee_amount = EXISTENTIAL_DEPOSIT;
let fee_asset: MultiAsset = (MultiLocation::parent(), fee_amount).into();
let fee_asset: Asset = (Location::parent(), fee_amount).into();
let who = frame_benchmarking::whitelisted_caller();
// Give some multiple of the existential deposit
@@ -1469,13 +1476,13 @@ impl_runtime_apis! {
Runtime,
pallet_assets::Instance1
>(true, initial_asset_amount);
let asset_location = MultiLocation::new(
let asset_location = Location::new(
0,
X2(PalletInstance(50), GeneralIndex(u32::from(asset_id).into()))
[PalletInstance(50), GeneralIndex(u32::from(asset_id).into())]
);
let transfer_asset: MultiAsset = (asset_location, asset_amount).into();
let transfer_asset: Asset = (asset_location, asset_amount).into();
let assets: MultiAssets = vec![fee_asset.clone(), transfer_asset].into();
let assets: xcm::v4::Assets = vec![fee_asset.clone(), transfer_asset].into();
let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
// verify transferred successfully
@@ -1504,14 +1511,14 @@ impl_runtime_apis! {
xcm_config::bridging::SiblingBridgeHubParaId::get().into()
);
}
fn ensure_bridged_target_destination() -> Result<MultiLocation, BenchmarkError> {
fn ensure_bridged_target_destination() -> Result<Location, BenchmarkError> {
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
xcm_config::bridging::SiblingBridgeHubParaId::get().into()
);
let bridged_asset_hub = xcm_config::bridging::to_rococo::AssetHubRococo::get();
let _ = PolkadotXcm::force_xcm_version(
RuntimeOrigin::root(),
Box::new(bridged_asset_hub),
Box::new(bridged_asset_hub.clone()),
XCM_VERSION,
).map_err(|e| {
log::error!(
@@ -1527,12 +1534,11 @@ impl_runtime_apis! {
}
}
use xcm::latest::prelude::*;
use xcm_config::{MaxAssetsIntoHolding, WestendLocation};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
WestendLocation::get(),
ExistentialDeposit::get()
).into());
@@ -1543,33 +1549,33 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(WestendLocation::get())
}
fn worst_case_holding(depositable_count: u32) -> MultiAssets {
fn worst_case_holding(depositable_count: u32) -> xcm::v4::Assets {
// A mix of fungible, non-fungible, and concrete assets.
let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count;
let holding_fungibles = holding_non_fungibles - 1;
let fungibles_amount: u128 = 100;
let mut assets = (0..holding_fungibles)
.map(|i| {
MultiAsset {
id: Concrete(GeneralIndex(i as u128).into()),
Asset {
id: AssetId(GeneralIndex(i as u128).into()),
fun: Fungible(fungibles_amount * i as u128),
}
})
.chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) }))
.chain((0..holding_non_fungibles).map(|i| MultiAsset {
id: Concrete(GeneralIndex(i as u128).into()),
.chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) }))
.chain((0..holding_non_fungibles).map(|i| Asset {
id: AssetId(GeneralIndex(i as u128).into()),
fun: NonFungible(asset_instance_from(i)),
}))
.collect::<Vec<_>>();
assets.push(MultiAsset {
id: Concrete(WestendLocation::get()),
assets.push(Asset {
id: AssetId(WestendLocation::get()),
fun: Fungible(1_000_000 * UNITS),
});
assets.into()
@@ -1577,16 +1583,16 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
WestendLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(WestendLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
// AssetHubWestend trusts AssetHubRococo as reserve for ROCs
pub TrustedReserve: Option<(MultiLocation, MultiAsset)> = Some(
pub TrustedReserve: Option<(Location, Asset)> = Some(
(
xcm_config::bridging::to_rococo::AssetHubRococo::get(),
MultiAsset::from((xcm_config::bridging::to_rococo::RocLocation::get(), 1000000000000 as u128))
Asset::from((xcm_config::bridging::to_rococo::RocLocation::get(), 1000000000000 as u128))
)
);
}
@@ -1598,9 +1604,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(WestendLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(WestendLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -1614,42 +1620,42 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(xcm::v4::Assets, xcm::v4::Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
match xcm_config::bridging::BridgingBenchmarksHelper::prepare_universal_alias() {
Some(alias) => Ok(alias),
None => Err(BenchmarkError::Skip)
}
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((WestendLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(WestendLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, xcm::v4::Assets), BenchmarkError> {
let origin = WestendLocation::get();
let assets: MultiAssets = (Concrete(WestendLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: xcm::v4::Assets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct AssetHubWestendXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -110,44 +106,36 @@ impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -162,7 +150,7 @@ impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -174,13 +162,13 @@ impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -213,16 +201,16 @@ impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -234,11 +222,11 @@ impl<Call> XcmWeightInfo<Call> for AssetHubWestendXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -20,12 +20,12 @@ use super::{
ToRococoXcmRouter, TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue,
};
use assets_common::{
local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation,
local_and_foreign_assets::MatchesLocalAndForeignAssetsLocation,
matching::{FromSiblingParachain, IsForeignConcreteAsset},
TrustBackedAssetsAsMultiLocation,
TrustBackedAssetsAsLocation,
};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{
tokens::imbalance::ResolveAssetTo, ConstU32, Contains, Equals, Everything, Nothing,
PalletInfoAccess,
@@ -61,25 +61,31 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const WestendLocation: MultiLocation = MultiLocation::parent();
pub const WestendLocation: Location = Location::parent();
pub const WestendLocationV3: xcm::v3::Location = xcm::v3::Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Westend);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap();
pub AssetsPalletIndex: u32 = <Assets as PalletInfoAccess>::index() as u32;
pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(AssetsPalletIndex::get() as u8).into();
pub ForeignAssetsPalletLocation: MultiLocation =
pub TrustBackedAssetsPalletLocation: Location =
PalletInstance(TrustBackedAssetsPalletIndex::get()).into();
pub TrustBackedAssetsPalletIndex: u8 = <Assets as PalletInfoAccess>::index() as u8;
pub TrustBackedAssetsPalletLocationV3: xcm::v3::Location =
xcm::v3::Junction::PalletInstance(<Assets as PalletInfoAccess>::index() as u8).into();
pub ForeignAssetsPalletLocation: Location =
PalletInstance(<ForeignAssets as PalletInfoAccess>::index() as u8).into();
pub PoolAssetsPalletLocation: MultiLocation =
pub PoolAssetsPalletLocation: Location =
PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub PoolAssetsPalletLocationV3: xcm::v3::Location =
xcm::v3::Junction::PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub StakingPot: AccountId = CollatorSelection::account_id();
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -104,7 +110,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<WestendLocation>,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -122,7 +128,7 @@ pub type FungiblesTransactor = FungiblesAdapter<
Assets,
// Use this currency when it is a fungible asset matching the given location or name:
TrustBackedAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -139,8 +145,8 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte
// Ignore `TrustBackedAssets` explicitly
StartsWith<TrustBackedAssetsPalletLocation>,
// Ignore asset which starts explicitly with our `GlobalConsensus(NetworkId)`, means:
// - foreign assets from our consensus should be: `MultiLocation {parents: 1,
// X*(Parachain(xyz), ..)}
// - foreign assets from our consensus should be: `Location {parents: 1, X*(Parachain(xyz),
// ..)}
// - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` wont
// be accepted here
StartsWithExplicitGlobalConsensus<UniversalLocationNetworkId>,
@@ -154,7 +160,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter<
ForeignAssets,
// Use this currency when it is a fungible asset matching the given location or name:
ForeignAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -174,7 +180,7 @@ pub type PoolFungiblesTransactor = FungiblesAdapter<
PoolAssets,
// Use this currency when it is a fungible asset matching the given location or name:
PoolAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -189,21 +195,33 @@ pub type PoolFungiblesTransactor = FungiblesAdapter<
pub type AssetTransactors =
(CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor);
/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`.
pub struct LocalAndForeignAssetsMultiLocationMatcher;
impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher {
fn is_local(location: &MultiLocation) -> bool {
use assets_common::fungible_conversion::MatchesMultiLocation;
TrustBackedAssetsConvertedConcreteId::contains(location)
/// Simple `Location` matcher for Local and Foreign asset `Location`.
pub struct LocalAndForeignAssetsLocationMatcher;
impl MatchesLocalAndForeignAssetsLocation<xcm::v3::Location>
for LocalAndForeignAssetsLocationMatcher
{
fn is_local(location: &xcm::v3::Location) -> bool {
use assets_common::fungible_conversion::MatchesLocation;
let latest_location: Location = if let Ok(location) = (*location).try_into() {
location
} else {
return false;
};
TrustBackedAssetsConvertedConcreteId::contains(&latest_location)
}
fn is_foreign(location: &MultiLocation) -> bool {
use assets_common::fungible_conversion::MatchesMultiLocation;
ForeignAssetsConvertedConcreteId::contains(location)
fn is_foreign(location: &xcm::v3::Location) -> bool {
use assets_common::fungible_conversion::MatchesLocation;
let latest_location: Location = if let Ok(location) = (*location).try_into() {
location
} else {
return false;
};
ForeignAssetsConvertedConcreteId::contains(&latest_location)
}
}
impl Contains<MultiLocation> for LocalAndForeignAssetsMultiLocationMatcher {
fn contains(location: &MultiLocation) -> bool {
impl Contains<xcm::v3::Location> for LocalAndForeignAssetsLocationMatcher {
fn contains(location: &xcm::v3::Location) -> bool {
Self::is_local(location) || Self::is_foreign(location)
}
}
@@ -238,23 +256,30 @@ parameter_types! {
pub XcmAssetFeesReceiver: Option<AccountId> = Authorship::author();
}
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub type FellowshipEntities: impl Contains<MultiLocation> = {
// Fellowship Plurality
MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } |
// Fellowship Salary Pallet
MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(64)) } |
// Fellowship Treasury Pallet
MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(65)) }
};
pub type AmbassadorEntities: impl Contains<MultiLocation> = {
// Ambassador Salary Pallet
MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(74)) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
pub struct FellowshipEntities;
impl Contains<Location> for FellowshipEntities {
fn contains(location: &Location) -> bool {
matches!(
location.unpack(),
(1, [Parachain(1001), Plurality { id: BodyId::Technical, .. }]) |
(1, [Parachain(1001), PalletInstance(64)]) |
(1, [Parachain(1001), PalletInstance(65)])
)
}
}
pub struct AmbassadorEntities;
impl Contains<Location> for AmbassadorEntities {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, [Parachain(1001), PalletInstance(74)]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -573,12 +598,12 @@ impl xcm_executor::Config for XcmConfig {
type Trader = (
UsingComponents<WeightToFee, WestendLocation, AccountId, Balances, ToStakingPot<Runtime>>,
cumulus_primitives_utility::SwapFirstAssetTrader<
WestendLocation,
WestendLocationV3,
crate::AssetConversion,
WeightToFee,
crate::NativeAndAssets,
(
TrustBackedAssetsAsMultiLocation<TrustBackedAssetsPalletLocation, Balance>,
TrustBackedAssetsAsLocation<TrustBackedAssetsPalletLocation, Balance>,
ForeignAssetsConvertedConcreteId,
),
ResolveAssetTo<StakingPot, crate::NativeAndAssets>,
@@ -671,9 +696,9 @@ pub type ForeignCreatorsSovereignAccountOf = (
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
pub struct XcmBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_assets::BenchmarkHelper<MultiLocation> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> MultiLocation {
MultiLocation { parents: 1, interior: X1(Parachain(id)) }
impl pallet_assets::BenchmarkHelper<xcm::v3::Location> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> xcm::v3::Location {
xcm::v3::Location::new(1, [xcm::v3::Junction::Parachain(id)])
}
}
@@ -704,7 +729,7 @@ pub mod bridging {
pub storage XcmBridgeHubRouterByteFee: Balance = TransactionByteFee::get();
pub SiblingBridgeHubParaId: u32 = bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID;
pub SiblingBridgeHub: MultiLocation = MultiLocation::new(1, X1(Parachain(SiblingBridgeHubParaId::get())));
pub SiblingBridgeHub: Location = Location::new(1, [Parachain(SiblingBridgeHubParaId::get())]);
/// Router expects payment with this `AssetId`.
/// (`AssetId` has to be aligned with `BridgeTable`)
pub XcmBridgeHubRouterFeeAssetId: AssetId = WestendLocation::get().into();
@@ -721,25 +746,25 @@ pub mod bridging {
use super::*;
parameter_types! {
pub SiblingBridgeHubWithBridgeHubRococoInstance: MultiLocation = MultiLocation::new(
pub SiblingBridgeHubWithBridgeHubRococoInstance: Location = Location::new(
1,
X2(
[
Parachain(SiblingBridgeHubParaId::get()),
PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)
)
]
);
pub const RococoNetwork: NetworkId = NetworkId::Rococo;
pub AssetHubRococo: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)));
pub RocLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(RococoNetwork::get())));
pub AssetHubRococo: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)]);
pub RocLocation: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get())]);
pub RocFromAssetHubRococo: (MultiAssetFilter, MultiLocation) = (
Wild(AllOf { fun: WildFungible, id: Concrete(RocLocation::get()) }),
pub RocFromAssetHubRococo: (AssetFilter, Location) = (
Wild(AllOf { fun: WildFungible, id: AssetId(RocLocation::get()) }),
AssetHubRococo::get()
);
/// Set up exporters configuration.
/// `Option<MultiAsset>` represents static "base fee" which is used for total delivery fee calculation.
/// `Option<Asset>` represents static "base fee" which is used for total delivery fee calculation.
pub BridgeTable: sp_std::vec::Vec<NetworkExportTableItem> = sp_std::vec![
NetworkExportTableItem::new(
RococoNetwork::get(),
@@ -756,15 +781,15 @@ pub mod bridging {
];
/// Universal aliases
pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter(
pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter(
sp_std::vec![
(SiblingBridgeHubWithBridgeHubRococoInstance::get(), GlobalConsensus(RococoNetwork::get()))
]
);
}
impl Contains<(MultiLocation, Junction)> for UniversalAliases {
fn contains(alias: &(MultiLocation, Junction)) -> bool {
impl Contains<(Location, Junction)> for UniversalAliases {
fn contains(alias: &(Location, Junction)) -> bool {
UniversalAliases::get().contains(alias)
}
}
@@ -799,7 +824,7 @@ pub mod bridging {
#[cfg(feature = "runtime-benchmarks")]
impl BridgingBenchmarksHelper {
pub fn prepare_universal_alias() -> Option<(MultiLocation, Junction)> {
pub fn prepare_universal_alias() -> Option<(Location, Junction)> {
let alias =
to_rococo::UniversalAliases::get().into_iter().find_map(|(location, junction)| {
match to_rococo::SiblingBridgeHubWithBridgeHubRococoInstance::get()
@@ -21,12 +21,16 @@ use asset_hub_westend_runtime::{
xcm_config,
xcm_config::{
bridging, ForeignCreatorsSovereignAccountOf, LocationToAccountId, WestendLocation,
WestendLocationV3,
},
AllPalletsWithoutSystem, MetadataDepositBase, MetadataDepositPerByte, PolkadotXcm, RuntimeCall,
RuntimeEvent, RuntimeOrigin, ToRococoXcmRouterInstance, XcmpQueue,
};
pub use asset_hub_westend_runtime::{
xcm_config::{CheckingAccount, TrustBackedAssetsPalletLocation, XcmConfig},
xcm_config::{
CheckingAccount, TrustBackedAssetsPalletLocation, TrustBackedAssetsPalletLocationV3,
XcmConfig,
},
AssetConversion, AssetDeposit, Assets, Balances, CollatorSelection, ExistentialDeposit,
ForeignAssets, ForeignAssetsInstance, ParachainSystem, Runtime, SessionKeys, System,
TrustBackedAssetsInstance,
@@ -51,14 +55,18 @@ use parachains_common::{
};
use sp_runtime::traits::MaybeEquivalence;
use std::convert::Into;
use xcm::latest::prelude::*;
use xcm_executor::traits::{Identity, JustTry, WeightTrader};
use xcm::latest::prelude::{Assets as XcmAssets, *};
use xcm_builder::V4V3LocationConverter;
use xcm_executor::traits::{JustTry, WeightTrader};
const ALICE: [u8; 32] = [1u8; 32];
const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32];
type AssetIdForTrustBackedAssetsConvert =
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>;
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocationV3>;
type AssetIdForTrustBackedAssetsConvertLatest =
assets_common::AssetIdForTrustBackedAssetsConvertLatest<TrustBackedAssetsPalletLocation>;
type RuntimeHelper = asset_test_utils::RuntimeHelper<Runtime, AllPalletsWithoutSystem>;
@@ -101,7 +109,7 @@ fn test_buy_and_refund_weight_in_native() {
let fee = WeightToFee::weight_to_fee(&weight);
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (native_location, fee + extra_amount).into();
let payment: Asset = (native_location.clone(), fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -110,7 +118,7 @@ fn test_buy_and_refund_weight_in_native() {
// assert.
let unused_amount =
unused_asset.fungible.get(&native_location.into()).map_or(0, |a| *a);
unused_asset.fungible.get(&native_location.clone().into()).map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Balances::total_issuance(), total_issuance);
@@ -146,7 +154,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let asset_1: u32 = 1;
let native_location = WestendLocation::get();
let native_location = WestendLocationV3::get();
let asset_1_location =
AssetIdForTrustBackedAssetsConvert::convert_back(&asset_1).unwrap();
// bob's initial balance for native and `asset1` assets.
@@ -182,6 +190,8 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
let asset_total_issuance = Assets::total_issuance(asset_1);
let native_total_issuance = Balances::total_issuance();
let asset_1_location_latest: Location = asset_1_location.try_into().unwrap();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
@@ -189,7 +199,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (asset_1_location, asset_fee + extra_amount).into();
let payment: Asset = (asset_1_location_latest.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -197,8 +207,10 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&asset_1_location.into()).map_or(0, |a| *a);
let unused_amount = unused_asset
.fungible
.get(&asset_1_location_latest.clone().into())
.map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Assets::total_issuance(asset_1), asset_total_issuance + asset_fee);
@@ -212,7 +224,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (asset_1_location, asset_refund).into());
assert_eq!(actual_refund, (asset_1_location_latest, asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
@@ -241,9 +253,15 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
.execute_with(|| {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let native_location = WestendLocation::get();
let foreign_location =
MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) };
let native_location = WestendLocationV3::get();
let foreign_location = xcm::v3::Location {
parents: 1,
interior: (
xcm::v3::Junction::Parachain(1234),
xcm::v3::Junction::GeneralIndex(12345),
)
.into(),
};
// bob's initial balance for native and `asset1` assets.
let initial_balance = 200 * UNITS;
// liquidity for both arms of (native, asset1) pool.
@@ -282,6 +300,8 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
let asset_total_issuance = ForeignAssets::total_issuance(foreign_location);
let native_total_issuance = Balances::total_issuance();
let foreign_location_latest: Location = foreign_location.try_into().unwrap();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
@@ -289,7 +309,7 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: MultiAsset = (foreign_location, asset_fee + extra_amount).into();
let payment: Asset = (foreign_location_latest.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
@@ -297,8 +317,10 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&foreign_location.into()).map_or(0, |a| *a);
let unused_amount = unused_asset
.fungible
.get(&foreign_location_latest.clone().into())
.map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(
ForeignAssets::total_issuance(foreign_location),
@@ -315,7 +337,7 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (foreign_location, asset_refund).into());
assert_eq!(actual_refund, (foreign_location_latest, asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
@@ -345,19 +367,25 @@ fn test_assets_balances_api_works() {
.build()
.execute_with(|| {
let local_asset_id = 1;
let foreign_asset_id_multilocation =
MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) };
let foreign_asset_id_location = xcm::v3::Location {
parents: 1,
interior: [
xcm::v3::Junction::Parachain(1234),
xcm::v3::Junction::GeneralIndex(12345),
]
.into(),
};
// check before
assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)),
ForeignAssets::balance(foreign_asset_id_location, AccountId::from(ALICE)),
0
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0);
assert!(Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_as::<MultiAssets>()
.try_as::<XcmAssets>()
.unwrap()
.is_none());
@@ -388,7 +416,7 @@ fn test_assets_balances_api_works() {
let foreign_asset_minimum_asset_balance = 3333333_u128;
assert_ok!(ForeignAssets::force_create(
RuntimeHelper::root_origin(),
foreign_asset_id_multilocation,
foreign_asset_id_location,
AccountId::from(SOME_ASSET_ADMIN).into(),
false,
foreign_asset_minimum_asset_balance
@@ -397,7 +425,7 @@ fn test_assets_balances_api_works() {
// We first mint enough asset for the account to exist for assets
assert_ok!(ForeignAssets::mint(
RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)),
foreign_asset_id_multilocation,
foreign_asset_id_location,
AccountId::from(ALICE).into(),
6 * foreign_asset_minimum_asset_balance
));
@@ -408,12 +436,12 @@ fn test_assets_balances_api_works() {
minimum_asset_balance
);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)),
ForeignAssets::balance(foreign_asset_id_location, AccountId::from(ALICE)),
6 * minimum_asset_balance
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency);
let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE))
let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_into()
.unwrap();
@@ -428,13 +456,13 @@ fn test_assets_balances_api_works() {
)));
// check trusted asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(),
AssetIdForTrustBackedAssetsConvertLatest::convert_back(&local_asset_id).unwrap(),
minimum_asset_balance
)
.into())));
// check foreign asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
Identity::convert_back(&foreign_asset_id_multilocation).unwrap(),
V4V3LocationConverter::convert_back(&foreign_asset_id_location).unwrap(),
6 * foreign_asset_minimum_asset_balance
)
.into())));
@@ -505,7 +533,7 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_
XcmConfig,
TrustBackedAssetsInstance,
AssetIdForTrustBackedAssets,
AssetIdForTrustBackedAssetsConvert,
AssetIdForTrustBackedAssetsConvertLatest,
collator_session_keys(),
ExistentialDeposit::get(),
12345,
@@ -522,11 +550,15 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_
Runtime,
XcmConfig,
ForeignAssetsInstance,
MultiLocation,
xcm::v3::Location,
JustTry,
collator_session_keys(),
ExistentialDeposit::get(),
MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) },
xcm::v3::Location {
parents: 1,
interior: [xcm::v3::Junction::Parachain(1313), xcm::v3::Junction::GeneralIndex(12345)]
.into()
},
Box::new(|| {
assert!(Assets::asset_ids().collect::<Vec<_>>().is_empty());
}),
@@ -541,8 +573,8 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p
WeightToFee,
ForeignCreatorsSovereignAccountOf,
ForeignAssetsInstance,
MultiLocation,
JustTry,
xcm::v3::Location,
V4V3LocationConverter,
collator_session_keys(),
ExistentialDeposit::get(),
AssetDeposit::get(),
@@ -626,12 +658,12 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_works() {
AccountId::from([73; 32]),
AccountId::from(BLOCK_AUTHOR_ACCOUNT),
// receiving ROCs
(MultiLocation { parents: 2, interior: X1(GlobalConsensus(Rococo)) }, 1000000000000, 1_000_000_000),
(xcm::v3::Location::new(2, [xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::Rococo)]), 1000000000000, 1_000_000_000),
bridging_to_asset_hub_rococo,
(
X1(PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)),
[PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)].into(),
GlobalConsensus(Rococo),
X1(Parachain(1000))
[Parachain(1000)].into()
)
)
}
@@ -19,26 +19,25 @@ use sp_std::marker::PhantomData;
use xcm::latest::prelude::*;
/// Creates asset pairs for liquidity pools with `Target` always being the first asset.
pub struct AssetPairFactory<Target, SelfParaId, PalletId>(
PhantomData<(Target, SelfParaId, PalletId)>,
pub struct AssetPairFactory<Target, SelfParaId, PalletId, L = Location>(
PhantomData<(Target, SelfParaId, PalletId, L)>,
);
impl<Target: Get<MultiLocation>, SelfParaId: Get<ParaId>, PalletId: Get<u32>>
pallet_asset_conversion::BenchmarkHelper<MultiLocation>
for AssetPairFactory<Target, SelfParaId, PalletId>
impl<Target: Get<L>, SelfParaId: Get<ParaId>, PalletId: Get<u32>, L: TryFrom<Location>>
pallet_asset_conversion::BenchmarkHelper<L> for AssetPairFactory<Target, SelfParaId, PalletId, L>
{
fn create_pair(seed1: u32, seed2: u32) -> (MultiLocation, MultiLocation) {
let with_id = MultiLocation::new(
fn create_pair(seed1: u32, seed2: u32) -> (L, L) {
let with_id = Location::new(
1,
X3(
[
Parachain(SelfParaId::get().into()),
PalletInstance(PalletId::get() as u8),
GeneralIndex(seed2.into()),
),
],
);
if seed1 % 2 == 0 {
(with_id, Target::get())
(with_id.try_into().map_err(|_| "Something went wrong").unwrap(), Target::get())
} else {
(Target::get(), with_id)
(Target::get(), with_id.try_into().map_err(|_| "Something went wrong").unwrap())
}
}
}
@@ -17,21 +17,21 @@ use frame_support::traits::{
ContainsPair, EnsureOrigin, EnsureOriginWithArg, Everything, OriginTrait,
};
use pallet_xcm::{EnsureXcm, Origin as XcmOrigin};
use xcm::latest::MultiLocation;
use xcm::latest::Location;
use xcm_executor::traits::ConvertLocation;
/// `EnsureOriginWithArg` impl for `CreateOrigin` that allows only XCM origins that are locations
/// containing the class location.
pub struct ForeignCreators<IsForeign, AccountOf, AccountId>(
sp_std::marker::PhantomData<(IsForeign, AccountOf, AccountId)>,
pub struct ForeignCreators<IsForeign, AccountOf, AccountId, L = Location>(
sp_std::marker::PhantomData<(IsForeign, AccountOf, AccountId, L)>,
);
impl<
IsForeign: ContainsPair<MultiLocation, MultiLocation>,
IsForeign: ContainsPair<L, L>,
AccountOf: ConvertLocation<AccountId>,
AccountId: Clone,
RuntimeOrigin: From<XcmOrigin> + OriginTrait + Clone,
> EnsureOriginWithArg<RuntimeOrigin, MultiLocation>
for ForeignCreators<IsForeign, AccountOf, AccountId>
L: TryFrom<Location> + TryInto<Location> + Clone,
> EnsureOriginWithArg<RuntimeOrigin, L> for ForeignCreators<IsForeign, AccountOf, AccountId, L>
where
RuntimeOrigin::PalletsOrigin:
From<XcmOrigin> + TryInto<XcmOrigin, Error = RuntimeOrigin::PalletsOrigin>,
@@ -40,17 +40,20 @@ where
fn try_origin(
origin: RuntimeOrigin,
asset_location: &MultiLocation,
asset_location: &L,
) -> sp_std::result::Result<Self::Success, RuntimeOrigin> {
let origin_location = EnsureXcm::<Everything>::try_origin(origin.clone())?;
let origin_location = EnsureXcm::<Everything, L>::try_origin(origin.clone())?;
if !IsForeign::contains(asset_location, &origin_location) {
return Err(origin)
}
AccountOf::convert_location(&origin_location).ok_or(origin)
let latest_location: Location =
origin_location.clone().try_into().map_err(|_| origin.clone())?;
AccountOf::convert_location(&latest_location).ok_or(origin)
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin(a: &MultiLocation) -> Result<RuntimeOrigin, ()> {
Ok(pallet_xcm::Origin::Xcm(*a).into())
fn try_successful_origin(a: &L) -> Result<RuntimeOrigin, ()> {
let latest_location: Location = (*a).clone().try_into().map_err(|_| ())?;
Ok(pallet_xcm::Origin::Xcm(latest_location).into())
}
}
@@ -19,52 +19,48 @@ use crate::runtime_api::FungiblesAccessError;
use frame_support::traits::Contains;
use sp_runtime::traits::MaybeEquivalence;
use sp_std::{borrow::Borrow, vec::Vec};
use xcm::latest::{MultiAsset, MultiLocation};
use xcm::latest::{Asset, Location};
use xcm_builder::{ConvertedConcreteId, MatchedConvertedConcreteId};
use xcm_executor::traits::MatchesFungibles;
/// Converting any [`(AssetId, Balance)`] to [`MultiAsset`]
pub trait MultiAssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>:
/// Converting any [`(AssetId, Balance)`] to [`Asset`]
pub trait AssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>:
MatchesFungibles<AssetId, Balance>
where
AssetId: Clone,
Balance: Clone,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
{
fn convert_ref(
value: impl Borrow<(AssetId, Balance)>,
) -> Result<MultiAsset, FungiblesAccessError>;
fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result<Asset, FungiblesAccessError>;
}
/// Checks for `MultiLocation`.
pub trait MatchesMultiLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>:
/// Checks for `Location`.
pub trait MatchesLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>:
MatchesFungibles<AssetId, Balance>
where
AssetId: Clone,
Balance: Clone,
MatchAssetId: Contains<MultiLocation>,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
MatchAssetId: Contains<Location>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
{
fn contains(location: &MultiLocation) -> bool;
fn contains(location: &Location) -> bool;
}
impl<
AssetId: Clone,
Balance: Clone,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
> MultiAssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>
> AssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>
for ConvertedConcreteId<AssetId, Balance, ConvertAssetId, ConvertBalance>
{
fn convert_ref(
value: impl Borrow<(AssetId, Balance)>,
) -> Result<MultiAsset, FungiblesAccessError> {
fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result<Asset, FungiblesAccessError> {
let (asset_id, balance) = value.borrow();
match ConvertAssetId::convert_back(asset_id) {
Some(asset_id_as_multilocation) => match ConvertBalance::convert_back(balance) {
Some(amount) => Ok((asset_id_as_multilocation, amount).into()),
Some(asset_id_as_location) => match ConvertBalance::convert_back(balance) {
Some(amount) => Ok((asset_id_as_location, amount).into()),
None => Err(FungiblesAccessError::AmountToBalanceConversionFailed),
},
None => Err(FungiblesAccessError::AssetIdConversionFailed),
@@ -75,19 +71,17 @@ impl<
impl<
AssetId: Clone,
Balance: Clone,
MatchAssetId: Contains<MultiLocation>,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
MatchAssetId: Contains<Location>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
> MultiAssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>
> AssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>
for MatchedConvertedConcreteId<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>
{
fn convert_ref(
value: impl Borrow<(AssetId, Balance)>,
) -> Result<MultiAsset, FungiblesAccessError> {
fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result<Asset, FungiblesAccessError> {
let (asset_id, balance) = value.borrow();
match ConvertAssetId::convert_back(asset_id) {
Some(asset_id_as_multilocation) => match ConvertBalance::convert_back(balance) {
Some(amount) => Ok((asset_id_as_multilocation, amount).into()),
Some(asset_id_as_location) => match ConvertBalance::convert_back(balance) {
Some(amount) => Ok((asset_id_as_location, amount).into()),
None => Err(FungiblesAccessError::AmountToBalanceConversionFailed),
},
None => Err(FungiblesAccessError::AssetIdConversionFailed),
@@ -98,13 +92,13 @@ impl<
impl<
AssetId: Clone,
Balance: Clone,
MatchAssetId: Contains<MultiLocation>,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
MatchAssetId: Contains<Location>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
> MatchesMultiLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>
> MatchesLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>
for MatchedConvertedConcreteId<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance>
{
fn contains(location: &MultiLocation) -> bool {
fn contains(location: &Location) -> bool {
MatchAssetId::contains(location)
}
}
@@ -113,12 +107,12 @@ impl<
impl<
AssetId: Clone,
Balance: Clone,
MatchAssetId: Contains<MultiLocation>,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
MatchAssetId: Contains<Location>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
> MatchesMultiLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance> for Tuple
> MatchesLocation<AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertBalance> for Tuple
{
fn contains(location: &MultiLocation) -> bool {
fn contains(location: &Location) -> bool {
for_tuples!( #(
match Tuple::contains(location) { o @ true => return o, _ => () }
)* );
@@ -127,27 +121,24 @@ impl<
}
}
/// Helper function to convert collections with [`(AssetId, Balance)`] to [`MultiAsset`]
/// Helper function to convert collections with [`(AssetId, Balance)`] to [`Asset`]
pub fn convert<'a, AssetId, Balance, ConvertAssetId, ConvertBalance, Converter>(
items: impl Iterator<Item = &'a (AssetId, Balance)>,
) -> Result<Vec<MultiAsset>, FungiblesAccessError>
) -> Result<Vec<Asset>, FungiblesAccessError>
where
AssetId: Clone + 'a,
Balance: Clone + 'a,
ConvertAssetId: MaybeEquivalence<MultiLocation, AssetId>,
ConvertAssetId: MaybeEquivalence<Location, AssetId>,
ConvertBalance: MaybeEquivalence<u128, Balance>,
Converter: MultiAssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>,
Converter: AssetConverter<AssetId, Balance, ConvertAssetId, ConvertBalance>,
{
items.map(Converter::convert_ref).collect()
}
/// Helper function to convert `Balance` with MultiLocation` to `MultiAsset`
pub fn convert_balance<
T: frame_support::pallet_prelude::Get<MultiLocation>,
Balance: TryInto<u128>,
>(
/// Helper function to convert `Balance` with Location` to `Asset`
pub fn convert_balance<T: frame_support::pallet_prelude::Get<Location>, Balance: TryInto<u128>>(
balance: Balance,
) -> Result<MultiAsset, FungiblesAccessError> {
) -> Result<Asset, FungiblesAccessError> {
match balance.try_into() {
Ok(balance) => Ok((T::get(), balance).into()),
Err(_) => Err(FungiblesAccessError::AmountToBalanceConversionFailed),
@@ -162,20 +153,20 @@ mod tests {
use xcm::latest::prelude::*;
use xcm_executor::traits::{Identity, JustTry};
type Converter = MatchedConvertedConcreteId<MultiLocation, u64, Everything, Identity, JustTry>;
type Converter = MatchedConvertedConcreteId<Location, u64, Everything, Identity, JustTry>;
#[test]
fn converted_concrete_id_fungible_multi_asset_conversion_roundtrip_works() {
let location = MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32]))));
let location = Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))]);
let amount = 123456_u64;
let expected_multi_asset = MultiAsset {
id: Concrete(MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32]))))),
let expected_multi_asset = Asset {
id: AssetId(Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))])),
fun: Fungible(123456_u128),
};
assert_eq!(
Converter::matches_fungibles(&expected_multi_asset).map_err(|_| ()),
Ok((location, amount))
Ok((location.clone(), amount))
);
assert_eq!(Converter::convert_ref((location, amount)), Ok(expected_multi_asset));
@@ -184,17 +175,17 @@ mod tests {
#[test]
fn converted_concrete_id_fungible_multi_asset_conversion_collection_works() {
let data = vec![
(MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32])))), 123456_u64),
(MultiLocation::new(1, X1(GlobalConsensus(ByGenesis([1; 32])))), 654321_u64),
(Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))]), 123456_u64),
(Location::new(1, [GlobalConsensus(ByGenesis([1; 32]))]), 654321_u64),
];
let expected_data = vec![
MultiAsset {
id: Concrete(MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32]))))),
Asset {
id: AssetId(Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))])),
fun: Fungible(123456_u128),
},
MultiAsset {
id: Concrete(MultiLocation::new(1, X1(GlobalConsensus(ByGenesis([1; 32]))))),
Asset {
id: AssetId(Location::new(1, [GlobalConsensus(ByGenesis([1; 32]))])),
fun: Fungible(654321_u128),
},
];
@@ -23,15 +23,24 @@ pub mod local_and_foreign_assets;
pub mod matching;
pub mod runtime_api;
use crate::matching::{LocalMultiLocationPattern, ParentLocation};
use crate::matching::{LocalLocationPattern, ParentLocation};
use frame_support::traits::{Equals, EverythingBut};
use parachains_common::AssetIdForTrustBackedAssets;
use xcm::prelude::MultiLocation;
use xcm_builder::{AsPrefixedGeneralIndex, MatchedConvertedConcreteId, StartsWith};
use xcm_executor::traits::{Identity, JustTry};
use xcm_builder::{
AsPrefixedGeneralIndex, MatchedConvertedConcreteId, StartsWith, V4V3LocationConverter,
};
use xcm_executor::traits::JustTry;
/// `MultiLocation` vs `AssetIdForTrustBackedAssets` converter for `TrustBackedAssets`
/// `Location` vs `AssetIdForTrustBackedAssets` converter for `TrustBackedAssets`
pub type AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation> =
AsPrefixedGeneralIndex<
TrustBackedAssetsPalletLocation,
AssetIdForTrustBackedAssets,
JustTry,
xcm::v3::Location,
>;
pub type AssetIdForTrustBackedAssetsConvertLatest<TrustBackedAssetsPalletLocation> =
AsPrefixedGeneralIndex<TrustBackedAssetsPalletLocation, AssetIdForTrustBackedAssets, JustTry>;
/// [`MatchedConvertedConcreteId`] converter dedicated for `TrustBackedAssets`
@@ -40,59 +49,55 @@ pub type TrustBackedAssetsConvertedConcreteId<TrustBackedAssetsPalletLocation, B
AssetIdForTrustBackedAssets,
Balance,
StartsWith<TrustBackedAssetsPalletLocation>,
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
AssetIdForTrustBackedAssetsConvertLatest<TrustBackedAssetsPalletLocation>,
JustTry,
>;
/// AssetId used for identifying assets by MultiLocation.
pub type MultiLocationForAssetId = MultiLocation;
/// [`MatchedConvertedConcreteId`] converter dedicated for storing `AssetId` as `Location`.
pub type LocationConvertedConcreteId<LocationFilter, Balance> = MatchedConvertedConcreteId<
xcm::v3::Location,
Balance,
LocationFilter,
V4V3LocationConverter,
JustTry,
>;
/// [`MatchedConvertedConcreteId`] converter dedicated for `TrustBackedAssets`
pub type TrustBackedAssetsAsMultiLocation<TrustBackedAssetsPalletLocation, Balance> =
pub type TrustBackedAssetsAsLocation<TrustBackedAssetsPalletLocation, Balance> =
MatchedConvertedConcreteId<
MultiLocationForAssetId,
xcm::v3::Location,
Balance,
StartsWith<TrustBackedAssetsPalletLocation>,
Identity,
JustTry,
>;
/// [`MatchedConvertedConcreteId`] converter dedicated for storing `AssetId` as `MultiLocation`.
pub type MultiLocationConvertedConcreteId<MultiLocationFilter, Balance> =
MatchedConvertedConcreteId<
MultiLocationForAssetId,
Balance,
MultiLocationFilter,
Identity,
V4V3LocationConverter,
JustTry,
>;
/// [`MatchedConvertedConcreteId`] converter dedicated for storing `ForeignAssets` with `AssetId` as
/// `MultiLocation`.
/// `Location`.
///
/// Excludes by default:
/// - parent as relay chain
/// - all local MultiLocations
/// - all local Locations
///
/// `AdditionalMultiLocationExclusionFilter` can customize additional excluded MultiLocations
pub type ForeignAssetsConvertedConcreteId<AdditionalMultiLocationExclusionFilter, Balance> =
MultiLocationConvertedConcreteId<
/// `AdditionalLocationExclusionFilter` can customize additional excluded Locations
pub type ForeignAssetsConvertedConcreteId<AdditionalLocationExclusionFilter, Balance> =
LocationConvertedConcreteId<
EverythingBut<(
// Excludes relay/parent chain currency
Equals<ParentLocation>,
// Here we rely on fact that something like this works:
// assert!(MultiLocation::new(1,
// X1(Parachain(100))).starts_with(&MultiLocation::parent()));
// assert!(X1(Parachain(100)).starts_with(&Here));
StartsWith<LocalMultiLocationPattern>,
// assert!(Location::new(1,
// [Parachain(100)]).starts_with(&Location::parent()));
// assert!([Parachain(100)].into().starts_with(&Here));
StartsWith<LocalLocationPattern>,
// Here we can exclude more stuff or leave it as `()`
AdditionalMultiLocationExclusionFilter,
AdditionalLocationExclusionFilter,
)>,
Balance,
>;
type AssetIdForPoolAssets = u32;
/// `MultiLocation` vs `AssetIdForPoolAssets` converter for `PoolAssets`.
/// `Location` vs `AssetIdForPoolAssets` converter for `PoolAssets`.
pub type AssetIdForPoolAssetsConvert<PoolAssetsPalletLocation> =
AsPrefixedGeneralIndex<PoolAssetsPalletLocation, AssetIdForPoolAssets, JustTry>;
/// [`MatchedConvertedConcreteId`] converter dedicated for `PoolAssets`
@@ -109,28 +114,28 @@ pub type PoolAssetsConvertedConcreteId<PoolAssetsPalletLocation, Balance> =
mod tests {
use super::*;
use sp_runtime::traits::MaybeEquivalence;
use xcm::latest::prelude::*;
use xcm::prelude::*;
use xcm_builder::StartsWithExplicitGlobalConsensus;
use xcm_executor::traits::{Error as MatchError, MatchesFungibles};
#[test]
fn asset_id_for_trust_backed_assets_convert_works() {
frame_support::parameter_types! {
pub TrustBackedAssetsPalletLocation: MultiLocation = MultiLocation::new(5, X1(PalletInstance(13)));
pub TrustBackedAssetsPalletLocation: Location = Location::new(5, [PalletInstance(13)]);
}
let local_asset_id = 123456789 as AssetIdForTrustBackedAssets;
let expected_reverse_ref =
MultiLocation::new(5, X2(PalletInstance(13), GeneralIndex(local_asset_id.into())));
Location::new(5, [PalletInstance(13), GeneralIndex(local_asset_id.into())]);
assert_eq!(
AssetIdForTrustBackedAssetsConvert::<TrustBackedAssetsPalletLocation>::convert_back(
AssetIdForTrustBackedAssetsConvertLatest::<TrustBackedAssetsPalletLocation>::convert_back(
&local_asset_id
)
.unwrap(),
expected_reverse_ref
);
assert_eq!(
AssetIdForTrustBackedAssetsConvert::<TrustBackedAssetsPalletLocation>::convert(
AssetIdForTrustBackedAssetsConvertLatest::<TrustBackedAssetsPalletLocation>::convert(
&expected_reverse_ref
)
.unwrap(),
@@ -141,7 +146,7 @@ mod tests {
#[test]
fn trust_backed_assets_match_fungibles_works() {
frame_support::parameter_types! {
pub TrustBackedAssetsPalletLocation: MultiLocation = MultiLocation::new(0, X1(PalletInstance(13)));
pub TrustBackedAssetsPalletLocation: Location = Location::new(0, [PalletInstance(13)]);
}
// setup convert
type TrustBackedAssetsConvert =
@@ -149,85 +154,86 @@ mod tests {
let test_data = vec![
// missing GeneralIndex
(ma_1000(0, X1(PalletInstance(13))), Err(MatchError::AssetIdConversionFailed)),
(ma_1000(0, [PalletInstance(13)].into()), Err(MatchError::AssetIdConversionFailed)),
(
ma_1000(0, X2(PalletInstance(13), GeneralKey { data: [0; 32], length: 32 })),
ma_1000(0, [PalletInstance(13), GeneralKey { data: [0; 32], length: 32 }].into()),
Err(MatchError::AssetIdConversionFailed),
),
(
ma_1000(0, X2(PalletInstance(13), Parachain(1000))),
ma_1000(0, [PalletInstance(13), Parachain(1000)].into()),
Err(MatchError::AssetIdConversionFailed),
),
// OK
(ma_1000(0, X2(PalletInstance(13), GeneralIndex(1234))), Ok((1234, 1000))),
(ma_1000(0, [PalletInstance(13), GeneralIndex(1234)].into()), Ok((1234, 1000))),
(
ma_1000(0, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))),
ma_1000(0, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()),
Ok((1234, 1000)),
),
(
ma_1000(
0,
X4(
[
PalletInstance(13),
GeneralIndex(1234),
GeneralIndex(2222),
GeneralKey { data: [0; 32], length: 32 },
),
]
.into(),
),
Ok((1234, 1000)),
),
// wrong pallet instance
(
ma_1000(0, X2(PalletInstance(77), GeneralIndex(1234))),
ma_1000(0, [PalletInstance(77), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(0, X3(PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222))),
ma_1000(0, [PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222)].into()),
Err(MatchError::AssetNotHandled),
),
// wrong parent
(
ma_1000(1, X2(PalletInstance(13), GeneralIndex(1234))),
ma_1000(1, [PalletInstance(13), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(1, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))),
ma_1000(1, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(1, X2(PalletInstance(77), GeneralIndex(1234))),
ma_1000(1, [PalletInstance(77), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(1, X3(PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222))),
ma_1000(1, [PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222)].into()),
Err(MatchError::AssetNotHandled),
),
// wrong parent
(
ma_1000(2, X2(PalletInstance(13), GeneralIndex(1234))),
ma_1000(2, [PalletInstance(13), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(2, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))),
ma_1000(2, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()),
Err(MatchError::AssetNotHandled),
),
// missing GeneralIndex
(ma_1000(0, X1(PalletInstance(77))), Err(MatchError::AssetNotHandled)),
(ma_1000(1, X1(PalletInstance(13))), Err(MatchError::AssetNotHandled)),
(ma_1000(2, X1(PalletInstance(13))), Err(MatchError::AssetNotHandled)),
(ma_1000(0, [PalletInstance(77)].into()), Err(MatchError::AssetNotHandled)),
(ma_1000(1, [PalletInstance(13)].into()), Err(MatchError::AssetNotHandled)),
(ma_1000(2, [PalletInstance(13)].into()), Err(MatchError::AssetNotHandled)),
];
for (multi_asset, expected_result) in test_data {
for (asset, expected_result) in test_data {
assert_eq!(
<TrustBackedAssetsConvert as MatchesFungibles<AssetIdForTrustBackedAssets, u128>>::matches_fungibles(&multi_asset),
expected_result, "multi_asset: {:?}", multi_asset);
<TrustBackedAssetsConvert as MatchesFungibles<AssetIdForTrustBackedAssets, u128>>::matches_fungibles(&asset.clone().try_into().unwrap()),
expected_result, "asset: {:?}", asset);
}
}
#[test]
fn multi_location_converted_concrete_id_converter_works() {
fn location_converted_concrete_id_converter_works() {
frame_support::parameter_types! {
pub Parachain100Pattern: MultiLocation = MultiLocation::new(1, X1(Parachain(100)));
pub Parachain100Pattern: Location = Location::new(1, [Parachain(100)]);
pub UniversalLocationNetworkId: NetworkId = NetworkId::ByGenesis([9; 32]);
}
@@ -243,95 +249,125 @@ mod tests {
let test_data = vec![
// excluded as local
(ma_1000(0, Here), Err(MatchError::AssetNotHandled)),
(ma_1000(0, X1(Parachain(100))), Err(MatchError::AssetNotHandled)),
(ma_1000(0, [Parachain(100)].into()), Err(MatchError::AssetNotHandled)),
(
ma_1000(0, X2(PalletInstance(13), GeneralIndex(1234))),
ma_1000(0, [PalletInstance(13), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
// excluded as parent
(ma_1000(1, Here), Err(MatchError::AssetNotHandled)),
// excluded as additional filter - Parachain100Pattern
(ma_1000(1, X1(Parachain(100))), Err(MatchError::AssetNotHandled)),
(ma_1000(1, X2(Parachain(100), GeneralIndex(1234))), Err(MatchError::AssetNotHandled)),
(ma_1000(1, [Parachain(100)].into()), Err(MatchError::AssetNotHandled)),
(
ma_1000(1, X3(Parachain(100), PalletInstance(13), GeneralIndex(1234))),
ma_1000(1, [Parachain(100), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(1, [Parachain(100), PalletInstance(13), GeneralIndex(1234)].into()),
Err(MatchError::AssetNotHandled),
),
// excluded as additional filter - StartsWithExplicitGlobalConsensus
(
ma_1000(1, X1(GlobalConsensus(NetworkId::ByGenesis([9; 32])))),
ma_1000(1, [GlobalConsensus(NetworkId::ByGenesis([9; 32]))].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(2, X1(GlobalConsensus(NetworkId::ByGenesis([9; 32])))),
ma_1000(2, [GlobalConsensus(NetworkId::ByGenesis([9; 32]))].into()),
Err(MatchError::AssetNotHandled),
),
(
ma_1000(
2,
X3(
[
GlobalConsensus(NetworkId::ByGenesis([9; 32])),
Parachain(200),
GeneralIndex(1234),
),
]
.into(),
),
Err(MatchError::AssetNotHandled),
),
// ok
(ma_1000(1, X1(Parachain(200))), Ok((MultiLocation::new(1, X1(Parachain(200))), 1000))),
(ma_1000(2, X1(Parachain(200))), Ok((MultiLocation::new(2, X1(Parachain(200))), 1000))),
(
ma_1000(1, X2(Parachain(200), GeneralIndex(1234))),
Ok((MultiLocation::new(1, X2(Parachain(200), GeneralIndex(1234))), 1000)),
ma_1000(1, [Parachain(200)].into()),
Ok((xcm::v3::Location::new(1, [xcm::v3::Junction::Parachain(200)]), 1000)),
),
(
ma_1000(2, X2(Parachain(200), GeneralIndex(1234))),
Ok((MultiLocation::new(2, X2(Parachain(200), GeneralIndex(1234))), 1000)),
ma_1000(2, [Parachain(200)].into()),
Ok((xcm::v3::Location::new(2, [xcm::v3::Junction::Parachain(200)]), 1000)),
),
(
ma_1000(2, X1(GlobalConsensus(NetworkId::ByGenesis([7; 32])))),
ma_1000(1, [Parachain(200), GeneralIndex(1234)].into()),
Ok((
MultiLocation::new(2, X1(GlobalConsensus(NetworkId::ByGenesis([7; 32])))),
xcm::v3::Location::new(
1,
[xcm::v3::Junction::Parachain(200), xcm::v3::Junction::GeneralIndex(1234)],
),
1000,
)),
),
(
ma_1000(2, [Parachain(200), GeneralIndex(1234)].into()),
Ok((
xcm::v3::Location::new(
2,
[xcm::v3::Junction::Parachain(200), xcm::v3::Junction::GeneralIndex(1234)],
),
1000,
)),
),
(
ma_1000(2, [GlobalConsensus(NetworkId::ByGenesis([7; 32]))].into()),
Ok((
xcm::v3::Location::new(
2,
[xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::ByGenesis(
[7; 32],
))],
),
1000,
)),
),
(
ma_1000(
2,
X3(
[
GlobalConsensus(NetworkId::ByGenesis([7; 32])),
Parachain(200),
GeneralIndex(1234),
),
]
.into(),
),
Ok((
MultiLocation::new(
xcm::v3::Location::new(
2,
X3(
GlobalConsensus(NetworkId::ByGenesis([7; 32])),
Parachain(200),
GeneralIndex(1234),
),
[
xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::ByGenesis(
[7; 32],
)),
xcm::v3::Junction::Parachain(200),
xcm::v3::Junction::GeneralIndex(1234),
],
),
1000,
)),
),
];
for (multi_asset, expected_result) in test_data {
for (asset, expected_result) in test_data {
assert_eq!(
<Convert as MatchesFungibles<MultiLocationForAssetId, u128>>::matches_fungibles(
&multi_asset
<Convert as MatchesFungibles<xcm::v3::MultiLocation, u128>>::matches_fungibles(
&asset.clone().try_into().unwrap()
),
expected_result,
"multi_asset: {:?}",
multi_asset
"asset: {:?}",
asset
);
}
}
// Create MultiAsset
fn ma_1000(parents: u8, interior: Junctions) -> MultiAsset {
(MultiLocation::new(parents, interior), 1000).into()
// Create Asset
fn ma_1000(parents: u8, interior: Junctions) -> Asset {
(Location::new(parents, interior), 1000).into()
}
}
@@ -20,32 +20,32 @@ use sp_runtime::{
Either::{Left, Right},
};
use sp_std::marker::PhantomData;
use xcm::latest::MultiLocation;
use xcm::latest::Location;
/// Converts a given [`MultiLocation`] to [`Either::Left`] when equal to `Target`, or
/// Converts a given [`Location`] to [`Either::Left`] when equal to `Target`, or
/// [`Either::Right`] otherwise.
///
/// Suitable for use as a `Criterion` with [`frame_support::traits::tokens::fungible::UnionOf`].
pub struct TargetFromLeft<Target>(PhantomData<Target>);
impl<Target: Get<MultiLocation>> Convert<MultiLocation, Either<(), MultiLocation>>
for TargetFromLeft<Target>
{
fn convert(l: MultiLocation) -> Either<(), MultiLocation> {
pub struct TargetFromLeft<Target, L = Location>(PhantomData<(Target, L)>);
impl<Target: Get<L>, L: PartialEq + Eq> Convert<L, Either<(), L>> for TargetFromLeft<Target, L> {
fn convert(l: L) -> Either<(), L> {
Target::get().eq(&l).then(|| Left(())).map_or(Right(l), |n| n)
}
}
/// Converts a given [`MultiLocation`] to [`Either::Left`] based on the `Equivalence` criteria.
/// Converts a given [`Location`] to [`Either::Left`] based on the `Equivalence` criteria.
/// Returns [`Either::Right`] if not equivalent.
///
/// Suitable for use as a `Criterion` with [`frame_support::traits::tokens::fungibles::UnionOf`].
pub struct LocalFromLeft<Equivalence, AssetId>(PhantomData<(Equivalence, AssetId)>);
impl<Equivalence, AssetId> Convert<MultiLocation, Either<AssetId, MultiLocation>>
for LocalFromLeft<Equivalence, AssetId>
pub struct LocalFromLeft<Equivalence, AssetId, L = Location>(
PhantomData<(Equivalence, AssetId, L)>,
);
impl<Equivalence, AssetId, L> Convert<L, Either<AssetId, L>>
for LocalFromLeft<Equivalence, AssetId, L>
where
Equivalence: MaybeEquivalence<MultiLocation, AssetId>,
Equivalence: MaybeEquivalence<L, AssetId>,
{
fn convert(l: MultiLocation) -> Either<AssetId, MultiLocation> {
fn convert(l: L) -> Either<AssetId, L> {
match Equivalence::convert(&l) {
Some(id) => Left(id),
None => Right(l),
@@ -53,7 +53,7 @@ where
}
}
pub trait MatchesLocalAndForeignAssetsMultiLocation {
fn is_local(location: &MultiLocation) -> bool;
fn is_foreign(location: &MultiLocation) -> bool;
pub trait MatchesLocalAndForeignAssetsLocation<L = Location> {
fn is_local(location: &L) -> bool;
fn is_foreign(location: &L) -> bool;
}
@@ -15,67 +15,72 @@
use cumulus_primitives_core::ParaId;
use frame_support::{pallet_prelude::Get, traits::ContainsPair};
use xcm::{
latest::prelude::{MultiAsset, MultiLocation},
prelude::*,
};
use xcm::prelude::*;
use xcm_builder::ensure_is_remote;
frame_support::parameter_types! {
pub LocalMultiLocationPattern: MultiLocation = MultiLocation::new(0, Here);
pub ParentLocation: MultiLocation = MultiLocation::parent();
pub LocalLocationPattern: Location = Location::new(0, Here);
pub ParentLocation: Location = Location::parent();
}
/// Accepts an asset if it is from the origin.
pub struct IsForeignConcreteAsset<IsForeign>(sp_std::marker::PhantomData<IsForeign>);
impl<IsForeign: ContainsPair<MultiLocation, MultiLocation>> ContainsPair<MultiAsset, MultiLocation>
impl<IsForeign: ContainsPair<Location, Location>> ContainsPair<Asset, Location>
for IsForeignConcreteAsset<IsForeign>
{
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
fn contains(asset: &Asset, origin: &Location) -> bool {
log::trace!(target: "xcm::contains", "IsForeignConcreteAsset asset: {:?}, origin: {:?}", asset, origin);
matches!(asset.id, Concrete(ref id) if IsForeign::contains(id, origin))
matches!(asset.id, AssetId(ref id) if IsForeign::contains(id, origin))
}
}
/// Checks if `a` is from sibling location `b`. Checks that `MultiLocation-a` starts with
/// `MultiLocation-b`, and that the `ParaId` of `b` is not equal to `a`.
pub struct FromSiblingParachain<SelfParaId>(sp_std::marker::PhantomData<SelfParaId>);
impl<SelfParaId: Get<ParaId>> ContainsPair<MultiLocation, MultiLocation>
for FromSiblingParachain<SelfParaId>
/// Checks if `a` is from sibling location `b`. Checks that `Location-a` starts with
/// `Location-b`, and that the `ParaId` of `b` is not equal to `a`.
pub struct FromSiblingParachain<SelfParaId, L = Location>(
sp_std::marker::PhantomData<(SelfParaId, L)>,
);
impl<SelfParaId: Get<ParaId>, L: TryFrom<Location> + TryInto<Location> + Clone> ContainsPair<L, L>
for FromSiblingParachain<SelfParaId, L>
{
fn contains(&a: &MultiLocation, b: &MultiLocation) -> bool {
// `a` needs to be from `b` at least
if !a.starts_with(b) {
return false
}
fn contains(a: &L, b: &L) -> bool {
// We convert locations to latest
let a = match ((*a).clone().try_into(), (*b).clone().try_into()) {
(Ok(a), Ok(b)) if a.starts_with(&b) => a, // `a` needs to be from `b` at least
_ => return false,
};
// here we check if sibling
match a {
MultiLocation { parents: 1, interior } =>
match a.unpack() {
(1, interior) =>
matches!(interior.first(), Some(Parachain(sibling_para_id)) if sibling_para_id.ne(&u32::from(SelfParaId::get()))),
_ => false,
}
}
}
/// Checks if `a` is from the expected global consensus network. Checks that `MultiLocation-a`
/// starts with `MultiLocation-b`, and that network is a foreign consensus system.
pub struct FromNetwork<UniversalLocation, ExpectedNetworkId>(
sp_std::marker::PhantomData<(UniversalLocation, ExpectedNetworkId)>,
/// Checks if `a` is from the expected global consensus network. Checks that `Location-a`
/// starts with `Location-b`, and that network is a foreign consensus system.
pub struct FromNetwork<UniversalLocation, ExpectedNetworkId, L = Location>(
sp_std::marker::PhantomData<(UniversalLocation, ExpectedNetworkId, L)>,
);
impl<UniversalLocation: Get<InteriorMultiLocation>, ExpectedNetworkId: Get<NetworkId>>
ContainsPair<MultiLocation, MultiLocation> for FromNetwork<UniversalLocation, ExpectedNetworkId>
impl<
UniversalLocation: Get<InteriorLocation>,
ExpectedNetworkId: Get<NetworkId>,
L: TryFrom<Location> + TryInto<Location> + Clone,
> ContainsPair<L, L> for FromNetwork<UniversalLocation, ExpectedNetworkId, L>
{
fn contains(&a: &MultiLocation, b: &MultiLocation) -> bool {
// `a` needs to be from `b` at least
if !a.starts_with(b) {
return false
}
fn contains(a: &L, b: &L) -> bool {
// We convert locations to latest
let a = match ((*a).clone().try_into(), (*b).clone().try_into()) {
(Ok(a), Ok(b)) if a.starts_with(&b) => a, // `a` needs to be from `b` at least
_ => return false,
};
let universal_source = UniversalLocation::get();
// ensure that `a`` is remote and from the expected network
match ensure_is_remote(universal_source, a) {
// ensure that `a` is remote and from the expected network
match ensure_is_remote(universal_source.clone(), a.clone()) {
Ok((network_id, _)) => network_id == ExpectedNetworkId::get(),
Err(e) => {
log::trace!(
@@ -89,19 +94,17 @@ impl<UniversalLocation: Get<InteriorMultiLocation>, ExpectedNetworkId: Get<Netwo
}
}
/// Adapter verifies if it is allowed to receive `MultiAsset` from `MultiLocation`.
/// Adapter verifies if it is allowed to receive `Asset` from `Location`.
///
/// Note: `MultiLocation` has to be from a different global consensus.
/// Note: `Location` has to be from a different global consensus.
pub struct IsTrustedBridgedReserveLocationForConcreteAsset<UniversalLocation, Reserves>(
sp_std::marker::PhantomData<(UniversalLocation, Reserves)>,
);
impl<
UniversalLocation: Get<InteriorMultiLocation>,
Reserves: ContainsPair<MultiAsset, MultiLocation>,
> ContainsPair<MultiAsset, MultiLocation>
impl<UniversalLocation: Get<InteriorLocation>, Reserves: ContainsPair<Asset, Location>>
ContainsPair<Asset, Location>
for IsTrustedBridgedReserveLocationForConcreteAsset<UniversalLocation, Reserves>
{
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
fn contains(asset: &Asset, origin: &Location) -> bool {
let universal_source = UniversalLocation::get();
log::trace!(
target: "xcm::contains",
@@ -110,7 +113,7 @@ impl<
);
// check remote origin
let _ = match ensure_is_remote(universal_source, *origin) {
let _ = match ensure_is_remote(universal_source.clone(), origin.clone()) {
Ok(devolved) => devolved,
Err(_) => {
log::trace!(
@@ -133,14 +136,14 @@ mod tests {
use frame_support::parameter_types;
parameter_types! {
pub UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(1000));
pub UniversalLocation: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into();
pub ExpectedNetworkId: NetworkId = Wococo;
}
#[test]
fn from_network_contains_works() {
// asset and origin from foreign consensus works
let asset: MultiLocation = (
let asset: Location = (
Parent,
Parent,
GlobalConsensus(Wococo),
@@ -149,12 +152,11 @@ mod tests {
GeneralIndex(1),
)
.into();
let origin: MultiLocation =
(Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into();
let origin: Location = (Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into();
assert!(FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
// asset and origin from local consensus fails
let asset: MultiLocation = (
let asset: Location = (
Parent,
Parent,
GlobalConsensus(Rococo),
@@ -163,17 +165,16 @@ mod tests {
GeneralIndex(1),
)
.into();
let origin: MultiLocation =
(Parent, Parent, GlobalConsensus(Rococo), Parachain(1000)).into();
let origin: Location = (Parent, Parent, GlobalConsensus(Rococo), Parachain(1000)).into();
assert!(!FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
// asset and origin from here fails
let asset: MultiLocation = (PalletInstance(1), GeneralIndex(1)).into();
let origin: MultiLocation = Here.into();
let asset: Location = (PalletInstance(1), GeneralIndex(1)).into();
let origin: Location = Here.into();
assert!(!FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
// asset from different consensus fails
let asset: MultiLocation = (
let asset: Location = (
Parent,
Parent,
GlobalConsensus(Polkadot),
@@ -182,12 +183,11 @@ mod tests {
GeneralIndex(1),
)
.into();
let origin: MultiLocation =
(Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into();
let origin: Location = (Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into();
assert!(!FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
// origin from different consensus fails
let asset: MultiLocation = (
let asset: Location = (
Parent,
Parent,
GlobalConsensus(Wococo),
@@ -196,12 +196,11 @@ mod tests {
GeneralIndex(1),
)
.into();
let origin: MultiLocation =
(Parent, Parent, GlobalConsensus(Polkadot), Parachain(1000)).into();
let origin: Location = (Parent, Parent, GlobalConsensus(Polkadot), Parachain(1000)).into();
assert!(!FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
// asset and origin from unexpected consensus fails
let asset: MultiLocation = (
let asset: Location = (
Parent,
Parent,
GlobalConsensus(Polkadot),
@@ -210,8 +209,7 @@ mod tests {
GeneralIndex(1),
)
.into();
let origin: MultiLocation =
(Parent, Parent, GlobalConsensus(Polkadot), Parachain(1000)).into();
let origin: Location = (Parent, Parent, GlobalConsensus(Polkadot), Parachain(1000)).into();
assert!(!FromNetwork::<UniversalLocation, ExpectedNetworkId>::contains(&asset, &origin));
}
}
@@ -18,12 +18,12 @@
use codec::{Codec, Decode, Encode};
use sp_runtime::RuntimeDebug;
#[cfg(feature = "std")]
use {sp_std::vec::Vec, xcm::latest::MultiAsset};
use {sp_std::vec::Vec, xcm::latest::Asset};
/// The possible errors that can happen querying the storage of assets.
#[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)]
pub enum FungiblesAccessError {
/// `MultiLocation` to `AssetId`/`ClassId` conversion failed.
/// `Location` to `AssetId`/`ClassId` conversion failed.
AssetIdConversionFailed,
/// `u128` amount to currency `Balance` conversion failed.
AmountToBalanceConversionFailed,
@@ -36,11 +36,11 @@ sp_api::decl_runtime_apis! {
where
AccountId: Codec,
{
/// Returns the list of all [`MultiAsset`] that an `AccountId` has.
/// Returns the list of all [`Asset`] that an `AccountId` has.
#[changed_in(2)]
fn query_account_balances(account: AccountId) -> Result<Vec<MultiAsset>, FungiblesAccessError>;
fn query_account_balances(account: AccountId) -> Result<Vec<Asset>, FungiblesAccessError>;
/// Returns the list of all [`MultiAsset`] that an `AccountId` has.
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedMultiAssets, FungiblesAccessError>;
/// Returns the list of all [`Asset`] that an `AccountId` has.
fn query_account_balances(account: AccountId) -> Result<xcm::VersionedAssets, FungiblesAccessError>;
}
}
@@ -28,7 +28,7 @@ use xcm::latest::prelude::*;
use xcm_builder::{CreateMatcher, MatchXcm};
/// Given a message, a sender, and a destination, it returns the delivery fees
fn get_fungible_delivery_fees<S: SendXcm>(destination: MultiLocation, message: Xcm<()>) -> u128 {
fn get_fungible_delivery_fees<S: SendXcm>(destination: Location, message: Xcm<()>) -> u128 {
let Ok((_, delivery_fees)) = validate_send::<S>(destination, message) else {
unreachable!("message can be sent; qed")
};
@@ -46,8 +46,8 @@ fn get_fungible_delivery_fees<S: SendXcm>(destination: MultiLocation, message: X
/// chain as part of a reserve-asset-transfer.
pub(crate) fn assert_matches_reserve_asset_deposited_instructions<RuntimeCall: Debug>(
xcm: &mut Xcm<RuntimeCall>,
expected_reserve_assets_deposited: &MultiAssets,
expected_beneficiary: &MultiLocation,
expected_reserve_assets_deposited: &Assets,
expected_beneficiary: &Location,
) {
let _ = xcm
.0
@@ -37,7 +37,7 @@ use sp_runtime::{
traits::{MaybeEquivalence, StaticLookup, Zero},
DispatchError, Saturating,
};
use xcm::{latest::prelude::*, VersionedMultiAssets};
use xcm::{latest::prelude::*, VersionedAssets};
use xcm_executor::{traits::ConvertLocation, XcmExecutor};
type RuntimeHelper<Runtime, AllPalletsWithoutSystem = ()> =
@@ -110,7 +110,7 @@ pub fn teleports_for_native_asset_works<
0.into()
);
let native_asset_id = MultiLocation::parent();
let native_asset_id = Location::parent();
let buy_execution_fee_amount_eta =
WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 1024));
let native_asset_amount_unit = existential_deposit;
@@ -119,38 +119,40 @@ pub fn teleports_for_native_asset_works<
// 1. process received teleported assets from relaychain
let xcm = Xcm(vec![
ReceiveTeleportedAsset(MultiAssets::from(vec![MultiAsset {
id: Concrete(native_asset_id),
ReceiveTeleportedAsset(Assets::from(vec![Asset {
id: AssetId(native_asset_id.clone()),
fun: Fungible(native_asset_amount_received.into()),
}])),
ClearOrigin,
BuyExecution {
fees: MultiAsset {
id: Concrete(native_asset_id),
fees: Asset {
id: AssetId(native_asset_id.clone()),
fun: Fungible(buy_execution_fee_amount_eta),
},
weight_limit: Limited(Weight::from_parts(3035310000, 65536)),
},
DepositAsset {
assets: Wild(AllCounted(1)),
beneficiary: MultiLocation {
beneficiary: Location {
parents: 0,
interior: X1(AccountId32 {
interior: [AccountId32 {
network: None,
id: target_account.clone().into(),
}),
}]
.into(),
},
},
ExpectTransactStatus(MaybeErrorCode::Success),
]);
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
Parent,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Parent),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
@@ -163,14 +165,14 @@ pub fn teleports_for_native_asset_works<
// 2. try to teleport asset back to the relaychain
{
let dest = MultiLocation::parent();
let mut dest_beneficiary = MultiLocation::parent()
let dest = Location::parent();
let mut dest_beneficiary = Location::parent()
.appended_with(AccountId32 {
network: None,
id: sp_runtime::AccountId32::new([3; 32]).into(),
})
.unwrap();
dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap();
dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap();
let target_account_balance_before_teleport =
<pallet_balances::Pallet<Runtime>>::free_balance(&target_account);
@@ -183,11 +185,11 @@ pub fn teleports_for_native_asset_works<
// Mint funds into account to ensure it has enough balance to pay delivery fees
let delivery_fees =
xcm_helpers::transfer_assets_delivery_fees::<XcmConfig::XcmSender>(
(native_asset_id, native_asset_to_teleport_away.into()).into(),
(native_asset_id.clone(), native_asset_to_teleport_away.into()).into(),
0,
Unlimited,
dest_beneficiary,
dest,
dest_beneficiary.clone(),
dest.clone(),
);
<pallet_balances::Pallet<Runtime>>::mint_into(
&target_account,
@@ -199,7 +201,7 @@ pub fn teleports_for_native_asset_works<
RuntimeHelper::<Runtime>::origin_of(target_account.clone()),
dest,
dest_beneficiary,
(native_asset_id, native_asset_to_teleport_away.into()),
(native_asset_id.clone(), native_asset_to_teleport_away.into()),
None,
included_head.clone(),
&alice,
@@ -228,14 +230,14 @@ pub fn teleports_for_native_asset_works<
// trust `IsTeleporter` for `(relay-native-asset, para(2345))` pair
{
let other_para_id = 2345;
let dest = MultiLocation::new(1, X1(Parachain(other_para_id)));
let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(other_para_id)))
let dest = Location::new(1, [Parachain(other_para_id)]);
let mut dest_beneficiary = Location::new(1, [Parachain(other_para_id)])
.appended_with(AccountId32 {
network: None,
id: sp_runtime::AccountId32::new([3; 32]).into(),
})
.unwrap();
dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap();
dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap();
let target_account_balance_before_teleport =
<pallet_balances::Pallet<Runtime>>::free_balance(&target_account);
@@ -245,6 +247,7 @@ pub fn teleports_for_native_asset_works<
native_asset_to_teleport_away <
target_account_balance_before_teleport - existential_deposit
);
assert_eq!(
RuntimeHelper::<Runtime>::do_teleport_assets::<HrmpChannelOpener>(
RuntimeHelper::<Runtime>::origin_of(target_account.clone()),
@@ -356,9 +359,9 @@ pub fn teleports_for_foreign_assets_works<
<WeightToFee as frame_support::weights::WeightToFee>::Balance: From<u128> + Into<u128>,
SovereignAccountOf: ConvertLocation<AccountIdOf<Runtime>>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::AssetId:
From<MultiLocation> + Into<MultiLocation>,
From<xcm::v3::Location> + Into<xcm::v3::Location>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::AssetIdParameter:
From<MultiLocation> + Into<MultiLocation>,
From<xcm::v3::Location> + Into<xcm::v3::Location>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::Balance:
From<Balance> + Into<u128>,
<Runtime as frame_system::Config>::AccountId:
@@ -370,23 +373,25 @@ pub fn teleports_for_foreign_assets_works<
{
// foreign parachain with the same consensus currency as asset
let foreign_para_id = 2222;
let foreign_asset_id_multilocation = MultiLocation {
let foreign_asset_id_location = xcm::v3::Location {
parents: 1,
interior: X2(Parachain(foreign_para_id), GeneralIndex(1234567)),
interior: [
xcm::v3::Junction::Parachain(foreign_para_id),
xcm::v3::Junction::GeneralIndex(1234567),
]
.into(),
};
// foreign creator, which can be sibling parachain to match ForeignCreators
let foreign_creator = MultiLocation { parents: 1, interior: X1(Parachain(foreign_para_id)) };
let foreign_creator = Location { parents: 1, interior: [Parachain(foreign_para_id)].into() };
let foreign_creator_as_account_id =
SovereignAccountOf::convert_location(&foreign_creator).expect("");
// we want to buy execution with local relay chain currency
let buy_execution_fee_amount =
WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 0));
let buy_execution_fee = MultiAsset {
id: Concrete(MultiLocation::parent()),
fun: Fungible(buy_execution_fee_amount),
};
let buy_execution_fee =
Asset { id: AssetId(Location::parent()), fun: Fungible(buy_execution_fee_amount) };
let teleported_foreign_asset_amount = 10_000_000_000_000;
let runtime_para_id = 1000;
@@ -425,14 +430,14 @@ pub fn teleports_for_foreign_assets_works<
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&CheckingAccount::get()
),
0.into()
@@ -441,14 +446,14 @@ pub fn teleports_for_foreign_assets_works<
assert_total::<
pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>,
AccountIdOf<Runtime>,
>(foreign_asset_id_multilocation, 0, 0);
>(foreign_asset_id_location, 0, 0);
// create foreign asset (0 total issuance)
let asset_minimum_asset_balance = 3333333_u128;
assert_ok!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::force_create(
RuntimeHelper::<Runtime>::root_origin(),
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
asset_owner.into(),
false,
asset_minimum_asset_balance.into()
@@ -457,47 +462,52 @@ pub fn teleports_for_foreign_assets_works<
assert_total::<
pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>,
AccountIdOf<Runtime>,
>(foreign_asset_id_multilocation, 0, 0);
>(foreign_asset_id_location, 0, 0);
assert!(teleported_foreign_asset_amount > asset_minimum_asset_balance);
let foreign_asset_id_location_latest: Location =
foreign_asset_id_location.try_into().unwrap();
// 1. process received teleported assets from sibling parachain (foreign_para_id)
let xcm = Xcm(vec![
// BuyExecution with relaychain native token
WithdrawAsset(buy_execution_fee.clone().into()),
BuyExecution {
fees: MultiAsset {
id: Concrete(MultiLocation::parent()),
fees: Asset {
id: AssetId(Location::parent()),
fun: Fungible(buy_execution_fee_amount),
},
weight_limit: Limited(Weight::from_parts(403531000, 65536)),
},
// Process teleported asset
ReceiveTeleportedAsset(MultiAssets::from(vec![MultiAsset {
id: Concrete(foreign_asset_id_multilocation),
ReceiveTeleportedAsset(Assets::from(vec![Asset {
id: AssetId(foreign_asset_id_location_latest.clone()),
fun: Fungible(teleported_foreign_asset_amount),
}])),
DepositAsset {
assets: Wild(AllOf {
id: Concrete(foreign_asset_id_multilocation),
id: AssetId(foreign_asset_id_location_latest.clone()),
fun: WildFungibility::Fungible,
}),
beneficiary: MultiLocation {
beneficiary: Location {
parents: 0,
interior: X1(AccountId32 {
interior: [AccountId32 {
network: None,
id: target_account.clone().into(),
}),
}]
.into(),
},
},
ExpectTransactStatus(MaybeErrorCode::Success),
]);
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
foreign_creator,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Sibling),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
@@ -508,7 +518,7 @@ pub fn teleports_for_foreign_assets_works<
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account
),
teleported_foreign_asset_amount.into()
@@ -520,7 +530,7 @@ pub fn teleports_for_foreign_assets_works<
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&CheckingAccount::get()
),
0.into()
@@ -530,25 +540,25 @@ pub fn teleports_for_foreign_assets_works<
pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>,
AccountIdOf<Runtime>,
>(
foreign_asset_id_multilocation,
foreign_asset_id_location,
teleported_foreign_asset_amount,
teleported_foreign_asset_amount,
);
// 2. try to teleport asset back to source parachain (foreign_para_id)
{
let dest = MultiLocation::new(1, X1(Parachain(foreign_para_id)));
let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(foreign_para_id)))
let dest = Location::new(1, [Parachain(foreign_para_id)]);
let mut dest_beneficiary = Location::new(1, [Parachain(foreign_para_id)])
.appended_with(AccountId32 {
network: None,
id: sp_runtime::AccountId32::new([3; 32]).into(),
})
.unwrap();
dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap();
dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap();
let target_account_balance_before_teleport =
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account,
);
let asset_to_teleport_away = asset_minimum_asset_balance * 3;
@@ -562,11 +572,11 @@ pub fn teleports_for_foreign_assets_works<
// Make sure the target account has enough native asset to pay for delivery fees
let delivery_fees =
xcm_helpers::transfer_assets_delivery_fees::<XcmConfig::XcmSender>(
(foreign_asset_id_multilocation, asset_to_teleport_away).into(),
(foreign_asset_id_location_latest.clone(), asset_to_teleport_away).into(),
0,
Unlimited,
dest_beneficiary,
dest,
dest_beneficiary.clone(),
dest.clone(),
);
<pallet_balances::Pallet<Runtime>>::mint_into(
&target_account,
@@ -578,7 +588,7 @@ pub fn teleports_for_foreign_assets_works<
RuntimeHelper::<Runtime>::origin_of(target_account.clone()),
dest,
dest_beneficiary,
(foreign_asset_id_multilocation, asset_to_teleport_away),
(foreign_asset_id_location_latest.clone(), asset_to_teleport_away),
Some((runtime_para_id, foreign_para_id)),
included_head,
&alice,
@@ -587,14 +597,14 @@ pub fn teleports_for_foreign_assets_works<
// check balances
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account
),
(target_account_balance_before_teleport - asset_to_teleport_away.into())
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&CheckingAccount::get()
),
0.into()
@@ -604,7 +614,7 @@ pub fn teleports_for_foreign_assets_works<
pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>,
AccountIdOf<Runtime>,
>(
foreign_asset_id_multilocation,
foreign_asset_id_location,
teleported_foreign_asset_amount - asset_to_teleport_away,
teleported_foreign_asset_amount - asset_to_teleport_away,
);
@@ -717,17 +727,19 @@ pub fn asset_transactor_transfer_with_local_consensus_currency_works<Runtime, Xc
// transfer_asset (deposit/withdraw) ALICE -> BOB
let _ = RuntimeHelper::<XcmConfig>::do_transfer(
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 { network: None, id: source_account.clone().into() }),
interior: [AccountId32 { network: None, id: source_account.clone().into() }]
.into(),
},
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 { network: None, id: target_account.clone().into() }),
interior: [AccountId32 { network: None, id: target_account.clone().into() }]
.into(),
},
// local_consensus_currency_asset, e.g.: relaychain token (KSM, DOT, ...)
(
MultiLocation { parents: 1, interior: Here },
Location { parents: 1, interior: Here },
(BalanceOf::<Runtime>::from(1_u128) * unit).into(),
),
)
@@ -779,7 +791,7 @@ macro_rules! include_asset_transactor_transfer_with_local_consensus_currency_wor
}
);
///Test-case makes sure that `Runtime`'s `xcm::AssetTransactor` can handle native relay chain
/// Test-case makes sure that `Runtime`'s `xcm::AssetTransactor` can handle native relay chain
/// currency
pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
Runtime,
@@ -820,8 +832,8 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
<<Runtime as frame_system::Config>::Lookup as StaticLookup>::Source:
From<<Runtime as frame_system::Config>::AccountId>,
AssetsPalletInstance: 'static,
AssetId: Clone + Copy,
AssetIdConverter: MaybeEquivalence<MultiLocation, AssetId>,
AssetId: Clone,
AssetIdConverter: MaybeEquivalence<Location, AssetId>,
{
ExtBuilder::<Runtime>::default()
.with_collators(collator_session_keys.collators())
@@ -836,10 +848,10 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
.execute_with(|| {
// create some asset class
let asset_minimum_asset_balance = 3333333_u128;
let asset_id_as_multilocation = AssetIdConverter::convert_back(&asset_id).unwrap();
let asset_id_as_location = AssetIdConverter::convert_back(&asset_id).unwrap();
assert_ok!(<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::force_create(
RuntimeHelper::<Runtime>::root_origin(),
asset_id.into(),
asset_id.clone().into(),
asset_owner.clone().into(),
false,
asset_minimum_asset_balance.into()
@@ -848,7 +860,7 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
// We first mint enough asset for the account to exist for assets
assert_ok!(<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::mint(
RuntimeHelper::<Runtime>::origin_of(asset_owner.clone()),
asset_id.into(),
asset_id.clone().into(),
alice_account.clone().into(),
(6 * asset_minimum_asset_balance).into()
));
@@ -856,28 +868,28 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
// check Assets before
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&alice_account
),
(6 * asset_minimum_asset_balance).into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&bob_account
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&charlie_account
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&asset_owner
),
0.into()
@@ -904,21 +916,20 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
// ExistentialDeposit)
assert_noop!(
RuntimeHelper::<XcmConfig>::do_transfer(
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 {
network: None,
id: alice_account.clone().into()
}),
interior: [AccountId32 { network: None, id: alice_account.clone().into() }]
.into(),
},
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 {
interior: [AccountId32 {
network: None,
id: charlie_account.clone().into()
}),
}]
.into(),
},
(asset_id_as_multilocation, asset_minimum_asset_balance),
(asset_id_as_location.clone(), asset_minimum_asset_balance),
),
XcmError::FailedToTransactAsset(Into::<&str>::into(
sp_runtime::TokenError::CannotCreate
@@ -928,18 +939,17 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
// transfer_asset (deposit/withdraw) ALICE -> BOB (ok - has ExistentialDeposit)
assert!(matches!(
RuntimeHelper::<XcmConfig>::do_transfer(
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 {
network: None,
id: alice_account.clone().into()
}),
interior: [AccountId32 { network: None, id: alice_account.clone().into() }]
.into(),
},
MultiLocation {
Location {
parents: 0,
interior: X1(AccountId32 { network: None, id: bob_account.clone().into() }),
interior: [AccountId32 { network: None, id: bob_account.clone().into() }]
.into(),
},
(asset_id_as_multilocation, asset_minimum_asset_balance),
(asset_id_as_location, asset_minimum_asset_balance),
),
Ok(_)
));
@@ -947,21 +957,21 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works<
// check Assets after
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&alice_account
),
(5 * asset_minimum_asset_balance).into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&bob_account
),
asset_minimum_asset_balance.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, AssetsPalletInstance>>::balance(
asset_id.into(),
asset_id.clone().into(),
&charlie_account
),
0.into()
@@ -1093,26 +1103,23 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
<<Runtime as frame_system::Config>::Lookup as StaticLookup>::Source:
From<<Runtime as frame_system::Config>::AccountId>,
ForeignAssetsPalletInstance: 'static,
AssetId: Clone + Copy,
AssetIdConverter: MaybeEquivalence<MultiLocation, AssetId>,
AssetId: Clone,
AssetIdConverter: MaybeEquivalence<Location, AssetId>,
{
// foreign parachain with the same consensus currency as asset
let foreign_asset_id_multilocation =
MultiLocation { parents: 1, interior: X2(Parachain(2222), GeneralIndex(1234567)) };
let asset_id = AssetIdConverter::convert(&foreign_asset_id_multilocation).unwrap();
// foreign parachain with the same consenus currency as asset
let foreign_asset_id_location = Location::new(1, [Parachain(2222), GeneralIndex(1234567)]);
let asset_id = AssetIdConverter::convert(&foreign_asset_id_location).unwrap();
// foreign creator, which can be sibling parachain to match ForeignCreators
let foreign_creator = MultiLocation { parents: 1, interior: X1(Parachain(2222)) };
let foreign_creator = Location { parents: 1, interior: [Parachain(2222)].into() };
let foreign_creator_as_account_id =
SovereignAccountOf::convert_location(&foreign_creator).expect("");
// we want to buy execution with local relay chain currency
let buy_execution_fee_amount =
WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 0));
let buy_execution_fee = MultiAsset {
id: Concrete(MultiLocation::parent()),
fun: Fungible(buy_execution_fee_amount),
};
let buy_execution_fee =
Asset { id: AssetId(Location::parent()), fun: Fungible(buy_execution_fee_amount) };
const ASSET_NAME: &str = "My super coin";
const ASSET_SYMBOL: &str = "MY_S_COIN";
@@ -1152,7 +1159,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
Runtime,
ForeignAssetsPalletInstance,
>::create {
id: asset_id.into(),
id: asset_id.clone().into(),
// admin as sovereign_account
admin: foreign_creator_as_account_id.clone().into(),
min_balance: 1.into(),
@@ -1162,7 +1169,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
Runtime,
ForeignAssetsPalletInstance,
>::set_metadata {
id: asset_id.into(),
id: asset_id.clone().into(),
name: Vec::from(ASSET_NAME),
symbol: Vec::from(ASSET_SYMBOL),
decimals: 12,
@@ -1172,7 +1179,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
Runtime,
ForeignAssetsPalletInstance,
>::set_team {
id: asset_id.into(),
id: asset_id.clone().into(),
issuer: foreign_creator_as_account_id.clone().into(),
admin: foreign_creator_as_account_id.clone().into(),
freezer: bob_account.clone().into(),
@@ -1202,14 +1209,15 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
]);
// messages with different consensus should go through the local bridge-hub
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
// execute xcm as XcmpQueue would do
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
foreign_creator,
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
foreign_creator.clone(),
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Sibling),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
@@ -1230,25 +1238,25 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
use frame_support::traits::fungibles::roles::Inspect as InspectRoles;
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::owner(
asset_id.into()
asset_id.clone().into()
),
Some(foreign_creator_as_account_id.clone())
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::admin(
asset_id.into()
asset_id.clone().into()
),
Some(foreign_creator_as_account_id.clone())
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::issuer(
asset_id.into()
asset_id.clone().into()
),
Some(foreign_creator_as_account_id.clone())
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::freezer(
asset_id.into()
asset_id.clone().into()
),
Some(bob_account.clone())
);
@@ -1262,13 +1270,13 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
assert_metadata::<
pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>,
AccountIdOf<Runtime>,
>(asset_id, ASSET_NAME, ASSET_SYMBOL, 12);
>(asset_id.clone(), ASSET_NAME, ASSET_SYMBOL, 12);
// check if changed freezer, can freeze
assert_noop!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::freeze(
RuntimeHelper::<Runtime>::origin_of(bob_account),
asset_id.into(),
asset_id.clone().into(),
alice_account.clone().into()
),
pallet_assets::Error::<Runtime, ForeignAssetsPalletInstance>::NoAccount
@@ -1284,9 +1292,9 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
// lets try create asset for different parachain(3333) (foreign_creator(2222) can create
// just his assets)
let foreign_asset_id_multilocation =
MultiLocation { parents: 1, interior: X2(Parachain(3333), GeneralIndex(1234567)) };
let asset_id = AssetIdConverter::convert(&foreign_asset_id_multilocation).unwrap();
let foreign_asset_id_location =
Location { parents: 1, interior: [Parachain(3333), GeneralIndex(1234567)].into() };
let asset_id = AssetIdConverter::convert(&foreign_asset_id_location).unwrap();
// prepare data for xcm::Transact(create)
let foreign_asset_create = runtime_call_encode(pallet_assets::Call::<
@@ -1310,14 +1318,15 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor
]);
// messages with different consensus should go through the local bridge-hub
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
// execute xcm as XcmpQueue would do
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
foreign_creator,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Sibling),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
@@ -1441,15 +1450,15 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works<
// reserve-transfer native asset with local reserve to remote parachain (2345)
let other_para_id = 2345;
let native_asset = MultiLocation::parent();
let dest = MultiLocation::new(1, X1(Parachain(other_para_id)));
let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(other_para_id)))
let native_asset = Location::parent();
let dest = Location::new(1, [Parachain(other_para_id)]);
let mut dest_beneficiary = Location::new(1, [Parachain(other_para_id)])
.appended_with(AccountId32 {
network: None,
id: sp_runtime::AccountId32::new([3; 32]).into(),
})
.unwrap();
dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap();
dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap();
let reserve_account = LocationToAccountId::convert_location(&dest)
.expect("Sovereign account for reserves");
@@ -1495,17 +1504,15 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works<
);
// local native asset (pallet_balances)
let asset_to_transfer = MultiAsset {
fun: Fungible(balance_to_transfer.into()),
id: Concrete(native_asset),
};
let asset_to_transfer =
Asset { fun: Fungible(balance_to_transfer.into()), id: AssetId(native_asset) };
// pallet_xcm call reserve transfer
assert_ok!(<pallet_xcm::Pallet<Runtime>>::limited_reserve_transfer_assets(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(alice_account.clone()),
Box::new(dest.into_versioned()),
Box::new(dest_beneficiary.into_versioned()),
Box::new(VersionedMultiAssets::from(MultiAssets::from(asset_to_transfer))),
Box::new(dest.clone().into_versioned()),
Box::new(dest_beneficiary.clone().into_versioned()),
Box::new(VersionedAssets::from(Assets::from(asset_to_transfer))),
0,
weight_limit,
));
@@ -1535,9 +1542,12 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works<
)
.unwrap();
let v4_xcm: Xcm<()> = xcm_sent.clone().try_into().unwrap();
dbg!(&v4_xcm);
let delivery_fees = get_fungible_delivery_fees::<
<XcmConfig as xcm_executor::Config>::XcmSender,
>(dest, Xcm::try_from(xcm_sent.clone()).unwrap());
>(dest.clone(), Xcm::try_from(xcm_sent.clone()).unwrap());
assert_eq!(
xcm_sent_message_hash,
@@ -1547,8 +1557,8 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works<
// check sent XCM Program to other parachain
println!("reserve_transfer_native_asset_works sent xcm: {:?}", xcm_sent);
let reserve_assets_deposited = MultiAssets::from(vec![MultiAsset {
id: Concrete(MultiLocation { parents: 1, interior: Here }),
let reserve_assets_deposited = Assets::from(vec![Asset {
id: AssetId(Location { parents: 1, interior: Here }),
fun: Fungible(1000000000000),
}]);
@@ -31,15 +31,15 @@ use parachains_runtimes_test_utils::{
};
use sp_runtime::{traits::StaticLookup, Saturating};
use sp_std::ops::Mul;
use xcm::{latest::prelude::*, VersionedMultiAssets};
use xcm::{latest::prelude::*, VersionedAssets};
use xcm_builder::{CreateMatcher, MatchXcm};
use xcm_executor::{traits::ConvertLocation, XcmExecutor};
pub struct TestBridgingConfig {
pub bridged_network: NetworkId,
pub local_bridge_hub_para_id: u32,
pub local_bridge_hub_location: MultiLocation,
pub bridged_target_location: MultiLocation,
pub local_bridge_hub_location: Location,
pub bridged_target_location: Location,
}
/// Test-case makes sure that `Runtime` can initiate **reserve transfer assets** over bridge.
@@ -117,7 +117,7 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works<
LocationToAccountId::convert_location(&target_location_from_different_consensus)
.expect("Sovereign account for reserves");
let balance_to_transfer = 1_000_000_000_000_u128;
let native_asset = MultiLocation::parent();
let native_asset = Location::parent();
// open HRMP to bridge hub
mock_open_hrmp_channel::<Runtime, HrmpChannelOpener>(
@@ -163,35 +163,33 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works<
.unwrap_or(0.into());
// local native asset (pallet_balances)
let asset_to_transfer = MultiAsset {
fun: Fungible(balance_to_transfer.into()),
id: Concrete(native_asset),
};
let asset_to_transfer =
Asset { fun: Fungible(balance_to_transfer.into()), id: native_asset.into() };
// destination is (some) account relative to the destination different consensus
let target_destination_account = MultiLocation {
parents: 0,
interior: X1(AccountId32 {
let target_destination_account = Location::new(
0,
[AccountId32 {
network: Some(bridged_network),
id: sp_runtime::AccountId32::new([3; 32]).into(),
}),
};
}],
);
let assets_to_transfer = MultiAssets::from(asset_to_transfer);
let assets_to_transfer = Assets::from(asset_to_transfer);
let mut expected_assets = assets_to_transfer.clone();
let context = XcmConfig::UniversalLocation::get();
expected_assets
.reanchor(&target_location_from_different_consensus, context)
.reanchor(&target_location_from_different_consensus, &context)
.unwrap();
let expected_beneficiary = target_destination_account;
let expected_beneficiary = target_destination_account.clone();
// do pallet_xcm call reserve transfer
assert_ok!(<pallet_xcm::Pallet<Runtime>>::limited_reserve_transfer_assets(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(alice_account.clone()),
Box::new(target_location_from_different_consensus.into_versioned()),
Box::new(target_location_from_different_consensus.clone().into_versioned()),
Box::new(target_destination_account.into_versioned()),
Box::new(VersionedMultiAssets::from(assets_to_transfer)),
Box::new(VersionedAssets::from(assets_to_transfer)),
0,
weight_limit,
));
@@ -266,13 +264,17 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works<
let (_, target_location_junctions_without_global_consensus) =
target_location_from_different_consensus
.interior
.clone()
.split_global()
.expect("split works");
assert_eq!(destination, &target_location_junctions_without_global_consensus);
// Call `SendXcm::validate` to get delivery fees.
delivery_fees = get_fungible_delivery_fees::<
<XcmConfig as xcm_executor::Config>::XcmSender,
>(target_location_from_different_consensus, inner_xcm.clone());
>(
target_location_from_different_consensus.clone(),
inner_xcm.clone(),
);
assert_matches_reserve_asset_deposited_instructions(
inner_xcm,
&expected_assets,
@@ -322,10 +324,10 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
target_account: AccountIdOf<Runtime>,
block_author_account: AccountIdOf<Runtime>,
(
foreign_asset_id_multilocation,
foreign_asset_id_location,
transfered_foreign_asset_id_amount,
foreign_asset_id_minimum_balance,
): (MultiLocation, u128, u128),
): (xcm::v3::Location, u128, u128),
prepare_configuration: fn() -> TestBridgingConfig,
(bridge_instance, universal_origin, descend_origin): (Junctions, Junction, Junctions), /* bridge adds origin manipulation on the way */
) where
@@ -347,9 +349,9 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
XcmConfig: xcm_executor::Config,
LocationToAccountId: ConvertLocation<AccountIdOf<Runtime>>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::AssetId:
From<MultiLocation> + Into<MultiLocation>,
From<xcm::v3::Location> + Into<xcm::v3::Location>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::AssetIdParameter:
From<MultiLocation> + Into<MultiLocation>,
From<xcm::v3::Location> + Into<xcm::v3::Location>,
<Runtime as pallet_assets::Config<ForeignAssetsPalletInstance>>::Balance:
From<Balance> + Into<u128> + From<u128>,
<Runtime as frame_system::Config>::AccountId: Into<<<Runtime as frame_system::Config>::RuntimeOrigin as OriginTrait>::AccountId>
@@ -357,7 +359,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
<<Runtime as frame_system::Config>::Lookup as StaticLookup>::Source:
From<<Runtime as frame_system::Config>::AccountId>,
<Runtime as pallet_asset_conversion::Config>::AssetKind:
From<MultiLocation> + Into<MultiLocation>,
From<xcm::v3::Location> + Into<xcm::v3::Location>,
<Runtime as pallet_asset_conversion::Config>::Balance: From<Balance>,
ForeignAssetsPalletInstance: 'static,
{
@@ -385,7 +387,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
// sovereign account as foreign asset owner (can be whoever for this scenario, doesnt
// matter)
let sovereign_account_as_owner_of_foreign_asset =
LocationToAccountId::convert_location(&MultiLocation::parent()).unwrap();
LocationToAccountId::convert_location(&Location::parent()).unwrap();
// staking pot account for collecting local native fees from `BuyExecution`
let staking_pot = <pallet_collator_selection::Pallet<Runtime>>::account_id();
@@ -398,16 +400,16 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
assert_ok!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::force_create(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::root_origin(),
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
sovereign_account_as_owner_of_foreign_asset.clone().into(),
true, // is_sufficient=true
foreign_asset_id_minimum_balance.into()
)
);
// setup a pool to pay fees with `foreign_asset_id_multilocation` tokens
// setup a pool to pay fees with `foreign_asset_id_location` tokens
let pool_owner: AccountIdOf<Runtime> = [1u8; 32].into();
let native_asset = MultiLocation::parent();
let native_asset = xcm::v3::Location::parent();
let pool_liquidity: u128 =
existential_deposit.into().max(foreign_asset_id_minimum_balance).mul(100_000);
@@ -420,7 +422,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(
sovereign_account_as_owner_of_foreign_asset
),
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
pool_owner.clone().into(),
(foreign_asset_id_minimum_balance + pool_liquidity).mul(2).into(),
));
@@ -428,13 +430,13 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
assert_ok!(<pallet_asset_conversion::Pallet<Runtime>>::create_pool(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(pool_owner.clone()),
Box::new(native_asset.into()),
Box::new(foreign_asset_id_multilocation.into())
Box::new(foreign_asset_id_location.into())
));
assert_ok!(<pallet_asset_conversion::Pallet<Runtime>>::add_liquidity(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(pool_owner.clone()),
Box::new(native_asset.into()),
Box::new(foreign_asset_id_multilocation.into()),
Box::new(foreign_asset_id_location.into()),
pool_liquidity.into(),
pool_liquidity.into(),
1.into(),
@@ -459,34 +461,37 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
// ForeignAssets balances before
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&block_author_account
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&staking_pot
),
0.into()
);
let expected_assets = MultiAssets::from(vec![MultiAsset {
id: Concrete(foreign_asset_id_multilocation),
let foreign_asset_id_location_latest: Location =
foreign_asset_id_location.try_into().unwrap();
let expected_assets = Assets::from(vec![Asset {
id: AssetId(foreign_asset_id_location_latest.clone()),
fun: Fungible(transfered_foreign_asset_id_amount),
}]);
let expected_beneficiary = MultiLocation {
parents: 0,
interior: X1(AccountId32 { network: None, id: target_account.clone().into() }),
};
let expected_beneficiary = Location::new(
0,
[AccountId32 { network: None, id: target_account.clone().into() }],
);
// Call received XCM execution
let xcm = Xcm(vec![
@@ -496,13 +501,16 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
ReserveAssetDeposited(expected_assets.clone()),
ClearOrigin,
BuyExecution {
fees: MultiAsset {
id: Concrete(foreign_asset_id_multilocation),
fees: Asset {
id: AssetId(foreign_asset_id_location_latest.clone()),
fun: Fungible(transfered_foreign_asset_id_amount),
},
weight_limit: Unlimited,
},
DepositAsset { assets: Wild(AllCounted(1)), beneficiary: expected_beneficiary },
DepositAsset {
assets: Wild(AllCounted(1)),
beneficiary: expected_beneficiary.clone(),
},
SetTopic([
220, 188, 144, 32, 213, 83, 111, 175, 44, 210, 111, 19, 90, 165, 191, 112, 140,
247, 192, 124, 42, 17, 153, 141, 114, 34, 189, 20, 83, 69, 237, 173,
@@ -514,16 +522,17 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
&expected_beneficiary,
);
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
// execute xcm as XcmpQueue would do
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
local_bridge_hub_location,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::xcm_max_weight(
XcmReceivedFrom::Sibling,
),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
@@ -545,20 +554,20 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works<
// ForeignAssets balances after
assert!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&target_account
) > 0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&staking_pot
),
0.into()
);
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
foreign_asset_id_location.into(),
&block_author_account
),
0.into()
@@ -614,14 +623,15 @@ pub fn report_bridge_status_from_xcm_bridge_router_works<
// Call received XCM execution
let xcm = if is_congested { congested_message() } else { uncongested_message() };
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
// execute xcm as XcmpQueue would do
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(
let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
local_bridge_hub_location,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::xcm_max_weight(XcmReceivedFrom::Sibling),
Weight::zero(),
);
assert_ok!(outcome.ensure_complete());
assert_eq!(is_congested, pallet_xcm_bridge_hub_router::Pallet::<Runtime, XcmBridgeHubRouterInstance>::bridge().is_congested);
@@ -23,11 +23,11 @@ use xcm::latest::prelude::*;
/// Because it returns only a `u128`, it assumes delivery fees are only paid
/// in one asset and that asset is known.
pub fn transfer_assets_delivery_fees<S: SendXcm>(
assets: MultiAssets,
assets: Assets,
fee_asset_item: u32,
weight_limit: WeightLimit,
beneficiary: MultiLocation,
destination: MultiLocation,
beneficiary: Location,
destination: Location,
) -> u128 {
let message = teleport_assets_dummy_message(assets, fee_asset_item, weight_limit, beneficiary);
get_fungible_delivery_fees::<S>(destination, message)
@@ -35,7 +35,7 @@ pub fn transfer_assets_delivery_fees<S: SendXcm>(
/// Returns the delivery fees amount for a query response as a result of the execution
/// of a `ExpectError` instruction with no error.
pub fn query_response_delivery_fees<S: SendXcm>(querier: MultiLocation) -> u128 {
pub fn query_response_delivery_fees<S: SendXcm>(querier: Location) -> u128 {
// Message to calculate delivery fees, it's encoded size is what's important.
// This message reports that there was no error, if an error is reported, the encoded size would
// be different.
@@ -45,7 +45,7 @@ pub fn query_response_delivery_fees<S: SendXcm>(querier: MultiLocation) -> u128
query_id: 0, // Dummy query id
response: Response::ExecutionResult(None),
max_weight: Weight::zero(),
querier: Some(querier),
querier: Some(querier.clone()),
},
SetTopic([0u8; 32]), // Dummy topic
]);
@@ -55,9 +55,9 @@ pub fn query_response_delivery_fees<S: SendXcm>(querier: MultiLocation) -> u128
/// Returns the delivery fees amount for the execution of `PayOverXcm`
pub fn pay_over_xcm_delivery_fees<S: SendXcm>(
interior: Junctions,
destination: MultiLocation,
beneficiary: MultiLocation,
asset: MultiAsset,
destination: Location,
beneficiary: Location,
asset: Asset,
) -> u128 {
// This is a dummy message.
// The encoded size is all that matters for delivery fees.
@@ -66,7 +66,11 @@ pub fn pay_over_xcm_delivery_fees<S: SendXcm>(
UnpaidExecution { weight_limit: Unlimited, check_origin: None },
SetAppendix(Xcm(vec![
SetFeesMode { jit_withdraw: true },
ReportError(QueryResponseInfo { destination, query_id: 0, max_weight: Weight::zero() }),
ReportError(QueryResponseInfo {
destination: destination.clone(),
query_id: 0,
max_weight: Weight::zero(),
}),
])),
TransferAsset { beneficiary, assets: vec![asset].into() },
]);
@@ -78,10 +82,10 @@ pub fn pay_over_xcm_delivery_fees<S: SendXcm>(
/// However, it should have the same encoded size, which is what matters for delivery fees.
/// Also has same encoded size as the one created by the reserve transfer assets extrinsic.
fn teleport_assets_dummy_message(
assets: MultiAssets,
assets: Assets,
fee_asset_item: u32,
weight_limit: WeightLimit,
beneficiary: MultiLocation,
beneficiary: Location,
) -> Xcm<()> {
Xcm(vec![
ReceiveTeleportedAsset(assets.clone()), // Same encoded size as `ReserveAssetDeposited`
@@ -93,7 +97,7 @@ fn teleport_assets_dummy_message(
}
/// Given a message, a sender, and a destination, it returns the delivery fees
fn get_fungible_delivery_fees<S: SendXcm>(destination: MultiLocation, message: Xcm<()>) -> u128 {
fn get_fungible_delivery_fees<S: SendXcm>(destination: Location, message: Xcm<()>) -> u128 {
let Ok((_, delivery_fees)) = validate_send::<S>(destination, message) else {
unreachable!("message can be sent; qed")
};
@@ -48,7 +48,7 @@ use frame_support::{parameter_types, traits::PalletInfoAccess};
use sp_runtime::RuntimeDebug;
use xcm::{
latest::prelude::*,
prelude::{InteriorMultiLocation, NetworkId},
prelude::{InteriorLocation, NetworkId},
};
use xcm_builder::BridgeBlobDispatcher;
@@ -65,16 +65,16 @@ parameter_types! {
/// Bridge specific chain (network) identifier of the Rococo Bulletin Chain.
pub const RococoBulletinChainId: bp_runtime::ChainId = bp_runtime::POLKADOT_BULLETIN_CHAIN_ID;
/// Interior location (relative to this runtime) of the with-RococoBulletin messages pallet.
pub BridgeRococoToRococoBulletinMessagesPalletInstance: InteriorMultiLocation = X1(
pub BridgeRococoToRococoBulletinMessagesPalletInstance: InteriorLocation = [
PalletInstance(<BridgeRococoBulletinMessages as PalletInfoAccess>::index() as u8)
);
].into();
/// Rococo Bulletin Network identifier.
pub RococoBulletinGlobalConsensusNetwork: NetworkId = NetworkId::PolkadotBulletin;
/// Relative location of the Rococo Bulletin chain.
pub RococoBulletinGlobalConsensusNetworkLocation: MultiLocation = MultiLocation {
parents: 2,
interior: X1(GlobalConsensus(RococoBulletinGlobalConsensusNetwork::get()))
};
pub RococoBulletinGlobalConsensusNetworkLocation: Location = Location::new(
2,
[GlobalConsensus(RococoBulletinGlobalConsensusNetwork::get())]
);
/// All active lanes that the current bridge supports.
pub ActiveOutboundLanesToRococoBulletin: &'static [bp_messages::LaneId]
= &[XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN];
@@ -94,11 +94,11 @@ parameter_types! {
/// A route (XCM location and bridge lane) that the Rococo People Chain -> Rococo Bulletin Chain
/// message is following.
pub FromRococoPeopleToRococoBulletinRoute: SenderAndLane = SenderAndLane::new(
ParentThen(X1(Parachain(RococoPeopleParaId::get().into()))).into(),
ParentThen(Parachain(RococoPeopleParaId::get().into()).into()).into(),
XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN,
);
/// All active routes and their destinations.
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![
(
FromRococoPeopleToRococoBulletinRoute::get(),
(RococoBulletinGlobalConsensusNetwork::get(), Here)
@@ -282,11 +282,11 @@ mod tests {
PriorityBoostPerMessage,
>(FEE_BOOST_PER_MESSAGE);
assert_eq!(
BridgeRococoToRococoBulletinMessagesPalletInstance::get(),
X1(PalletInstance(
bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_BULLETIN_MESSAGES_PALLET_INDEX
))
);
let expected: InteriorLocation = PalletInstance(
bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_BULLETIN_MESSAGES_PALLET_INDEX,
)
.into();
assert_eq!(BridgeRococoToRococoBulletinMessagesPalletInstance::get(), expected,);
}
}
@@ -48,7 +48,7 @@ use frame_support::{parameter_types, traits::PalletInfoAccess};
use sp_runtime::RuntimeDebug;
use xcm::{
latest::prelude::*,
prelude::{InteriorMultiLocation, NetworkId},
prelude::{InteriorLocation, NetworkId},
};
use xcm_builder::BridgeBlobDispatcher;
@@ -58,12 +58,12 @@ parameter_types! {
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
pub const BridgeHubWestendChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_WESTEND_CHAIN_ID;
pub BridgeRococoToWestendMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(<BridgeWestendMessages as PalletInfoAccess>::index() as u8));
pub BridgeRococoToWestendMessagesPalletInstance: InteriorLocation = [PalletInstance(<BridgeWestendMessages as PalletInfoAccess>::index() as u8)].into();
pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::Westend;
pub WestendGlobalConsensusNetworkLocation: MultiLocation = MultiLocation {
parents: 2,
interior: X1(GlobalConsensus(WestendGlobalConsensusNetwork::get()))
};
pub WestendGlobalConsensusNetworkLocation: Location = Location::new(
2,
[GlobalConsensus(WestendGlobalConsensusNetwork::get())]
);
// see the `FEE_BOOST_PER_MESSAGE` constant to get the meaning of this value
pub PriorityBoostPerMessage: u64 = 182_044_444_444_444;
@@ -74,26 +74,26 @@ parameter_types! {
pub ActiveOutboundLanesToBridgeHubWestend: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND];
pub const AssetHubRococoToAssetHubWestendMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND;
pub FromAssetHubRococoToAssetHubWestendRoute: SenderAndLane = SenderAndLane::new(
ParentThen(X1(Parachain(AssetHubRococoParaId::get().into()))).into(),
ParentThen([Parachain(AssetHubRococoParaId::get().into())].into()).into(),
XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND,
);
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![
(
FromAssetHubRococoToAssetHubWestendRoute::get(),
(WestendGlobalConsensusNetwork::get(), X1(Parachain(AssetHubWestendParaId::get().into())))
(WestendGlobalConsensusNetwork::get(), [Parachain(AssetHubWestendParaId::get().into())].into())
)
];
pub CongestedMessage: Xcm<()> = build_congestion_message(true).into();
pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into();
pub BridgeHubWestendLocation: MultiLocation = MultiLocation {
parents: 2,
interior: X2(
pub BridgeHubWestendLocation: Location = Location::new(
2,
[
GlobalConsensus(WestendGlobalConsensusNetwork::get()),
Parachain(<bp_bridge_hub_westend::BridgeHubWestend as bp_runtime::Parachain>::PARACHAIN_ID)
)
};
]
);
}
pub const XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND: LaneId = LaneId([0, 0, 0, 2]);
@@ -327,11 +327,11 @@ mod tests {
PriorityBoostPerMessage,
>(FEE_BOOST_PER_MESSAGE);
assert_eq!(
BridgeRococoToWestendMessagesPalletInstance::get(),
X1(PalletInstance(
bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX
))
);
let expected: InteriorLocation = [PalletInstance(
bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX,
)]
.into();
assert_eq!(BridgeRococoToWestendMessagesPalletInstance::get(), expected,);
}
}
@@ -78,7 +78,7 @@ use bridge_hub_common::{
use pallet_xcm::EnsureXcm;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
pub use sp_runtime::{MultiAddress, Perbill, Permill};
use xcm::VersionedMultiLocation;
use xcm::VersionedLocation;
use xcm_config::{TreasuryAccount, XcmOriginToTransactDispatchOrigin, XcmRouter};
#[cfg(any(feature = "std", test))]
@@ -385,7 +385,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(xcm_config::TokenLocation::get());
pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -517,7 +517,7 @@ pub mod benchmark_helpers {
use snowbridge_beacon_primitives::CompactExecutionHeader;
use snowbridge_pallet_inbound_queue::BenchmarkHelper;
use sp_core::H256;
use xcm::latest::{MultiAssets, MultiLocation, SendError, SendResult, SendXcm, Xcm, XcmHash};
use xcm::latest::{Assets, Location, SendError, SendResult, SendXcm, Xcm, XcmHash};
impl<T: snowbridge_pallet_ethereum_client::Config> BenchmarkHelper<T> for Runtime {
fn initialize_storage(block_hash: H256, header: CompactExecutionHeader) {
@@ -530,10 +530,10 @@ pub mod benchmark_helpers {
type Ticket = Xcm<()>;
fn validate(
_dest: &mut Option<MultiLocation>,
_dest: &mut Option<Location>,
xcm: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
Ok((xcm.clone().unwrap(), MultiAssets::new()))
Ok((xcm.clone().unwrap(), Assets::new()))
}
fn deliver(xcm: Xcm<()>) -> Result<XcmHash, SendError> {
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
@@ -542,7 +542,7 @@ pub mod benchmark_helpers {
}
impl snowbridge_pallet_system::BenchmarkHelper<RuntimeOrigin> for () {
fn make_xcm_origin(location: MultiLocation) -> RuntimeOrigin {
fn make_xcm_origin(location: Location) -> RuntimeOrigin {
RuntimeOrigin::from(pallet_xcm::Origin::Xcm(location))
}
}
@@ -1016,7 +1016,7 @@ impl_runtime_apis! {
}
impl snowbridge_system_runtime_api::ControlApi<Block> for Runtime {
fn agent_id(location: VersionedMultiLocation) -> Option<AgentId> {
fn agent_id(location: VersionedLocation) -> Option<AgentId> {
snowbridge_pallet_system::api::agent_id::<Runtime>(location)
}
}
@@ -1095,28 +1095,28 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between BH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled on BH.
None
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
// BH only supports teleports to system parachain.
// Relay/native token can be teleported between BH and Relay.
let native_location = Parent.into();
@@ -1132,7 +1132,7 @@ impl_runtime_apis! {
use xcm_config::TokenLocation;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
TokenLocation::get(),
ExistentialDeposit::get()
).into());
@@ -1143,17 +1143,17 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(TokenLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(TokenLocation::get()),
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -1162,12 +1162,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
TokenLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(TokenLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -1177,9 +1177,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(TokenLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -1193,35 +1193,35 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(TokenLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = TokenLocation::get();
let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
// save XCM version for remote bridge hub
let _ = PolkadotXcm::force_xcm_version(
RuntimeOrigin::root(),
@@ -1241,12 +1241,12 @@ impl_runtime_apis! {
(
bridge_to_westend_config::FromAssetHubRococoToAssetHubWestendRoute::get().location,
NetworkId::Westend,
X1(Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into()))
[Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into())].into()
)
)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -1296,7 +1296,7 @@ impl_runtime_apis! {
Runtime,
bridge_common_config::BridgeGrandpaWestendInstance,
bridge_to_westend_config::WithBridgeHubWestendMessageBridge,
>(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Rococo), Parachain(42))))
>(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into()))
}
fn prepare_message_delivery_proof(
@@ -1331,7 +1331,7 @@ impl_runtime_apis! {
Runtime,
bridge_common_config::BridgeGrandpaRococoBulletinInstance,
bridge_to_bulletin_config::WithRococoBulletinMessageBridge,
>(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Rococo), Parachain(42))))
>(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into()))
}
fn prepare_message_delivery_proof(
@@ -24,14 +24,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -50,40 +50,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct BridgeHubRococoXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -111,44 +107,36 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -163,7 +151,7 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -175,13 +163,13 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -215,16 +203,16 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
let inner_encoded_len = inner.encode().len() as u32;
XcmGeneric::<Runtime>::export_message(inner_encoded_len)
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -236,11 +224,11 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubRococoXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -32,7 +32,7 @@ use bp_messages::LaneId;
use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams};
use bp_runtime::ChainId;
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -69,19 +69,19 @@ use xcm_executor::{
};
parameter_types! {
pub const TokenLocation: MultiLocation = MultiLocation::parent();
pub const TokenLocation: Location = Location::parent();
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub RelayNetwork: NetworkId = NetworkId::Rococo;
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
pub SiblingPeople: MultiLocation = (Parent, Parachain(rococo_runtime_constants::system_parachain::PEOPLE_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
pub SiblingPeople: Location = (Parent, Parachain(rococo_runtime_constants::system_parachain::PEOPLE_ID)).into();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -100,7 +100,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<TokenLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -132,11 +132,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -331,7 +331,7 @@ impl xcm_executor::Config for XcmConfig {
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// Converts a local signed origin into an XCM multilocation.
/// Converts a local signed origin into an XCM location.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -407,14 +407,10 @@ impl<
BridgeLaneId,
>
{
fn handle_fee(
fee: MultiAssets,
maybe_context: Option<&XcmContext>,
reason: FeeReason,
) -> MultiAssets {
fn handle_fee(fee: Assets, maybe_context: Option<&XcmContext>, reason: FeeReason) -> Assets {
if matches!(reason, FeeReason::Export { network: bridged_network, destination }
if bridged_network == DestNetwork::get() &&
destination == X1(Parachain(DestParaId::get().into())))
destination == [Parachain(DestParaId::get().into())])
{
// We have 2 relayer rewards accounts:
// - the SA of the source parachain on this BH: this pays the relayers for delivering
@@ -445,14 +441,14 @@ impl<
Fungible(total_fee) => {
let source_fee = total_fee / 2;
deposit_or_burn_fee::<AssetTransactor, _>(
MultiAsset { id: asset.id, fun: Fungible(source_fee) }.into(),
Asset { id: asset.id.clone(), fun: Fungible(source_fee) }.into(),
maybe_context,
source_para_account.clone(),
);
let dest_fee = total_fee - source_fee;
deposit_or_burn_fee::<AssetTransactor, _>(
MultiAsset { id: asset.id, fun: Fungible(dest_fee) }.into(),
Asset { id: asset.id, fun: Fungible(dest_fee) }.into(),
maybe_context,
dest_para_account.clone(),
);
@@ -467,7 +463,7 @@ impl<
}
}
return MultiAssets::new()
return Assets::new()
}
fee
@@ -477,10 +473,10 @@ impl<
pub struct XcmFeeManagerFromComponentsBridgeHub<WaivedLocations, HandleFee>(
PhantomData<(WaivedLocations, HandleFee)>,
);
impl<WaivedLocations: Contains<MultiLocation>, FeeHandler: HandleFee> FeeManager
impl<WaivedLocations: Contains<Location>, FeeHandler: HandleFee> FeeManager
for XcmFeeManagerFromComponentsBridgeHub<WaivedLocations, FeeHandler>
{
fn is_waived(origin: Option<&MultiLocation>, fee_reason: FeeReason) -> bool {
fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool {
let Some(loc) = origin else { return false };
if let Export { network, destination: Here } = fee_reason {
return !(network == EthereumNetwork::get())
@@ -488,7 +484,7 @@ impl<WaivedLocations: Contains<MultiLocation>, FeeHandler: HandleFee> FeeManager
WaivedLocations::contains(loc)
}
fn handle_fee(fee: MultiAssets, context: Option<&XcmContext>, reason: FeeReason) {
fn handle_fee(fee: Assets, context: Option<&XcmContext>, reason: FeeReason) {
FeeHandler::handle_fee(fee, context, reason);
}
}
@@ -241,7 +241,7 @@ mod bridge_hub_westend_tests {
_ => None,
}
}),
|| ExportMessage { network: Westend, destination: X1(Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into())), xcm: Xcm(vec![]) },
|| ExportMessage { network: Westend, destination: [Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into())].into(), xcm: Xcm(vec![]) },
XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND,
Some((TokenLocation::get(), ExistentialDeposit::get()).into()),
// value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer`
@@ -47,7 +47,7 @@ use frame_support::{
use sp_runtime::RuntimeDebug;
use xcm::{
latest::prelude::*,
prelude::{InteriorMultiLocation, NetworkId},
prelude::{InteriorLocation, NetworkId},
};
use xcm_builder::BridgeBlobDispatcher;
@@ -63,12 +63,12 @@ parameter_types! {
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_bridge_hub_westend::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
pub const BridgeHubRococoChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_ROCOCO_CHAIN_ID;
pub BridgeWestendToRococoMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(<BridgeRococoMessages as PalletInfoAccess>::index() as u8));
pub BridgeWestendToRococoMessagesPalletInstance: InteriorLocation = [PalletInstance(<BridgeRococoMessages as PalletInfoAccess>::index() as u8)].into();
pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo;
pub RococoGlobalConsensusNetworkLocation: MultiLocation = MultiLocation {
parents: 2,
interior: X1(GlobalConsensus(RococoGlobalConsensusNetwork::get()))
};
pub RococoGlobalConsensusNetworkLocation: Location = Location::new(
2,
[GlobalConsensus(RococoGlobalConsensusNetwork::get())]
);
// see the `FEE_BOOST_PER_MESSAGE` constant to get the meaning of this value
pub PriorityBoostPerMessage: u64 = 182_044_444_444_444;
@@ -79,26 +79,26 @@ parameter_types! {
pub ActiveOutboundLanesToBridgeHubRococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO];
pub const AssetHubWestendToAssetHubRococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO;
pub FromAssetHubWestendToAssetHubRococoRoute: SenderAndLane = SenderAndLane::new(
ParentThen(X1(Parachain(AssetHubWestendParaId::get().into()))).into(),
ParentThen([Parachain(AssetHubWestendParaId::get().into())].into()).into(),
XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO,
);
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![
pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![
(
FromAssetHubWestendToAssetHubRococoRoute::get(),
(RococoGlobalConsensusNetwork::get(), X1(Parachain(AssetHubRococoParaId::get().into())))
(RococoGlobalConsensusNetwork::get(), [Parachain(AssetHubRococoParaId::get().into())].into())
)
];
pub CongestedMessage: Xcm<()> = build_congestion_message(true).into();
pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into();
pub BridgeHubRococoLocation: MultiLocation = MultiLocation {
parents: 2,
interior: X2(
pub BridgeHubRococoLocation: Location = Location::new(
2,
[
GlobalConsensus(RococoGlobalConsensusNetwork::get()),
Parachain(<bp_bridge_hub_rococo::BridgeHubRococo as bp_runtime::Parachain>::PARACHAIN_ID)
)
};
]
);
}
pub const XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO: LaneId = LaneId([0, 0, 0, 2]);
@@ -363,9 +363,9 @@ mod tests {
assert_eq!(
BridgeWestendToRococoMessagesPalletInstance::get(),
X1(PalletInstance(
[PalletInstance(
bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX
))
)]
);
}
}
@@ -352,7 +352,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(xcm_config::WestendLocation::get());
pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -797,28 +797,28 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between BH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled on BH.
None
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
// BH only supports teleports to system parachain.
// Relay/native token can be teleported between BH and Relay.
let native_location = Parent.into();
@@ -834,7 +834,7 @@ impl_runtime_apis! {
use xcm_config::WestendLocation;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
WestendLocation::get(),
ExistentialDeposit::get()
).into());
@@ -845,17 +845,17 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(WestendLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(WestendLocation::get()),
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just assets according to relay chain.
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(WestendLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -864,12 +864,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
WestendLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(WestendLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -879,9 +879,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(WestendLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(WestendLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -895,35 +895,35 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((WestendLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(WestendLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = WestendLocation::get();
let assets: MultiAssets = (Concrete(WestendLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
// save XCM version for remote bridge hub
let _ = PolkadotXcm::force_xcm_version(
RuntimeOrigin::root(),
@@ -943,12 +943,12 @@ impl_runtime_apis! {
(
bridge_to_rococo_config::FromAssetHubWestendToAssetHubRococoRoute::get().location,
NetworkId::Rococo,
X1(Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into()))
[Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into())].into()
)
)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -995,7 +995,7 @@ impl_runtime_apis! {
Runtime,
bridge_to_rococo_config::BridgeGrandpaRococoInstance,
bridge_to_rococo_config::WithBridgeHubRococoMessageBridge,
>(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Westend), Parachain(42))))
>(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Westend), Parachain(42)].into()))
}
fn prepare_message_delivery_proof(
@@ -25,14 +25,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -51,40 +51,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct BridgeHubWestendXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -112,44 +108,36 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -164,7 +152,7 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -176,13 +164,13 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -216,16 +204,16 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
let inner_encoded_len = inner.encode().len() as u32;
XcmGeneric::<Runtime>::export_message(inner_encoded_len)
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -237,11 +225,11 @@ impl<Call> XcmWeightInfo<Call> for BridgeHubWestendXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -21,7 +21,7 @@ use super::{
};
use crate::bridge_common_config::{DeliveryRewardInBalance, RequiredStakeForStakeAndSlash};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -52,18 +52,18 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const WestendLocation: MultiLocation = MultiLocation::parent();
pub const WestendLocation: Location = Location::parent();
pub const RelayNetwork: NetworkId = NetworkId::Westend;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -82,7 +82,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<WestendLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -114,11 +114,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -270,7 +270,7 @@ impl xcm_executor::Config for XcmConfig {
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// Converts a local signed origin into an XCM multilocation.
/// Converts a local signed origin into an XCM location.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -207,7 +207,7 @@ fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() {
_ => None,
}
}),
|| ExportMessage { network: Rococo, destination: X1(Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into())), xcm: Xcm(vec![]) },
|| ExportMessage { network: Rococo, destination: [Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into())].into(), xcm: Xcm(vec![]) },
XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO,
Some((WestendLocation::get(), ExistentialDeposit::get()).into()),
// value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer`
@@ -23,7 +23,7 @@ use pallet_message_queue::OnQueueChanged;
use scale_info::TypeInfo;
use snowbridge_core::ChannelId;
use sp_std::{marker::PhantomData, prelude::*};
use xcm::v3::{Junction, MultiLocation};
use xcm::v4::{Junction, Location};
/// The aggregate origin of an inbound message.
/// This is specialized for BridgeHub, as the snowbridge-outbound-queue-pallet is also using
@@ -46,16 +46,16 @@ pub enum AggregateMessageOrigin {
Snowbridge(ChannelId),
}
impl From<AggregateMessageOrigin> for MultiLocation {
impl From<AggregateMessageOrigin> for Location {
fn from(origin: AggregateMessageOrigin) -> Self {
use AggregateMessageOrigin::*;
match origin {
Here => MultiLocation::here(),
Parent => MultiLocation::parent(),
Sibling(id) => MultiLocation::new(1, Junction::Parachain(id.into())),
Here => Location::here(),
Parent => Location::parent(),
Sibling(id) => Location::new(1, Junction::Parachain(id.into())),
// NOTE: We don't need this conversion for Snowbridge. However we have to
// implement it anyway as xcm_builder::ProcessXcmMessage requires it.
Snowbridge(_) => MultiLocation::default(),
Snowbridge(_) => Location::default(),
}
}
}
@@ -336,9 +336,9 @@ where
(),
>(
LaneId::default(),
vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(),
vec![Instruction::<()>::ClearOrigin; 1_024].into(),
1,
X2(GlobalConsensus(Polkadot), Parachain(1_000)),
[GlobalConsensus(Polkadot), Parachain(1_000)].into(),
1u32.into(),
);
@@ -418,9 +418,9 @@ where
(),
>(
LaneId::default(),
vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(),
vec![Instruction::<()>::ClearOrigin; 1_024].into(),
1,
X2(GlobalConsensus(Polkadot), Parachain(1_000)),
[GlobalConsensus(Polkadot), Parachain(1_000)].into(),
1,
5,
1_000,
@@ -230,7 +230,7 @@ pub fn relayed_incoming_message_works<Runtime, AllPalletsWithoutSystem, MPI>(
prepare_message_proof_import: impl FnOnce(
Runtime::AccountId,
Runtime::InboundRelayer,
InteriorMultiLocation,
InteriorLocation,
MessageNonce,
Xcm<()>,
) -> CallsAndVerifiers<Runtime>,
@@ -276,21 +276,21 @@ pub fn relayed_incoming_message_works<Runtime, AllPalletsWithoutSystem, MPI>(
// set up relayer details and proofs
let message_destination =
X2(GlobalConsensus(local_relay_chain_id), Parachain(sibling_parachain_id));
let message_destination: InteriorLocation =
[GlobalConsensus(local_relay_chain_id), Parachain(sibling_parachain_id)].into();
// some random numbers (checked by test)
let message_nonce = 1;
let xcm = vec![xcm::v3::Instruction::<()>::ClearOrigin; 42];
let xcm = vec![Instruction::<()>::ClearOrigin; 42];
let expected_dispatch = xcm::latest::Xcm::<()>({
let mut expected_instructions = xcm.clone();
// dispatch prepends bridge pallet instance
expected_instructions.insert(
0,
DescendOrigin(X1(PalletInstance(
DescendOrigin([PalletInstance(
<pallet_bridge_messages::Pallet<Runtime, MPI> as PalletInfoAccess>::index()
as u8,
))),
)].into()),
);
expected_instructions
});
@@ -319,8 +319,8 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
>,
export_message_instruction: fn() -> Instruction<XcmConfig::RuntimeCall>,
expected_lane_id: LaneId,
existential_deposit: Option<MultiAsset>,
maybe_paid_export_message: Option<MultiAsset>,
existential_deposit: Option<Asset>,
maybe_paid_export_message: Option<Asset>,
prepare_configuration: impl Fn(),
) where
Runtime: BasicParachainRuntime + BridgeMessagesConfig<MessagesPalletInstance>,
@@ -328,7 +328,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
MessagesPalletInstance: 'static,
{
assert_ne!(runtime_para_id, sibling_parachain_id);
let sibling_parachain_location = MultiLocation::new(1, Parachain(sibling_parachain_id));
let sibling_parachain_location = Location::new(1, [Parachain(sibling_parachain_id)]);
run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
prepare_configuration();
@@ -361,7 +361,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
.expect("deposited fee");
Xcm(vec![
WithdrawAsset(MultiAssets::from(vec![fee.clone()])),
WithdrawAsset(Assets::from(vec![fee.clone()])),
BuyExecution { fees: fee, weight_limit: Unlimited },
export_message_instruction(),
])
@@ -373,12 +373,13 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
};
// execute XCM
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
assert_ok!(XcmExecutor::<XcmConfig>::execute_xcm(
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
assert_ok!(XcmExecutor::<XcmConfig>::prepare_and_execute(
sibling_parachain_location,
xcm,
hash,
&mut hash,
RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Sibling),
Weight::zero(),
)
.ensure_complete());
@@ -446,9 +447,9 @@ pub fn message_dispatch_routing_works<
NetworkDistanceAsParentCount: Get<u8>,
{
struct NetworkWithParentCount<N, C>(core::marker::PhantomData<(N, C)>);
impl<N: Get<NetworkId>, C: Get<u8>> Get<MultiLocation> for NetworkWithParentCount<N, C> {
fn get() -> MultiLocation {
MultiLocation { parents: C::get(), interior: X1(GlobalConsensus(N::get())) }
impl<N: Get<NetworkId>, C: Get<u8>> Get<Location> for NetworkWithParentCount<N, C> {
fn get() -> Location {
Location::new(C::get(), [GlobalConsensus(N::get())])
}
}
@@ -495,7 +496,7 @@ pub fn message_dispatch_routing_works<
BridgedNetwork,
NetworkWithParentCount<RuntimeNetwork, NetworkDistanceAsParentCount>,
AlwaysLatest,
>((RuntimeNetwork::get(), X1(Parachain(sibling_parachain_id))));
>((RuntimeNetwork::get(), [Parachain(sibling_parachain_id)].into()));
// 2.1. WITHOUT opened hrmp channel -> RoutingError
let result =
@@ -565,52 +566,43 @@ where
{
// data here are not relevant for weighing
let mut xcm = Xcm(vec![
WithdrawAsset(MultiAssets::from(vec![MultiAsset {
id: Concrete(MultiLocation { parents: 1, interior: Here }),
WithdrawAsset(Assets::from(vec![Asset {
id: AssetId(Location::new(1, [])),
fun: Fungible(34333299),
}])),
BuyExecution {
fees: MultiAsset {
id: Concrete(MultiLocation { parents: 1, interior: Here }),
fun: Fungible(34333299),
},
fees: Asset { id: AssetId(Location::new(1, [])), fun: Fungible(34333299) },
weight_limit: Unlimited,
},
ExportMessage {
network: Polkadot,
destination: X1(Parachain(1000)),
destination: [Parachain(1000)].into(),
xcm: Xcm(vec![
ReserveAssetDeposited(MultiAssets::from(vec![MultiAsset {
id: Concrete(MultiLocation {
parents: 2,
interior: X1(GlobalConsensus(Kusama)),
}),
ReserveAssetDeposited(Assets::from(vec![Asset {
id: AssetId(Location::new(2, [GlobalConsensus(Kusama)])),
fun: Fungible(1000000000000),
}])),
ClearOrigin,
BuyExecution {
fees: MultiAsset {
id: Concrete(MultiLocation {
parents: 2,
interior: X1(GlobalConsensus(Kusama)),
}),
fees: Asset {
id: AssetId(Location::new(2, [GlobalConsensus(Kusama)])),
fun: Fungible(1000000000000),
},
weight_limit: Unlimited,
},
DepositAsset {
assets: Wild(AllCounted(1)),
beneficiary: MultiLocation {
parents: 0,
interior: X1(xcm::latest::prelude::AccountId32 {
beneficiary: Location::new(
0,
[xcm::latest::prelude::AccountId32 {
network: None,
id: [
212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159,
214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165,
109, 162, 125,
],
}),
},
}],
),
},
SetTopic([
116, 82, 194, 132, 171, 114, 217, 165, 23, 37, 161, 177, 165, 179, 247, 114,
@@ -618,10 +610,7 @@ where
]),
]),
},
DepositAsset {
assets: Wild(All),
beneficiary: MultiLocation { parents: 1, interior: X1(Parachain(1000)) },
},
DepositAsset { assets: Wild(All), beneficiary: Location::new(1, [Parachain(1000)]) },
SetTopic([
36, 224, 250, 165, 82, 195, 67, 110, 160, 170, 140, 87, 217, 62, 201, 164, 42, 98, 219,
157, 124, 105, 248, 25, 131, 218, 199, 36, 109, 173, 100, 122,
@@ -37,10 +37,10 @@ use xcm_executor::traits::{validate_export, ExportXcm};
pub fn prepare_inbound_xcm<InnerXcmRuntimeCall>(
xcm_message: Xcm<InnerXcmRuntimeCall>,
destination: InteriorMultiLocation,
destination: InteriorLocation,
) -> Vec<u8> {
let location = xcm::VersionedInteriorMultiLocation::V3(destination);
let xcm = xcm::VersionedXcm::<InnerXcmRuntimeCall>::V3(xcm_message);
let location = xcm::VersionedInteriorLocation::V4(destination);
let xcm = xcm::VersionedXcm::<InnerXcmRuntimeCall>::V4(xcm_message);
// this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor
// or public fields, so just tuple
// (double encoding, because `.encode()` is called on original Xcm BLOB when it is pushed
@@ -101,7 +101,7 @@ macro_rules! grab_haul_blob (
/// which are transferred over bridge.
pub(crate) fn simulate_message_exporter_on_bridged_chain<
SourceNetwork: Get<NetworkId>,
DestinationNetwork: Get<MultiLocation>,
DestinationNetwork: Get<Location>,
DestinationVersion: GetVersion,
>(
(destination_network, destination_junctions): (NetworkId, Junctions),
@@ -109,8 +109,8 @@ pub(crate) fn simulate_message_exporter_on_bridged_chain<
grab_haul_blob!(GrabbingHaulBlob, GRABBED_HAUL_BLOB_PAYLOAD);
// lets pretend that some parachain on bridged chain exported the message
let universal_source_on_bridged_chain =
X2(GlobalConsensus(SourceNetwork::get()), Parachain(5678));
let universal_source_on_bridged_chain: Junctions =
[GlobalConsensus(SourceNetwork::get()), Parachain(5678)].into();
let channel = 1_u32;
// simulate XCM message export
@@ -215,7 +215,7 @@ pub type AmbassadorSalaryInstance = pallet_salary::Instance2;
parameter_types! {
// The interior location on AssetHub for the paying account. This is the Ambassador Salary
// pallet instance (which sits at index 74). This sovereign account will need funding.
pub AmbassadorSalaryLocation: InteriorMultiLocation = PalletInstance(74).into();
pub AmbassadorSalaryLocation: InteriorLocation = PalletInstance(74).into();
}
/// [`PayOverXcm`] setup to pay the Ambassador salary on the AssetHub in WND.
@@ -43,7 +43,7 @@ use parachains_common::{
westend::{account, currency::GRAND},
};
use polkadot_runtime_common::impls::{
LocatableAssetConverter, VersionedLocatableAsset, VersionedMultiLocationConverter,
LocatableAssetConverter, VersionedLocatableAsset, VersionedLocationConverter,
};
use sp_arithmetic::Permill;
use sp_core::{ConstU128, ConstU32};
@@ -202,7 +202,7 @@ pub type FellowshipSalaryInstance = pallet_salary::Instance1;
parameter_types! {
// The interior location on AssetHub for the paying account. This is the Fellowship Salary
// pallet instance (which sits at index 64). This sovereign account will need funding.
pub Interior: InteriorMultiLocation = PalletInstance(64).into();
pub Interior: InteriorLocation = PalletInstance(64).into();
}
const USDT_UNITS: u128 = 1_000_000;
@@ -250,7 +250,7 @@ parameter_types! {
pub const MaxBalance: Balance = Balance::max_value();
// The asset's interior location for the paying account. This is the Fellowship Treasury
// pallet instance (which sits at index 65).
pub FellowshipTreasuryInteriorLocation: InteriorMultiLocation = PalletInstance(65).into();
pub FellowshipTreasuryInteriorLocation: InteriorLocation = PalletInstance(65).into();
}
#[cfg(feature = "runtime-benchmarks")]
@@ -269,10 +269,10 @@ pub type FellowshipTreasuryPaymaster = PayOverXcm<
crate::xcm_config::XcmRouter,
crate::PolkadotXcm,
ConstU32<{ 6 * HOURS }>,
VersionedMultiLocation,
VersionedLocation,
VersionedLocatableAsset,
LocatableAssetConverter,
VersionedMultiLocationConverter,
VersionedLocationConverter,
>;
pub type FellowshipTreasuryInstance = pallet_treasury::Instance1;
@@ -327,7 +327,7 @@ impl pallet_treasury::Config<FellowshipTreasuryInstance> for Runtime {
>,
>;
type AssetKind = VersionedLocatableAsset;
type Beneficiary = VersionedMultiLocation;
type Beneficiary = VersionedLocation;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
#[cfg(not(feature = "runtime-benchmarks"))]
type Paymaster = FellowshipTreasuryPaymaster;
@@ -427,7 +427,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(xcm_config::WndLocation::get());
pub FeeAssetId: AssetId = AssetId(xcm_config::WndLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -974,28 +974,28 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between Collectives and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
}.into(),
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled on Collectives.
None
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
// Collectives only supports teleports to system parachain.
// Relay/native token can be teleported between Collectives and Relay.
let native_location = Parent.into();
@@ -19,7 +19,7 @@ use super::{
TransactionByteFee, WeightToFee, WestendTreasuryAccount, XcmpQueue,
};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
weights::Weight,
};
@@ -51,17 +51,17 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const WndLocation: MultiLocation = MultiLocation::parent();
pub const WndLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Westend);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub const GovernanceLocation: Location = Location::parent();
pub const FellowshipAdminBodyId: BodyId = BodyId::Index(xcm_constants::body::FELLOWSHIP_ADMIN_INDEX);
pub AssetHub: Location = (Parent, Parachain(1000)).into();
pub const TreasurerBodyId: BodyId = BodyId::Index(xcm_constants::body::TREASURER_INDEX);
pub AssetHub: MultiLocation = (Parent, Parachain(1000)).into();
pub AssetHubUsdtId: AssetId = (PalletInstance(50), GeneralIndex(1984)).into();
pub UsdtAssetHub: LocatableAssetId = LocatableAssetId {
location: AssetHub::get(),
@@ -73,7 +73,7 @@ parameter_types! {
};
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -92,7 +92,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<WndLocation>,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -136,11 +136,11 @@ parameter_types! {
pub const FellowsBodyId: BodyId = BodyId::Technical;
}
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -292,7 +292,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation.
/// Converts a local signed origin into an XCM location.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -310,10 +310,10 @@ pub type XcmRouter = WithUniqueTopic<(
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
pub ReachableDest: Option<Location> = Some(Parent.into());
}
/// Type to convert the Fellows origin to a Plurality `MultiLocation` value.
/// Type to convert the Fellows origin to a Plurality `Location` value.
pub type FellowsToPlurality = OriginToPluralityVoice<RuntimeOrigin, Fellows, FellowsBodyId>;
impl pallet_xcm::Config for Runtime {
@@ -704,28 +704,28 @@ impl_runtime_apis! {
use xcm::latest::prelude::*;
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between Contracts-System-Para and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled on Contracts-System-Para.
None
}
fn set_up_complex_asset_transfer(
) -> Option<(MultiAssets, u32, MultiLocation, Box<dyn FnOnce()>)> {
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
// Contracts-System-Para only supports teleports to system parachain.
// Relay/native token can be teleported between Contracts-System-Para and Relay.
let native_location = Parent.into();
@@ -20,8 +20,8 @@ use super::{
use crate::common::rococo::currency::CENTS;
use cumulus_primitives_core::AggregateMessageOrigin;
use frame_support::{
match_types, parameter_types,
traits::{ConstU32, EitherOfDiverse, Equals, Everything, Nothing},
parameter_types,
traits::{ConstU32, Contains, EitherOfDiverse, Equals, Everything, Nothing},
weights::Weight,
};
use frame_system::EnsureRoot;
@@ -51,13 +51,13 @@ use xcm_builder::{
use xcm_executor::XcmExecutor;
parameter_types! {
pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = None;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
pub UniversalLocation: InteriorLocation = Parachain(ParachainInfo::parachain_id().into()).into();
pub const ExecutiveBody: BodyId = BodyId::Executive;
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// We allow root and the Relay Chain council to execute privileged collator selection operations.
@@ -66,7 +66,7 @@ pub type CollatorSelectionUpdateOrigin = EitherOfDiverse<
EnsureXcm<IsMajorityOfBody<RelayLocation, ExecutiveBody>>,
>;
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -85,7 +85,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -123,11 +123,11 @@ parameter_types! {
pub const MaxInstructions: u32 = 100;
}
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
pub type Barrier = TrailingSetTopicAsId<
@@ -200,7 +200,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation.
/// Converts a local signed origin into an XCM location.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -254,7 +254,7 @@ impl cumulus_pallet_xcm::Config for Runtime {
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(RelayLocation::get());
pub FeeAssetId: AssetId = AssetId(RelayLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -98,7 +98,7 @@ impl CoretimeInterface for CoretimeAllocator {
},
]);
match PolkadotXcm::send_xcm(Here, MultiLocation::parent(), message.clone()) {
match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
Ok(_) => log::info!(
target: "runtime::coretime",
"Request to update schedulable cores sent successfully."
@@ -128,7 +128,7 @@ impl CoretimeInterface for CoretimeAllocator {
},
]);
match PolkadotXcm::send_xcm(Here, MultiLocation::parent(), message.clone()) {
match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
Ok(_) => log::info!(
target: "runtime::coretime",
"Request for revenue information sent successfully."
@@ -157,7 +157,7 @@ impl CoretimeInterface for CoretimeAllocator {
},
]);
match PolkadotXcm::send_xcm(Here, MultiLocation::parent(), message.clone()) {
match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
Ok(_) => log::info!(
target: "runtime::coretime",
"Instruction to credit account sent successfully."
@@ -192,7 +192,7 @@ impl CoretimeInterface for CoretimeAllocator {
},
]);
match PolkadotXcm::send_xcm(Here, MultiLocation::parent(), message.clone()) {
match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
Ok(_) => log::info!(
target: "runtime::coretime",
"Core assignment sent successfully."
@@ -315,7 +315,7 @@ pub type RootOrFellows = EitherOfDiverse<
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(RocRelayLocation::get());
pub FeeAssetId: AssetId = AssetId(RocRelayLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -698,29 +698,29 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between AH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled
None
}
}
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
RocRelayLocation::get(),
ExistentialDeposit::get()
).into());
@@ -730,18 +730,18 @@ impl_runtime_apis! {
type XcmConfig = xcm_config::XcmConfig;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
type AccountIdConverter = xcm_config::LocationToAccountId;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(RocRelayLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(RocRelayLocation::get()),
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(RocRelayLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -750,12 +750,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
RocRelayLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(RocRelayLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(RocRelayLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -765,9 +765,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(RocRelayLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(RocRelayLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -781,39 +781,39 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((RocRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(RocRelayLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = RocRelayLocation::get();
let assets: MultiAssets = (Concrete(RocRelayLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(RocRelayLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -24,14 +24,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -50,40 +50,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct CoretimeRococoXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -111,43 +107,35 @@ impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -162,7 +150,7 @@ impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -174,13 +162,13 @@ impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -213,16 +201,16 @@ impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -234,11 +222,11 @@ impl<Call> XcmWeightInfo<Call> for CoretimeRococoXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -20,7 +20,7 @@ use super::{
TransactionByteFee, WeightToFee, XcmpQueue,
};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -51,18 +51,18 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const RocRelayLocation: MultiLocation = MultiLocation::parent();
pub const RocRelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Rococo);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub const FellowshipLocation: MultiLocation = MultiLocation::parent();
pub const GovernanceLocation: Location = Location::parent();
pub const FellowshipLocation: Location = Location::parent();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -81,7 +81,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RocRelayLocation>,
// Do a simple punn to convert an `AccountId32` `MultiLocation` into a native chain
// Do a simple punn to convert an `AccountId32` `Location` into a native chain
// `AccountId`:
LocationToAccountId,
// Our chain's `AccountId` type (we can't get away without mentioning it explicitly):
@@ -114,11 +114,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -191,7 +191,7 @@ pub type Barrier = TrailingSetTopicAsId<
parameter_types! {
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// Locations that will not be charged fees in the executor, neither for execution nor delivery.
@@ -240,7 +240,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation. Forms the basis for local origins
/// Converts a local signed origin into an XCM location. Forms the basis for local origins
/// sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -306,7 +306,7 @@ pub type RootOrFellows = EitherOfDiverse<
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(WndRelayLocation::get());
pub FeeAssetId: AssetId = AssetId(WndRelayLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
@@ -689,29 +689,29 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between AH and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
// Reserve transfers are disabled
None
}
}
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
WndRelayLocation::get(),
ExistentialDeposit::get()
).into());
@@ -721,18 +721,18 @@ impl_runtime_apis! {
type XcmConfig = xcm_config::XcmConfig;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
type AccountIdConverter = xcm_config::LocationToAccountId;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(WndRelayLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(WndRelayLocation::get()),
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(WndRelayLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -741,12 +741,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
WndRelayLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(WndRelayLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(WndRelayLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -756,9 +756,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(WndRelayLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(WndRelayLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -772,39 +772,39 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((WndRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(WndRelayLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = WndRelayLocation::get();
let assets: MultiAssets = (Concrete(WndRelayLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(WndRelayLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct CoretimeWestendXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
fn reserve_asset_deposited(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
fn reserve_asset_deposited(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::reserve_asset_deposited())
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -110,44 +106,36 @@ impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset())
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -162,7 +150,7 @@ impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -174,13 +162,13 @@ impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -213,16 +201,16 @@ impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -234,11 +222,11 @@ impl<Call> XcmWeightInfo<Call> for CoretimeWestendXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -20,7 +20,7 @@ use super::{
TransactionByteFee, WeightToFee, XcmpQueue,
};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -51,18 +51,18 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const WndRelayLocation: MultiLocation = MultiLocation::parent();
pub const WndRelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Westend);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001));
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub FellowshipLocation: Location = Location::new(1, Parachain(1001));
pub const GovernanceLocation: Location = Location::parent();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -81,7 +81,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<WndRelayLocation>,
// Do a simple punn to convert an `AccountId32` `MultiLocation` into a native chain
// Do a simple punn to convert an `AccountId32` `Location` into a native chain
// `AccountId`:
LocationToAccountId,
// Our chain's `AccountId` type (we can't get away without mentioning it explicitly):
@@ -114,14 +114,18 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub type FellowsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) }
};
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
pub struct FellowsPlurality;
impl Contains<Location> for FellowsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, [Parachain(1001), Plurality { id: BodyId::Technical, .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -192,7 +196,7 @@ pub type Barrier = TrailingSetTopicAsId<
parameter_types! {
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
}
/// Locations that will not be charged fees in the executor, neither for execution nor delivery.
@@ -241,7 +245,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation. Forms the basis for local origins
/// Converts a local signed origin into an XCM location. Forms the basis for local origins
/// sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -18,8 +18,8 @@ use super::{
RuntimeOrigin,
};
use frame_support::{
match_types, parameter_types,
traits::{Everything, Nothing},
parameter_types,
traits::{Contains, Everything, Nothing},
weights::Weight,
};
use xcm::latest::prelude::*;
@@ -29,9 +29,9 @@ use xcm_builder::{
};
parameter_types! {
pub const WestendLocation: MultiLocation = MultiLocation::parent();
pub const WestendLocation: Location = Location::parent();
pub const WestendNetwork: Option<NetworkId> = Some(NetworkId::Westend);
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into();
}
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
@@ -47,8 +47,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
ParentAsSuperuser<RuntimeOrigin>,
);
match_types! {
pub type JustTheParent: impl Contains<MultiLocation> = { MultiLocation { parents:1, interior: Here } };
pub struct JustTheParent;
impl Contains<Location> for JustTheParent {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []))
}
}
parameter_types! {
@@ -682,22 +682,22 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between People and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
None
}
}
@@ -706,7 +706,7 @@ impl_runtime_apis! {
use xcm_config::{PriceForParentDelivery, RelayLocation};
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
RelayLocation::get(),
ExistentialDeposit::get()
).into());
@@ -717,17 +717,17 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(RelayLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(RelayLocation::get()),
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(RelayLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -736,12 +736,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
RelayLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(RelayLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(RelayLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -751,9 +751,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(RelayLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(RelayLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -767,39 +767,39 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((RelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(RelayLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = RelayLocation::get();
let assets: MultiAssets = (Concrete(RelayLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(RelayLocation::get()), 1_000 * UNITS).into();
let ticket = Location::new(0, []);
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -49,42 +49,38 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct PeopleRococoXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
// Currently there is no trusted reserve
fn reserve_asset_deposited(_assets: &MultiAssets) -> Weight {
fn reserve_asset_deposited(_assets: &Assets) -> Weight {
// TODO: hardcoded - fix https://github.com/paritytech/cumulus/issues/1974
Weight::from_parts(1_000_000_000_u64, 0)
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -112,47 +108,39 @@ impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
// Hardcoded till the XCM pallet is fixed
let hardcoded_weight = Weight::from_parts(1_000_000_000_u64, 0);
let weight = assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset());
let weight = assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset());
hardcoded_weight.min(weight)
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmGeneric::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport())
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -167,7 +155,7 @@ impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -179,13 +167,13 @@ impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -218,16 +206,16 @@ impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -239,11 +227,11 @@ impl<Call> XcmWeightInfo<Call> for PeopleRococoXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -19,7 +19,7 @@ use super::{
};
use crate::{TransactionByteFee, CENTS};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -49,22 +49,22 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const RootLocation: MultiLocation = MultiLocation::here();
pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RootLocation: Location = Location::here();
pub const RelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Rococo);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub const FellowshipLocation: MultiLocation = MultiLocation::parent();
pub const GovernanceLocation: Location = Location::parent();
pub const FellowshipLocation: Location = Location::parent();
/// The asset ID for the asset that we use to pay for message delivery fees. Just ROC.
pub FeeAssetId: AssetId = Concrete(RelayLocation::get());
pub FeeAssetId: AssetId = AssetId(RelayLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation =
pub RelayTreasuryLocation: Location =
(Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into();
}
@@ -82,7 +82,7 @@ pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender:
XcmpQueue,
>;
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -103,7 +103,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Do a simple punn to convert an `AccountId32` `MultiLocation` into a native chain
// Do a simple punn to convert an `AccountId32` `Location` into a native chain
// `AccountId`:
LocationToAccountId,
// Our chain's `AccountId` type (we can't get away without mentioning it explicitly):
@@ -136,18 +136,25 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type LocalPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 0, interior: X1(Plurality { .. }) }
};
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub type ParentOrSiblings: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Parachain(_)) }
};
pub struct LocalPlurality;
impl Contains<Location> for LocalPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (0, [Plurality { .. }]))
}
}
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
pub struct ParentOrSiblings;
impl Contains<Location> for ParentOrSiblings {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Parachain(_)]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -268,7 +275,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation. Forms the basis for local origins
/// Converts a local signed origin into an XCM location. Forms the basis for local origins
/// sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -682,22 +682,22 @@ impl_runtime_apis! {
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
fn reachable_dest() -> Option<MultiLocation> {
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between People and Relay.
Some((
MultiAsset {
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Concrete(Parent.into())
id: AssetId(Parent.into())
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> {
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
None
}
}
@@ -706,7 +706,7 @@ impl_runtime_apis! {
use xcm_config::{PriceForParentDelivery, RelayLocation};
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
pub ExistentialDepositAsset: Option<Asset> = Some((
RelayLocation::get(),
ExistentialDeposit::get()
).into());
@@ -717,17 +717,17 @@ impl_runtime_apis! {
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
ExistentialDepositAsset,
PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(RelayLocation::get())
}
fn worst_case_holding(_depositable_count: u32) -> MultiAssets {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// just concrete assets according to relay chain.
let assets: Vec<MultiAsset> = vec![
MultiAsset {
id: Concrete(RelayLocation::get()),
let assets: Vec<Asset> = vec![
Asset {
id: AssetId(RelayLocation::get()),
fun: Fungible(1_000_000 * UNITS),
}
];
@@ -736,12 +736,12 @@ impl_runtime_apis! {
}
parameter_types! {
pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some((
pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
RelayLocation::get(),
MultiAsset { fun: Fungible(UNITS), id: Concrete(RelayLocation::get()) },
Asset { fun: Fungible(UNITS), id: AssetId(RelayLocation::get()) },
));
pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None;
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
@@ -751,9 +751,9 @@ impl_runtime_apis! {
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_multi_asset() -> MultiAsset {
MultiAsset {
id: Concrete(RelayLocation::get()),
fn get_asset() -> Asset {
Asset {
id: AssetId(RelayLocation::get()),
fun: Fungible(UNITS),
}
}
@@ -767,39 +767,39 @@ impl_runtime_apis! {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> {
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> {
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> {
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((RelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<MultiLocation, BenchmarkError> {
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(RelayLocation::get())
}
fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = RelayLocation::get();
let assets: MultiAssets = (Concrete(RelayLocation::get()), 1_000 * UNITS).into();
let ticket = MultiLocation { parents: 0, interior: Here };
let assets: Assets = (AssetId(RelayLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> {
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> {
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> {
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
@@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric;
use sp_std::prelude::*;
use xcm::{latest::prelude::*, DoubleEncoded};
trait WeighMultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight;
trait WeighAssets {
fn weigh_assets(&self, weight: Weight) -> Weight;
}
const MAX_ASSETS: u64 = 100;
impl WeighMultiAssets for MultiAssetFilter {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for AssetFilter {
fn weigh_assets(&self, weight: Weight) -> Weight {
match self {
Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64),
Self::Wild(asset) => match asset {
@@ -49,42 +49,38 @@ impl WeighMultiAssets for MultiAssetFilter {
}
}
impl WeighMultiAssets for MultiAssets {
fn weigh_multi_assets(&self, weight: Weight) -> Weight {
impl WeighAssets for Assets {
fn weigh_assets(&self, weight: Weight) -> Weight {
weight.saturating_mul(self.inner().iter().count() as u64)
}
}
pub struct PeopleWestendXcmWeight<Call>(core::marker::PhantomData<Call>);
impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn withdraw_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
fn withdraw_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::withdraw_asset())
}
// Currently there is no trusted reserve
fn reserve_asset_deposited(_assets: &MultiAssets) -> Weight {
fn reserve_asset_deposited(_assets: &Assets) -> Weight {
// TODO: hardcoded - fix https://github.com/paritytech/cumulus/issues/1974
Weight::from_parts(1_000_000_000_u64, 0)
}
fn receive_teleported_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
fn receive_teleported_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::receive_teleported_asset())
}
fn query_response(
_query_id: &u64,
_response: &Response,
_max_weight: &Weight,
_querier: &Option<MultiLocation>,
_querier: &Option<Location>,
) -> Weight {
XcmGeneric::<Runtime>::query_response()
}
fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_asset())
}
fn transfer_reserve_asset(
assets: &MultiAssets,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::transfer_reserve_asset())
}
fn transact(
_origin_type: &OriginKind,
@@ -112,50 +108,42 @@ impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn clear_origin() -> Weight {
XcmGeneric::<Runtime>::clear_origin()
}
fn descend_origin(_who: &InteriorMultiLocation) -> Weight {
fn descend_origin(_who: &InteriorLocation) -> Weight {
XcmGeneric::<Runtime>::descend_origin()
}
fn report_error(_query_response_info: &QueryResponseInfo) -> Weight {
XcmGeneric::<Runtime>::report_error()
}
fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight {
fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight {
// Hardcoded till the XCM pallet is fixed
let hardcoded_weight = Weight::from_parts(1_000_000_000_u64, 0);
let weight = assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_asset());
let weight = assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_asset());
hardcoded_weight.min(weight)
}
fn deposit_reserve_asset(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
assets.weigh_assets(XcmFungibleWeight::<Runtime>::deposit_reserve_asset())
}
fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight {
fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight {
Weight::MAX
}
fn initiate_reserve_withdraw(
assets: &MultiAssetFilter,
_reserve: &MultiLocation,
assets: &AssetFilter,
_reserve: &Location,
_xcm: &Xcm<()>,
) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::initiate_reserve_withdraw())
assets.weigh_assets(XcmGeneric::<Runtime>::initiate_reserve_withdraw())
}
fn initiate_teleport(
assets: &MultiAssetFilter,
_dest: &MultiLocation,
_xcm: &Xcm<()>,
) -> Weight {
fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight {
// Hardcoded till the XCM pallet is fixed
let hardcoded_weight = Weight::from_parts(200_000_000_u64, 0);
let weight = assets.weigh_multi_assets(XcmFungibleWeight::<Runtime>::initiate_teleport());
let weight = assets.weigh_assets(XcmFungibleWeight::<Runtime>::initiate_teleport());
hardcoded_weight.min(weight)
}
fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight {
fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight {
XcmGeneric::<Runtime>::report_holding()
}
fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight {
fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight {
XcmGeneric::<Runtime>::buy_execution()
}
fn refund_surplus() -> Weight {
@@ -170,7 +158,7 @@ impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn clear_error() -> Weight {
XcmGeneric::<Runtime>::clear_error()
}
fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight {
fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight {
XcmGeneric::<Runtime>::claim_asset()
}
fn trap(_code: &u64) -> Weight {
@@ -182,13 +170,13 @@ impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn unsubscribe_version() -> Weight {
XcmGeneric::<Runtime>::unsubscribe_version()
}
fn burn_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::burn_asset())
fn burn_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::burn_asset())
}
fn expect_asset(assets: &MultiAssets) -> Weight {
assets.weigh_multi_assets(XcmGeneric::<Runtime>::expect_asset())
fn expect_asset(assets: &Assets) -> Weight {
assets.weigh_assets(XcmGeneric::<Runtime>::expect_asset())
}
fn expect_origin(_origin: &Option<MultiLocation>) -> Weight {
fn expect_origin(_origin: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::expect_origin()
}
fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight {
@@ -221,16 +209,16 @@ impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight {
Weight::MAX
}
fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn lock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn unlock_asset(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn note_unlockable(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight {
fn request_unlock(_: &Asset, _: &Location) -> Weight {
Weight::MAX
}
fn set_fees_mode(_: &bool) -> Weight {
@@ -242,11 +230,11 @@ impl<Call> XcmWeightInfo<Call> for PeopleWestendXcmWeight<Call> {
fn clear_topic() -> Weight {
XcmGeneric::<Runtime>::clear_topic()
}
fn alias_origin(_: &MultiLocation) -> Weight {
fn alias_origin(_: &Location) -> Weight {
// XCM Executor does not currently support alias origin operations
Weight::MAX
}
fn unpaid_execution(_: &WeightLimit, _: &Option<MultiLocation>) -> Weight {
fn unpaid_execution(_: &WeightLimit, _: &Option<Location>) -> Weight {
XcmGeneric::<Runtime>::unpaid_execution()
}
}
@@ -19,7 +19,7 @@ use super::{
};
use crate::{TransactionByteFee, CENTS};
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{ConstU32, Contains, Equals, Everything, Nothing},
};
use frame_system::EnsureRoot;
@@ -49,22 +49,22 @@ use xcm_builder::{
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
parameter_types! {
pub const RootLocation: MultiLocation = MultiLocation::here();
pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RootLocation: Location = Location::here();
pub const RelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = Some(NetworkId::Westend);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation =
[GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001));
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub FellowshipLocation: Location = Location::new(1, Parachain(1001));
pub const GovernanceLocation: Location = Location::parent();
/// The asset ID for the asset that we use to pay for message delivery fees. Just WND.
pub FeeAssetId: AssetId = Concrete(RelayLocation::get());
pub FeeAssetId: AssetId = AssetId(RelayLocation::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
pub RelayTreasuryLocation: MultiLocation =
pub RelayTreasuryLocation: Location =
(Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
}
@@ -82,7 +82,7 @@ pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender:
XcmpQueue,
>;
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -103,7 +103,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Do a simple punn to convert an `AccountId32` `MultiLocation` into a native chain
// Do a simple punn to convert an `AccountId32` `Location` into a native chain
// `AccountId`:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
@@ -136,21 +136,32 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<RuntimeOrigin>,
);
match_types! {
pub type LocalPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 0, interior: X1(Plurality { .. }) }
};
pub type ParentOrParentsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { .. }) }
};
pub type ParentOrSiblings: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Parachain(_)) }
};
pub type FellowsPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) }
};
pub struct LocalPlurality;
impl Contains<Location> for LocalPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (0, [Plurality { .. }]))
}
}
pub struct ParentOrParentsPlurality;
impl Contains<Location> for ParentOrParentsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
}
}
pub struct ParentOrSiblings;
impl Contains<Location> for ParentOrSiblings {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Parachain(_)]))
}
}
pub struct FellowsPlurality;
impl Contains<Location> for FellowsPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, [Parachain(1001), Plurality { id: BodyId::Technical, .. }]))
}
}
/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
@@ -272,7 +283,7 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
/// Converts a local signed origin into an XCM multilocation. Forms the basis for local origins
/// Converts a local signed origin into an XCM location. Forms the basis for local origins
/// sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -18,8 +18,8 @@ use super::{
RuntimeOrigin,
};
use frame_support::{
match_types, parameter_types,
traits::{Everything, Nothing},
parameter_types,
traits::{Contains, Everything, Nothing},
weights::Weight,
};
use xcm::latest::prelude::*;
@@ -29,9 +29,9 @@ use xcm_builder::{
};
parameter_types! {
pub const RococoLocation: MultiLocation = MultiLocation::parent();
pub const RococoLocation: Location = Location::parent();
pub const RococoNetwork: Option<NetworkId> = Some(NetworkId::Rococo);
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into();
}
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
@@ -47,8 +47,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
ParentAsSuperuser<RuntimeOrigin>,
);
match_types! {
pub type JustTheParent: impl Contains<MultiLocation> = { MultiLocation { parents:1, interior: Here } };
pub struct JustTheParent;
impl Contains<Location> for JustTheParent {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []))
}
}
parameter_types! {
@@ -37,11 +37,11 @@ use sp_consensus_aura::{SlotDuration, AURA_ENGINE_ID};
use sp_core::Encode;
use sp_runtime::{traits::Header, BuildStorage, Digest, DigestItem};
use xcm::{
latest::{MultiAsset, MultiLocation, XcmContext, XcmHash},
latest::{Asset, Location, XcmContext, XcmHash},
prelude::*,
VersionedXcm, MAX_XCM_DECODE_DEPTH,
};
use xcm_executor::{traits::TransactAsset, Assets};
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
pub mod test_cases;
@@ -307,12 +307,12 @@ impl<XcmConfig: xcm_executor::Config, AllPalletsWithoutSystem>
RuntimeHelper<XcmConfig, AllPalletsWithoutSystem>
{
pub fn do_transfer(
from: MultiLocation,
to: MultiLocation,
(asset, amount): (MultiLocation, u128),
) -> Result<Assets, XcmError> {
from: Location,
to: Location,
(asset, amount): (Location, u128),
) -> Result<AssetsInHolding, XcmError> {
<XcmConfig::AssetTransactor as TransactAsset>::transfer_asset(
&MultiAsset { id: Concrete(asset), fun: Fungible(amount) },
&Asset { id: AssetId(asset), fun: Fungible(amount) },
&from,
&to,
// We aren't able to track the XCM that initiated the fee deposit, so we create a
@@ -329,9 +329,9 @@ impl<
{
pub fn do_teleport_assets<HrmpChannelOpener>(
origin: <Runtime as frame_system::Config>::RuntimeOrigin,
dest: MultiLocation,
beneficiary: MultiLocation,
(asset, amount): (MultiLocation, u128),
dest: Location,
beneficiary: Location,
(asset, amount): (Location, u128),
open_hrmp_channel: Option<(u32, u32)>,
included_head: HeaderFor<Runtime>,
slot_digest: &[u8],
@@ -356,7 +356,7 @@ impl<
origin,
Box::new(dest.into()),
Box::new(beneficiary.into()),
Box::new((Concrete(asset), amount).into()),
Box::new((AssetId(asset), amount).into()),
0,
)
}
@@ -379,12 +379,13 @@ impl<
]);
// execute xcm as parent origin
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
<<Runtime as pallet_xcm::Config>::XcmExecutor>::execute_xcm(
MultiLocation::parent(),
let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
<<Runtime as pallet_xcm::Config>::XcmExecutor>::prepare_and_execute(
Location::parent(),
xcm,
hash,
&mut hash,
Self::xcm_max_weight(XcmReceivedFrom::Parent),
Weight::zero(),
)
}
}
@@ -451,7 +452,7 @@ impl<
}
pub fn assert_metadata<Fungibles, AccountId>(
asset_id: impl Into<Fungibles::AssetId> + Copy,
asset_id: impl Into<Fungibles::AssetId> + Clone,
expected_name: &str,
expected_symbol: &str,
expected_decimals: u8,
@@ -459,20 +460,20 @@ pub fn assert_metadata<Fungibles, AccountId>(
Fungibles: frame_support::traits::fungibles::metadata::Inspect<AccountId>
+ frame_support::traits::fungibles::Inspect<AccountId>,
{
assert_eq!(Fungibles::name(asset_id.into()), Vec::from(expected_name),);
assert_eq!(Fungibles::symbol(asset_id.into()), Vec::from(expected_symbol),);
assert_eq!(Fungibles::name(asset_id.clone().into()), Vec::from(expected_name),);
assert_eq!(Fungibles::symbol(asset_id.clone().into()), Vec::from(expected_symbol),);
assert_eq!(Fungibles::decimals(asset_id.into()), expected_decimals);
}
pub fn assert_total<Fungibles, AccountId>(
asset_id: impl Into<Fungibles::AssetId> + Copy,
asset_id: impl Into<Fungibles::AssetId> + Clone,
expected_total_issuance: impl Into<Fungibles::Balance>,
expected_active_issuance: impl Into<Fungibles::Balance>,
) where
Fungibles: frame_support::traits::fungibles::metadata::Inspect<AccountId>
+ frame_support::traits::fungibles::Inspect<AccountId>,
{
assert_eq!(Fungibles::total_issuance(asset_id.into()), expected_total_issuance.into());
assert_eq!(Fungibles::total_issuance(asset_id.clone().into()), expected_total_issuance.into());
assert_eq!(Fungibles::active_issuance(asset_id.into()), expected_active_issuance.into());
}
@@ -32,7 +32,6 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
mod weights;
pub mod xcm_config;
use assets_common::MultiLocationForAssetId;
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
use frame_support::{
@@ -474,8 +473,8 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2;
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type AssetId = MultiLocationForAssetId;
type AssetIdParameter = MultiLocationForAssetId;
type AssetId = xcm::v3::Location;
type AssetIdParameter = xcm::v3::Location;
type Currency = Balances;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type ForceOrigin = EnsureRoot<AccountId>;
@@ -29,7 +29,7 @@ use super::{
};
use core::marker::PhantomData;
use frame_support::{
match_types, parameter_types,
parameter_types,
traits::{
fungibles::{self, Balanced, Credit},
ConstU32, Contains, ContainsPair, Everything, Get, Nothing,
@@ -59,13 +59,13 @@ use xcm_builder::{
use xcm_executor::{traits::JustTry, XcmExecutor};
parameter_types! {
pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = None;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -84,7 +84,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -115,7 +115,7 @@ pub type FungiblesTransactor = FungiblesAdapter<
JustTry,
>,
),
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -180,14 +180,18 @@ parameter_types! {
pub const MaxAssetsIntoHolding: u32 = 64;
}
match_types! {
pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
};
pub type CommonGoodAssetsParachain: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: X1(Parachain(1000)) }
};
pub struct ParentOrParentsExecutivePlurality;
impl Contains<Location> for ParentOrParentsExecutivePlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Executive, .. }]))
}
}
pub struct CommonGoodAssetsParachain;
impl Contains<Location> for CommonGoodAssetsParachain {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, [Parachain(1000)]))
}
}
pub type Barrier = TrailingSetTopicAsId<
@@ -224,15 +228,15 @@ pub type AccountIdOf<R> = <R as frame_system::Config>::AccountId;
/// Asset filter that allows all assets from a certain location matching asset id.
pub struct AssetPrefixFrom<Prefix, Origin>(PhantomData<(Prefix, Origin)>);
impl<Prefix, Origin> ContainsPair<MultiAsset, MultiLocation> for AssetPrefixFrom<Prefix, Origin>
impl<Prefix, Origin> ContainsPair<Asset, Location> for AssetPrefixFrom<Prefix, Origin>
where
Prefix: Get<MultiLocation>,
Origin: Get<MultiLocation>,
Prefix: Get<Location>,
Origin: Get<Location>,
{
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
fn contains(asset: &Asset, origin: &Location) -> bool {
let loc = Origin::get();
&loc == origin &&
matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) }
matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) }
if asset_loc.starts_with(&Prefix::get()))
}
}
@@ -241,12 +245,12 @@ type AssetsFrom<T> = AssetPrefixFrom<T, T>;
/// Asset filter that allows native/relay asset if coming from a certain location.
pub struct NativeAssetFrom<T>(PhantomData<T>);
impl<T: Get<MultiLocation>> ContainsPair<MultiAsset, MultiLocation> for NativeAssetFrom<T> {
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
impl<T: Get<Location>> ContainsPair<Asset, Location> for NativeAssetFrom<T> {
fn contains(asset: &Asset, origin: &Location) -> bool {
let loc = T::get();
&loc == origin &&
matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) }
if *asset_loc == MultiLocation::from(Parent))
matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) }
if *asset_loc == Location::from(Parent))
}
}
@@ -282,29 +286,34 @@ where
pub const TELEPORTABLE_ASSET_ID: u32 = 2;
parameter_types! {
/// The location that this chain recognizes as the Relay network's Asset Hub.
pub SystemAssetHubLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000)));
pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
// ALWAYS ensure that the index in PalletInstance stays up-to-date with
// the Relay Chain's Asset Hub's Assets pallet index
pub SystemAssetHubAssetsPalletLocation: MultiLocation =
MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50)));
pub AssetsPalletLocation: MultiLocation =
MultiLocation::new(0, X1(PalletInstance(50)));
pub SystemAssetHubAssetsPalletLocation: Location =
Location::new(1, [Parachain(1000), PalletInstance(50)]);
pub AssetsPalletLocation: Location =
Location::new(0, [PalletInstance(50)]);
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub LocalTeleportableToAssetHub: MultiLocation = MultiLocation::new(
pub LocalTeleportableToAssetHub: Location = Location::new(
0,
X2(PalletInstance(50), GeneralIndex(TELEPORTABLE_ASSET_ID.into()))
[PalletInstance(50), GeneralIndex(TELEPORTABLE_ASSET_ID.into())]
);
pub EthereumLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(EthereumNetwork::get())));
pub LocalTeleportableToAssetHubV3: xcm::v3::Location = xcm::v3::Location::new(
0,
[xcm::v3::Junction::PalletInstance(50), xcm::v3::Junction::GeneralIndex(TELEPORTABLE_ASSET_ID.into())]
);
pub EthereumLocation: Location = Location::new(2, [GlobalConsensus(EthereumNetwork::get())]);
}
/// Accepts asset with ID `AssetLocation` and is coming from `Origin` chain.
pub struct AssetFromChain<AssetLocation, Origin>(PhantomData<(AssetLocation, Origin)>);
impl<AssetLocation: Get<MultiLocation>, Origin: Get<MultiLocation>>
ContainsPair<MultiAsset, MultiLocation> for AssetFromChain<AssetLocation, Origin>
impl<AssetLocation: Get<Location>, Origin: Get<Location>> ContainsPair<Asset, Location>
for AssetFromChain<AssetLocation, Origin>
{
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
fn contains(asset: &Asset, origin: &Location) -> bool {
log::trace!(target: "xcm::contains", "AssetFromChain asset: {:?}, origin: {:?}", asset, origin);
*origin == Origin::get() && matches!(asset.id, Concrete(id) if id == AssetLocation::get())
*origin == Origin::get() &&
matches!(asset.id.clone(), AssetId(id) if id == AssetLocation::get())
}
}
@@ -398,8 +407,8 @@ impl cumulus_pallet_xcm::Config for Runtime {
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
pub struct XcmBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_assets::BenchmarkHelper<MultiLocation> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> MultiLocation {
MultiLocation { parents: 1, interior: X1(Parachain(id)) }
impl pallet_assets::BenchmarkHelper<xcm::v3::Location> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> xcm::v3::Location {
xcm::v3::Location::new(1, [xcm::v3::Junction::Parachain(id)])
}
}
@@ -42,10 +42,10 @@ pub use frame_support::{
construct_runtime, derive_impl,
dispatch::DispatchClass,
genesis_builder_helper::{build_config, create_default_config},
match_types, parameter_types,
parameter_types,
traits::{
AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything,
IsInVec, Nothing, Randomness,
AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
Everything, IsInVec, Nothing, Randomness,
},
weights::{
constants::{
@@ -330,14 +330,14 @@ impl pallet_message_queue::Config for Runtime {
impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
pub const RocLocation: MultiLocation = MultiLocation::parent();
pub const RocLocation: Location = Location::parent();
pub const RococoNetwork: Option<NetworkId> = Some(NetworkId::Rococo);
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
@@ -356,7 +356,7 @@ pub type CurrencyTransactor = CurrencyAdapter<
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RocLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -379,7 +379,7 @@ pub type FungiblesTransactor = FungiblesAdapter<
>,
JustTry,
>,
// Convert an XCM MultiLocation into a local account id:
// Convert an XCM Location into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
@@ -420,20 +420,22 @@ parameter_types! {
// One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
// One ROC buys 1 second of weight.
pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), ROC);
pub const WeightPrice: (Location, u128) = (Location::parent(), ROC);
pub const MaxInstructions: u32 = 100;
}
match_types! {
// The parent or the parent's unit plurality.
pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }
};
// The location recognized as the Relay network's Asset Hub.
pub type AssetHub: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: X1(Parachain(1000)) }
};
pub struct ParentOrParentsUnitPlurality;
impl Contains<Location> for ParentOrParentsUnitPlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Unit, .. }]))
}
}
pub struct AssetHub;
impl Contains<Location> for AssetHub {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, [Parachain(1000)]))
}
}
pub type Barrier = TrailingSetTopicAsId<(
@@ -451,11 +453,11 @@ pub type Barrier = TrailingSetTopicAsId<(
parameter_types! {
pub MaxAssetsIntoHolding: u32 = 64;
pub SystemAssetHubLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000)));
pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
// ALWAYS ensure that the index in PalletInstance stays up-to-date with
// the Relay Chain's Asset Hub's Assets pallet index
pub SystemAssetHubAssetsPalletLocation: MultiLocation =
MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50)));
pub SystemAssetHubAssetsPalletLocation: Location =
Location::new(1, [Parachain(1000), PalletInstance(50)]);
}
pub type Reserves = (NativeAsset, AssetsFrom<SystemAssetHubLocation>);