diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 147fdc758..bad34207c 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -36,34 +36,34 @@ scale-info = { version = "2.10.0", default-features = false, features = ["derive serde = { version = "1.0.189" } parity-scale-codec = { version = "3.6.5", default-features = false, features = ["max-encoded-len"] } -cumulus-pallet-xcm = { version = "0.7.0", default-features = false } -cumulus-primitives-core = { version = "0.7.0", default-features = false } -frame-benchmarking = { version = "28.0.0", default-features = false } -frame-support = { version = "28.0.0", default-features = false } -frame-system = { version = "28.0.0", default-features = false } -pallet-balances = { version = "28.0.0", default-features = false } -pallet-elections-phragmen = { version = "29.0.0", default-features = false } -pallet-message-queue = { version = "31.0.0", default-features = false } -pallet-preimage = { version = "28.0.0", default-features = false } -pallet-root-testing = { version = "4.0.0", default-features = false } -pallet-scheduler = { version = "29.0.0", default-features = false } -pallet-treasury = { version = "27.0.0", default-features = false } -pallet-xcm = { version = "7.0.0", default-features = false } -polkadot-parachain-primitives = { version = "6.0.0", default-features = false } -polkadot-runtime-common = { version = "7.0.0", default-features = false } -polkadot-runtime-parachains = { version = "7.0.0", default-features = false } -sp-api = { version = "26.0.0", default-features = false } -sp-application-crypto = { version = "30.0.0", default-features = false } -sp-arithmetic = { version = "23.0.0", default-features = false } -sp-core = { version = "28.0.0", default-features = false } -sp-io = { version = "30.0.0", default-features = false } -sp-runtime = { version = "31.0.1", default-features = false } -sp-runtime-interface = { version = "24.0.0", default-features = false } -sp-staking = { version = "26.0.0", default-features = false } +cumulus-pallet-xcm = { version = "0.8.0", default-features = false } +cumulus-primitives-core = { version = "0.8.0", default-features = false } +frame-benchmarking = { version = "29.0.0", default-features = false } +frame-support = { version = "29.0.0", default-features = false } +frame-system = { version = "29.0.0", default-features = false } +pallet-balances = { version = "29.0.0", default-features = false } +pallet-elections-phragmen = { version = "30.0.0", default-features = false } +pallet-message-queue = { version = "32.0.0", default-features = false } +pallet-preimage = { version = "29.0.0", default-features = false } +pallet-root-testing = { version = "5.0.0", default-features = false } +pallet-scheduler = { version = "30.0.0", default-features = false } +pallet-treasury = { version = "28.0.0", default-features = false } +pallet-xcm = { version = "8.0.0", default-features = false } +polkadot-parachain-primitives = { version = "7.0.0", default-features = false } +polkadot-runtime-common = { version = "8.0.0", default-features = false } +polkadot-runtime-parachains = { version = "8.0.0", default-features = false } +sp-api = { version = "27.0.0", default-features = false } +sp-application-crypto = { version = "31.0.0", default-features = false } +sp-arithmetic = { version = "24.0.0", default-features = false } +sp-core = { version = "29.0.0", default-features = false } +sp-io = { version = "31.0.0", default-features = false } +sp-runtime = { version = "32.0.0", default-features = false } +sp-runtime-interface = { version = "25.0.0", default-features = false } +sp-staking = { version = "27.0.0", default-features = false } sp-std = { version = "14.0.0", default-features = false } -sp-storage = { version = "19.0.0", default-features = false } -xcm = { package = "staging-xcm", version = "7.0.0", default-features = false } -xcm-builder = { package = "staging-xcm-builder", version = "7.0.0", default-features = false } -xcm-executor = { package = "staging-xcm-executor", version = "7.0.0", default-features = false } +sp-storage = { version = "20.0.0", default-features = false } +xcm = { package = "staging-xcm", version = "8.0.0", default-features = false } +xcm-builder = { package = "staging-xcm-builder", version = "8.0.0", default-features = false } +xcm-executor = { package = "staging-xcm-executor", version = "8.0.0", default-features = false } -xcm-simulator = { version = "7.0.0" } +xcm-simulator = { version = "8.0.0" } diff --git a/README.md b/README.md index 8b9ad960f..a26d49340 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S #### Tokens - [asset-registry](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/asset-registry) - - Register asset / token metadata including name, decimals, and XCM MultiLocation + - Register asset / token metadata including name, decimals, and XCM Location - Partially based on the Acala’s asset-registry pallet, which includes some Acala specific code (e.g. EVM+) so not suitable for other teams. - [currencies](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/currencies) - Provide an unified interface to combine pallet-balances and orml-tokens diff --git a/asset-registry/src/impls.rs b/asset-registry/src/impls.rs index 52199e6b4..2a33094e3 100644 --- a/asset-registry/src/impls.rs +++ b/asset-registry/src/impls.rs @@ -12,10 +12,13 @@ use sp_runtime::{ ArithmeticError, FixedU128, }; use sp_std::prelude::*; -use xcm::v3::{prelude::*, Weight as XcmWeight}; -use xcm::VersionedMultiLocation; +use xcm::VersionedLocation; +use xcm::{ + v3, + v4::{prelude::*, Weight as XcmWeight}, +}; use xcm_builder::TakeRevenue; -use xcm_executor::{traits::WeightTrader, Assets}; +use xcm_executor::{traits::WeightTrader, AssetsInHolding}; /// Alias for AssetMetadata to improve readability (and to placate clippy) pub type DefaultAssetMetadata = @@ -54,7 +57,7 @@ where /// conversion rate. pub struct FixedRateAssetRegistryTrader(PhantomData

); impl WeightToFeeConverter for FixedRateAssetRegistryTrader

{ - fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option { + fn convert_weight_to_fee(location: &Location, weight: Weight) -> Option { let fee_per_second = P::get_fee_per_second(location)?; let weight_ratio = FixedU128::saturating_from_rational(weight.ref_time(), WEIGHT_REF_TIME_PER_SECOND); let amount = weight_ratio.saturating_mul_int(fee_per_second); @@ -66,7 +69,7 @@ impl WeightToFeeConverter for FixedRateAssetRegi /// bought weight. pub struct BoughtWeight { weight: Weight, - asset_location: MultiLocation, + asset_location: Location, amount: u128, } @@ -90,7 +93,12 @@ impl WeightTrader for AssetRegistryTrad } } - fn buy_weight(&mut self, weight: XcmWeight, payment: Assets, _context: &XcmContext) -> Result { + fn buy_weight( + &mut self, + weight: XcmWeight, + payment: AssetsInHolding, + _context: &XcmContext, + ) -> Result { log::trace!( target: "xcm::weight", "AssetRegistryTrader::buy_weight weight: {:?}, payment: {:?}", @@ -98,41 +106,40 @@ impl WeightTrader for AssetRegistryTrad ); for (asset, _) in payment.fungible.iter() { - if let AssetId::Concrete(ref location) = asset { - if matches!(self.bought_weight, Some(ref bought) if &bought.asset_location != location) { - // we already bought another asset - don't attempt to buy this one since - // we won't be able to refund it - continue; + let AssetId(ref location) = asset; + if matches!(self.bought_weight, Some(ref bought) if &bought.asset_location != location) { + // we already bought another asset - don't attempt to buy this one since + // we won't be able to refund it + continue; + } + + if let Some(fee_increase) = W::convert_weight_to_fee(location, weight) { + if fee_increase == 0 { + // if the fee is set very low it could lead to zero fees, in which case + // constructing the fee asset item to subtract from payment would fail. + // Therefore, provide early exit + return Ok(payment); } - if let Some(fee_increase) = W::convert_weight_to_fee(location, weight) { - if fee_increase == 0 { - // if the fee is set very low it could lead to zero fees, in which case - // constructing the fee asset item to subtract from payment would fail. - // Therefore, provide early exit - return Ok(payment); - } - - if let Ok(unused) = payment.clone().checked_sub((*asset, fee_increase).into()) { - let (existing_weight, existing_fee) = match self.bought_weight { - Some(ref x) => (x.weight, x.amount), - None => (Weight::zero(), 0), - }; - - self.bought_weight = Some(BoughtWeight { - amount: existing_fee.checked_add(fee_increase).ok_or(XcmError::Overflow)?, - weight: existing_weight.checked_add(&weight).ok_or(XcmError::Overflow)?, - asset_location: *location, - }); - return Ok(unused); - } + if let Ok(unused) = payment.clone().checked_sub((asset.clone(), fee_increase).into()) { + let (existing_weight, existing_fee) = match self.bought_weight { + Some(ref x) => (x.weight, x.amount), + None => (Weight::zero(), 0), + }; + + self.bought_weight = Some(BoughtWeight { + amount: existing_fee.checked_add(fee_increase).ok_or(XcmError::Overflow)?, + weight: existing_weight.checked_add(&weight).ok_or(XcmError::Overflow)?, + asset_location: location.clone(), + }); + return Ok(unused); } } } Err(XcmError::TooExpensive) } - fn refund_weight(&mut self, weight: XcmWeight, _context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: XcmWeight, _context: &XcmContext) -> Option { log::trace!(target: "xcm::weight", "AssetRegistryTrader::refund_weight weight: {:?}", weight); match self.bought_weight { @@ -144,7 +151,7 @@ impl WeightTrader for AssetRegistryTrad bought.weight = new_weight; bought.amount = new_amount; - Some((AssetId::Concrete(bought.asset_location), refunded_amount).into()) + Some((AssetId(bought.asset_location.clone()), refunded_amount).into()) } None => None, // nothing to refund } @@ -154,7 +161,7 @@ impl WeightTrader for AssetRegistryTrad impl Drop for AssetRegistryTrader { fn drop(&mut self) { if let Some(ref bought) = self.bought_weight { - R::take_revenue((AssetId::Concrete(bought.asset_location), bought.amount).into()); + R::take_revenue((AssetId(bought.asset_location.clone()), bought.amount).into()); } } } @@ -180,8 +187,8 @@ impl Inspect for Pallet { type CustomMetadata = T::CustomMetadata; type StringLimit = T::StringLimit; - fn asset_id(location: &MultiLocation) -> Option { - Pallet::::location_to_asset_id(location) + fn asset_id(location: &Location) -> Option { + Pallet::::location_to_asset_id(v3::Location::try_from(location.clone()).ok()?) } fn metadata(id: &Self::AssetId) -> Option> { @@ -189,13 +196,13 @@ impl Inspect for Pallet { } fn metadata_by_location( - location: &MultiLocation, + location: &Location, ) -> Option> { - Pallet::::fetch_metadata_by_location(location) + Pallet::::fetch_metadata_by_location(&v3::Location::try_from(location.clone()).ok()?) } - fn location(asset_id: &Self::AssetId) -> Result, DispatchError> { - Pallet::::multilocation(asset_id) + fn location(asset_id: &Self::AssetId) -> Result, DispatchError> { + Pallet::::location(asset_id).map(|l| l.and_then(|l| l.try_into().ok())) } } @@ -213,7 +220,7 @@ impl Mutate for Pallet { name: Option>, symbol: Option>, existential_deposit: Option, - location: Option>, + location: Option>, additional: Option, ) -> DispatchResult { Pallet::::do_update_asset( diff --git a/asset-registry/src/lib.rs b/asset-registry/src/lib.rs index 7f6e4caef..1f16ce894 100644 --- a/asset-registry/src/lib.rs +++ b/asset-registry/src/lib.rs @@ -14,10 +14,10 @@ use sp_runtime::{ DispatchResult, }; use sp_std::prelude::*; -use xcm::{v3::prelude::*, VersionedMultiLocation}; +use xcm::{v3::prelude::*, VersionedLocation}; pub use impls::*; -pub use module::*; +use module::*; pub use weights::WeightInfo; mod impls; @@ -67,7 +67,7 @@ pub mod module { pub enum Error { /// Asset was not found. AssetNotFound, - /// The version of the `VersionedMultiLocation` value used is not able + /// The version of the `VersionedLocation` value used is not able /// to be interpreted. BadVersion, /// The asset id is invalid. @@ -104,11 +104,11 @@ pub mod module { OptionQuery, >; - /// Maps a multilocation to an asset id - useful when processing xcm + /// Maps a location to an asset id - useful when processing xcm /// messages. #[pallet::storage] #[pallet::getter(fn location_to_asset_id)] - pub type LocationToAssetId = StorageMap<_, Twox64Concat, MultiLocation, T::AssetId, OptionQuery>; + pub type LocationToAssetId = StorageMap<_, Twox64Concat, Location, T::AssetId, OptionQuery>; /// The last processed asset id - used when assigning a sequential id. #[pallet::storage] @@ -172,7 +172,7 @@ pub mod module { name: Option>, symbol: Option>, existential_deposit: Option, - location: Option>, + location: Option>, additional: Option, ) -> DispatchResult { T::AuthorityOrigin::ensure_origin(origin, &Some(asset_id.clone()))?; @@ -239,7 +239,7 @@ impl Pallet { name: Option>, symbol: Option>, existential_deposit: Option, - location: Option>, + location: Option>, additional: Option, ) -> DispatchResult { Metadata::::try_mutate(&asset_id, |maybe_metadata| -> DispatchResult { @@ -281,13 +281,13 @@ impl Pallet { } pub fn fetch_metadata_by_location( - location: &MultiLocation, + location: &Location, ) -> Option> { let asset_id = LocationToAssetId::::get(location)?; Metadata::::get(asset_id) } - pub fn multilocation(asset_id: &T::AssetId) -> Result, DispatchError> { + pub fn location(asset_id: &T::AssetId) -> Result, DispatchError> { Metadata::::get(asset_id) .and_then(|metadata| { metadata @@ -300,14 +300,14 @@ impl Pallet { /// update LocationToAssetId mapping if the location changed fn do_update_location( asset_id: T::AssetId, - old_location: Option, - new_location: Option, + old_location: Option, + new_location: Option, ) -> DispatchResult { // Update `LocationToAssetId` only if location changed if new_location != old_location { // remove the old location lookup if it exists if let Some(ref old_location) = old_location { - let location: MultiLocation = old_location.clone().try_into().map_err(|()| Error::::BadVersion)?; + let location: Location = old_location.clone().try_into().map_err(|()| Error::::BadVersion)?; LocationToAssetId::::remove(location); } @@ -321,9 +321,9 @@ impl Pallet { } /// insert location into the LocationToAssetId map - fn do_insert_location(asset_id: T::AssetId, location: VersionedMultiLocation) -> DispatchResult { + fn do_insert_location(asset_id: T::AssetId, location: VersionedLocation) -> DispatchResult { // if the metadata contains a location, set the LocationToAssetId - let location: MultiLocation = location.try_into().map_err(|()| Error::::BadVersion)?; + let location: Location = location.try_into().map_err(|()| Error::::BadVersion)?; LocationToAssetId::::try_mutate(location, |maybe_asset_id| { ensure!(maybe_asset_id.is_none(), Error::::ConflictingLocation); *maybe_asset_id = Some(asset_id); diff --git a/asset-registry/src/mock/mod.rs b/asset-registry/src/mock/mod.rs index 092b3a194..9d1da52fb 100644 --- a/asset-registry/src/mock/mod.rs +++ b/asset-registry/src/mock/mod.rs @@ -8,6 +8,10 @@ use serde::{Deserialize, Serialize}; use sp_core::bounded::BoundedVec; use sp_io::TestExternalities; use sp_runtime::{traits::Convert, AccountId32, BuildStorage}; +use xcm::{ + v3, + v4::{Asset, Location}, +}; use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; pub mod para; @@ -51,10 +55,10 @@ pub enum CurrencyId { } pub struct CurrencyIdConvert; -impl Convert> for CurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { - match id { - CurrencyId::R => Some(Parent.into()), +impl Convert> for CurrencyIdConvert { + fn convert(id: CurrencyId) -> Option { + let loc: Option = match id { + CurrencyId::R => Some(Parent.try_into().unwrap()), CurrencyId::A => Some( ( Parent, @@ -103,50 +107,57 @@ impl Convert> for CurrencyIdConvert { ) .into(), ), - CurrencyId::RegisteredAsset(id) => AssetRegistry::multilocation(&id).unwrap_or_default(), - } + CurrencyId::RegisteredAsset(id) => AssetRegistry::location(&id).unwrap_or_default(), + }; + loc.and_then(|l| l.try_into().ok()) } } -impl Convert> for CurrencyIdConvert { - fn convert(l: MultiLocation) -> Option { +impl Convert> for CurrencyIdConvert { + fn convert(l: Location) -> Option { + use xcm::v4::Junction::*; + let a: Vec = "A".into(); let a1: Vec = "A1".into(); let b: Vec = "B".into(); let b1: Vec = "B1".into(); let b2: Vec = "B2".into(); let d: Vec = "D".into(); - if l == MultiLocation::parent() { + if l == Location::parent() { return Some(CurrencyId::R); } - let currency_id = match l.clone() { - MultiLocation { parents, interior } if parents == 1 => match interior { - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X2(Parachain(4), GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D), + let currency_id = match l.clone().unpack() { + (parents, interior) if parents == 1 => match interior { + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [Parachain(4), GeneralKey { data, .. }] if data.to_vec() == d => Some(CurrencyId::D), _ => None, }, - MultiLocation { parents, interior } if parents == 0 => match interior { - X1(GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X1(GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X1(GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X1(GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X1(GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X1(GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D), + (parents, interior) if parents == 0 => match interior { + [GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [GeneralKey { data, .. }] if data.to_vec() == d => Some(CurrencyId::D), _ => None, }, _ => None, }; - currency_id.or_else(|| AssetRegistry::location_to_asset_id(&l).map(CurrencyId::RegisteredAsset)) + currency_id.or_else(|| { + let loc = v3::Location::try_from(l.clone()).ok()?; + AssetRegistry::location_to_asset_id(&loc).map(CurrencyId::RegisteredAsset) + }) } } -impl Convert> for CurrencyIdConvert { - fn convert(a: MultiAsset) -> Option { - if let MultiAsset { +impl Convert> for CurrencyIdConvert { + fn convert(a: Asset) -> Option { + use xcm::v4::prelude::*; + if let Asset { fun: Fungible(_), - id: Concrete(id), + id: AssetId(id), } = a { Self::convert(id) diff --git a/asset-registry/src/mock/para.rs b/asset-registry/src/mock/para.rs index 72a48c043..55d96df9f 100644 --- a/asset-registry/src/mock/para.rs +++ b/asset-registry/src/mock/para.rs @@ -2,14 +2,14 @@ use super::{Amount, Balance, CurrencyId, CurrencyIdConvert, ParachainXcmRouter}; use crate as orml_asset_registry; +use crate::impls::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use cumulus_primitives_core::AggregateMessageOrigin; use frame_support::{ - construct_runtime, derive_impl, match_types, ord_parameter_types, parameter_types, - traits::{ConstU128, ConstU32, EnsureOrigin, EnsureOriginWithArg, Everything, Nothing}, + construct_runtime, derive_impl, ord_parameter_types, parameter_types, + traits::{ConstU128, ConstU32, Contains, EnsureOrigin, EnsureOriginWithArg, Everything, Nothing}, PalletId, }; use frame_system::{EnsureRoot, EnsureSignedBy}; -use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{ location::{AbsoluteReserveProvider, RelativeReserveProvider}, parameter_type_with_key, FixedConversionRateProvider, MultiCurrency, @@ -23,7 +23,7 @@ use sp_runtime::{ traits::{AccountIdConversion, Convert, IdentityLookup}, AccountId32, }; -use xcm::v3::{prelude::*, Weight}; +use xcm::v4::{prelude::*, Weight}; use xcm_builder::{ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, @@ -54,7 +54,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } @@ -137,8 +136,8 @@ impl orml_asset_registry::Config for Runtime { parameter_types! { pub const RelayNetwork: NetworkId = NetworkId::Kusama; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())].into(); } pub type LocationToAccountId = ( @@ -175,9 +174,9 @@ parameter_types! { pub struct ToTreasury; impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - if let MultiAsset { - id: Concrete(location), + fn take_revenue(revenue: Asset) { + if let Asset { + id: AssetId(location), fun: Fungible(amount), } = revenue { @@ -193,8 +192,8 @@ pub type AssetRegistryWeightTrader = pub struct MyFixedConversionRateProvider; impl FixedConversionRateProvider for MyFixedConversionRateProvider { - fn get_fee_per_second(location: &MultiLocation) -> Option { - let metadata = AssetRegistry::fetch_metadata_by_location(location)?; + fn get_fee_per_second(location: &Location) -> Option { + let metadata = AssetRegistry::fetch_metadata_by_location(&location.clone().try_into().unwrap())?; Some(metadata.additional.fee_per_second) } } @@ -244,7 +243,7 @@ impl cumulus_pallet_xcm::Config for Runtime { pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { - pub SelfLocation: MultiLocation = MultiLocation::here(); + pub SelfLocation: Location = Location::here(); pub const MaxAssetsForTransfer: usize = 3; } @@ -274,31 +273,35 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); } -pub struct AccountIdToMultiLocation; -impl Convert for AccountIdToMultiLocation { - fn convert(account: AccountId) -> MultiLocation { - X1(Junction::AccountId32 { +pub struct AccountIdToLocation; +impl Convert for AccountIdToLocation { + fn convert(account: AccountId) -> Location { + [Junction::AccountId32 { network: None, id: account.into(), - }) + }] .into() } } -match_types! { - pub type ParentOrParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(1), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(2), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(3), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(4), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(100), Junction::AccountId32 { .. }) } - }; +pub struct ParentOrParachains; +impl Contains for ParentOrParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Junction::AccountId32 { .. }]) + | (1, [Junction::AccountId32 { .. }]) + | (1, [Parachain(1), Junction::AccountId32 { .. }]) + | (1, [Parachain(2), Junction::AccountId32 { .. }]) + | (1, [Parachain(3), Junction::AccountId32 { .. }]) + | (1, [Parachain(4), Junction::AccountId32 { .. }]) + | (1, [Parachain(100), Junction::AccountId32 { .. }]) + ) + } } parameter_type_with_key! { - pub ParachainMinFee: |location: MultiLocation| -> Option { + pub ParachainMinFee: |location: Location| -> Option { #[allow(clippy::match_ref_pats)] // false positive match (location.parents, location.first_interior()) { (1, Some(Parachain(2))) => Some(40), @@ -312,9 +315,9 @@ impl orml_xtokens::Config for Runtime { type Balance = Balance; type CurrencyId = CurrencyId; type CurrencyIdConvert = CurrencyIdConvert; - type AccountIdToMultiLocation = AccountIdToMultiLocation; + type AccountIdToLocation = AccountIdToLocation; type SelfLocation = SelfLocation; - type MultiLocationsFilter = ParentOrParachains; + type LocationsFilter = ParentOrParachains; type MinXcmFee = ParachainMinFee; type XcmExecutor = XcmExecutor; type Weigher = FixedWeightBounds; diff --git a/asset-registry/src/mock/relay.rs b/asset-registry/src/mock/relay.rs index a064231b0..146d71b0e 100644 --- a/asset-registry/src/mock/relay.rs +++ b/asset-registry/src/mock/relay.rs @@ -12,7 +12,7 @@ use polkadot_runtime_parachains::{ origin, shared, }; use sp_runtime::{traits::IdentityLookup, AccountId32}; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, FixedWeightBounds, FungibleAdapter, IsConcrete, SignedAccountId32AsNative, SignedToAccountId32, @@ -44,20 +44,21 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } -impl shared::Config for Runtime {} +impl shared::Config for Runtime { + type DisabledValidators = (); +} impl configuration::Config for Runtime { type WeightInfo = configuration::TestWeightInfo; } parameter_types! { - pub KsmLocation: MultiLocation = Here.into(); + pub KsmLocation: Location = Here.into(); pub const KusamaNetwork: NetworkId = NetworkId::Kusama; - pub UniversalLocation: InteriorMultiLocation = Here; + pub UniversalLocation: InteriorLocation = Here; } pub type SovereignAccountOf = ( @@ -114,7 +115,7 @@ impl Config for XcmConfig { pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { - pub SelfLocation: MultiLocation = MultiLocation::here(); + pub SelfLocation: Location = Location::here(); } impl pallet_xcm::Config for Runtime { diff --git a/asset-registry/src/tests.rs b/asset-registry/src/tests.rs index 36a840f26..4ef4311b4 100644 --- a/asset-registry/src/tests.rs +++ b/asset-registry/src/tests.rs @@ -1,20 +1,26 @@ #![cfg(test)] -use super::*; +use super::mock; use crate as orml_asset_registry; -use crate::tests::para::{AdminAssetTwo, AssetRegistry, CustomMetadata, RuntimeOrigin, Tokens, TreasuryAccount}; -use frame_support::{assert_noop, assert_ok}; +use crate::{ + tests::para::{AdminAssetTwo, AssetRegistry, CustomMetadata, RuntimeOrigin, Tokens, TreasuryAccount}, + Error, LastAssetId, Metadata, +}; +use frame_support::{assert_noop, assert_ok, pallet_prelude::*}; use mock::{para::RuntimeCall, *}; +use orml_traits::asset_registry::AssetMetadata; use orml_traits::MultiCurrency; use polkadot_parachain_primitives::primitives::Sibling; +use scale_info::TypeInfo; use sp_runtime::{ traits::{AccountIdConversion, BadOrigin, Dispatchable}, AccountId32, }; +use xcm::{v3, v4::prelude::*, VersionedLocation}; use xcm_simulator::TestExt; -type OldMultiLocation = xcm::v2::MultiLocation; +type OldLocation = xcm::v2::MultiLocation; type OldJunctions = xcm::v2::Junctions; type OldJunction = xcm::v2::Junction; @@ -49,18 +55,17 @@ fn dummy_metadata() -> AssetMetadata< CustomMetadata, ::StringLimit, > { + let loc: VersionedLocation = Location::new( + 1, + [Parachain(1), Junction::from(BoundedVec::try_from(vec![0]).unwrap())], + ) + .into(); AssetMetadata { decimals: 12, name: BoundedVec::truncate_from("para A native token".as_bytes().to_vec()), symbol: BoundedVec::truncate_from("paraA".as_bytes().to_vec()), existential_deposit: 0, - location: Some( - MultiLocation::new( - 1, - X2(Parachain(1), Junction::from(BoundedVec::try_from(vec![0]).unwrap())), - ) - .into(), - ), + location: Some(loc), additional: CustomMetadata { fee_per_second: 1_000_000_000_000, }, @@ -110,8 +115,10 @@ fn send_self_parachain_asset_to_sibling() { }); ParaA::execute_with(|| { - metadata.location = - Some(MultiLocation::new(0, X1(Junction::from(BoundedVec::try_from(vec![0]).unwrap()))).into()); + metadata.location = Some(Into::::into(Location::new( + 0, + [Junction::from(BoundedVec::try_from(vec![0]).unwrap())], + ))); AssetRegistry::register_asset(RuntimeOrigin::root(), metadata, None).unwrap(); assert_ok!(ParaTokens::deposit(CurrencyId::RegisteredAsset(1), &ALICE, 1_000)); @@ -121,15 +128,15 @@ fn send_self_parachain_asset_to_sibling() { CurrencyId::RegisteredAsset(1), 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -164,9 +171,9 @@ fn send_sibling_asset_to_non_reserve_sibling() { RuntimeOrigin::root(), AssetMetadata { location: Some( - MultiLocation::new( + Location::new( 1, - X2(Parachain(2), Junction::from(BoundedVec::try_from(vec![0]).unwrap())), + [Parachain(2), Junction::from(BoundedVec::try_from(vec![0]).unwrap())], ) .into(), ), @@ -182,9 +189,7 @@ fn send_sibling_asset_to_non_reserve_sibling() { AssetRegistry::register_asset( RuntimeOrigin::root(), AssetMetadata { - location: Some( - MultiLocation::new(0, X1(Junction::from(BoundedVec::try_from(vec![0]).unwrap()))).into(), - ), + location: Some(Location::new(0, [Junction::from(BoundedVec::try_from(vec![0]).unwrap())]).into()), ..dummy_metadata() }, None, @@ -202,9 +207,9 @@ fn send_sibling_asset_to_non_reserve_sibling() { RuntimeOrigin::root(), AssetMetadata { location: Some( - MultiLocation::new( + Location::new( 1, - X2(Parachain(2), Junction::from(BoundedVec::try_from(vec![0]).unwrap())), + [Parachain(2), Junction::from(BoundedVec::try_from(vec![0]).unwrap())], ) .into(), ), @@ -221,15 +226,15 @@ fn send_sibling_asset_to_non_reserve_sibling() { CurrencyId::RegisteredAsset(1), 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(3), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -267,9 +272,9 @@ fn test_sequential_id_normal_behavior() { name: BoundedVec::truncate_from("para A native token 2".as_bytes().to_vec()), symbol: BoundedVec::truncate_from("paraA2".as_bytes().to_vec()), location: Some( - MultiLocation::new( + Location::new( 1, - X2(Parachain(1), Junction::from(BoundedVec::try_from(vec![1]).unwrap())), + [Parachain(1), Junction::from(BoundedVec::try_from(vec![1]).unwrap())], ) .into(), ), @@ -313,7 +318,7 @@ fn test_fixed_rate_asset_trader() { ParaA::execute_with(|| { let para_a_metadata = AssetMetadata { - location: Some(MultiLocation::new(0, X1(Junction::from(BoundedVec::try_from(vec![0]).unwrap()))).into()), + location: Some(Location::new(0, [Junction::from(BoundedVec::try_from(vec![0]).unwrap())]).into()), ..metadata.clone() }; AssetRegistry::register_asset(RuntimeOrigin::root(), para_a_metadata, None).unwrap(); @@ -325,15 +330,15 @@ fn test_fixed_rate_asset_trader() { CurrencyId::RegisteredAsset(1), 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -376,15 +381,15 @@ fn test_fixed_rate_asset_trader() { CurrencyId::RegisteredAsset(1), 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -466,9 +471,9 @@ fn test_update_metadata_works() { symbol: BoundedVec::truncate_from("paraA2".as_bytes().to_vec()), existential_deposit: 1, location: Some( - MultiLocation::new( + Location::new( 1, - X2(Parachain(1), Junction::from(BoundedVec::try_from(vec![1]).unwrap())), + [Parachain(1), Junction::from(BoundedVec::try_from(vec![1]).unwrap())], ) .into(), ), @@ -487,8 +492,8 @@ fn test_update_metadata_works() { Some(new_metadata.additional.clone()) )); - let old_location: MultiLocation = old_metadata.location.unwrap().try_into().unwrap(); - let new_location: MultiLocation = new_metadata.location.clone().unwrap().try_into().unwrap(); + let old_location: v3::Location = old_metadata.location.unwrap().try_into().unwrap(); + let new_location: v3::Location = new_metadata.location.clone().unwrap().try_into().unwrap(); // check that the old location was removed and the new one added assert_eq!(AssetRegistry::location_to_asset_id(old_location), None); @@ -579,13 +584,13 @@ fn test_asset_authority() { #[test] fn test_v2_to_v3_incompatible_multilocation() { - // Assert that V2 and V3 Multilocation both are encoded differently + // Assert that V2 and V3 Location both are encoded differently assert!( - OldMultiLocation::new( + OldLocation::new( 0, OldJunctions::X1(OldJunction::GeneralKey(vec![0].try_into().unwrap())) ) - .encode() != MultiLocation::new(0, X1(Junction::from(BoundedVec::try_from(vec![0]).unwrap()))).encode() + .encode() != Location::new(0, [Junction::from(BoundedVec::try_from(vec![0]).unwrap())]).encode() ); } @@ -614,7 +619,7 @@ fn test_decode_bounded_vec() { pub name: Vec, pub symbol: Vec, pub existential_deposit: Balance, - pub location: Option, + pub location: Option, pub additional: CustomMetadata, } } diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index 8c17bae4c..e00f1b4d0 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -45,7 +45,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } diff --git a/traits/src/asset_registry.rs b/traits/src/asset_registry.rs index c119d29df..903838cea 100644 --- a/traits/src/asset_registry.rs +++ b/traits/src/asset_registry.rs @@ -1,15 +1,15 @@ use frame_support::pallet_prelude::*; use sp_runtime::DispatchResult; use sp_std::fmt::Debug; -use xcm::v3::prelude::*; -use xcm::VersionedMultiLocation; +use xcm::v4::prelude::*; +use xcm::VersionedLocation; pub trait WeightToFeeConverter { - fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option; + fn convert_weight_to_fee(location: &Location, weight: Weight) -> Option; } pub trait FixedConversionRateProvider { - fn get_fee_per_second(location: &MultiLocation) -> Option; + fn get_fee_per_second(location: &Location) -> Option; } pub trait AssetProcessor { @@ -33,7 +33,7 @@ where pub name: BoundedVec, pub symbol: BoundedVec, pub existential_deposit: Balance, - pub location: Option, + pub location: Option, pub additional: CustomMetadata, } @@ -47,14 +47,14 @@ pub trait Inspect { /// Name and symbol string limit type StringLimit: Get; - fn asset_id(location: &MultiLocation) -> Option; + fn asset_id(location: &Location) -> Option; fn metadata( asset_id: &Self::AssetId, ) -> Option>; fn metadata_by_location( - location: &MultiLocation, + location: &Location, ) -> Option>; - fn location(asset_id: &Self::AssetId) -> Result, DispatchError>; + fn location(asset_id: &Self::AssetId) -> Result, DispatchError>; } pub trait Mutate: Inspect { @@ -69,7 +69,7 @@ pub trait Mutate: Inspect { name: Option>, symbol: Option>, existential_deposit: Option, - location: Option>, + location: Option>, additional: Option, ) -> DispatchResult; } diff --git a/traits/src/location.rs b/traits/src/location.rs index aad202300..761304424 100644 --- a/traits/src/location.rs +++ b/traits/src/location.rs @@ -1,39 +1,39 @@ use sp_core::{bounded::BoundedVec, ConstU32}; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; pub trait Parse { /// Returns the "chain" location part. It could be parent, sibling /// parachain, or child parachain. - fn chain_part(&self) -> Option; + fn chain_part(&self) -> Option; /// Returns "non-chain" location part. - fn non_chain_part(&self) -> Option; + fn non_chain_part(&self) -> Option; } fn is_chain_junction(junction: Option<&Junction>) -> bool { matches!(junction, Some(Parachain(_))) } -impl Parse for MultiLocation { - fn chain_part(&self) -> Option { +impl Parse for Location { + fn chain_part(&self) -> Option { match (self.parents, self.first_interior()) { // sibling parachain - (1, Some(Parachain(id))) => Some(MultiLocation::new(1, X1(Parachain(*id)))), + (1, Some(Parachain(id))) => Some(Location::new(1, [Parachain(*id)])), // parent - (1, _) => Some(MultiLocation::parent()), + (1, _) => Some(Location::parent()), // children parachain - (0, Some(Parachain(id))) => Some(MultiLocation::new(0, X1(Parachain(*id)))), + (0, Some(Parachain(id))) => Some(Location::new(0, [Parachain(*id)])), _ => None, } } - fn non_chain_part(&self) -> Option { - let mut junctions = *self.interior(); + fn non_chain_part(&self) -> Option { + let mut junctions = self.interior().clone(); while is_chain_junction(junctions.first()) { let _ = junctions.take_first(); } if junctions != Here { - Some(MultiLocation::new(0, junctions)) + Some(Location::new(0, junctions)) } else { None } @@ -42,19 +42,16 @@ impl Parse for MultiLocation { pub trait Reserve { /// Returns assets reserve location. - fn reserve(asset: &MultiAsset) -> Option; + fn reserve(asset: &Asset) -> Option; } // Provide reserve in absolute path view pub struct AbsoluteReserveProvider; impl Reserve for AbsoluteReserveProvider { - fn reserve(asset: &MultiAsset) -> Option { - if let Concrete(location) = &asset.id { - location.chain_part() - } else { - None - } + fn reserve(asset: &Asset) -> Option { + let AssetId(location) = &asset.id; + location.chain_part() } } @@ -63,26 +60,23 @@ impl Reserve for AbsoluteReserveProvider { pub struct RelativeReserveProvider; impl Reserve for RelativeReserveProvider { - fn reserve(asset: &MultiAsset) -> Option { - if let Concrete(location) = &asset.id { - if location.parents == 0 && !is_chain_junction(location.first_interior()) { - Some(MultiLocation::here()) - } else { - location.chain_part() - } + fn reserve(asset: &Asset) -> Option { + let AssetId(location) = &asset.id; + if location.parents == 0 && !is_chain_junction(location.first_interior()) { + Some(Location::here()) } else { - None + location.chain_part() } } } pub trait RelativeLocations { - fn sibling_parachain_general_key(para_id: u32, general_key: BoundedVec>) -> MultiLocation; + fn sibling_parachain_general_key(para_id: u32, general_key: BoundedVec>) -> Location; } -impl RelativeLocations for MultiLocation { - fn sibling_parachain_general_key(para_id: u32, general_key: BoundedVec>) -> MultiLocation { - return MultiLocation::new(1, X2(Parachain(para_id), general_key.as_bounded_slice().into())); +impl RelativeLocations for Location { + fn sibling_parachain_general_key(para_id: u32, general_key: BoundedVec>) -> Location { + return Location::new(1, [Parachain(para_id), general_key.as_bounded_slice().into()]); } } @@ -93,42 +87,42 @@ mod tests { const PARACHAIN: Junction = Parachain(1); const GENERAL_INDEX: Junction = GeneralIndex(1); - fn concrete_fungible(id: MultiLocation) -> MultiAsset { + fn concrete_fungible(id: Location) -> Asset { (id, 1).into() } #[test] fn parent_as_reserve_chain() { assert_eq!( - AbsoluteReserveProvider::reserve(&concrete_fungible(MultiLocation::new(1, X1(GENERAL_INDEX)))), - Some(MultiLocation::parent()) + AbsoluteReserveProvider::reserve(&concrete_fungible(Location::new(1, [GENERAL_INDEX]))), + Some(Location::parent()) ); assert_eq!( - RelativeReserveProvider::reserve(&concrete_fungible(MultiLocation::new(1, X1(GENERAL_INDEX)))), - Some(MultiLocation::parent()) + RelativeReserveProvider::reserve(&concrete_fungible(Location::new(1, [GENERAL_INDEX]))), + Some(Location::parent()) ); } #[test] fn sibling_parachain_as_reserve_chain() { assert_eq!( - AbsoluteReserveProvider::reserve(&concrete_fungible(MultiLocation::new(1, X2(PARACHAIN, GENERAL_INDEX)))), - Some(MultiLocation::new(1, X1(PARACHAIN))) + AbsoluteReserveProvider::reserve(&concrete_fungible(Location::new(1, [PARACHAIN, GENERAL_INDEX]))), + Some(Location::new(1, [PARACHAIN])) ); assert_eq!( - RelativeReserveProvider::reserve(&concrete_fungible(MultiLocation::new(1, X2(PARACHAIN, GENERAL_INDEX)))), - Some(MultiLocation::new(1, X1(PARACHAIN))) + RelativeReserveProvider::reserve(&concrete_fungible(Location::new(1, [PARACHAIN, GENERAL_INDEX]))), + Some(Location::new(1, [PARACHAIN])) ); } #[test] fn child_parachain_as_reserve_chain() { assert_eq!( - AbsoluteReserveProvider::reserve(&concrete_fungible(MultiLocation::new(0, X2(PARACHAIN, GENERAL_INDEX)))), + AbsoluteReserveProvider::reserve(&concrete_fungible(Location::new(0, [PARACHAIN, GENERAL_INDEX]))), Some(PARACHAIN.into()) ); assert_eq!( - RelativeReserveProvider::reserve(&concrete_fungible(MultiLocation::new(0, X2(PARACHAIN, GENERAL_INDEX)))), + RelativeReserveProvider::reserve(&concrete_fungible(Location::new(0, [PARACHAIN, GENERAL_INDEX]))), Some(PARACHAIN.into()) ); } @@ -136,41 +130,41 @@ mod tests { #[test] fn no_reserve_chain_for_absolute_self_for_relative() { assert_eq!( - AbsoluteReserveProvider::reserve(&concrete_fungible(MultiLocation::new( + AbsoluteReserveProvider::reserve(&concrete_fungible(Location::new( 0, - X1(Junction::from(BoundedVec::try_from(b"DOT".to_vec()).unwrap())) + [Junction::from(BoundedVec::try_from(b"DOT".to_vec()).unwrap())] ))), None ); assert_eq!( - RelativeReserveProvider::reserve(&concrete_fungible(MultiLocation::new( + RelativeReserveProvider::reserve(&concrete_fungible(Location::new( 0, - X1(Junction::from(BoundedVec::try_from(b"DOT".to_vec()).unwrap())) + [Junction::from(BoundedVec::try_from(b"DOT".to_vec()).unwrap())] ))), - Some(MultiLocation::here()) + Some(Location::here()) ); } #[test] fn non_chain_part_works() { - assert_eq!(MultiLocation::parent().non_chain_part(), None); - assert_eq!(MultiLocation::new(1, X1(PARACHAIN)).non_chain_part(), None); - assert_eq!(MultiLocation::new(0, X1(PARACHAIN)).non_chain_part(), None); + assert_eq!(Location::parent().non_chain_part(), None); + assert_eq!(Location::new(1, [PARACHAIN]).non_chain_part(), None); + assert_eq!(Location::new(0, [PARACHAIN]).non_chain_part(), None); assert_eq!( - MultiLocation::new(1, X1(GENERAL_INDEX)).non_chain_part(), + Location::new(1, [GENERAL_INDEX]).non_chain_part(), Some(GENERAL_INDEX.into()) ); assert_eq!( - MultiLocation::new(1, X2(GENERAL_INDEX, GENERAL_INDEX)).non_chain_part(), + Location::new(1, [GENERAL_INDEX, GENERAL_INDEX]).non_chain_part(), Some((GENERAL_INDEX, GENERAL_INDEX).into()) ); assert_eq!( - MultiLocation::new(1, X2(PARACHAIN, GENERAL_INDEX)).non_chain_part(), + Location::new(1, [PARACHAIN, GENERAL_INDEX]).non_chain_part(), Some(GENERAL_INDEX.into()) ); assert_eq!( - MultiLocation::new(0, X2(PARACHAIN, GENERAL_INDEX)).non_chain_part(), + Location::new(0, [PARACHAIN, GENERAL_INDEX]).non_chain_part(), Some(GENERAL_INDEX.into()) ); } diff --git a/traits/src/multi_asset.rs b/traits/src/multi_asset.rs index 3697467fc..1bb3217ad 100644 --- a/traits/src/multi_asset.rs +++ b/traits/src/multi_asset.rs @@ -1,23 +1,19 @@ use sp_core::{bounded::BoundedVec, ConstU32}; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; use crate::location::RelativeLocations; pub trait ConcreteFungibleAsset { - fn sibling_parachain_asset(para_id: u32, general_key: BoundedVec>, amount: u128) -> MultiAsset; - fn parent_asset(amount: u128) -> MultiAsset; + fn sibling_parachain_asset(para_id: u32, general_key: BoundedVec>, amount: u128) -> Asset; + fn parent_asset(amount: u128) -> Asset; } -impl ConcreteFungibleAsset for MultiAsset { - fn sibling_parachain_asset(para_id: u32, general_key: BoundedVec>, amount: u128) -> MultiAsset { - ( - MultiLocation::sibling_parachain_general_key(para_id, general_key), - amount, - ) - .into() +impl ConcreteFungibleAsset for Asset { + fn sibling_parachain_asset(para_id: u32, general_key: BoundedVec>, amount: u128) -> Asset { + (Location::sibling_parachain_general_key(para_id, general_key), amount).into() } - fn parent_asset(amount: u128) -> MultiAsset { - (MultiLocation::parent(), amount).into() + fn parent_asset(amount: u128) -> Asset { + (Location::parent(), amount).into() } } diff --git a/traits/src/xcm_transfer.rs b/traits/src/xcm_transfer.rs index 90731fdd3..bfc74c919 100644 --- a/traits/src/xcm_transfer.rs +++ b/traits/src/xcm_transfer.rs @@ -1,14 +1,14 @@ use sp_runtime::DispatchError; use sp_std::vec::Vec; use xcm::{ - v3::{prelude::*, Weight}, - VersionedMultiAsset, VersionedMultiAssets, VersionedMultiLocation, + v4::{prelude::*, Weight}, + VersionedAsset, VersionedAssets, VersionedLocation, }; pub struct Transferred { pub sender: AccountId, - pub assets: MultiAssets, - pub fee: MultiAsset, - pub dest: MultiLocation, + pub assets: Assets, + pub fee: Asset, + pub dest: Location, } /// Abstraction over cross-chain token transfers. @@ -18,15 +18,15 @@ pub trait XcmTransfer { who: AccountId, currency_id: CurrencyId, amount: Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; - /// Transfer `MultiAsset` assets. + /// Transfer `Asset` assets. fn transfer_multiasset( who: AccountId, - asset: MultiAsset, - dest: MultiLocation, + asset: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; @@ -36,16 +36,16 @@ pub trait XcmTransfer { currency_id: CurrencyId, amount: Balance, fee: Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; - /// Transfer `MultiAsset` specifying the fee and amount as separate. + /// Transfer `Asset` specifying the fee and amount as separate. fn transfer_multiasset_with_fee( who: AccountId, - asset: MultiAsset, - fee: MultiAsset, - dest: MultiLocation, + asset: Asset, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; @@ -54,31 +54,27 @@ pub trait XcmTransfer { who: AccountId, currencies: Vec<(CurrencyId, Balance)>, fee_item: u32, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; - /// Transfer several `MultiAsset` specifying the item to be used as fee. + /// Transfer several `Asset` specifying the item to be used as fee. fn transfer_multiassets( who: AccountId, - assets: MultiAssets, - fee: MultiAsset, - dest: MultiLocation, + assets: Assets, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError>; } pub trait XtokensWeightInfo { - fn weight_of_transfer_multiasset(asset: &VersionedMultiAsset, dest: &VersionedMultiLocation) -> Weight; - fn weight_of_transfer(currency_id: CurrencyId, amount: Balance, dest: &VersionedMultiLocation) -> Weight; + fn weight_of_transfer_multiasset(asset: &VersionedAsset, dest: &VersionedLocation) -> Weight; + fn weight_of_transfer(currency_id: CurrencyId, amount: Balance, dest: &VersionedLocation) -> Weight; fn weight_of_transfer_multicurrencies( currencies: &[(CurrencyId, Balance)], fee_item: &u32, - dest: &VersionedMultiLocation, - ) -> Weight; - fn weight_of_transfer_multiassets( - assets: &VersionedMultiAssets, - fee_item: &u32, - dest: &VersionedMultiLocation, + dest: &VersionedLocation, ) -> Weight; + fn weight_of_transfer_multiassets(assets: &VersionedAssets, fee_item: &u32, dest: &VersionedLocation) -> Weight; } diff --git a/unknown-tokens/src/lib.rs b/unknown-tokens/src/lib.rs index 1cc6caf67..abe0eebaf 100644 --- a/unknown-tokens/src/lib.rs +++ b/unknown-tokens/src/lib.rs @@ -3,7 +3,7 @@ use frame_support::pallet_prelude::*; use sp_std::vec::Vec; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; use orml_xcm_support::UnknownAsset; @@ -25,9 +25,9 @@ pub mod module { #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { /// Deposit success. - Deposited { asset: MultiAsset, who: MultiLocation }, + Deposited { asset: Asset, who: Location }, /// Withdraw success. - Withdrawn { asset: MultiAsset, who: MultiLocation }, + Withdrawn { asset: Asset, who: Location }, } #[pallet::error] @@ -54,7 +54,7 @@ pub mod module { #[pallet::storage] #[pallet::getter(fn concrete_fungible_balances)] pub(crate) type ConcreteFungibleBalances = - StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, MultiLocation, u128, ValueQuery>; + StorageDoubleMap<_, Blake2_128Concat, Location, Blake2_128Concat, Location, u128, ValueQuery>; /// Abstract fungible balances under a given location and a abstract /// fungible id. @@ -63,59 +63,45 @@ pub mod module { #[pallet::storage] #[pallet::getter(fn abstract_fungible_balances)] pub(crate) type AbstractFungibleBalances = - StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, Vec, u128, ValueQuery>; + StorageDoubleMap<_, Blake2_128Concat, Location, Blake2_128Concat, Vec, u128, ValueQuery>; } impl UnknownAsset for Pallet { - fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult { + fn deposit(asset: &Asset, to: &Location) -> DispatchResult { match asset { - MultiAsset { + Asset { fun: Fungible(amount), - id: Concrete(location), + id: AssetId(location), } => ConcreteFungibleBalances::::try_mutate(to, location, |b| -> DispatchResult { *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; Ok(()) }), - MultiAsset { - fun: Fungible(amount), - id: Abstract(key), - } => AbstractFungibleBalances::::try_mutate(to, key.to_vec(), |b| -> DispatchResult { - *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; - Ok(()) - }), _ => Err(Error::::UnhandledAsset.into()), }?; Self::deposit_event(Event::Deposited { asset: asset.clone(), - who: *to, + who: to.clone(), }); Ok(()) } - fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult { + fn withdraw(asset: &Asset, from: &Location) -> DispatchResult { match asset { - MultiAsset { + Asset { fun: Fungible(amount), - id: Concrete(location), + id: AssetId(location), } => ConcreteFungibleBalances::::try_mutate(from, location, |b| -> DispatchResult { *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; Ok(()) }), - MultiAsset { - fun: Fungible(amount), - id: Abstract(key), - } => AbstractFungibleBalances::::try_mutate(from, key.to_vec(), |b| -> DispatchResult { - *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; - Ok(()) - }), _ => Err(Error::::UnhandledAsset.into()), }?; Self::deposit_event(Event::Withdrawn { asset: asset.clone(), - who: *from, + who: from.clone(), }); Ok(()) diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs index 99b247f4c..08988fd24 100644 --- a/unknown-tokens/src/tests.rs +++ b/unknown-tokens/src/tests.rs @@ -7,21 +7,13 @@ use mock::*; use frame_support::{assert_err, assert_ok}; -const MOCK_RECIPIENT: MultiLocation = MultiLocation::parent(); -const MOCK_CONCRETE_FUNGIBLE_ID: MultiLocation = MultiLocation::parent(); +const MOCK_RECIPIENT: Location = Location::parent(); +const MOCK_CONCRETE_FUNGIBLE_ID: Location = Location::parent(); -fn mock_abstract_fungible_id() -> [u8; 32] { - [1; 32] -} - -fn concrete_fungible(amount: u128) -> MultiAsset { +fn concrete_fungible(amount: u128) -> Asset { (MOCK_CONCRETE_FUNGIBLE_ID, amount).into() } -fn abstract_fungible(amount: u128) -> MultiAsset { - (mock_abstract_fungible_id(), amount).into() -} - #[test] fn deposit_concrete_fungible_asset_works() { ExtBuilder.build().execute_with(|| { @@ -45,41 +37,14 @@ fn deposit_concrete_fungible_asset_works() { }); } -#[test] -fn deposit_abstract_fungible_asset() { - ExtBuilder.build().execute_with(|| { - let asset = abstract_fungible(3); - assert_ok!(UnknownTokens::deposit(&asset, &MOCK_RECIPIENT)); - assert_eq!( - UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id().to_vec()), - 3 - ); - System::assert_last_event(RuntimeEvent::UnknownTokens(crate::Event::Deposited { - asset, - who: MOCK_RECIPIENT, - })); - - // overflow case - let max_asset = abstract_fungible(u128::max_value()); - assert_err!( - UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), - Error::::BalanceOverflow - ); - assert_eq!( - UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id().to_vec()), - 3 - ); - }); -} - #[test] fn deposit_unhandled_asset_should_fail() { ExtBuilder.build().execute_with(|| { assert_err!( UnknownTokens::deposit( - &MultiAsset { + &Asset { fun: NonFungible(Undefined), - id: Concrete(MultiLocation::parent()) + id: AssetId(Location::parent()) }, &MOCK_RECIPIENT ), @@ -112,38 +77,14 @@ fn withdraw_concrete_fungible_asset_works() { }); } -#[test] -fn withdraw_abstract_fungible_asset_works() { - ExtBuilder.build().execute_with(|| { - AbstractFungibleBalances::::insert(&MOCK_RECIPIENT, &mock_abstract_fungible_id().to_vec(), 3); - - let asset = abstract_fungible(3); - assert_ok!(UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT)); - assert_eq!( - UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id().to_vec()), - 0 - ); - System::assert_last_event(RuntimeEvent::UnknownTokens(crate::Event::Withdrawn { - asset: asset.clone(), - who: MOCK_RECIPIENT, - })); - - // balance too low case - assert_err!( - UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), - Error::::BalanceTooLow - ); - }); -} - #[test] fn withdraw_unhandled_asset_should_fail() { ExtBuilder.build().execute_with(|| { assert_err!( UnknownTokens::withdraw( - &MultiAsset { + &Asset { fun: NonFungible(Undefined), - id: Concrete(MultiLocation::parent()) + id: AssetId(Location::parent()) }, &MOCK_RECIPIENT ), diff --git a/vesting/src/mock.rs b/vesting/src/mock.rs index 6f561b9e0..5e0af38f9 100644 --- a/vesting/src/mock.rs +++ b/vesting/src/mock.rs @@ -37,7 +37,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } diff --git a/xcm-mock-message-queue/src/lib.rs b/xcm-mock-message-queue/src/lib.rs index b3f2a17b3..367016ffc 100644 --- a/xcm-mock-message-queue/src/lib.rs +++ b/xcm-mock-message-queue/src/lib.rs @@ -8,7 +8,7 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_parachain_primitives::primitives::DmpMessageHandler; use sp_std::prelude::*; use xcm::{ - v3::{prelude::*, Weight}, + v4::{prelude::*, Weight}, VersionedXcm, }; @@ -96,11 +96,11 @@ pub mod module { max_weight, Weight::zero(), ) { - Outcome::Error(error) => (Err(error), Event::Fail(Some(hash), error)), - Outcome::Complete(used) => (Ok(used), Event::Success(Some(hash))), + Outcome::Error { error } => (Err(error), Event::Fail(Some(hash), error)), + Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so // we just report the weight used. - Outcome::Incomplete(used, error) => (Ok(used), Event::Fail(Some(hash), error)), + Outcome::Incomplete { used, error } => (Ok(used), Event::Fail(Some(hash), error)), } } Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs index 33189309f..ad78676a7 100644 --- a/xcm-support/src/currency_adapter.rs +++ b/xcm-support/src/currency_adapter.rs @@ -12,10 +12,10 @@ use sp_std::{ result, }; -use xcm::v3::{prelude::*, Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm::v4::{prelude::*, Asset, Error as XcmError, Location, Result}; use xcm_executor::{ traits::{ConvertLocation, MatchesFungible, TransactAsset}, - Assets, + AssetsInHolding, }; use crate::UnknownAsset as UnknownAssetT; @@ -24,7 +24,7 @@ use crate::UnknownAsset as UnknownAssetT; enum Error { /// Failed to match fungible. FailedToMatchFungible, - /// `MultiLocation` to `AccountId` Conversion failed. + /// `Location` to `AccountId` Conversion failed. AccountIdConversionFailed, /// `CurrencyId` conversion failed. CurrencyIdConversionFailed, @@ -52,7 +52,7 @@ pub trait OnDepositFail { ) -> Result; /// Called on unknown asset deposit errors. - fn on_deposit_unknown_asset_fail(err: DispatchError, _asset: &MultiAsset, _location: &MultiLocation) -> Result { + fn on_deposit_unknown_asset_fail(err: DispatchError, _asset: &Asset, _location: &Location) -> Result { Err(XcmError::FailedToTransactAsset(err.into())) } } @@ -93,7 +93,7 @@ impl< } } -/// The `TransactAsset` implementation, to handle `MultiAsset` deposit/withdraw. +/// The `TransactAsset` implementation, to handle `Asset` deposit/withdraw. /// Note that teleport related functions are unimplemented. /// /// Methods of `DepositFailureHandler` would be called on multi-currency deposit @@ -131,7 +131,7 @@ impl< AccountId: sp_std::fmt::Debug + Clone, AccountIdConvert: ConvertLocation, CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, - CurrencyIdConvert: Convert>, + CurrencyIdConvert: Convert>, DepositFailureHandler: OnDepositFail, > TransactAsset for MultiCurrencyAdapter< @@ -145,7 +145,7 @@ impl< DepositFailureHandler, > { - fn deposit_asset(asset: &MultiAsset, location: &MultiLocation, _context: Option<&XcmContext>) -> Result { + fn deposit_asset(asset: &Asset, location: &Location, _context: Option<&XcmContext>) -> Result { match ( AccountIdConvert::convert_location(location), CurrencyIdConvert::convert(asset.clone()), @@ -161,10 +161,10 @@ impl< } fn withdraw_asset( - asset: &MultiAsset, - location: &MultiLocation, + asset: &Asset, + location: &Location, _maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { UnknownAsset::withdraw(asset, location).or_else(|_| { let who = AccountIdConvert::convert_location(location) .ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; @@ -180,11 +180,11 @@ impl< } fn transfer_asset( - asset: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + asset: &Asset, + from: &Location, + to: &Location, _context: &XcmContext, - ) -> result::Result { + ) -> result::Result { let from_account = AccountIdConvert::convert_location(from).ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; let to_account = diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index 1b3ed2e69..19af03909 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -16,7 +16,7 @@ use sp_runtime::{ }; use sp_std::marker::PhantomData; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; use xcm_executor::traits::MatchesFungible; use orml_traits::{location::Reserve, GetByKey}; @@ -32,12 +32,12 @@ mod tests; pub struct IsNativeConcrete(PhantomData<(CurrencyId, CurrencyIdConvert)>); impl MatchesFungible for IsNativeConcrete where - CurrencyIdConvert: Convert>, + CurrencyIdConvert: Convert>, Amount: TryFrom, { - fn matches_fungible(a: &MultiAsset) -> Option { - if let (Fungible(ref amount), Concrete(ref location)) = (&a.fun, &a.id) { - if CurrencyIdConvert::convert(*location).is_some() { + fn matches_fungible(a: &Asset) -> Option { + if let (Fungible(ref amount), AssetId(location)) = (&a.fun, &a.id) { + if CurrencyIdConvert::convert(location.clone()).is_some() { return CheckedConversion::checked_from(*amount); } } @@ -48,11 +48,11 @@ where /// A `ContainsPair` implementation. Filters multi native assets whose /// reserve is same with `origin`. pub struct MultiNativeAsset(PhantomData); -impl ContainsPair for MultiNativeAsset +impl ContainsPair for MultiNativeAsset where ReserveProvider: Reserve, { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn contains(asset: &Asset, origin: &Location) -> bool { if let Some(ref reserve) = ReserveProvider::reserve(asset) { if reserve == origin { return true; @@ -65,27 +65,27 @@ where /// Handlers unknown asset deposit and withdraw. pub trait UnknownAsset { /// Deposit unknown asset. - fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult; + fn deposit(asset: &Asset, to: &Location) -> DispatchResult; /// Withdraw unknown asset. - fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult; + fn withdraw(asset: &Asset, from: &Location) -> DispatchResult; } const NO_UNKNOWN_ASSET_IMPL: &str = "NoUnknownAssetImpl"; impl UnknownAsset for () { - fn deposit(_asset: &MultiAsset, _to: &MultiLocation) -> DispatchResult { + fn deposit(_asset: &Asset, _to: &Location) -> DispatchResult { Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) } - fn withdraw(_asset: &MultiAsset, _from: &MultiLocation) -> DispatchResult { + fn withdraw(_asset: &Asset, _from: &Location) -> DispatchResult { Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) } } // Default implementation for xTokens::MinXcmFee pub struct DisabledParachainFee; -impl GetByKey> for DisabledParachainFee { - fn get(_key: &MultiLocation) -> Option { +impl GetByKey> for DisabledParachainFee { + fn get(_key: &Location) -> Option { None } } diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs index 69f8dd159..9b38d0360 100644 --- a/xcm-support/src/tests.rs +++ b/xcm-support/src/tests.rs @@ -14,17 +14,17 @@ pub enum TestCurrencyId { } pub struct CurrencyIdConvert; -impl Convert> for CurrencyIdConvert { - fn convert(l: MultiLocation) -> Option { +impl Convert> for CurrencyIdConvert { + fn convert(l: Location) -> Option { use TestCurrencyId::*; - if l == MultiLocation::parent() { + if l == Location::parent() { return Some(RelayChainToken); } - if l == MultiLocation::sibling_parachain_general_key(1, b"TokenA".to_vec().try_into().unwrap()) { + if l == Location::sibling_parachain_general_key(1, b"TokenA".to_vec().try_into().unwrap()) { return Some(TokenA); } - if l == MultiLocation::sibling_parachain_general_key(2, b"TokenB".to_vec().try_into().unwrap()) { + if l == Location::sibling_parachain_general_key(2, b"TokenB".to_vec().try_into().unwrap()) { return Some(TokenB); } None @@ -36,12 +36,12 @@ type MatchesCurrencyId = IsNativeConcrete; #[test] fn is_native_concrete_matches_native_currencies() { assert_eq!( - MatchesCurrencyId::matches_fungible(&MultiAsset::parent_asset(100)), + MatchesCurrencyId::matches_fungible(&Asset::parent_asset(100)), Some(100), ); assert_eq!( - MatchesCurrencyId::matches_fungible(&MultiAsset::sibling_parachain_asset( + MatchesCurrencyId::matches_fungible(&Asset::sibling_parachain_asset( 1, b"TokenA".to_vec().try_into().unwrap(), 100 @@ -50,7 +50,7 @@ fn is_native_concrete_matches_native_currencies() { ); assert_eq!( - MatchesCurrencyId::matches_fungible(&MultiAsset::sibling_parachain_asset( + MatchesCurrencyId::matches_fungible(&Asset::sibling_parachain_asset( 2, b"TokenB".to_vec().try_into().unwrap(), 100 @@ -62,7 +62,7 @@ fn is_native_concrete_matches_native_currencies() { #[test] fn is_native_concrete_does_not_matches_non_native_currencies() { assert!( - >::matches_fungible(&MultiAsset::sibling_parachain_asset( + >::matches_fungible(&Asset::sibling_parachain_asset( 2, b"TokenC".to_vec().try_into().unwrap(), 100 @@ -70,42 +70,40 @@ fn is_native_concrete_does_not_matches_non_native_currencies() { .is_none() ); assert!( - >::matches_fungible(&MultiAsset::sibling_parachain_asset( + >::matches_fungible(&Asset::sibling_parachain_asset( 1, b"TokenB".to_vec().try_into().unwrap(), 100 )) .is_none() ); - assert!( - >::matches_fungible(&MultiAsset { - fun: Fungible(100), - id: Concrete(MultiLocation::new( - 1, - X1(Junction::from( - sp_runtime::BoundedVec::try_from(b"TokenB".to_vec()).unwrap() - )) - )), - }) - .is_none() - ); + assert!(>::matches_fungible(&Asset { + fun: Fungible(100), + id: AssetId(Location::new( + 1, + [Junction::from( + sp_runtime::BoundedVec::try_from(b"TokenB".to_vec()).unwrap() + )] + )), + }) + .is_none()); } #[test] fn multi_native_asset() { assert!(MultiNativeAsset::::contains( - &MultiAsset { + &Asset { fun: Fungible(10), - id: Concrete(MultiLocation::parent()) + id: AssetId(Location::parent()) }, &Parent.into() )); assert!(MultiNativeAsset::::contains( - &MultiAsset::sibling_parachain_asset(1, b"TokenA".to_vec().try_into().unwrap(), 100), - &MultiLocation::new(1, X1(Parachain(1))), + &Asset::sibling_parachain_asset(1, b"TokenA".to_vec().try_into().unwrap(), 100), + &Location::new(1, [Parachain(1)]), )); assert!(!MultiNativeAsset::::contains( - &MultiAsset::sibling_parachain_asset(1, b"TokenA".to_vec().try_into().unwrap(), 100), - &MultiLocation::parent(), + &Asset::sibling_parachain_asset(1, b"TokenA".to_vec().try_into().unwrap(), 100), + &Location::parent(), )); } diff --git a/xcm/src/lib.rs b/xcm/src/lib.rs index 15b029640..ee510a0a6 100644 --- a/xcm/src/lib.rs +++ b/xcm/src/lib.rs @@ -6,7 +6,7 @@ use frame_support::{pallet_prelude::*, traits::EnsureOrigin}; use frame_system::pallet_prelude::*; use sp_std::boxed::Box; -use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; +use xcm::{v4::prelude::*, VersionedLocation, VersionedXcm}; pub use module::*; @@ -31,7 +31,7 @@ pub mod module { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// XCM message sent. \[to, message\] - Sent { to: MultiLocation, message: Xcm<()> }, + Sent { to: Location, message: Xcm<()> }, } #[pallet::error] @@ -55,14 +55,14 @@ pub mod module { #[pallet::weight(Weight::from_parts(100_000_000, 0))] pub fn send_as_sovereign( origin: OriginFor, - dest: Box, + dest: Box, message: Box>, ) -> DispatchResult { let _ = T::SovereignOrigin::ensure_origin(origin)?; - let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; + let dest = Location::try_from(*dest).map_err(|()| Error::::BadVersion)?; let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; - pallet_xcm::Pallet::::send_xcm(Here, dest, message.clone()).map_err(|e| match e { + pallet_xcm::Pallet::::send_xcm(Here, dest.clone(), message.clone()).map_err(|e| match e { SendError::Unroutable => Error::::Unreachable, _ => Error::::SendFailure, })?; diff --git a/xtokens/README.md b/xtokens/README.md index ab0138ef4..f6ff491f8 100644 --- a/xtokens/README.md +++ b/xtokens/README.md @@ -41,7 +41,7 @@ Integration tests could be done manually after integrating `xtokens` into a runt Notice, in the case of parachain A transfer parachain B token to parachain B, and use relay chain token as fee. Because fee asset is relaychain token, and non fee asset is parachain B token, this is two different chain. We call chain of fee asset as `fee_reserve`, and chain of non fee asset as `non_fee_reserve`. And in this case `fee_reserve` location is also refer to destination parachain. -The current implementation sends two XCM from a sender parachain. First XCM is sent to the fee reserve chain which will also route the XCM message to the destination parachain. Second XCM directly sent to destination parachain. +The current implementation sends two XCM from a sender parachain. First XCM is sent to the fee reserve chain which will also route the XCM message to the destination parachain. Second XCM directly sent to destination parachain. The fee amount in fee asset is split into two parts: 1. Fee asset sent to fee reserve chain = fee_amount - min_xcm_fee @@ -51,7 +51,7 @@ Parachains should implement config `MinXcmFee` in `xtokens` module config: ```rust parameter_type_with_key! { - pub MinXcmReserveFee: |location: MultiLocation| -> Option { + pub MinXcmReserveFee: |location: Location| -> Option { #[allow(clippy::match_ref_pats)] // false positive match (location.parents, location.first_interior()) { (1, Some(Parachain(parachains::statemine::ID))) => Some(4_000_000_000), @@ -65,7 +65,7 @@ If Parachain don't want have this case, can simply return None. A default implem ```rust parameter_type_with_key! { - pub ParachainMinFee: |_location: MultiLocation| -> Option { + pub ParachainMinFee: |_location: Location| -> Option { None }; } diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 3f7433447..77c54b7e2 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -15,15 +15,15 @@ //! ### Dispatchable functions //! //! - `transfer`: Transfer local assets with given `CurrencyId` and `Amount`. -//! - `transfer_multiasset`: Transfer `MultiAsset` assets. +//! - `transfer_multiasset`: Transfer `Asset` assets. //! - `transfer_with_fee`: Transfer native currencies specifying the fee and //! amount as separate. -//! - `transfer_multiasset_with_fee`: Transfer `MultiAsset` specifying the fee -//! and amount as separate. +//! - `transfer_multiasset_with_fee`: Transfer `Asset` specifying the fee and +//! amount as separate. //! - `transfer_multicurrencies`: Transfer several currencies specifying the //! item to be used as fee. -//! - `transfer_multiassets`: Transfer several `MultiAsset` specifying the item -//! to be used as fee. +//! - `transfer_multiassets`: Transfer several `Asset` specifying the item to be +//! used as fee. #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::from_over_into)] @@ -46,8 +46,8 @@ use sp_runtime::{ use sp_std::{prelude::*, result::Result}; use xcm::{ - v3::{prelude::*, Weight}, - VersionedMultiAsset, VersionedMultiAssets, VersionedMultiLocation, + v4::{prelude::*, Weight}, + VersionedAsset, VersionedAssets, VersionedLocation, }; use xcm_executor::traits::WeightBounds; @@ -91,24 +91,24 @@ pub mod module { /// Currency Id. type CurrencyId: Parameter + Member + Clone; - /// Convert `T::CurrencyId` to `MultiLocation`. - type CurrencyIdConvert: Convert>; + /// Convert `T::CurrencyId` to `Location`. + type CurrencyIdConvert: Convert>; - /// Convert `T::AccountId` to `MultiLocation`. - type AccountIdToMultiLocation: Convert; + /// Convert `T::AccountId` to `Location`. + type AccountIdToLocation: Convert; /// Self chain location. #[pallet::constant] - type SelfLocation: Get; + type SelfLocation: Get; /// Minimum xcm execution fee paid on destination chain. - type MinXcmFee: GetByKey>; + type MinXcmFee: GetByKey>; /// XCM executor. type XcmExecutor: ExecuteXcm; - /// MultiLocation filter - type MultiLocationsFilter: Contains; + /// Location filter + type LocationsFilter: Contains; /// Means of measuring the weight consumed by an XCM message locally. type Weigher: WeightBounds; @@ -121,13 +121,13 @@ pub mod module { type BaseXcmWeight: Get; /// This chain's Universal Location. - type UniversalLocation: Get; + type UniversalLocation: Get; /// The maximum number of distinct assets allowed to be transferred in a /// single helper extrinsic. type MaxAssetsForTransfer: Get; - /// The way to retreave the reserve of a MultiAsset. This can be + /// The way to retreave the reserve of a Asset. This can be /// configured to accept absolute or relative paths for self tokens type ReserveProvider: Reserve; } @@ -135,12 +135,12 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// Transferred `MultiAsset` with fee. - TransferredMultiAssets { + /// Transferred `Asset` with fee. + TransferredAssets { sender: T::AccountId, - assets: MultiAssets, - fee: MultiAsset, - dest: MultiLocation, + assets: Assets, + fee: Asset, + dest: Location, }, } @@ -163,9 +163,9 @@ pub mod module { CannotReanchor, /// Could not get ancestry of asset reserve location. InvalidAncestry, - /// The MultiAsset is invalid. + /// The Asset is invalid. InvalidAsset, - /// The destination `MultiLocation` provided cannot be inverted. + /// The destination `Location` provided cannot be inverted. DestinationNotInvertible, /// The version of the `Versioned` value used is not able to be /// interpreted. @@ -179,12 +179,12 @@ pub mod module { ZeroAmount, /// The number of assets to be sent is over the maximum. TooManyAssetsBeingSent, - /// The specified index does not exist in a MultiAssets struct. + /// The specified index does not exist in a Assets struct. AssetIndexNonExistent, /// Fee is not enough. FeeNotEnough, - /// Not supported MultiLocation - NotSupportedMultiLocation, + /// Not supported Location + NotSupportedLocation, /// MinXcmFee not registered for certain reserve location MinXcmFeeNotDefined, } @@ -215,15 +215,15 @@ pub mod module { origin: OriginFor, currency_id: T::CurrencyId, amount: T::Balance, - dest: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; Self::do_transfer(who, currency_id, amount, dest, dest_weight_limit).map(|_| ()) } - /// Transfer `MultiAsset`. + /// Transfer `Asset`. /// /// `dest_weight_limit` is the weight for XCM execution on the dest /// chain, and it would be charged from the transferred assets. If set @@ -239,14 +239,14 @@ pub mod module { #[pallet::weight(XtokensWeight::::weight_of_transfer_multiasset(asset, dest))] pub fn transfer_multiasset( origin: OriginFor, - asset: Box, - dest: Box, + asset: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let asset: MultiAsset = (*asset).try_into().map_err(|()| Error::::BadVersion)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; - Self::do_transfer_multiasset(who, asset, dest, dest_weight_limit).map(|_| ()) + let asset: Asset = (*asset).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + Self::do_transfer_asset(who, asset, dest, dest_weight_limit).map(|_| ()) } /// Transfer native currencies specifying the fee and amount as @@ -277,26 +277,26 @@ pub mod module { currency_id: T::CurrencyId, amount: T::Balance, fee: T::Balance, - dest: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; Self::do_transfer_with_fee(who, currency_id, amount, fee, dest, dest_weight_limit).map(|_| ()) } - /// Transfer `MultiAsset` specifying the fee and amount as separate. + /// Transfer `Asset` specifying the fee and amount as separate. /// /// `dest_weight_limit` is the weight for XCM execution on the dest /// chain, and it would be charged from the transferred assets. If set /// below requirements, the execution may fail and assets wouldn't be /// received. /// - /// `fee` is the multiasset to be spent to pay for execution in + /// `fee` is the Asset to be spent to pay for execution in /// destination chain. Both fee and amount will be subtracted form the /// callers balance For now we only accept fee and asset having the same - /// `MultiLocation` id. + /// `Location` id. /// /// If `fee` is not high enough to cover for the execution costs in the /// destination chain, then the assets will be trapped in the @@ -311,17 +311,17 @@ pub mod module { #[pallet::weight(XtokensWeight::::weight_of_transfer_multiasset(asset, dest))] pub fn transfer_multiasset_with_fee( origin: OriginFor, - asset: Box, - fee: Box, - dest: Box, + asset: Box, + fee: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let asset: MultiAsset = (*asset).try_into().map_err(|()| Error::::BadVersion)?; - let fee: MultiAsset = (*fee).try_into().map_err(|()| Error::::BadVersion)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + let asset: Asset = (*asset).try_into().map_err(|()| Error::::BadVersion)?; + let fee: Asset = (*fee).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; - Self::do_transfer_multiasset_with_fee(who, asset, fee, dest, dest_weight_limit).map(|_| ()) + Self::do_transfer_asset_with_fee(who, asset, fee, dest, dest_weight_limit).map(|_| ()) } /// Transfer several currencies specifying the item to be used as fee @@ -345,23 +345,23 @@ pub mod module { origin: OriginFor, currencies: Vec<(T::CurrencyId, T::Balance)>, fee_item: u32, - dest: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; Self::do_transfer_multicurrencies(who, currencies, fee_item, dest, dest_weight_limit).map(|_| ()) } - /// Transfer several `MultiAsset` specifying the item to be used as fee + /// Transfer several `Asset` specifying the item to be used as fee /// /// `dest_weight_limit` is the weight for XCM execution on the dest /// chain, and it would be charged from the transferred assets. If set /// below requirements, the execution may fail and assets wouldn't be /// received. /// - /// `fee_item` is index of the MultiAssets that we want to use for + /// `fee_item` is index of the Assets that we want to use for /// payment /// /// It's a no-op if any error on local XCM execution or message sending. @@ -373,19 +373,19 @@ pub mod module { #[pallet::weight(XtokensWeight::::weight_of_transfer_multiassets(assets, fee_item, dest))] pub fn transfer_multiassets( origin: OriginFor, - assets: Box, + assets: Box, fee_item: u32, - dest: Box, + dest: Box, dest_weight_limit: WeightLimit, ) -> DispatchResult { let who = ensure_signed(origin)?; - let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; - let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::::BadVersion)?; + let assets: Assets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; + let dest: Location = (*dest).try_into().map_err(|()| Error::::BadVersion)?; // We first grab the fee - let fee: &MultiAsset = assets.get(fee_item as usize).ok_or(Error::::AssetIndexNonExistent)?; + let fee: &Asset = assets.get(fee_item as usize).ok_or(Error::::AssetIndexNonExistent)?; - Self::do_transfer_multiassets(who, assets.clone(), fee.clone(), dest, dest_weight_limit).map(|_| ()) + Self::do_transfer_assets(who, assets.clone(), fee.clone(), dest, dest_weight_limit).map(|_| ()) } } @@ -394,20 +394,17 @@ pub mod module { who: T::AccountId, currency_id: T::CurrencyId, amount: T::Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - let location: MultiLocation = + let location: Location = T::CurrencyIdConvert::convert(currency_id).ok_or(Error::::NotCrossChainTransferableCurrency)?; ensure!(!amount.is_zero(), Error::::ZeroAmount); - ensure!( - T::MultiLocationsFilter::contains(&dest), - Error::::NotSupportedMultiLocation - ); + ensure!(T::LocationsFilter::contains(&dest), Error::::NotSupportedLocation); - let asset: MultiAsset = (location, amount.into()).into(); - Self::do_transfer_multiassets(who, vec![asset.clone()].into(), asset, dest, dest_weight_limit) + let asset: Asset = (location, amount.into()).into(); + Self::do_transfer_assets(who, vec![asset.clone()].into(), asset, dest, dest_weight_limit) } fn do_transfer_with_fee( @@ -415,71 +412,65 @@ pub mod module { currency_id: T::CurrencyId, amount: T::Balance, fee: T::Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - let location: MultiLocation = + let location: Location = T::CurrencyIdConvert::convert(currency_id).ok_or(Error::::NotCrossChainTransferableCurrency)?; ensure!(!amount.is_zero(), Error::::ZeroAmount); ensure!(!fee.is_zero(), Error::::ZeroFee); - ensure!( - T::MultiLocationsFilter::contains(&dest), - Error::::NotSupportedMultiLocation - ); + ensure!(T::LocationsFilter::contains(&dest), Error::::NotSupportedLocation); - let asset = (location, amount.into()).into(); - let fee_asset: MultiAsset = (location, fee.into()).into(); + let asset = (location.clone(), amount.into()).into(); + let fee_asset: Asset = (location, fee.into()).into(); // Push contains saturated addition, so we should be able to use it safely - let mut assets = MultiAssets::new(); + let mut assets = Assets::new(); assets.push(asset); assets.push(fee_asset.clone()); - Self::do_transfer_multiassets(who, assets, fee_asset, dest, dest_weight_limit) + Self::do_transfer_assets(who, assets, fee_asset, dest, dest_weight_limit) } - fn do_transfer_multiasset( + fn do_transfer_asset( who: T::AccountId, - asset: MultiAsset, - dest: MultiLocation, + asset: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - Self::do_transfer_multiassets(who, vec![asset.clone()].into(), asset, dest, dest_weight_limit) + Self::do_transfer_assets(who, vec![asset.clone()].into(), asset, dest, dest_weight_limit) } - fn do_transfer_multiasset_with_fee( + fn do_transfer_asset_with_fee( who: T::AccountId, - asset: MultiAsset, - fee: MultiAsset, - dest: MultiLocation, + asset: Asset, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { // Push contains saturated addition, so we should be able to use it safely - let mut assets = MultiAssets::new(); + let mut assets = Assets::new(); assets.push(asset); assets.push(fee.clone()); - Self::do_transfer_multiassets(who, assets, fee, dest, dest_weight_limit) + Self::do_transfer_assets(who, assets, fee, dest, dest_weight_limit) } fn do_transfer_multicurrencies( who: T::AccountId, currencies: Vec<(T::CurrencyId, T::Balance)>, fee_item: u32, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { ensure!( currencies.len() <= T::MaxAssetsForTransfer::get(), Error::::TooManyAssetsBeingSent ); - ensure!( - T::MultiLocationsFilter::contains(&dest), - Error::::NotSupportedMultiLocation - ); + ensure!(T::LocationsFilter::contains(&dest), Error::::NotSupportedLocation); - let mut assets = MultiAssets::new(); + let mut assets = Assets::new(); // Lets grab the fee amount and location first let (fee_currency_id, fee_amount) = currencies @@ -487,7 +478,7 @@ pub mod module { .ok_or(Error::::AssetIndexNonExistent)?; for (currency_id, amount) in ¤cies { - let location: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone()) + let location: Location = T::CurrencyIdConvert::convert(currency_id.clone()) .ok_or(Error::::NotCrossChainTransferableCurrency)?; ensure!(!amount.is_zero(), Error::::ZeroAmount); @@ -497,29 +488,26 @@ pub mod module { // We construct the fee now, since getting it from assets wont work as assets // sorts it - let fee_location: MultiLocation = T::CurrencyIdConvert::convert(fee_currency_id.clone()) + let fee_location: Location = T::CurrencyIdConvert::convert(fee_currency_id.clone()) .ok_or(Error::::NotCrossChainTransferableCurrency)?; - let fee: MultiAsset = (fee_location, (*fee_amount).into()).into(); + let fee: Asset = (fee_location, (*fee_amount).into()).into(); - Self::do_transfer_multiassets(who, assets, fee, dest, dest_weight_limit) + Self::do_transfer_assets(who, assets, fee, dest, dest_weight_limit) } - fn do_transfer_multiassets( + fn do_transfer_assets( who: T::AccountId, - assets: MultiAssets, - fee: MultiAsset, - dest: MultiLocation, + assets: Assets, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { ensure!( assets.len() <= T::MaxAssetsForTransfer::get(), Error::::TooManyAssetsBeingSent ); - ensure!( - T::MultiLocationsFilter::contains(&dest), - Error::::NotSupportedMultiLocation - ); + ensure!(T::LocationsFilter::contains(&dest), Error::::NotSupportedLocation); // Fee payment can only be made by using the non-zero amount of fungibles ensure!( @@ -527,9 +515,9 @@ pub mod module { Error::::InvalidAsset ); - let origin_location = T::AccountIdToMultiLocation::convert(who.clone()); + let origin_location = T::AccountIdToLocation::convert(who.clone()); - let mut non_fee_reserve: Option = None; + let mut non_fee_reserve: Option = None; let asset_len = assets.len(); for i in 0..asset_len { let asset = assets.get(i).ok_or(Error::::AssetIndexNonExistent)?; @@ -560,14 +548,14 @@ pub mod module { // like `NonReserve` or `SelfReserve` with relay-chain fee is not support. ensure!(non_fee_reserve == dest.chain_part(), Error::::InvalidAsset); - let reserve_location = non_fee_reserve.ok_or(Error::::AssetHasNoReserve)?; + let reserve_location = non_fee_reserve.clone().ok_or(Error::::AssetHasNoReserve)?; let min_xcm_fee = T::MinXcmFee::get(&reserve_location).ok_or(Error::::MinXcmFeeNotDefined)?; // min xcm fee should less than user fee - let fee_to_dest: MultiAsset = (fee.id, min_xcm_fee).into(); + let fee_to_dest: Asset = (fee.id.clone(), min_xcm_fee).into(); ensure!(fee_to_dest < fee, Error::::FeeNotEnough); - let mut assets_to_dest = MultiAssets::new(); + let mut assets_to_dest = Assets::new(); for i in 0..asset_len { let asset = assets.get(i).ok_or(Error::::AssetIndexNonExistent)?; if fee != *asset { @@ -577,16 +565,16 @@ pub mod module { } } - let mut assets_to_fee_reserve = MultiAssets::new(); + let mut assets_to_fee_reserve = Assets::new(); let asset_to_fee_reserve = subtract_fee(&fee, min_xcm_fee); assets_to_fee_reserve.push(asset_to_fee_reserve.clone()); let mut override_recipient = T::SelfLocation::get(); - if override_recipient == MultiLocation::here() { + if override_recipient == Location::here() { let dest_chain_part = dest.chain_part().ok_or(Error::::InvalidDest)?; let ancestry = T::UniversalLocation::get(); let _ = override_recipient - .reanchor(&dest_chain_part, ancestry) + .reanchor(&dest_chain_part, &ancestry) .map_err(|_| Error::::CannotReanchor); } @@ -595,7 +583,7 @@ pub mod module { // teleport. But as current there's only one case which is Parachain send back // asset to Statemine/t, So we set `use_teleport` to always `true` in this case. Self::execute_and_send_reserve_kind_xcm( - origin_location, + origin_location.clone(), assets_to_fee_reserve, asset_to_fee_reserve, fee_reserve, @@ -629,11 +617,11 @@ pub mod module { )?; } - Self::deposit_event(Event::::TransferredMultiAssets { + Self::deposit_event(Event::::TransferredAssets { sender: who.clone(), assets: assets.clone(), fee: fee.clone(), - dest, + dest: dest.clone(), }); Ok(Transferred { @@ -647,12 +635,12 @@ pub mod module { /// Execute and send xcm with given assets and fee to dest chain or /// reserve chain. fn execute_and_send_reserve_kind_xcm( - origin_location: MultiLocation, - assets: MultiAssets, - fee: MultiAsset, - reserve: Option, - dest: &MultiLocation, - maybe_recipient_override: Option, + origin_location: Location, + assets: Assets, + fee: Asset, + reserve: Option, + dest: &Location, + maybe_recipient_override: Option, dest_weight_limit: WeightLimit, use_teleport: bool, ) -> DispatchResult { @@ -674,10 +662,10 @@ pub mod module { use_teleport, )?, }; - let hash = msg.using_encoded(sp_io::hashing::blake2_256); + let mut hash = msg.using_encoded(sp_io::hashing::blake2_256); let weight = T::Weigher::weight(&mut msg).map_err(|()| Error::::UnweighableMessage)?; - T::XcmExecutor::execute_xcm_in_credit(origin_location, msg, hash, weight, weight) + T::XcmExecutor::prepare_and_execute(origin_location, msg, &mut hash, weight, weight) .ensure_complete() .map_err(|error| { log::error!("Failed execute transfer message with {:?}", error); @@ -688,15 +676,15 @@ pub mod module { } fn transfer_self_reserve_asset( - assets: MultiAssets, - fee: MultiAsset, - dest: MultiLocation, - recipient: MultiLocation, + assets: Assets, + fee: Asset, + dest: Location, + recipient: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { Ok(Xcm(vec![TransferReserveAsset { assets: assets.clone(), - dest, + dest: dest.clone(), xcm: Xcm(vec![ Self::buy_execution(fee, &dest, dest_weight_limit)?, Self::deposit_asset(recipient, assets.len() as u32), @@ -705,17 +693,17 @@ pub mod module { } fn transfer_to_reserve( - assets: MultiAssets, - fee: MultiAsset, - reserve: MultiLocation, - recipient: MultiLocation, + assets: Assets, + fee: Asset, + reserve: Location, + recipient: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { Ok(Xcm(vec![ WithdrawAsset(assets.clone()), InitiateReserveWithdraw { assets: All.into(), - reserve, + reserve: reserve.clone(), xcm: Xcm(vec![ Self::buy_execution(fee, &reserve, dest_weight_limit)?, Self::deposit_asset(recipient, assets.len() as u32), @@ -725,22 +713,18 @@ pub mod module { } fn transfer_to_non_reserve( - assets: MultiAssets, - fee: MultiAsset, - reserve: MultiLocation, - dest: MultiLocation, - recipient: MultiLocation, + assets: Assets, + fee: Asset, + reserve: Location, + dest: Location, + recipient: Location, dest_weight_limit: WeightLimit, use_teleport: bool, ) -> Result, DispatchError> { - let mut reanchored_dest = dest; - if reserve == MultiLocation::parent() { - if let MultiLocation { - parents: 1, - interior: X1(Parachain(id)), - } = dest - { - reanchored_dest = Parachain(id).into(); + let mut reanchored_dest = dest.clone(); + if reserve == Location::parent() { + if let (1, [Parachain(id)]) = dest.unpack() { + reanchored_dest = Parachain(*id).into(); } } @@ -750,7 +734,7 @@ pub mod module { WithdrawAsset(assets), InitiateReserveWithdraw { assets: All.into(), - reserve, + reserve: reserve.clone(), xcm: Xcm(vec![ Self::buy_execution(half(&fee), &reserve, dest_weight_limit.clone())?, DepositReserveAsset { @@ -769,7 +753,7 @@ pub mod module { WithdrawAsset(assets), InitiateReserveWithdraw { assets: All.into(), - reserve, + reserve: reserve.clone(), xcm: Xcm(vec![ Self::buy_execution(half(&fee), &reserve, dest_weight_limit.clone())?, InitiateTeleport { @@ -786,7 +770,7 @@ pub mod module { } } - fn deposit_asset(recipient: MultiLocation, max_assets: u32) -> Instruction<()> { + fn deposit_asset(recipient: Location, max_assets: u32) -> Instruction<()> { DepositAsset { assets: AllCounted(max_assets).into(), beneficiary: recipient, @@ -794,18 +778,20 @@ pub mod module { } fn buy_execution( - asset: MultiAsset, - at: &MultiLocation, + asset: Asset, + at: &Location, weight_limit: WeightLimit, ) -> Result, DispatchError> { let ancestry = T::UniversalLocation::get(); - let fees = asset.reanchored(at, ancestry).map_err(|_| Error::::CannotReanchor)?; + let fees = asset + .reanchored(at, &ancestry) + .map_err(|_| Error::::CannotReanchor)?; Ok(BuyExecution { fees, weight_limit }) } /// Ensure has the `dest` has chain part and recipient part. - fn ensure_valid_dest(dest: &MultiLocation) -> Result<(MultiLocation, MultiLocation), DispatchError> { + fn ensure_valid_dest(dest: &Location) -> Result<(Location, Location), DispatchError> { if let (Some(dest), Some(recipient)) = (dest.chain_part(), dest.non_chain_part()) { Ok((dest, recipient)) } else { @@ -822,9 +808,9 @@ pub mod module { /// - `dest` parachain or relay chain location. /// - `recipient` location. fn transfer_kind( - reserve: Option, - dest: &MultiLocation, - ) -> Result<(TransferKind, MultiLocation, MultiLocation, MultiLocation), DispatchError> { + reserve: Option, + dest: &Location, + ) -> Result<(TransferKind, Location, Location, Location), DispatchError> { let (dest, recipient) = Self::ensure_valid_dest(dest)?; let self_location = T::SelfLocation::get(); @@ -843,7 +829,7 @@ pub mod module { /// Get reserve location by `assets` and `fee_item`. the `assets` /// includes fee asset and non fee asset. make sure assets have ge one /// asset. all non fee asset should share same reserve location. - fn get_reserve_location(assets: &MultiAssets, fee_item: &u32) -> Option { + fn get_reserve_location(assets: &Assets, fee_item: &u32) -> Option { let reserve_idx = if assets.len() == 1 { 0 } else { @@ -858,8 +844,8 @@ pub mod module { // weights impl XtokensWeightInfo for XtokensWeight { /// Returns weight of `transfer_multiasset` call. - fn weight_of_transfer_multiasset(asset: &VersionedMultiAsset, dest: &VersionedMultiLocation) -> Weight { - let asset: Result = asset.clone().try_into(); + fn weight_of_transfer_multiasset(asset: &VersionedAsset, dest: &VersionedLocation) -> Weight { + let asset: Result = asset.clone().try_into(); let dest = dest.clone().try_into(); if let (Ok(asset), Ok(dest)) = (asset, dest) { if let Ok((transfer_kind, dest, _, reserve)) = @@ -872,7 +858,7 @@ pub mod module { xcm: Xcm(vec![]), }]), ToReserve | ToNonReserve => Xcm(vec![ - WithdrawAsset(MultiAssets::from(asset)), + WithdrawAsset(Assets::from(asset)), InitiateReserveWithdraw { assets: All.into(), // `dest` is always (equal to) `reserve` in both cases @@ -889,7 +875,7 @@ pub mod module { } /// Returns weight of `transfer` call. - fn weight_of_transfer(currency_id: T::CurrencyId, amount: T::Balance, dest: &VersionedMultiLocation) -> Weight { + fn weight_of_transfer(currency_id: T::CurrencyId, amount: T::Balance, dest: &VersionedLocation) -> Weight { if let Some(location) = T::CurrencyIdConvert::convert(currency_id) { let asset = (location, amount.into()).into(); Self::weight_of_transfer_multiasset(&asset, dest) @@ -902,28 +888,28 @@ pub mod module { fn weight_of_transfer_multicurrencies( currencies: &[(T::CurrencyId, T::Balance)], fee_item: &u32, - dest: &VersionedMultiLocation, + dest: &VersionedLocation, ) -> Weight { - let mut assets: Vec = Vec::new(); + let mut assets: Vec = Vec::new(); for (currency_id, amount) in currencies { if let Some(location) = T::CurrencyIdConvert::convert(currency_id.clone()) { - let asset: MultiAsset = (location, (*amount).into()).into(); + let asset: Asset = (location, (*amount).into()).into(); assets.push(asset); } else { return Weight::zero(); } } - Self::weight_of_transfer_multiassets(&VersionedMultiAssets::from(MultiAssets::from(assets)), fee_item, dest) + Self::weight_of_transfer_multiassets(&VersionedAssets::from(Assets::from(assets)), fee_item, dest) } /// Returns weight of `transfer_multiassets` call. fn weight_of_transfer_multiassets( - assets: &VersionedMultiAssets, + assets: &VersionedAssets, fee_item: &u32, - dest: &VersionedMultiLocation, + dest: &VersionedLocation, ) -> Weight { - let assets: Result = assets.clone().try_into(); + let assets: Result = assets.clone().try_into(); let dest = dest.clone().try_into(); if let (Ok(assets), Ok(dest)) = (assets, dest) { let reserve_location = Pallet::::get_reserve_location(&assets, fee_item); @@ -958,7 +944,7 @@ pub mod module { who: T::AccountId, currency_id: T::CurrencyId, amount: T::Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { Self::do_transfer(who, currency_id, amount, dest, dest_weight_limit) @@ -967,11 +953,11 @@ pub mod module { #[require_transactional] fn transfer_multiasset( who: T::AccountId, - asset: MultiAsset, - dest: MultiLocation, + asset: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - Self::do_transfer_multiasset(who, asset, dest, dest_weight_limit) + Self::do_transfer_asset(who, asset, dest, dest_weight_limit) } #[require_transactional] @@ -980,7 +966,7 @@ pub mod module { currency_id: T::CurrencyId, amount: T::Balance, fee: T::Balance, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { Self::do_transfer_with_fee(who, currency_id, amount, fee, dest, dest_weight_limit) @@ -989,12 +975,12 @@ pub mod module { #[require_transactional] fn transfer_multiasset_with_fee( who: T::AccountId, - asset: MultiAsset, - fee: MultiAsset, - dest: MultiLocation, + asset: Asset, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - Self::do_transfer_multiasset_with_fee(who, asset, fee, dest, dest_weight_limit) + Self::do_transfer_asset_with_fee(who, asset, fee, dest, dest_weight_limit) } #[require_transactional] @@ -1002,7 +988,7 @@ pub mod module { who: T::AccountId, currencies: Vec<(T::CurrencyId, T::Balance)>, fee_item: u32, - dest: MultiLocation, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { Self::do_transfer_multicurrencies(who, currencies, fee_item, dest, dest_weight_limit) @@ -1011,18 +997,18 @@ pub mod module { #[require_transactional] fn transfer_multiassets( who: T::AccountId, - assets: MultiAssets, - fee: MultiAsset, - dest: MultiLocation, + assets: Assets, + fee: Asset, + dest: Location, dest_weight_limit: WeightLimit, ) -> Result, DispatchError> { - Self::do_transfer_multiassets(who, assets, fee, dest, dest_weight_limit) + Self::do_transfer_assets(who, assets, fee, dest, dest_weight_limit) } } } /// Returns amount if `asset` is fungible, or zero. -fn fungible_amount(asset: &MultiAsset) -> u128 { +fn fungible_amount(asset: &Asset) -> u128 { if let Fungible(amount) = &asset.fun { *amount } else { @@ -1030,20 +1016,20 @@ fn fungible_amount(asset: &MultiAsset) -> u128 { } } -fn half(asset: &MultiAsset) -> MultiAsset { +fn half(asset: &Asset) -> Asset { let half_amount = fungible_amount(asset) .checked_div(2) .expect("div 2 can't overflow; qed"); - MultiAsset { + Asset { fun: Fungible(half_amount), - id: asset.id, + id: asset.id.clone(), } } -fn subtract_fee(asset: &MultiAsset, amount: u128) -> MultiAsset { +fn subtract_fee(asset: &Asset, amount: u128) -> Asset { let final_amount = fungible_amount(asset).checked_sub(amount).expect("fee too low; qed"); - MultiAsset { + Asset { fun: Fungible(final_amount), - id: asset.id, + id: asset.id.clone(), } } diff --git a/xtokens/src/mock/mod.rs b/xtokens/src/mock/mod.rs index 48a9365ba..2b67897e9 100644 --- a/xtokens/src/mock/mod.rs +++ b/xtokens/src/mock/mod.rs @@ -9,7 +9,7 @@ use sp_io::TestExternalities; use sp_runtime::{AccountId32, BoundedVec, BuildStorage}; use xcm_builder::{CreateMatcher, MatchXcm}; use xcm_executor::traits::{ShouldExecute, WeightTrader}; -use xcm_executor::Assets; +use xcm_executor::AssetsInHolding; use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, ProcessMessageError, TestExt}; @@ -56,8 +56,8 @@ pub enum CurrencyId { } pub struct CurrencyIdConvert; -impl Convert> for CurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { +impl Convert> for CurrencyIdConvert { + fn convert(id: CurrencyId) -> Option { match id { CurrencyId::R => Some(Parent.into()), CurrencyId::A => Some( @@ -119,8 +119,8 @@ impl Convert> for CurrencyIdConvert { } } } -impl Convert> for CurrencyIdConvert { - fn convert(l: MultiLocation) -> Option { +impl Convert> for CurrencyIdConvert { + fn convert(l: Location) -> Option { let mut a: Vec = "A".into(); a.resize(32, 0); let mut a1: Vec = "A1".into(); @@ -135,39 +135,39 @@ impl Convert> for CurrencyIdConvert { c.resize(32, 0); let mut d: Vec = "D".into(); d.resize(32, 0); - if l == MultiLocation::parent() { + if l == Location::parent() { return Some(CurrencyId::R); } - match l { - MultiLocation { parents, interior } if parents == 1 => match interior { - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X2(Parachain(3), GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C), - X2(Parachain(4), GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D), + match l.unpack() { + (parents, interior) if parents == 1 => match interior { + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [Parachain(3), GeneralKey { data, .. }] if data.to_vec() == c => Some(CurrencyId::C), + [Parachain(4), GeneralKey { data, .. }] if data.to_vec() == d => Some(CurrencyId::D), _ => None, }, - MultiLocation { parents, interior } if parents == 0 => match interior { - X1(GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X1(GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X1(GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X1(GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X1(GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X1(GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C), - X1(GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D), + (parents, interior) if parents == 0 => match interior { + [GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [GeneralKey { data, .. }] if data.to_vec() == c => Some(CurrencyId::C), + [GeneralKey { data, .. }] if data.to_vec() == d => Some(CurrencyId::D), _ => None, }, _ => None, } } } -impl Convert> for CurrencyIdConvert { - fn convert(a: MultiAsset) -> Option { - if let MultiAsset { +impl Convert> for CurrencyIdConvert { + fn convert(a: Asset) -> Option { + if let Asset { fun: Fungible(_), - id: Concrete(id), + id: AssetId(id), } = a { Self::convert(id) @@ -315,37 +315,41 @@ pub fn relay_ext() -> sp_io::TestExternalities { /// which is not true, but good enough to mock the fee payment of XCM execution. /// /// This mock will always trade `n` amount of weight to `n` amount of tokens. -pub struct AllTokensAreCreatedEqualToWeight(MultiLocation); +pub struct AllTokensAreCreatedEqualToWeight(Location); impl WeightTrader for AllTokensAreCreatedEqualToWeight { fn new() -> Self { - Self(MultiLocation::parent()) + Self(Location::parent()) } - fn buy_weight(&mut self, weight: Weight, payment: Assets, _context: &XcmContext) -> Result { + fn buy_weight( + &mut self, + weight: Weight, + payment: AssetsInHolding, + _context: &XcmContext, + ) -> Result { let asset_id = payment .fungible .iter() .next() .expect("Payment must be something; qed") .0; - let required = MultiAsset { + let required = Asset { id: asset_id.clone(), fun: Fungible(weight.ref_time() as u128), }; - if let MultiAsset { + let Asset { fun: _, - id: Concrete(ref id), - } = &required - { - self.0 = id.clone(); - } + id: AssetId(ref id), + } = &required; + + self.0 = id.clone(); let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?; Ok(unused) } - fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option { if weight.is_zero() { None } else { @@ -366,7 +370,7 @@ impl WeightTrader for AllTokensAreCreatedEqualToWeight { pub struct AllowTopLevelPaidExecution; impl ShouldExecute for AllowTopLevelPaidExecution { fn should_execute( - _origin: &MultiLocation, + _origin: &Location, instructions: &mut [Instruction], max_weight: Weight, _properties: &mut xcm_executor::traits::Properties, diff --git a/xtokens/src/mock/para.rs b/xtokens/src/mock/para.rs index 885598c0b..c2e7ec311 100644 --- a/xtokens/src/mock/para.rs +++ b/xtokens/src/mock/para.rs @@ -2,8 +2,8 @@ use super::{AllowTopLevelPaidExecution, Amount, Balance, CurrencyId, CurrencyIdC use crate as orml_xtokens; use frame_support::{ - construct_runtime, derive_impl, match_types, parameter_types, - traits::{ConstU128, ConstU32, Everything, Get, Nothing}, + construct_runtime, derive_impl, parameter_types, + traits::{ConstU128, ConstU32, Contains, Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; @@ -12,7 +12,7 @@ use sp_runtime::{ traits::{Convert, IdentityLookup}, AccountId32, }; -use xcm::v3::{prelude::*, Weight}; +use xcm::v4::{prelude::*, Weight}; use xcm_builder::{ AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, NativeAsset, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, @@ -47,7 +47,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } @@ -74,8 +73,8 @@ impl orml_tokens::Config for Runtime { parameter_types! { pub const RelayNetwork: NetworkId = NetworkId::Kusama; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())].into(); } pub type LocationToAccountId = ( @@ -175,36 +174,40 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); } -pub struct AccountIdToMultiLocation; -impl Convert for AccountIdToMultiLocation { - fn convert(account: AccountId) -> MultiLocation { - X1(Junction::AccountId32 { +pub struct AccountIdToLocation; +impl Convert for AccountIdToLocation { + fn convert(account: AccountId) -> Location { + [Junction::AccountId32 { network: None, id: account.into(), - }) + }] .into() } } parameter_types! { - pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(MsgQueue::get().into()))); + pub SelfLocation: Location = Location::new(1, [Parachain(MsgQueue::get().into())]); pub const MaxAssetsForTransfer: usize = 3; } -match_types! { - pub type ParentOrParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(1), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(2), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(3), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(4), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(100), Junction::AccountId32 { .. }) } - }; +pub struct ParentOrParachains; +impl Contains for ParentOrParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Junction::AccountId32 { .. }]) + | (1, [Junction::AccountId32 { .. }]) + | (1, [Parachain(1), Junction::AccountId32 { .. }]) + | (1, [Parachain(2), Junction::AccountId32 { .. }]) + | (1, [Parachain(3), Junction::AccountId32 { .. }]) + | (1, [Parachain(4), Junction::AccountId32 { .. }]) + | (1, [Parachain(100), Junction::AccountId32 { .. }]) + ) + } } parameter_type_with_key! { - pub ParachainMinFee: |location: MultiLocation| -> Option { + pub ParachainMinFee: |location: Location| -> Option { #[allow(clippy::match_ref_pats)] // false positive match (location.parents, location.first_interior()) { (1, Some(Parachain(3))) => Some(40), @@ -218,9 +221,9 @@ impl orml_xtokens::Config for Runtime { type Balance = Balance; type CurrencyId = CurrencyId; type CurrencyIdConvert = CurrencyIdConvert; - type AccountIdToMultiLocation = AccountIdToMultiLocation; + type AccountIdToLocation = AccountIdToLocation; type SelfLocation = SelfLocation; - type MultiLocationsFilter = ParentOrParachains; + type LocationsFilter = ParentOrParachains; type MinXcmFee = ParachainMinFee; type XcmExecutor = XcmExecutor; type Weigher = FixedWeightBounds; diff --git a/xtokens/src/mock/para_relative_view.rs b/xtokens/src/mock/para_relative_view.rs index 836d7b318..2776bc276 100644 --- a/xtokens/src/mock/para_relative_view.rs +++ b/xtokens/src/mock/para_relative_view.rs @@ -2,8 +2,8 @@ use super::{Amount, Balance, CurrencyId, CurrencyIdConvert, ParachainXcmRouter}; use crate as orml_xtokens; use frame_support::{ - construct_runtime, derive_impl, match_types, parameter_types, - traits::{ConstU128, ConstU32, Everything, Get, Nothing}, + construct_runtime, derive_impl, parameter_types, + traits::{ConstU128, ConstU32, Contains, Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; @@ -12,7 +12,7 @@ use sp_runtime::{ traits::{Convert, IdentityLookup}, AccountId32, BoundedVec, }; -use xcm::v3::{prelude::*, Weight}; +use xcm::v4::{prelude::*, Weight}; use xcm_builder::{ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, @@ -50,7 +50,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } @@ -77,8 +76,8 @@ impl orml_tokens::Config for Runtime { parameter_types! { pub const RelayNetwork: NetworkId = NetworkId::Kusama; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())].into(); } pub type LocationToAccountId = ( @@ -178,20 +177,20 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); } -pub struct AccountIdToMultiLocation; -impl Convert for AccountIdToMultiLocation { - fn convert(account: AccountId) -> MultiLocation { - X1(Junction::AccountId32 { +pub struct AccountIdToLocation; +impl Convert for AccountIdToLocation { + fn convert(account: AccountId) -> Location { + [Junction::AccountId32 { network: None, id: account.into(), - }) + }] .into() } } pub struct RelativeCurrencyIdConvert; -impl Convert> for RelativeCurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { +impl Convert> for RelativeCurrencyIdConvert { + fn convert(id: CurrencyId) -> Option { match id { CurrencyId::R => Some(Parent.into()), CurrencyId::A => Some( @@ -246,8 +245,8 @@ impl Convert> for RelativeCurrencyIdConvert { } } } -impl Convert> for RelativeCurrencyIdConvert { - fn convert(l: MultiLocation) -> Option { +impl Convert> for RelativeCurrencyIdConvert { + fn convert(l: Location) -> Option { let mut a: Vec = "A".into(); a.resize(32, 0); let mut a1: Vec = "A1".into(); @@ -264,41 +263,41 @@ impl Convert> for RelativeCurrencyIdConvert { d.resize(32, 0); let self_para_id: u32 = MsgQueue::get().into(); - if l == MultiLocation::parent() { + if l == Location::parent() { return Some(CurrencyId::R); } - match l { - MultiLocation { parents, interior } if parents == 1 => match interior { - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X2(Parachain(3), GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C), - X2(Parachain(para_id), GeneralKey { data, .. }) if data.to_vec() == d && para_id == self_para_id => { + match l.unpack() { + (parents, interior) if parents == 1 => match interior { + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [Parachain(1), GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [Parachain(2), GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [Parachain(3), GeneralKey { data, .. }] if data.to_vec() == c => Some(CurrencyId::C), + [Parachain(para_id), GeneralKey { data, .. }] if data.to_vec() == d && *para_id == self_para_id => { Some(CurrencyId::D) } _ => None, }, - MultiLocation { parents, interior } if parents == 0 => match interior { - X1(GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A), - X1(GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B), - X1(GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1), - X1(GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1), - X1(GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2), - X1(GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C), - X1(GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D), + (parents, interior) if parents == 0 => match interior { + [GeneralKey { data, .. }] if data.to_vec() == a => Some(CurrencyId::A), + [GeneralKey { data, .. }] if data.to_vec() == b => Some(CurrencyId::B), + [GeneralKey { data, .. }] if data.to_vec() == a1 => Some(CurrencyId::A1), + [GeneralKey { data, .. }] if data.to_vec() == b1 => Some(CurrencyId::B1), + [GeneralKey { data, .. }] if data.to_vec() == b2 => Some(CurrencyId::B2), + [GeneralKey { data, .. }] if data.to_vec() == c => Some(CurrencyId::C), + [GeneralKey { data, .. }] if data.to_vec() == d => Some(CurrencyId::D), _ => None, }, _ => None, } } } -impl Convert> for RelativeCurrencyIdConvert { - fn convert(a: MultiAsset) -> Option { - if let MultiAsset { +impl Convert> for RelativeCurrencyIdConvert { + fn convert(a: Asset) -> Option { + if let Asset { fun: Fungible(_), - id: Concrete(id), + id: AssetId(id), } = a { Self::convert(id) @@ -309,24 +308,28 @@ impl Convert> for RelativeCurrencyIdConvert { } parameter_types! { - pub SelfLocation: MultiLocation = MultiLocation::here(); + pub SelfLocation: Location = Location::here(); pub const MaxAssetsForTransfer: usize = 2; } -match_types! { - pub type ParentOrParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(1), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(2), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(3), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(4), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(100), Junction::AccountId32 { .. }) } - }; +pub struct ParentOrParachains; +impl Contains for ParentOrParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Junction::AccountId32 { .. }]) + | (1, [Junction::AccountId32 { .. }]) + | (1, [Parachain(1), Junction::AccountId32 { .. }]) + | (1, [Parachain(2), Junction::AccountId32 { .. }]) + | (1, [Parachain(3), Junction::AccountId32 { .. }]) + | (1, [Parachain(4), Junction::AccountId32 { .. }]) + | (1, [Parachain(100), Junction::AccountId32 { .. }]) + ) + } } parameter_type_with_key! { - pub ParachainMinFee: |location: MultiLocation| -> Option { + pub ParachainMinFee: |location: Location| -> Option { #[allow(clippy::match_ref_pats)] // false positive match (location.parents, location.first_interior()) { (1, Some(Parachain(2))) => Some(40), @@ -341,9 +344,9 @@ impl orml_xtokens::Config for Runtime { type Balance = Balance; type CurrencyId = CurrencyId; type CurrencyIdConvert = RelativeCurrencyIdConvert; - type AccountIdToMultiLocation = AccountIdToMultiLocation; + type AccountIdToLocation = AccountIdToLocation; type SelfLocation = SelfLocation; - type MultiLocationsFilter = ParentOrParachains; + type LocationsFilter = ParentOrParachains; type MinXcmFee = ParachainMinFee; type XcmExecutor = XcmExecutor; type Weigher = FixedWeightBounds; diff --git a/xtokens/src/mock/para_teleport.rs b/xtokens/src/mock/para_teleport.rs index 8822fbfd6..9b572670a 100644 --- a/xtokens/src/mock/para_teleport.rs +++ b/xtokens/src/mock/para_teleport.rs @@ -2,8 +2,8 @@ use super::{AllowTopLevelPaidExecution, Amount, Balance, CurrencyId, CurrencyIdC use crate as orml_xtokens; use frame_support::{ - construct_runtime, derive_impl, match_types, parameter_types, - traits::{ConstU128, ConstU32, Everything, Get, Nothing}, + construct_runtime, derive_impl, parameter_types, + traits::{ConstU128, ConstU32, Contains, Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; @@ -12,7 +12,7 @@ use sp_runtime::{ traits::{Convert, IdentityLookup}, AccountId32, }; -use xcm::v3::{prelude::*, Weight}; +use xcm::v4::{prelude::*, Weight}; use xcm_builder::{ AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, NativeAsset, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, @@ -48,7 +48,6 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } @@ -75,8 +74,8 @@ impl orml_tokens::Config for Runtime { parameter_types! { pub const RelayNetwork: NetworkId = NetworkId::Kusama; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::get().into())].into(); } pub type LocationToAccountId = ( @@ -176,32 +175,36 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); } -pub struct AccountIdToMultiLocation; -impl Convert for AccountIdToMultiLocation { - fn convert(account: AccountId) -> MultiLocation { - X1(Junction::AccountId32 { +pub struct AccountIdToLocation; +impl Convert for AccountIdToLocation { + fn convert(account: AccountId) -> Location { + [Junction::AccountId32 { network: None, id: account.into(), - }) + }] .into() } } parameter_types! { - pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(MsgQueue::get().into()))); + pub SelfLocation: Location = Location::new(1, [Parachain(MsgQueue::get().into())]).into(); pub const MaxAssetsForTransfer: usize = 3; } -match_types! { - pub type ParentOrParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X1(Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(1), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(2), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(3), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(4), Junction::AccountId32 { .. }) } | - MultiLocation { parents: 1, interior: X2(Parachain(100), Junction::AccountId32 { .. }) } - }; +pub struct ParentOrParachains; +impl Contains for ParentOrParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Junction::AccountId32 { .. }]) + | (1, [Junction::AccountId32 { .. }]) + | (1, [Parachain(1), Junction::AccountId32 { .. }]) + | (1, [Parachain(2), Junction::AccountId32 { .. }]) + | (1, [Parachain(3), Junction::AccountId32 { .. }]) + | (1, [Parachain(4), Junction::AccountId32 { .. }]) + | (1, [Parachain(100), Junction::AccountId32 { .. }]) + ) + } } impl orml_xtokens::Config for Runtime { @@ -209,9 +212,9 @@ impl orml_xtokens::Config for Runtime { type Balance = Balance; type CurrencyId = CurrencyId; type CurrencyIdConvert = CurrencyIdConvert; - type AccountIdToMultiLocation = AccountIdToMultiLocation; + type AccountIdToLocation = AccountIdToLocation; type SelfLocation = SelfLocation; - type MultiLocationsFilter = ParentOrParachains; + type LocationsFilter = ParentOrParachains; type MinXcmFee = DisabledParachainFee; type XcmExecutor = XcmExecutor; type Weigher = FixedWeightBounds; diff --git a/xtokens/src/mock/relay.rs b/xtokens/src/mock/relay.rs index 9eabc96f2..c8c02c6bd 100644 --- a/xtokens/src/mock/relay.rs +++ b/xtokens/src/mock/relay.rs @@ -13,7 +13,7 @@ use polkadot_runtime_parachains::{ inclusion::{AggregateMessageOrigin, UmpQueueId}, origin, shared, }; -use xcm::v3::prelude::*; +use xcm::v4::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, FixedWeightBounds, FungibleAdapter, IsConcrete, SignedAccountId32AsNative, SignedToAccountId32, @@ -45,20 +45,21 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = [u8; 8]; - type MaxHolds = (); type MaxFreezes = (); } -impl shared::Config for Runtime {} +impl shared::Config for Runtime { + type DisabledValidators = (); +} impl configuration::Config for Runtime { type WeightInfo = configuration::TestWeightInfo; } parameter_types! { - pub KsmLocation: MultiLocation = Here.into(); + pub KsmLocation: Location = Here.into(); pub const KusamaNetwork: NetworkId = NetworkId::Kusama; - pub UniversalLocation: InteriorMultiLocation = X1(GlobalConsensus(KusamaNetwork::get())); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(KusamaNetwork::get())].into(); } pub type SovereignAccountOf = ( @@ -78,9 +79,9 @@ pub type XcmRouter = super::RelayChainXcmRouter; pub type Barrier = (TakeWeightCredit, AllowTopLevelPaidExecutionFrom); parameter_types! { - pub Kusama: MultiAssetFilter = Wild(AllOf { fun: WildFungible, id: Concrete(KsmLocation::get()) }); - pub Statemine: MultiLocation = Parachain(3).into(); - pub KusamaForStatemine: (MultiAssetFilter, MultiLocation) = (Kusama::get(), Statemine::get()); + pub Kusama: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId(KsmLocation::get()) }); + pub Statemine: Location = Parachain(3).into(); + pub KusamaForStatemine: (AssetFilter, Location) = (Kusama::get(), Statemine::get()); } pub type TrustedTeleporters = xcm_builder::Case; diff --git a/xtokens/src/mock/teleport_currency_adapter.rs b/xtokens/src/mock/teleport_currency_adapter.rs index b05356428..8f44dd75e 100644 --- a/xtokens/src/mock/teleport_currency_adapter.rs +++ b/xtokens/src/mock/teleport_currency_adapter.rs @@ -9,17 +9,17 @@ use sp_std::{ }; use orml_xcm_support::{OnDepositFail, UnknownAsset as UnknownAssetT}; -use xcm::v3::{prelude::*, Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm::v4::{prelude::*, Asset, Error as XcmError, Location, Result}; use xcm_executor::{ traits::{ConvertLocation, MatchesFungible, TransactAsset}, - Assets, + AssetsInHolding, }; /// Asset transaction errors. enum Error { /// Failed to match fungible. FailedToMatchFungible, - /// `MultiLocation` to `AccountId` Conversion failed. + /// `Location` to `AccountId` Conversion failed. AccountIdConversionFailed, /// `CurrencyId` conversion failed. CurrencyIdConversionFailed, @@ -35,7 +35,7 @@ impl From for XcmError { } } -/// The `TransactAsset` implementation, to handle `MultiAsset` deposit/withdraw. +/// The `TransactAsset` implementation, to handle `Asset` deposit/withdraw. /// Note that teleport related functions are unimplemented. /// /// Methods of `DepositFailureHandler` would be called on multi-currency deposit @@ -73,7 +73,7 @@ impl< AccountId: sp_std::fmt::Debug + Clone, AccountIdConvert: ConvertLocation, CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, - CurrencyIdConvert: Convert>, + CurrencyIdConvert: Convert>, DepositFailureHandler: OnDepositFail, > TransactAsset for MultiTeleportCurrencyAdapter< @@ -87,13 +87,13 @@ impl< DepositFailureHandler, > { - fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) -> Result { + fn can_check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) -> Result { Ok(()) } - fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {} + fn check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) {} - fn deposit_asset(asset: &MultiAsset, location: &MultiLocation, _context: Option<&XcmContext>) -> Result { + fn deposit_asset(asset: &Asset, location: &Location, _context: Option<&XcmContext>) -> Result { match ( AccountIdConvert::convert_location(location), CurrencyIdConvert::convert(asset.clone()), @@ -109,10 +109,10 @@ impl< } fn withdraw_asset( - asset: &MultiAsset, - location: &MultiLocation, + asset: &Asset, + location: &Location, _maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { UnknownAsset::withdraw(asset, location).or_else(|_| { let who = AccountIdConvert::convert_location(location) .ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; diff --git a/xtokens/src/tests.rs b/xtokens/src/tests.rs index 654063fb7..5efd4c86b 100644 --- a/xtokens/src/tests.rs +++ b/xtokens/src/tests.rs @@ -8,7 +8,7 @@ use orml_traits::{ConcreteFungibleAsset, MultiCurrency}; use parity_scale_codec::Encode; use polkadot_parachain_primitives::primitives::Sibling; use sp_runtime::{traits::AccountIdConversion, AccountId32}; -use xcm::{v3::OriginKind::SovereignAccount, VersionedXcm}; +use xcm::{v4::OriginKind::SovereignAccount, VersionedXcm}; use xcm_simulator::TestExt; fn para_a_account() -> AccountId32 { @@ -63,12 +63,12 @@ fn send_relay_chain_asset_to_relay_chain() { CurrencyId::R, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X1(Junction::AccountId32 { + [Junction::AccountId32 { network: None, id: BOB.into(), - }) + }] ) .into() ), @@ -98,12 +98,12 @@ fn send_relay_chain_asset_to_relay_chain_with_fee() { 450, 50, Box::new( - MultiLocation::new( + Location::new( 1, - X1(Junction::AccountId32 { + [Junction::AccountId32 { network: None, id: BOB.into(), - }) + }] ) .into() ), @@ -164,15 +164,15 @@ fn send_relay_chain_asset_to_sibling() { CurrencyId::R, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -206,15 +206,15 @@ fn send_relay_chain_asset_to_sibling_with_fee() { 410, 90, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -453,15 +453,15 @@ fn send_sibling_asset_to_non_reserve_sibling() { CurrencyId::B, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(3), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -500,15 +500,15 @@ fn send_sibling_asset_to_non_reserve_sibling_with_fee() { 410, 90, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(3), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -542,15 +542,15 @@ fn send_self_parachain_asset_to_sibling() { CurrencyId::A, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -579,15 +579,15 @@ fn send_self_parachain_asset_to_sibling_with_fee() { 450, 50, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -617,15 +617,15 @@ fn send_self_parachain_asset_to_sibling_with_distinct_fee() { vec![(CurrencyId::A, 450), (CurrencyId::A1, 50)], 1, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -936,7 +936,7 @@ fn transfer_no_reserve_assets_fails() { TestNet::reset(); ParaA::execute_with(|| { - let asset_id: AssetId = X1(Junction::from(BoundedVec::try_from(b"B".to_vec()).unwrap())).into(); + let asset_id: AssetId = [Junction::from(BoundedVec::try_from(b"B".to_vec()).unwrap())].into(); assert_noop!( ParaXTokens::transfer_multiasset( Some(ALICE).into(), @@ -967,17 +967,17 @@ fn transfer_to_self_chain_fails() { assert_noop!( ParaXTokens::transfer_multiasset( Some(ALICE).into(), - Box::new(MultiAsset::sibling_parachain_asset(1, b"A".to_vec().try_into().unwrap(), 100).into()), + Box::new(Asset::sibling_parachain_asset(1, b"A".to_vec().try_into().unwrap(), 100).into()), Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(1), Junction::AccountId32 { network: None, id: BOB.into() } - ) + ] ) .into() ), @@ -996,14 +996,14 @@ fn transfer_to_invalid_dest_fails() { assert_noop!( ParaXTokens::transfer_multiasset( Some(ALICE).into(), - Box::new(MultiAsset::sibling_parachain_asset(1, b"A".to_vec().try_into().unwrap(), 100).into()), + Box::new(Asset::sibling_parachain_asset(1, b"A".to_vec().try_into().unwrap(), 100).into()), Box::new( - MultiLocation::new( + Location::new( 0, - X1(Junction::AccountId32 { + [Junction::AccountId32 { network: None, id: BOB.into() - }) + }] ) .into() ), @@ -1026,7 +1026,7 @@ fn send_as_sovereign() { let call = relay::RuntimeCall::System(frame_system::Call::::remark_with_event { remark: vec![1, 1, 1], }); - let assets: MultiAsset = (Here, 1_000_000_000_000u128).into(); + let assets: Asset = (Here, 1_000_000_000_000u128).into(); assert_ok!(para::OrmlXcm::send_as_sovereign( para::RuntimeOrigin::root(), Box::new(Parent.into()), @@ -1067,7 +1067,7 @@ fn send_as_sovereign_fails_if_bad_origin() { let call = relay::RuntimeCall::System(frame_system::Call::::remark_with_event { remark: vec![1, 1, 1], }); - let assets: MultiAsset = (Here, 1_000_000_000_000u128).into(); + let assets: Asset = (Here, 1_000_000_000_000u128).into(); assert_err!( para::OrmlXcm::send_as_sovereign( para::RuntimeOrigin::signed(ALICE), @@ -1123,15 +1123,15 @@ fn send_with_zero_fee_should_yield_an_error() { 450, 0, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1157,15 +1157,15 @@ fn send_with_insufficient_fee_traps_assets() { 450, 30, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1200,15 +1200,15 @@ fn send_with_fee_should_handle_overflow() { u128::MAX, 100, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1409,15 +1409,15 @@ fn send_self_parachain_asset_to_sibling_relative_parachain() { CurrencyId::D, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1523,15 +1523,15 @@ fn send_relative_view_sibling_asset_to_non_reserve_sibling() { CurrencyId::D, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1571,15 +1571,15 @@ fn send_relay_chain_asset_to_relative_view_sibling() { CurrencyId::R, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(4), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1623,7 +1623,7 @@ fn unsupported_multilocation_should_be_filtered() { ), WeightLimit::Unlimited ), - Error::::NotSupportedMultiLocation + Error::::NotSupportedLocation ); assert_noop!( @@ -1644,7 +1644,7 @@ fn unsupported_multilocation_should_be_filtered() { ), WeightLimit::Unlimited ), - Error::::NotSupportedMultiLocation + Error::::NotSupportedLocation ); }); } @@ -1661,15 +1661,15 @@ fn send_with_sufficient_weight_limit() { CurrencyId::A, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1697,15 +1697,15 @@ fn send_with_insufficient_weight_limit() { CurrencyId::A, 500, Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into(), } - ) + ] ) .into() ), @@ -1726,23 +1726,23 @@ fn send_with_insufficient_weight_limit() { fn send_multiasset_with_zero_fee_should_yield_an_error() { TestNet::reset(); - let asset_id: AssetId = X1(Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())).into(); + let asset_id: AssetId = [Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())].into(); ParaA::execute_with(|| { assert_noop!( ParaXTokens::transfer_multiasset_with_fee( Some(ALICE).into(), - Box::new((asset_id, 100).into()), + Box::new((asset_id.clone(), 100).into()), Box::new((asset_id, Fungibility::Fungible(0)).into()), Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into() }, - ) + ] ) .into() ), @@ -1757,8 +1757,8 @@ fn send_multiasset_with_zero_fee_should_yield_an_error() { fn send_undefined_nft_should_yield_an_error() { TestNet::reset(); - let fee_id: AssetId = X1(Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())).into(); - let nft_id: AssetId = X1(Junction::GeneralIndex(42)).into(); + let fee_id: AssetId = [Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())].into(); + let nft_id: AssetId = [Junction::GeneralIndex(42)].into(); ParaA::execute_with(|| { assert_noop!( @@ -1767,15 +1767,15 @@ fn send_undefined_nft_should_yield_an_error() { Box::new((nft_id, Undefined).into()), Box::new((fee_id, 100).into()), Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into() }, - ) + ] ) .into() ), @@ -1790,8 +1790,8 @@ fn send_undefined_nft_should_yield_an_error() { fn nfts_cannot_be_fee_assets() { TestNet::reset(); - let asset_id: AssetId = X1(Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())).into(); - let nft_id: AssetId = X1(Junction::GeneralIndex(42)).into(); + let asset_id: AssetId = [Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap())].into(); + let nft_id: AssetId = [Junction::GeneralIndex(42)].into(); ParaA::execute_with(|| { assert_noop!( @@ -1800,15 +1800,15 @@ fn nfts_cannot_be_fee_assets() { Box::new((asset_id, 100).into()), Box::new((nft_id, Index(1)).into()), Box::new( - MultiLocation::new( + Location::new( 1, - X2( + [ Parachain(2), Junction::AccountId32 { network: None, id: BOB.into() }, - ) + ] ) .into() ),