# 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
@@ -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()
)
)
}